Skip to content

code_review: review every changed file before SUBMIT, configurable RLM output cap - #62

Merged
khezen merged 2 commits into
mainfrom
fix/code-review-full-coverage
Nov 24, 2026
Merged

khezen merged 2 commits into
mainfrom
fix/code-review-full-coverage

Conversation

@khezen

@khezen khezen commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Problem

Each review of the same PR found different issues (PR #61: 5 runs, 5 different finding sets; a High in implement/agent.py first appeared on run 4). A larger budget (DEFAULT_MAX_ITERS=50 / DEFAULT_MAX_LLM_CALLS=160) did not help. The root model only sees patches through REPL prints capped at dspy's 10k chars (middle omitted), and the prompt told it it had "very little time", so it submitted before reading the whole diff.

Changes

  • SUBMIT gate (CodespyRLM, opt-in via submit_check): a valid SUBMIT is sent back with [Coverage] Not reviewed yet: … while changed files are unseen and budget remains. There is no rejection cap. Once the budget is spent (last iteration or max_llm_calls exhausted), SUBMIT is accepted, the unseen files are logged as a WARNING and the findings are published. An invalid SUBMIT still gets dspy's error. Agents without a check behave as before.
  • Coverage from what the model actually saw (unseen_files): each step's output after the cap, plus its code. A file counts as seen when ≥90% of its significant patch lines appear.
  • code_review prompt: the "very little time" / "extremely terse" lines are removed. A new COVERAGE section asks for grouped prints up to the cap, large files in slices, reprinting omitted parts, and SUBMIT only after every file. The cap is filled into the prompt; the inputs are unchanged.
  • Configurable cap: llm.default_max_output_chars (DEFAULT_MAX_OUTPUT_CHARS, default 40000, min 1000) and a per-agent review.<sig>.max_output_chars. Applies to every agent built with build_rlm_agent and to the ContextSafe fallback. Action inputs default-max-output-chars and code-review-max-output-chars.
  • Telemetry: log_rlm_outcome logs iterations, end reason, gate rejections, truncated outputs and unseen files.

Behaviour change

Every RLM agent now sees step outputs of up to 40k chars instead of 10k. Expect fewer steps and larger prompts. DEFAULT_MAX_OUTPUT_CHARS=10000 restores the old behaviour.

Tests

  • New tests/test_rlm_coverage.py: coverage helper, gate (sync and async, budget exhaustion, extract fallback, invalid SUBMIT), plumbing, telemetry. The gate tests run the real dspy loop with a scripted interpreter (no deno). A test pins the private dspy 3.4.1 budget attributes the gate reads.
  • tests/test_config.py: defaults, env/YAML overrides, precedence, minimum value.
  • Full suite: 38 new tests pass; the 40 failing and 3 erroring tests were already failing on main.

Not yet done

Validation on PR #61 (unseen files, omitted outputs, rejections, iterations, findings, cost at 40k vs 10k) and a full run with all agents to check for new content_filter refusals.

@peaks-admin peaks-admin left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 CodeSpy Review v2.4.4

Issues Found: 3 | Critical: 0 | High: 0 | Medium: 1

🧠 memories
Briefing: khezen/codespy/codespy-ai

Overview

The khezen/codespy/codespy-ai codebase centers around a holistic implementation planner that processes all scopes and issues in a single run, replacing the previous per-scope planning approach. Key structural elements include repository-root-relative file paths, globally numbered steps with explicit scope and dependency tracking, and a filesystem tool that returns ToolError exceptions instead of crashing the agent. Important constants like PLAN_BUDGET_SCOPE_CAP = 8 govern planner behavior. Several documentation files remain outdated regarding the holistic planner changes, and certain coding practices (like using assert for runtime preconditions) have been identified as problematic.

The repository uses a multi-stage Dockerfile with Poetry-managed dependencies (pyproject.toml, poetry.lock). Key directories include src/codespy (source), tests, docs, assets, and Formula. A non-root user 'codespy' with uid 1000 is created in the final Dockerfile stage. The coding agent (review.implement) executes the plan generated by the holistic implementation planner.

Structure and Where Things Live

The implementation planner now operates holistically: a single run processes all scopes and issues, ordering steps by cross-scope dependency then severity.

Steps are grouped by scope with global numbering and explicit 'Depends on' lines.

Each step lists its title, scope, files, the change, how to verify it, the steps it depends on, and the issues it addresses.

File paths in the planner are now repository-root-relative (not scope-relative). Steps include a scope field indicating which subroot they affect, and files lists use repo-root paths.

Key files changed in the holistic planner PR: CHANGELOG.md (docs change), action.yml (inputs updated), docs/architecture.md (pipeline diagram updated), docs/configuration.md (planner behavior docs), docs/usage.md (usage docs), src/codespy/agents/review/plan/models.py (Step model with scope/depends_on/number), src/codespy/workflows/review/models.py (markdown rendering with dependencies).

Issues are structured as dictionaries with keys: severity, category, filename, line_start, title, description.

Issue severity levels: high, medium, low; issue categories include smell, documentation.

Key directories in the repository: src/codespy (source), tests, docs, assets, Formula.

Conventions

Steps are grouped by scope with global numbering and explicit Depends on lines (repeated across multiple sources as a key convention).

The print statement in the trajectory outputs issue fields space-separated followed by '|' and the description.

To assess code quality, list all issues with their attributes to orient, then formulate a holistic QA and recommendation based on severity and category distribution.

Boolean flag parameters is_local and is_fork in pipeline.py should be replaced with a review-target object or checked at call site to avoid flag proliferation and improve clarity.

Invariants and Constants

PLAN_BUDGET_SCOPE_CAP = 8: the planner caps the number of scopes considered in budget calculation at 8, regardless of total scopes with issues.

Dependencies and Integrations

The implementation planner now runs once across all scopes, ordering steps by dependency and severity instead of planning per scope in isolation.

Steps are globally numbered, each tied to one scope, with explicit depends_on references for cross-scope dependencies.

Filesystem tool errors are returned as ToolError rather than crashing the agent; filesystem tool errors (missing paths, file vs directory, permission, root-escape) are returned as ToolError to the agent, not as unhandled exceptions that crash the agent.

Filesystem tool errors now return ToolError exceptions (not crashes) for missing paths, file/directory mismatches, permission denied, and path escaping root; real crashes remain unchanged.

Filesystem tool errors (e.g., missing path, permission denied) are now caught by the _agent_errors decorator and re-raised as ToolError to the agent, preserving error messages without crashing.

Poetry lockfile is a TOML-like format wrapped in JSON with a 'content' field, where dependencies are listed under [[package]] sections with name and version fields.

Pitfalls and Recurring Problems

Assert statements are inappropriate for runtime preconditions as they are stripped under -O; plan/agent.py:194 uses assert on review_context.metadata as a runtime precondition; asserts are stripped under -O; should raise ValueError instead.

Assert on review_context.metadata should be replaced with explicit check raising ValueError; asserts are stripped under -O.

filesystem/server.py _EXPECTED_ERRORS includes bare ValueError, which hides genuine server bugs as agent errors; should use a dedicated root-escape exception.

Broad ValueError in _EXPECTED_ERRORS should be narrowed to a dedicated root-escape exception to avoid hiding genuine server bugs as agent errors.

Pre-existing untracked files are incorrectly published as agent changes because collect_changes ignores the before snapshot, allowing leftover cache files to reach the fix PR.

Unused reserve parameter in _build_review_body function; all callers pass 0 after body_suffix removal, making the parameter redundant.

Assert is used for runtime precondition in fix_pull_request.py, which is unsafe because asserts are stripped under Python's -O optimization flag.

Code smells identified: assert used as runtime precondition in fix_pull_request.py:46 (same pattern previously accepted in plan/agent.py), unused reserve parameter in git.py:402, private _planner_scope imported across modules, private fs._resolve_path called from MCP server, is_local/is_fork boolean flags in pipeline.py:612.

Cross-module import of private helper function _planner_scope from plan-agent module in review/implement/agent.py, violating encapsulation.

Dockerfile final stage copies root-owned files (lines 42-43), posing a security risk; recommendation is to use --chown flag in COPY commands or adjust ownership after copy.

Dockerfile build stage runs as root (lines 9-23), posing a security risk; recommendation is to add USER instruction or use --chown with COPY commands.

Dockerfile apt-get install commands (lines 9-22) do not pin exact package versions, creating a security risk; recommendation is to pin exact versions for apt-get install packages.

Dockerfile pip install command (line 14) lacks --no-cache-dir optimization, presenting a low security risk; recommendation is to add --no-cache-dir to pip install command.

Facts Shown to Be Wrong (Outdated Documentation)

docs/architecture.md:108 still describes the old per-scope ImplementationPlanSignature and needs updating for the single run over all scopes, repo-root tools, and scope/depends_on step fields.

docs/configuration.md:262 step field list omits scope and Depends on fields.

docs/architecture.md:108 still describes the old per-scope ImplementationPlanSignature and needs updating for the single run over all scopes, repo-root tools, and scope/depends_on step fields.

docs/configuration.md:262 step field list omits scope and Depends on fields.

Around this work

The khezen/codespy codebase implements a holistic code review system via pull request 61 (PR #61), which replaced per-scope planning with a single holistic implementation planner that processes all scopes and issues in one run. This planner generates globally numbered steps with explicit dependency tracking (via 'Depends on' lines) and repository-root-relative file paths, grouping steps by scope post-run. Key constants include PLAN_BUDGET_SCOPE_CAP = 8, which caps the number of scopes considered in budget calculation at 8 regardless of total scopes with issues, meaning max_iters and max_llm_calls are multiplied by the number of scopes with issues but never exceed 8× the per-scope setting.

PR #61 exhibited inconsistent review results: 5 runs produced 5 different finding sets, with a High severity issue in implement/agent.py first appearing on run 4. Increasing the budget (DEFAULT_MAX_ITERS=50 / DEFAULT_MAX_LLM_CALLS=160) did not resolve this inconsistency. The root cause lies in how the underlying model processes code changes: it only sees patches through REPL prints that are capped at dspy's 10,000 characters (with middle content omitted), and the prompt instructs the model it has "very little time," leading to rushed or incomplete analysis.

Files modified in this PR include configuration files (src/codespy/config_llm.py, codespy.yaml, .env.example, src/codespy/config.py, src/codespy/config_dspy.py), agent utilities (src/codespy/agents/context_safe.py), workflow definitions (action.yml, src/codespy/workflows/review/pipeline.py), and related components. The holistic planner's architecture is documented in action.yml (updated inputs), docs/architecture.md (pipeline diagram), docs/configuration.md (planner behavior), docs/usage.md (usage), and modeling files such as src/codespy/agents/review/plan/models.py (Step model with scope/depends_on/number) and src/codespy/workflows/review/models.py (markdown rendering with dependencies).

The planner operates with specific invariants: steps include title, scope, files, change, verification method, dependencies, and addressed issues; issue severity levels are high/medium/low with categories like smell and documentation. Filesystem tool errors are now returned as ToolError exceptions instead of crashing the agent, handled via the _agent_errors decorator.

However, several issues were identified during review:

  • Assert statements used as runtime preconditions (e.g., plan/agent.py:194 on review_context.metadata) are unsafe because they are stripped under Python's -O optimization flag; these should be replaced with explicit ValueError checks.
  • The collect_changes function in implement/agent.py ignores the before snapshot, causing pre-existing untracked files (such as caches) to be incorrectly published as agent changes in fix PRs—a High severity bug.
  • Bare ValueError in filesystem/server.py:22-23 (_EXPECTED_ERRORS) risks hiding genuine server bugs as agent errors; it should be narrowed to a dedicated PathEscapesRootError exception.
  • Documentation remains outdated: docs/architecture.md:108 still describes the old per-scope ImplementationPlanSignature, and docs/configuration.md:262 omits scope and Depends on fields from the step field list.
  • Code smells include unused reserve parameter in git.py:402, private _planner_scope imported across modules, private fs._resolve_path called from MCP server, and boolean flag parameters is_local/is_fork in pipeline.py:612 that should be replaced with a review-target object.
  • Dockerfile hardening opportunities exist but were assessed as low risk and likely outside PR intent: build stage runs as root, final stage copies root-owned files without --chown, apt packages lack version pinning, and pip install lacks --no-cache-dir.

Recommendations from the review process include fixing the untracked-file leak by passing untracked_before to collect_changes and skipping '??' entries present before the run, updating stale documentation (architecture step count, README, memory.md) in the same PR, and addressing assert-related issues and documentation omissions before merging. Other improvements like Dockerfile hardening and boolean flag refactoring are suggested for follow-up work.

Seen before
  • [observation] Non-root user 'codespy' with uid 1000 is created in the final stage of the Dockerfile.
  • [2026-11-23 · doc] Implementation Agent added to pipeline flow in memory docs as read-only with no episode. | When: 2026-11-23 | Updates documentation to reflect the agent's role and memory characteristics.
  • [observation] Review of github.com/khezen/codespy found no issues.
  • [observation] Key directories in the repository: src/codespy (source), tests, docs, assets, Formula.
  • [observation] Key files defining holistic planner: plan agent (src/codespy/agents/review/plan/agent.py), plan models (src/codespy/agents/review/plan/models.py), implementation agent (src/codespy/agents/review/implement/agent.py), implementation models (src/codespy/agents/review/implement/models.py), workflow models (src/codespy/workflows/review/models.py), filesystem protected tool (src/codespy/tools/storage/filesystem/protected.py).
  • [observation] Repository structure: source code in src/codespy, tests in tests/, documentation in docs/, managed by Poetry using pyproject.toml and poetry.lock files.
  • [2026-11-23 · audit] In plan/agent.py:194, assert is used as a runtime precondition, which is stripped under -O optimization flag. | When: 2026-11-23 | Low severity issue identified during audit; accepted by reviewer but not yet fixed
  • [observation] PlanStep files are repository-root-relative paths; each step's 'scope' field indicates the affected subroot (e.g., 'src', 'docs'); paths are normalized: leading './' stripped, empty/'.' treated as repo root.
  • [2026-11-23 · summary] Includes related documentation and version updates | When: 2026-11-23
  • [2026-11-24 · code_review] Holistic implementation planner processes all scopes/issues in one run, generating ordered steps with global numbering, explicit depends_on (1-based indices), and per-step scope indicating affected subroot; steps are grouped by scope post-run and file paths are repository-root-relative. | When: 2026-11-24 | Enables cross-scope dependency ordering and global step numbering for implementation planning.
  • [observation] The documentation file docs/development.md at line 72 omits the new implementation agent (agents/review/implement) from the source tree and pipeline stages list.
  • [observation] Code smells identified: assert used as runtime precondition in fix_pull_request.py:46 (same pattern previously accepted in plan/agent.py), unused reserve parameter in git.py:402, private _planner_scope imported across modules, private fs._resolve_path called from MCP server, is_local/is_fork boolean flags in pipeline.py:612.
  • [observation] Assert on review_context.metadata in src/codespy/agents/review/plan/agent.py:194 should be replaced with explicit ValueError check to avoid being stripped under -O optimization flag.
  • [observation] Recommendation: Approve pull request with minor changes; fix assert in plan/agent.py and docs field list in docs/configuration.md before merge (both accepted as low-severity).
  • [2026-11-23 · audit] Holistic implementation planner processes all scopes and issues in a single run with global step numbering, includes review.implement coding agent, improved filesystem error handling returning ToolError exceptions, documentation updates, and version bump to 2.4.4. | When: Monday, November 23, 2026
  • [observation] Review pipeline updated to a 6-step flow with Implementation Agent as step 6.
  • [observation] Changes span planner agent, models, workflows, filesystem server, tests, and documentation.
  • [observation] Bare ValueError in src/codespy/tools/storage/filesystem/server.py:22-23 should be narrowed to a dedicated PathEscapesRootError exception to avoid masking server bugs as agent errors.
  • [observation] Holistic planner processes all scopes/issues in one run with global step numbering, explicit 'depends_on' (1-based indices), and per-step 'scope' field; post-run, steps are grouped by scope; file paths are repository-root-relative; budget is per-scope settings × scopes with issues (capped at 8).
  • [observation] Coding agent (review.implement) added to carry out the implementation plan.
  • [observation] Filesystem MCP server now raises ToolError (not logged as crash) for: missing path, file vs directory, permission denied, path escaping root; real crashes (e.g., segfault, OOM) still log tracebacks; agent sees errors like 'Directory not found: deploy' instead of internal tracebacks
  • [observation] Boolean flag parameters is_local and is_fork in pipeline.py should be replaced with a review-target object or checked at call site to avoid flag proliferation and improve clarity
  • [observation] Implementation planner now operates holistically across all scopes in a single run, ordering steps by cross-scope dependency and severity, with global step numbering and per-scope grouping. Filesystem tool errors (missing paths, permissions, etc.) are returned as ToolError instead of crashing the agent.
  • [observation] A new implementation agent carries out the plan using write-enabled filesystem tools, and filesystem errors are returned as ToolError exceptions instead of crashing the agent.
  • [observation] Repository contains a Dockerfile using multi-stage build and Python dependencies managed by Poetry (pyproject.toml, poetry.lock).
  • [observation] filesystem/server.py _EXPECTED_ERRORS includes bare ValueError, which hides genuine server bugs as agent errors; should use a dedicated root-escape exception.
  • [observation] Audit found 3 low-severity findings: (1) plan/agent.py:194 uses assert as runtime precondition (stripped under -O; should raise ValueError), (2) filesystem/server.py:22-23 has bare ValueError in _EXPECTED_ERRORS turning server bugs into agent-facing errors (should use PathEscapesRootError subclass), (3) docs/configuration.md:262 omits global number, scope, and depends_on from step field list.
  • [observation] Added coding agent (review.implement) that carries out the plan
  • [observation] Assert used for runtime precondition in review agent code should be replaced with explicit ValueError check | When: 2026-11-23 | Asserts are stripped under -O optimization flag, making runtime checks unreliable
  • [observation] Filesystem tool error handling improved to return ToolError exceptions instead of crashing.
  • [observation] Misplaced comment and vague variable name in review workflow models reduce code clarity
Decisions
  • [2026-11-23 · doc] Each step should list its global number, title, scope, files, the change, how to verify it, the steps it depends on, and the issues it addresses. | When: 2026-11-23
  • [2026-11-23 · summary] Added coding agent (review.implement) that carries out the plan | When: 2026-11-23
  • [observation] Earlier accepted findings (assert precondition, step field docs) addressed in commit a1d7fd8.
  • [observation] Steps are grouped by scope with global numbering and explicit Depends on lines.
  • [observation] Issue severity levels: high, medium, low; issue categories include smell, documentation.
  • [observation] Includes related documentation and version updates
  • [observation] Issues are structured as dictionaries with keys: severity, category, filename, line_start, title, description.
  • [2026-11-24 · summary] Filesystem tool errors (invalid paths, file vs directory, permission, root-escape) are returned as ToolError exceptions to the agent | When: 2026-11-24
  • [observation] Holistic implementation planner processes all scopes/issues in one run, generating ordered steps with global numbering, explicit depends_on (1-based indices), and per-step scope indicating affected subroot; steps are grouped by scope post-run and file paths are repository-root-relative.
  • [observation] ImplementationPlanSignature row in docs/architecture.md:108 should be updated to reflect one run over all scopes and issues, repo-root tools, with steps carrying scope and depends_on.
  • [2026-11-23 · audit] In docs/architecture.md:108, ImplementationPlanSignature row still describes per-scope planning, which is outdated due to holistic implementation. | When: 2026-11-23 | Medium severity issue identified during audit
  • [observation] README documentation updated to describe one cross-scope plan (Goal/Decisions/Tasks/Risks/Validation) grouped per scope.
  • [observation] The holistic planner's budget caps at ×8: max_iters and max_llm_calls are multiplied by the number of scopes with issues, but never exceed 8× the per-scope setting.
  • [observation] Dockerfile hardening issues: root user in build stage, root-owned COPY in final stage without --chown, unpinned apt packages, pip install without --no-cache-dir; assessed as low risk and likely outside PR intent. Additionally, Dockerfile build stage runs as root (lines 9-23), posing a security risk; recommendation is to add USER instruction or use --chown with COPY commands. Dockerfile apt-get install commands (lines 9-22) do not pin exact package versions, creating a security risk; recommendation is to pin exact versions for apt-get install packages.
  • [observation] Implementation planner creates one holistic plan for entire review instead of per-scope, enabling cross-scope dependency ordering and global step numbering with steps grouped by scope and linked via 'Depends on'.
Recurring patterns
  • [observation] Pre-existing untracked files are incorrectly published as agent changes because collect_changes ignores the before snapshot, allowing leftover cache files to reach the fix PR
  • [observation] Holistic implementation planner processes all scopes and issues in a single run with cross-scope dependency-aware planning and global step numbering
  • [observation] Recommendation: REQUEST CHANGES. Fix untracked-file leak by passing untracked_before to collect_changes and skipping '??' entries present before run. Update stale docs (architecture step count, README, memory.md) in same PR. Address smells and Dockerfile hardening in follow-ups.
  • [observation] To assess code quality, list all issues with their attributes to orient, then formulate a holistic QA and recommendation based on severity and category distribution.
  • [observation] High severity bug in implement/agent.py lines 121-150: collect_changes ignores the before snapshot, causing pre-existing untracked files (e.g. caches) to be published in the fix PR.
  • [observation] Implementation agent collects changes via git status, filters preexisting untracked files/protected paths/symlinks, validates UTF-8, fails closed on byte/file caps (MAX_CHANGED_FILES=100, MAX_CHANGED_BYTES=2,000,000), then restores clone using git reset and cleanup.
  • [observation] In docs/configuration.md:262, the Step field list omits scope and depends_on fields.
  • [observation] Holistic planner processes all scopes/issues in one run with global step numbering, explicit 'depends_on' (1-based indices of prior steps), and per-step 'scope' field for cross-scope dependency resolution; steps are grouped by scope post-run.
📋 Summary

This PR adds a SUBMIT gate to ensure every changed file is reviewed before submission and makes the RLM output cap configurable (increased from 10k to 40k chars) to prevent the model from submitting before reading the whole diff, which was causing inconsistent review findings.

🎯 Quality Assessment

Solid, targeted change. Fixes premature SUBMIT and the truncated-diff reads that caused inconsistent findings. 3 smells: 1 medium, 2 low. No bugs or security issues found. Medium: the SUBMIT gate reads private dspy _LLMCallBudget._count/_limit. On a dspy upgrade an AttributeError silently disables budget detection, so the gate keeps rejecting SUBMIT and can loop until the iteration cap. Low: _run_submit_check uses assert as a runtime precondition; it is stripped under -O. Low: literal 10_000 duplicates the dspy default output cap; use a named constant.

📊 Statistics
Severity Security Bugs Documentation Smells SEO Total
Critical 0 0 0 0 0 0
High 0 0 0 0 0 0
Medium 0 0 0 1 0 1
Low 0 0 0 2 0 2
Info 0 0 0 0 0 0
Total 0 0 0 3 0 3
💰 Cost Summary

Total: $1.6070 | LLM Calls: 39

  • Memory: pending (retain, consolidation, mental models)

Review

Signature In Tokens Out Tokens In Cost Out Cost Calls Duration
doc 166,336 1,532 $0.6079 $0.0306 6 36.7s
code_review 178,964 4,413 $0.5357 $0.0883 8 61.3s
plan 85,034 3,599 $0.2296 $0.0720 7 49.0s
audit 7,544 483 $0.0258 $0.0097 2 18.1s
summary 15,529 1,616 $0.0022 $0.0009 7 14.9s

Subtotal: $1.6025 | LLM Calls: 30

Memory

Signature In Tokens Out Tokens In Cost Out Cost Calls Duration
memory_recall 25,215 1,051 $0.0038 $0.0007 3 133.4s
memory_recall_embeddings 305 0 $0.0000 $0.0000 6 1.6s

Subtotal: $0.0045 | LLM Calls: 9

⚠️ Issues without line reference or could not post inline

🟡 [Medium] SUBMIT gate depends on private dspy budget attributes

File: src/codespy/agents/context_safe.py:2-11
Category: smell | Confidence: 85%

Stop reading private _LLMCallBudget._count/_limit; an AttributeError silently disables budget detection and keeps rejecting SUBMIT.

Suggestion:
Count sub-LLM calls in a wrapper around the llm_query tools from _make_llm_tools instead of reading dspy internals.


🔵 [Low] Magic number duplicates dspy default output cap

File: src/codespy/agents/rlm_tools.py:2
Category: smell | Confidence: 80%

Replace literal 10_000 with a named constant, such as DSPY_DEFAULT_MAX_OUTPUT_CHARS, shared with CodespyRLM documentation.

Suggestion:
Define a module-level constant and reuse it.


🔵 [Low] assert used as runtime precondition

File: src/codespy/agents/context_safe.py:2
Category: smell | Confidence: 70%

Replace assert in _run_submit_check with an explicit check; asserts are stripped under python -O.

Suggestion:
Return None early when self._submit_check is None.


💡 Recommendation

Request changes. Replace the private-attribute read with a call counter that wraps the _make_llm_tools llm_query tools. Replace the assert with an explicit early return. Add a named constant for the default cap.

🛠️ Implementation Plan (3 steps)

Goal

CodespyRLM's SUBMIT gate detects an exhausted LLM budget without dspy private attributes. It checks preconditions explicitly, and the default output cap is a single named constant.

Decisions

  • Count calls in codespy's own tool wrapper, not via a public dspy API: dspy 3.4.1 exposes none for the budget.
  • Compare the count against self.max_llm_calls, which is a public RLM attribute, so the limit needs no private read.
  • Put the constant in context_safe.py, because CodespyRLM owns the cap semantics; rlm_tools imports it.
  • Remove the pin test for private attributes instead of keeping it, since nothing reads those attributes any more.

Tasks

1. Count sub-LLM calls in own tool wrapper

Files: src/codespy/agents/context_safe.py, tests/test_rlm_coverage.py

In CodespyRLM._make_llm_tools, wrap each llm_query/llm_query_batched tool returned by super() to add to self._llm_calls (batched adds len(prompts)). Reset in _reset_gate_state. _llm_budget_spent returns self._llm_calls >= self.max_llm_calls. Drop self._llm_budget, the _count/_limit read and the AttributeError swallow.

Verify: Delete test_pin_dspy_private_budget_attrs and the _LLMCallBudget import. Keep test_accepted_once_llm_calls_exhausted green. Add a test that a batched call of N prompts counts N and that the counter resets per forward.

Addresses: SUBMIT gate depends on private dspy budget attributes

2. Replace assert with explicit early return

Files: src/codespy/agents/context_safe.py, tests/test_rlm_coverage.py

In CodespyRLM._run_submit_check, replace assert self._submit_check is not None with if self._submit_check is None: return None.

Verify: Add a test: CodespyRLM without submit_check, _run_submit_check(history) returns None. Run pytest under python -O for tests/test_rlm_coverage.py.

Addresses: assert used as runtime precondition

3. Name dspy default output cap constant

Files: src/codespy/agents/context_safe.py, src/codespy/agents/rlm_tools.py, tests/test_rlm_coverage.py

Define DSPY_DEFAULT_MAX_OUTPUT_CHARS = 10_000 in context_safe.py next to the CodespyRLM docs and reference it in the docstring. Import it in rlm_tools.log_rlm_outcome: cap = max_output_chars or DSPY_DEFAULT_MAX_OUTPUT_CHARS.

Verify: test_fallback_default_cap_is_dspy_default asserts the constant equals dspy RLM's default max_output_chars. grep 10_000 src/ shows only the constant definition.

Addresses: Magic number duplicates dspy default output cap

Risks

  • dspy also enforces its own budget via reserve(). If our count drifts from it (batched calls, or failed calls that dspy refunds), the gate may accept early or reject one call too long.
  • The super()._make_llm_tools return shape (dict of names to callables) is dspy-internal; the wrapper must keep tool names and signatures so the REPL still exposes llm_query.
  • aforward and forward both have to reset the counter; test_async_path_gated covers only rejection, not the budget.
  • Importing context_safe from rlm_tools could create an import cycle; check the existing import direction (COVERAGE_REJECTION_PREFIX).

Validation

  • pytest tests/test_rlm_coverage.py tests/test_context_safe.py tests/test_rlm_tools.py
  • python -O -m pytest tests/test_rlm_coverage.py
  • grep -rn '_count|_limit|_LLMCallBudget' src/ returns nothing.
  • Full pytest suite green.

@khezen
khezen merged commit 8c1404a into main Nov 24, 2026
6 checks passed
@khezen
khezen deleted the fix/code-review-full-coverage branch November 24, 2026 14:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants