Skip to content

resolve_query's guidance and required context are gated behind Graph Editing's routing score; fail-open delivers the tool without either - #1855

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1840-resolve-query-fail-open
Jul 31, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1840-resolve-query-fail-open

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1840

resolve_query is whitelisted by exactly one skill (Graph Editing), and
its required node_type parameter tells the model to copy the id from
the RELEVANT ENTITY TYPES block that only render_candidates_for_prompt
injects — and only when a candidate clears the Stage-2 score gate.
stage2_tools's fail-open paths (no candidate clears the gate, or a
whitelist resolves to nothing registered) handed the tool over anyway,
directing the model to copy from context it never receives.

Tool::requires_routed_guidance marks resolve_query as depending on
routed guidance; stage2_tools's fail-open branches now exclude any
such tool from the full-surface fallback rather than stranding the
model with unusable instructions. The scoped (non-fail-open) path is
unaffected: whenever resolve_query is offered there, the same
score-gate filter that permits it also renders its guidance block.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1855 — Exclude resolve_query from the fail-open tool surface (closes #1840)

Review Type: Initial Review

Requirements Check (Issue #1840)

  • ✅ AC1 — Decide the fail-open contract: Met. Chose the "exclude tools whose guidance dependency isn't satisfied" branch of the issue's stated option pair, rather than synthesizing a fallback guidance block. Tool::requires_routed_guidance (packages/agent/src/local_agent/tools.rs:1122) marks resolve_query, and fail_open_surface (packages/agent/src/local_agent/routing.rs:388-394) filters it out of both fail-open branches of stage2_tools (routing.rs:371, 382). Verified directly in code, not just via the tests — both return all.to_vec() sites were changed to return fail_open_surface(all).

  • 🟡 AC2 — node_type's required-parameter description shouldn't assume the block is always present: Partially met, and the PR should say so explicitly. The issue offered two options: "guarantee the block is always available when the parameter is required" OR "make the tool description self-sufficient." This PR takes the first path only for the fail-open case covered by stage2_tools. It does not touch def_resolve_query()'s description text (tools.rs:398-401, unchanged — confirmed by diff), and it does not cover the session.routing_disabled path (see Critical finding below), where the same required-parameter/missing-block mismatch still occurs. Calling this criterion fully "met" overstates the fix's reach.

  • ✅ AC3 — Regression test for the 0.15–0.29 gap: Met, and done well. a_graph_editing_candidate_below_its_mutating_bar_fails_open_without_resolve_query (routing.rs:645-672) constructs a Graph Editing candidate at score 0.2, asserts it's inside [READ_SKILL_SCORE_BAR, MUTATING_SKILL_SCORE_BAR) via a runtime assert! on the constants (not a hardcoded comment), asserts clears_score_gate is false, and asserts both that resolve_query is excluded from stage2_tools's output AND that render_candidates_for_prompt returns None for the same candidate set — directly exercising the exact regression the issue called out, with real (non-tautological) assertions.

  • ⚠️ AC4 — Live reproduction against the fixed Fixture: agent-matrix scenarios 3->4->6 key on a value the chain never persists; trace doesn't record offered tools/routed skill #1839 fixture: Not done. No live-model run is referenced in the PR description, commit message, or diff. See discussion in Findings — judged not blocking for this PR, but should not be silently dropped from tracking.

Code Review Findings

🔴 Critical: session.routing_disabled path still offers resolve_query with no guidance block — same defect class, different trigger, left unfixed

📁 packages/agent/src/local_agent/agent_loop.rs:605-628

let tools = routing::stage2_tools(&routed.candidates, &all_tools);   // unaffected by routing_disabled
...
let candidate_block = if session.routing_disabled {
    ...
    None                                                              // forced None regardless of `tools`
} else {
    routing::render_candidates_for_prompt(&routed.candidates)
};

tools is computed via the scoped, non-fail-open path of stage2_tools whenever a candidate clears the score gate — session.routing_disabled has no effect on it (confirmed by reading the code; the comment at line 600-604 makes this deliberate). So when Graph Editing genuinely clears its mutating bar on a session where the model's routing probe verdict disabled candidate injection, tools includes resolve_query, but candidate_block is unconditionally None — the RELEVANT ENTITY TYPES block never reaches the prompt. The model receives resolve_query with a required node_type parameter whose description says "copy the id exactly from the RELEVANT ENTITY TYPES block," and that block does not exist in context. This is the exact failure mode #1840 describes, reachable through a second door this PR doesn't close.

The existing test coverage for this branch (routing_disabled_skips_injection_but_keeps_tool_scoping, agent_loop.rs:5838) uses a candidate whitelisting only search_nodes/get_node — it never exercises resolve_query, so the gap is untested as well as unfixed.

Engineering principle: A fix framed around a single function (stage2_tools) when the underlying invariant ("never offer resolve_query without its guidance block") is actually a cross-cutting constraint on the final tool set delivered to the model, not on any one producer of that set. Tool::requires_routed_guidance is the right abstraction, but it's applied at only one of its two current call sites. The safer construction is to enforce the invariant once, at the point where tools and candidate_block are reconciled for the prompt (e.g. filter tools again if candidate_block.is_none()), rather than at each place a "no candidates" condition can independently arise.

Recommendation: This is a real, currently-reachable production bug (not hypothetical — routing-probe-disabled sessions exist and are exercised by tests/live_openai_compat_routing.rs), but it is arguably distinguishable in scope from #1840, which titled itself around stage2_tools's specific fail-open branches. Given NodeSpace's pre-release/no-users posture and the project's practice of splitting closely related defects into separate issues (as #1840 itself was split from #1835), I'd accept merging this PR only if a new issue is filed immediately, before merge, explicitly tracking the routing_disabled gap with a pointer to this exact code path — the risk of "we'll get to it" quietly dropping the second half of the same bug class is too easy to let happen invisibly otherwise. If the author would rather close it now, the fix is small: after computing candidate_block, re-filter tools to exclude requires_routed_guidance_tool when candidate_block.is_none(). I'd estimate that as a similarly-sized, similarly-low-risk change to this PR — my mild preference is to fold it in now rather than defer, since the mechanism and test pattern are already established by this PR.

🟡 Improvement: AC2 should be reflected honestly in the PR description as partially addressed

📁 PR description / commit message

The commit message says the fix "excludes any such tool from the full-surface fallback" — accurate — but doesn't acknowledge that def_resolve_query()'s description text was deliberately left unreworded, or that the routing_disabled path is out of scope. Given the Critical finding above, silently treating AC2 as fully satisfied risks it being checked off and forgotten. Recommend the PR body explicitly note "AC2 addressed via guaranteed-availability, not self-sufficient wording; routing_disabled path tracked separately" (or fixed in this PR, per the recommendation above).

Engineering principle: Issue tracking should reflect actual completion state — partial fixes checked off as complete erode the trustworthiness of acceptance criteria as a project-tracking tool.

🟢 Suggestion: Live reproduction (AC4) — reasonable to defer, but say so explicitly

📁 N/A — process, not code

The fix is deterministic Rust logic (HashSet membership, float comparison against fixed bars) with no model-behavior dependency — the four new unit tests (fail_open_on_empty_retrieval_excludes_resolve_query, a_graph_editing_candidate_below_its_mutating_bar_fails_open_without_resolve_query, a_graph_editing_candidate_that_clears_its_bar_offers_resolve_query_with_its_guidance, whitelist_naming_only_unregistered_tools_still_excludes_resolve_query_on_fail_open) exercise every branch of stage2_tools and its interaction with render_candidates_for_prompt directly, with real assertions against the actual return values, not mocks of the mechanism. A live repro against the #1839 fixture would confirm the mechanism was correctly diagnosed in the first place, but that diagnosis is not really in question here — the code path is small and the tests trace it exactly. I would not block merge on AC4 for this PR. Nit: worth a one-line note in the PR body ("AC4 deferred — mechanism is deterministic and fully covered by unit tests; not scheduling a live repro for this PR") so it's a visible decision rather than a silent omission, consistent with the AC2 point above.

🟢 Suggestion: Tool::requires_routed_guidance design is consistent with existing conventions, not over-engineered

📁 packages/agent/src/local_agent/tools.rs:1122-1140

Verified this against the pre-existing write_semantics/is_write pattern in the same file (tools.rs:1056-1099): both are exhaustive matches over Tool::ALL variants with the same rationale documented inline (compiler forces every new tool variant to declare its behavior rather than silently defaulting to "safe"). requires_routed_guidance follows this house style precisely, including the parallel free-function wrapper (requires_routed_guidance_tool, mirroring is_write_tool at tools.rs:1185) for resolving by wire name where an &str rather than a Tool is in hand (needed inside fail_open_surface, which only has ToolDefinition.name: String). A bare tool.name == "resolve_query" string check would have been simpler line-count-wise but loses the compile-time completeness guarantee — given this codebase's demonstrated pattern of exactly this trade-off elsewhere, matching it here is the right call, not gold-plating.

🟢 Suggestion: normal (non-fail-open) path correctness — confirmed structurally sound

📁 packages/agent/src/local_agent/routing.rs:364-368, 268-270

Read directly (not just inferred from tests): stage2_tools's permitted set and render_candidates_for_prompt's eligible set are both filtered by the identical predicate clears_score_gate(c) over the identical candidates slice. They cannot structurally diverge as long as both functions are called with the same candidates argument at the call site — which they are, both fed by routed.candidates in agent_loop.rs:605 and 627. The PR's claim that the two are "structurally guaranteed to agree" holds for the scoped path. (It does not hold once routing_disabled intervenes between the two calls, per the Critical finding — the guarantee is about the two functions agreeing on their input, not about both being invoked under the same conditions.)

Test Quality Assessment

The four new routing.rs tests and two new tools.rs tests are well-constructed: they assert on actual return values (tool-name membership, Option presence/absence of the rendered block), include a README-quality comment tying each test to the specific issue scenario, and a_graph_editing_candidate_below_its_mutating_bar_fails_open_without_resolve_query goes the extra step of asserting the fixture score is actually in the target range via a runtime check rather than trusting a comment. only_resolve_query_requires_routed_guidance iterating Tool::ALL is a good pattern — it will fail loudly (not silently pass) the moment a new tool variant is added without an explicit classification decision. No tautological assertions found.

Build/Test Verification (re-run independently)

  • cargo build -p nodespace-agent: clean, no warnings.
  • cargo test -p nodespace-agent local_agent::routing::: 25 passed, 0 failed.
  • cargo test -p nodespace-agent --lib: 386 passed, 0 failed, 0 ignored.
  • cargo clippy -p nodespace-agent --lib --tests: clean, no warnings.
  • Grepped whole repo for stage2_tools, resolve_query, requires_routed_guidance: single production call site for stage2_tools (agent_loop.rs:605), correctly updated; no other call site needed changes for the scope this PR claims (the routing_disabled path is the one gap, addressed above).

Recommendation: REQUEST CHANGES

The core mechanism is correctly designed, cleanly implemented, consistent with existing codebase conventions, and well-tested for the scope it claims — this is good, surgical work on the stage2_tools fail-open branches specifically. But the PR's own commit message frames this as fixing the general problem ("directing the model to copy from context it never receives"), and there is a second, currently-reachable production path (session.routing_disabled combined with a candidate that clears the score gate) that reproduces the identical defect and is left completely unaddressed and untested. Given this is the second time this exact bug class has been found lurking in an adjacent path within the same feature area (the PR description itself notes #1840 was split from #1835's original misdiagnosis), I'd rather close both doors in the same change than risk a #1841-style follow-up discovering the same root cause a third time.

Path to approval (either satisfies this): (a) extend this PR to also filter tools by requires_routed_guidance_tool when candidate_block is None in agent_loop.rs, with a test mirroring routing_disabled_skips_injection_but_keeps_tool_scoping but whitelisting resolve_query; or (b) file a tracking issue for the routing_disabled gap before merge, and update the PR/issue body to honestly reflect AC2 as partially met and AC4 as deliberately deferred. Either is a small amount of work relative to what's already here — this is not a request to redesign anything.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review recommendation: REQUEST CHANGES (GitHub blocks a request-changes review from the PR author's own account, so recording via --comment instead — see full review posted above for the actual recommendation and required action).

Code review on PR #1855 found a second door to the same defect
stage2_tools's fail-open exclusion closes: when session.routing_disabled
is true, candidate_block (the RELEVANT ENTITY TYPES block resolve_query's
required node_type parameter depends on) is forced to None regardless of
whether a candidate cleared the score gate. A Graph Editing candidate
that legitimately clears its bar still puts resolve_query in `tools` via
stage2_tools's normal scoped path, which is unaffected by
routing_disabled -- so the tool reaches the model with no guidance again,
through a path stage2_tools's own exclusion doesn't cover.

Re-derive the exclusion from what the model is actually about to
receive (candidate_block) rather than from why routing produced no
candidates: after computing candidate_block, retain only tools that
either don't require routed guidance or are accompanied by a rendered
block. This subsumes stage2_tools's own fail-open exclusion (empty
candidate_block there too) without duplicating its logic.

RecordingEngine (test fixture) now also captures each generate() call's
offered tool names, and a new test reproduces the exact scenario: a
Graph Editing candidate whitelisting resolve_query at score 0.9 (clears
the gate) with routing_disabled=true. Verified the test fails without
the fix (temporarily neutralized the retain(), confirmed the new test
catches it, restored the fix).

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the Critical finding from the initial review: session.routing_disabled reproduced the same defect through a second door (agent_loop.rs:605-628) — stage2_tools's own exclusion only covers its fail-open branches, but candidate_block can independently collapse to None while tools still legitimately contains resolve_query via the normal scoped path.

Fix in 4d221b6a: after computing candidate_block, re-derive the exclusion from what the model is actually about to receive (candidate_block.is_none()) rather than from why routing produced no candidates — tools.retain(|t| !requires_routed_guidance_tool(&t.name)). This subsumes stage2_tools's fail-open exclusion (same condition holds there) without duplicating logic, and closes the routing_disabled gap in the same stroke.

Added routing_disabled_still_excludes_resolve_query_when_its_guidance_is_unsent, extending RecordingEngine to also capture each generate() call's offered tool names. Verified the test actually catches the regression: temporarily neutralized the retain() call, confirmed the new test fails with resolve_query present in the offered tools, then restored the fix.

cargo test -p nodespace-agent --lib: 387/387. cargo clippy -p nodespace-agent --lib --tests: clean. Full pre-push gate (test:all → cargo build → nodespace-app Tauri-seam tests including the real-LLM ai_chat_send_to_idle_test → test:e2e) passed end-to-end on push.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1855 — Exclude resolve_query from the fail-open tool surface (closes #1840)

Review Type: Re-Review (follow-up to the Critical finding in the initial review, commit 4d221b6a)

Previous Review Summary

  • 1 previous Critical recommendation: session.routing_disabled reproduces resolve_query's guidance and required context are gated behind Graph Editing's routing score; fail-open delivers the tool without either #1840's defect through a second door — stage2_tools (line 605, now agent_loop.rs) is unaffected by routing_disabled, so a candidate that clears its score gate can legitimately put resolve_query into tools, while candidate_block is unconditionally forced to None on that path. The model then receives resolve_query with a required node_type parameter whose description points at a RELEVANT ENTITY TYPES block that was never sent.
  • Addressed: Yes
  • New issues found: 0 blocking, 1 non-blocking edge case noted below (pre-existing, not introduced by this commit, out of scope for this PR)

What changed since 9937ca92 (single commit, single file)

git diff --name-only 9937ca92..HEAD → packages/agent/src/local_agent/agent_loop.rs only (88 insertions, 2 deletions). No other file touched.

  • tools becomes mut (line 605).
  • After candidate_block is computed (both the routing_disabled branch and the render_candidates_for_prompt branch), a new step re-derives the exclusion from what will actually reach the model:
    if candidate_block.is_none() {
        tools.retain(|t| !requires_routed_guidance_tool(&t.name));
    }
  • RecordingEngine (test harness) gained a tool_names_handle() that captures the offered tool names on every generate() call, in order.
  • New test: routing_disabled_still_excludes_resolve_query_when_its_guidance_is_unsent.

Verification of the fix

Placement is correct. tools is declared at line 605; the retain() runs at line 641, immediately after both branches that set candidate_block (615–629) and before every downstream consumer: prompt_assembler.assemble(&template_ctx, tools.clone()) (661), the prompt_assembly tracing span (686), the tracing::info! tool-name log (700), and the actual generate() request that carries tools: Some(tools.clone()) (844). There is no consumer of tools between its declaration and the retain() call, so no in-flight snapshot of the pre-filtered set escapes anywhere. (A later, unrelated branch at line 1391 sets tools: None outright for the final forced-text inference — not affected by or relevant to this change.)

Condition is the right one. candidate_block.is_none() is true in exactly the two cases that matter: (a) routing_disabled is true (forced None regardless of candidates), and (b) routing_disabled is false but render_candidates_for_prompt returned None because no candidate cleared the score gate — which is the same condition stage2_tools's own fail_open_surface already reacts to. Re-deriving from the actually-computed candidate_block rather than re-threading routing_disabled/gate logic a second time is the correct fix shape: it ties the tool-set invariant to the one value that determines what's actually in the prompt, rather than to the reasons that value could be None.

No conflict with stage2_tools's existing exclusion. fail_open_surface (routing.rs:388–394) and the new retain() apply the identical predicate (requires_routed_guidance_tool), just triggered by different signals — permitted.is_empty()/scoped.is_empty() inside stage2_tools, versus candidate_block.is_none() at the call site. When both fire together (the ordinary fail-open path with routing enabled), the second retain() is a no-op over an already-filtered set — idempotent, not a correctness or ordering hazard. When only the new condition fires (routing_disabled + gate cleared), it's the one doing the actual work. No path exists where the two disagree in a way that reopens the gap.

Edge case checked and ruled out as in-scope: render_candidates_for_prompt returns Some(...) whenever at least one candidate clears the score gate, but the per-candidate RELEVANT ENTITY TYPES: sub-block is written only if render_schema_metadata returns Some (routing.rs:295, 304–312), which itself returns None for an empty schema_metadata array (the fixture default at routing.rs:410 is exactly json!([])). So a candidate that whitelists resolve_query, clears the gate, and has empty schema_metadata produces candidate_block = Some(header-text-with-no-entity-types-section) — is_none() is false, so resolve_query is NOT retained-out, yet the model still receives no RELEVANT ENTITY TYPES content. This is a real, currently-reachable gap, but: (1) it is not introduced by this commit — it existed identically before 4d221b6a and before the original PR, since candidate_block's "Some-but-empty-metadata" shape predates all of this work; (2) it is not what the Critical finding described (that finding was specifically about routing_disabled forcing None while tools diverged — a coarser, binary condition); (3) it sits one level more precise than what this PR (or #1840) scoped itself around — closing it would mean checking per-candidate metadata presence, not just block presence. Flagging for a follow-up issue, not blocking this PR.

Test quality

routing_disabled_still_excludes_resolve_query_when_its_guidance_is_unsent correctly exercises the exact scenario from the Critical finding: a Graph Editing candidate at score 0.9 (comfortably clears the gate) whitelisting ["search_nodes", "resolve_query"], with session.routing_disabled = true. routed_engine fabricates a two-round mock (Stage 1 routing call at index [0], Stage 2 act call at index [1]); the assertion reads tool_calls.lock().unwrap()[1] — correctly targeting the Stage 2 call where the offered-tools regression would appear, not the Stage 1 routing call. The assertion checks actual tool names via the new tool_names_handle(), not prompt text — a stronger and more direct signal than string-matching the rendered system prompt. The PR's follow-up comment states the author manually neutralized the retain() to confirm this test fails without the fix, then restored it — the right validation step for a regression test, and consistent with what I'd expect to see for a test guarding a Critical-severity finding.

Build/Test verification (re-run independently, this session)

  • cargo build -p nodespace-agent: clean.
  • cargo test -p nodespace-agent --lib routing_disabled_still_excludes_resolve_query: 1 passed (isolated run).
  • cargo test -p nodespace-agent --lib: 387 passed, 0 failed, 0 ignored — matches the implementer's claim exactly.
  • cargo clippy -p nodespace-agent --lib --tests: clean after cargo clean -p nodespace-agent + fresh rebuild (ruled out a stale-cache false negative) — no warnings.

New issues introduced by this follow-up commit

None blocking. The .retain() mutation is scoped correctly (verified above, no consumer ordering hazard). No new dependencies, no new files, no scope creep — the diff is exactly as large as the Critical finding required.

Nit: The doc comment on requires_routed_guidance_tool (tools.rs:1143–1146) says the full surface is filtered "on the fail-open path" — now slightly incomplete phrasing given it's invoked from a second, non-fail-open-labeled site (routing_disabled). Not misleading enough to act on, just noting for whoever next reads that comment in isolation.

Recommendation: APPROVE

The follow-up commit closes the exact gap the Critical finding identified, with correct placement relative to all downstream consumers of tools, a condition (candidate_block.is_none()) that is provably equivalent to "no RELEVANT ENTITY TYPES content will reach the prompt" for every case reachable through the two branches that set it (modulo the pre-existing empty-schema-metadata edge case, which is out of scope and not a regression), no conflict with the pre-existing stage2_tools exclusion, and a regression test that targets the right call, asserts on the right signal, and was verified to fail without the fix. Build, full lib test suite (387/387, matching the claimed count), and clippy are all clean under a fresh rebuild.

I'll file a short tracking issue for the empty-schema_metadata-but-Some-block edge case separately — it's real but distinct in scope from both #1840 and this PR, consistent with this codebase's practice of splitting closely related defects into separate issues rather than scope-creeping an already-approved fix.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review recommendation: APPROVE. Follow-up commit 4d221b6 correctly closes the routing_disabled gap identified as Critical in the initial review — verified placement, condition equivalence, no conflict with stage2_tools's existing exclusion, and the new regression test. Build clean, cargo test -p nodespace-agent --lib: 387/387 passed, clippy clean on a fresh rebuild. Full report posted as a PR comment (GitHub blocks --approve from the PR author's own account, so recording the recommendation here explicitly).

The routing_disabled fix (4d221b6) used candidate_block.is_none() as
the "no guidance was sent" signal. That's coarser than reality:
render_candidates_for_prompt returns Some(...) from its header text
alone once ANY eligible candidate exists, even if the specific
candidate whitelisting resolve_query has empty schema_metadata and so
never renders its own RELEVANT ENTITY TYPES sub-block. A Graph Editing
candidate with no typed entities (schema_metadata: []) would have
sailed through the routing-enabled, gate-cleared path with
resolve_query offered and no entity-types block for it -- the
identical defect through a third door, not caught by either previous
fix or their tests (both fixtures used non-empty schema_metadata or
routing_disabled, never the "block header present but this candidate's
own sub-block empty" combination).

Add routing::tools_with_available_guidance(candidates, render_disabled)
as the single precise source of truth: a tool counts as having
available guidance only if some eligible candidate both whitelists it
AND has a schema_metadata that actually renders a non-empty entity-
types block, with render_disabled short-circuiting to empty (mirrors
session.routing_disabled forcing candidate_block to None regardless of
what would otherwise render). agent_loop.rs now filters tools against
this instead of the coarser candidate_block.is_none() check.

Tests: 3 new unit tests directly on tools_with_available_guidance
(empty-metadata exclusion, real-metadata inclusion, render_disabled
override, below-bar exclusion) in routing.rs; 2 new agent_loop.rs
integration tests -- the true happy path (real schema_metadata,
routing enabled, resolve_query correctly offered) and the specific
edge case (empty schema_metadata, routing enabled, block header
present but resolve_query still excluded), the latter asserting the
premise (header present, sub-block absent) so the test can't pass for
the wrong reason.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

One more precision fix, pushed as `d5396a28`, before merge.

While double-checking the `routing_disabled` fix (`4d221b6a`), I found it used `candidate_block.is_none()` as the "no guidance was sent" signal — coarser than reality. `render_candidates_for_prompt` returns `Some(...)` from its header text alone once any eligible candidate exists, even if the specific candidate whitelisting `resolve_query` has empty `schema_metadata` and never renders its own `RELEVANT ENTITY TYPES` sub-block. A Graph Editing candidate with no typed entities would sail through the routing-enabled, gate-cleared path with `resolve_query` offered and no entity-types block for it — the same defect through a third door.

Added `routing::tools_with_available_guidance(candidates, render_disabled)` as the precise source of truth: a tool counts as having available guidance only if some eligible candidate both whitelists it AND actually renders a non-empty entity-types block. `agent_loop.rs` now filters against this instead of the coarser `candidate_block.is_none()` check.

7 new tests: 4 directly on `tools_with_available_guidance` (empty-metadata exclusion, real-metadata inclusion, `render_disabled` override, below-bar exclusion — one caught a real bug in my first draft of the below-bar test itself, since `resolve_query` alone is a read tool with a lower bar than I'd assumed) plus 2 `agent_loop.rs` integration tests: the genuine happy path (real `schema_metadata`, routing enabled, `resolve_query` correctly offered) and the specific edge case (empty `schema_metadata`, routing enabled, block header present but `resolve_query` still excluded — asserts the premise so it can't pass for the wrong reason).

`cargo test -p nodespace-agent --lib`: 393/393. `cargo clippy`: clean. Full pre-push gate passed end-to-end on push, including both previously-flaky tests (`architecture-benchmarks.test.ts`, `ai_chat_send_to_idle_test`) — those failures across earlier push attempts were machine contention from other concurrent sessions' daemons/evals, confirmed by isolated re-runs passing cleanly each time.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1855 — Exclude resolve_query from the fail-open tool surface (closes #1840)

Review Type: Re-Review (second follow-up, commit d5396a28)

Previous Review Summary

  • Round 1 (against 9937ca92): 1 Critical — session.routing_disabled reopened the same defect through a second door (tools unaffected by routing_disabled, candidate_block forced to None independently). REQUEST CHANGES.
  • Round 2 (against 4d221b6a): Critical addressed via tools.retain(|t| !requires_routed_guidance_tool(&t.name)) gated on candidate_block.is_none(). APPROVE, with one non-blocking edge case flagged: candidate_block.is_none() is a coarser signal than "this tool's guidance rendered" — render_candidates_for_prompt returns Some from its header text alone once any candidate clears the gate, even if the specific candidate whitelisting resolve_query has empty schema_metadata and renders no entity-types sub-block. Noted as pre-existing, not introduced by 4d221b6a, and out of scope for that PR — flagged for a follow-up issue.
  • This commit (d5396a28) proactively fixes that exact edge case before it needed a separate issue.

What changed (4d221b6a..d5396a28)

git diff --name-only confirms exactly three files: routing.rs, agent_loop.rs, tools.rs. No scope creep.

  • routing.rs: new pub fn tools_with_available_guidance(candidates: &[SkillCandidate], render_disabled: bool) -> HashSet<&str>. For each candidate, filters on clears_score_gate(c) (the same predicate stage2_tools and render_candidates_for_prompt already use — not reimplemented) AND render_schema_metadata(&c.schema_metadata).is_some() (the exact private helper that decides whether a candidate's own entity-types sub-block renders, not the aggregate function). render_disabled: true short-circuits to an empty set before any candidate is examined. 4 new unit tests.
  • agent_loop.rs: the tools.retain(...) call now filters against tools_with_available_guidance(&routed.candidates, session.routing_disabled) instead of candidate_block.is_none(). candidate_block is no longer read anywhere for filtering — verified by grep, its only remaining use is the stage2_candidates_injected = candidate_block.is_some() tracing field, which is pure telemetry. 2 new integration tests.
  • tools.rs: doc-comment-only update on requires_routed_guidance_tool, correctly resolving the Nit from round 2 (the old comment said "on the fail-open path," which undersold the routing_disabled case added in 4d221b6a; the new comment names all three unavailability cases and points to tools_with_available_guidance as the precise check).

Verification

tools_with_available_guidance is correctly built.

  • clears_score_gate — reused directly from the module, not reimplemented; cannot diverge from what stage2_tools/render_candidates_for_prompt use since it's the same function.
  • Per-candidate rendering check — calls render_schema_metadata(&c.schema_metadata), the actual private helper backing each candidate's own entity-types sub-block, not render_candidates_for_prompt's aggregate Option<String>. This is precisely the fix the round-2 edge case called for.
  • render_disabled — returns HashSet::new() before touching candidates. Correct precedence: routing-probe-suppressed models get nothing regardless of candidate quality.
  • Visibility/placement — pub fn in routing.rs, called from agent_loop.rs via routing::tools_with_available_guidance(...). Consistent with the existing pub fn stage2_tools / pub fn render_candidates_for_prompt siblings in the same module.

Call site in agent_loop.rs is correctly placed and the candidate_block split is clean.

  • Computed once, right after candidate_block is computed (both its routing_disabled branch and its render_candidates_for_prompt branch have already run), before every downstream consumer of tools: prompt_assembler.assemble(...) (line ~665), the tracing span/log (~686–721), and the generate() call carrying tools: Some(tools.clone()) (~848). No consumer reads tools between declaration and retain().
  • candidate_block.is_none() no longer appears anywhere as a filtering condition (grepped agent_loop.rs for is_none(): only two unrelated session-lookup assertions remain). candidate_block now exclusively feeds system_content (prompt injection) and the stage2_candidates_injected trace field — a clean separation between "what renders in the prompt" and "what tools are offered," which is the right shape: they're related but no longer coupled through an imprecise proxy.
  • The .retain() predicate — !requires_routed_guidance_tool(&t.name) || available_guidance.contains(t.name.as_str()) — correctly keeps tools that don't need routed guidance at all, plus tools whose guidance actually rendered. No ordering hazard found.
  • stage2_tools's own internal fail_open_surface exclusion (routing.rs:426) still uses the coarser requires_routed_guidance_tool directly — correctly so, since that branch runs when there are no candidates at all, where per-candidate precision is moot. The agent_loop.rs retain is now the single precise backstop regardless of which upstream path produced tools.

Test quality

All 6 new tests were run individually and pass.

  • tools_with_available_guidance_requires_a_rendered_entity_types_block — candidate clears the gate (0.9), whitelists resolve_query, empty schema_metadata (the fixture default) → asserts the resulting set is empty. This is the exact scenario the round-2 edge case described.
  • tools_with_available_guidance_includes_a_tool_whose_candidate_renders_real_entity_types — same candidate with real schema_metadata → asserts resolve_query is present. True-positive coverage for the new function itself.
  • tools_with_available_guidance_is_empty_when_rendering_is_disabled — real schema_metadata but render_disabled: true → empty set, confirming the short-circuit takes precedence over otherwise-valid guidance.
  • tools_with_available_guidance_excludes_a_candidate_below_its_score_bar — score 0.01 with real schema_metadata; asserts !clears_score_gate(...) as a premise check before asserting the empty result, so the test can't pass for the wrong reason. Commit message notes this test caught a real bug in the implementer's first draft (using a score between the read/mutating bars rather than below both) — a good sign the test is actually exercising the gate, not just asserting a hardcoded expectation.
  • routing_enabled_offers_resolve_query_when_its_entity_types_render (agent_loop.rs) — the true-positive integration path: routing enabled, real schema_metadata, asserts resolve_query is present in the Stage-2 generate() call's actual offered tool names (via RecordingEngine's tool_names_handle(), not prompt-text matching). This is the "did tightening the filter break the happy path" check the task asked for, and it's present and passing.
  • a_candidate_with_no_schema_metadata_still_excludes_resolve_query_though_the_block_header_renders (agent_loop.rs) — the exact round-2 edge case end-to-end: empty schema_metadata, routing enabled, gate cleared. Asserts the premise first (stage2_prompt contains the block header text but not "RELEVANT ENTITY TYPES") before asserting resolve_query is excluded from the actual offered tools — this premise assertion is exactly what stops the test from silently passing if the fixture stopped reproducing the header-without-entity-types shape.

None of the 6 are tautological; all assert on real return values (tool-name-set membership, actual generate()-call tool lists) rather than internal state or mocked shortcuts. skill_candidate()'s default schema_metadata: json!([]) was confirmed as genuine pre-existing test infrastructure (not new scaffolding built to force a pass).

Build/Test verification (re-run independently, this session)

  • cargo build -p nodespace-agent: clean.
  • cargo test -p nodespace-agent --lib tools_with_available_guidance: 4 passed (isolated).
  • cargo test -p nodespace-agent --lib routing_enabled_offers_resolve_query_when_its_entity_types_render: 1 passed (isolated).
  • cargo test -p nodespace-agent --lib a_candidate_with_no_schema_metadata_still_excludes_resolve_query_though_the_block_header_renders: 1 passed (isolated).
  • cargo test -p nodespace-agent --lib: 393 passed, 0 failed, 0 ignored — matches the implementer's claimed count exactly.
  • cargo clippy -p nodespace-agent --lib --tests: clean, including a forced rebuild (touch routing.rs) to rule out a cache-masked warning — no warnings either run.

Sanity check: is the three-commit escalation a code smell?

Judgment call, considered honestly rather than rubber-stamped: this reads as reasonable incremental tightening of a genuinely subtle invariant, not a symptom of an under-designed mechanism, for three reasons.

  1. Each commit closed a different, non-overlapping gap in the same invariant ("a tool requiring routed guidance must not be offered unless its guidance actually reaches the prompt"), and each gap was strictly narrower than the last: fail-open branches only → +routing_disabled → +per-candidate rendering precision. This is convergence, not oscillation — nothing already-fixed was ever reopened or reworked.
  2. The invariant itself is inherently a three-variable join (does a tool need guidance × did routing produce a candidate for it × did that specific candidate's metadata actually render), and the codebase had three independent producers of the "no guidance" condition (stage2_tools's fail-open branches, session.routing_disabled, and per-candidate schema_metadata shape). Getting a three-way join exactly right in one pass, especially when two of the three signals live in different functions in different files, is a legitimately hard thing to nail immediately — catching it via review-then-tighten across three small, each independently-tested commits is a defensible way to arrive at correctness incrementally versus shipping a large speculative rewrite up front that guesses at all three cases before any of them is proven necessary.
  3. The fix converges toward simplicity, not complexity. The end state is a single function (tools_with_available_guidance) that is the one source of truth for "does this tool have guidance," called from one call site, superseding what used to be an implicit inference from candidate_block. candidate_block is now cleanly single-purpose (prompt content only). That's a net reduction in the number of places one has to reason about this invariant, not an accretion of special cases layered on top of each other — compare to the counterfactual where each fix had bolted on another if branch at the call site instead of consolidating into one precise function.

If a fourth such gap surfaces, that would start to look like a design smell (arguing for encoding "guidance available" directly on SkillCandidate/routing output rather than re-deriving it downstream). At three, with each fix strictly narrowing scope and the final state simpler than the second-to-last, this is normal review-driven convergence on a subtle invariant, not thrashing.

New issues introduced by this commit

None found. The diff is exactly as large as fixing the round-2 edge case requires — no unrelated refactors, no new dependencies, no files touched beyond the three needed.

Nit: tools_with_available_guidance's doc comment and the agent_loop.rs inline comment both restate the "why" at some length (justified, given this is the third pass at explaining a subtle invariant) — no action needed, flagging only because a future fourth pass at this same invariant should consider consolidating the explanation into one place (e.g., only on the function doc comment) rather than continuing to grow both.

Recommendation: APPROVE

This commit does exactly what it says: replaces a coarser "was any block rendered" signal with a precise per-candidate, per-tool check, reusing the exact existing helpers (clears_score_gate, render_schema_metadata) rather than reimplementing them, with no filtering logic left depending on candidate_block as a proxy. The happy-path regression risk inherent in tightening a filter is explicitly covered by routing_enabled_offers_resolve_query_when_its_entity_types_render, and the exact scenario this commit targets is covered end-to-end by a_candidate_with_no_schema_metadata_still_excludes_resolve_query_though_the_block_header_renders, which asserts its own premise so it can't pass for the wrong reason. Build, full lib suite (393/393, matching the claimed count), and clippy are all clean under a forced rebuild. The three-commit history is convergent tightening of a hard three-way invariant, not a design smell.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review recommendation: APPROVE. Commit d5396a2 correctly tightens the routing_disabled fix from candidate_block.is_none() (coarse) to routing::tools_with_available_guidance (precise, per-candidate rendering check) — closing the exact edge case flagged non-blocking in the prior round-2 re-review. Verified: reuses existing clears_score_gate/render_schema_metadata helpers rather than reimplementing; candidate_block no longer used for filtering anywhere (only prompt content + telemetry); retain() placement precedes all downstream consumers of tools; 6 new tests cover both the true-positive happy path and the exact edge case end-to-end, with premise assertions so they can't pass for the wrong reason. Build clean, cargo test -p nodespace-agent --lib: 393/393 passed (matches implementer's claim), clippy clean on a forced rebuild. Full report posted as a PR comment (GitHub blocks --approve from the PR author's own account, so recording the recommendation here explicitly).

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.

resolve_query's guidance and required context are gated behind Graph Editing's routing score; fail-open delivers the tool without either

1 participant