Skip to content

Register a Stage-2-callable route_clarify tool - #2161

Merged
mstomar125 merged 2 commits into
mainfrom
worktree-issue-2149-route-clarify
Aug 19, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
worktree-issue-2149-route-clarify

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Closes #2149

Problem

route_clarify existed only as a Stage-1 routing tool (routing::stage1_tool_definitions) — not registered in the Stage-2 tool registry, so no Stage-2 skill could whitelist it and no Stage-2 turn could call it. The golden corpus (dev-ambiguous-clarify.toml) measured that calling a clarify tool mid-skill is more reliable than answering in prose, but today's only mid-skill ambiguity path is skill_rules::AMBIGUITY_CLARIFY's imperative text, with no structured tool call backing it.

What changed

  1. Registered Tool::RouteClarify in packages/agent/src/local_agent/tools.rs, threaded through the exhaustive Tool enum (name, definition, humanized label, write semantics = Read, no routed-guidance dependency).

  2. Deliberately different argument shape from Stage 1, reusing only the tool name (routing::ROUTE_CLARIFY_TOOL): Stage 1 only ever asks "which capability" (no natural id — a query phrase is the whole candidate), while Stage 2 clarification is almost always "which of these specific records a prior tool result already named". options therefore carries {id, label} pairs rather than bare strings — the exact shape dev-ambiguous-clarify.toml already measured, so this PR made the implementation match the golden rather than the reverse. A new parse_route_clarify_args parses this Stage-2 shape; routing::parse_route_decision (Stage 1's parser) is untouched.

  3. Whitelisted route_clarify on Graph Editing — the only skill carrying AMBIGUITY_CLARIFY (confirmed by grep — no other skill interpolates it) — and retargeted that rule's imperative text, plus the parallel "multiple_matches" clause already inline in graph_editing_guidance(), from prose ("ask one specific clarifying question") to calling the tool. AMBIGUITY_CLARIFY's prose/skill_md_key_phrase fields are unchanged — they serve packages/skill/SKILL.md, a separate external-agent-facing document with no route_clarify tool of its own.

  4. agent_loop.rs intercepts a Stage-2 route_clarify call before it reaches the generic tool executor, the same way the duplicate-write and second-create_schema guards already do — an executor can only return a tool result, it has no way to end a turn or address the user. The interception builds a normal tool result (so the assistant tool-calls message already pushed for that iteration stays well-formed even if the model called more than one tool), and once every call in that iteration is recorded, ends the turn immediately: surfaces the question via the existing format_clarification/ClarifyPrompt path (options flattened to labels — matching Stage 1's existing frontend-facing Vec<String> shape, so no downstream/UI contract changed), runs no further inference round.

Why not literally reuse Stage 1's handler

The issue permits reuse "if structurally sound." Evaluated and decided against for the argument shape specifically: Stage 1's flat Vec<String> has no id, and Stage-2 clarification is almost always about disambiguating specific already-resolved records — dropping the id would lose exactly the thing that lets the model (and a future UI) act precisely on whichever candidate the user picks. The tool name and the turn-ending handling are shared; only the argument shape and its parser are new.

Testing

  • 12 new unit tests in tools.rs: Tool::RouteClarify registration/naming, schema shape (required: [question, options], options.items.required: [id, label]), parse_route_clarify_args success + malformed cases (blank question, missing question, option missing id/label, unknown top-level field), direct-dispatch exec_route_clarify (success + invalid-arguments error).
  • 2 new integration-style tests in agent_loop.rs using the existing MockEngine/RoutingToolExecutor test harness: a whitelisted Stage-2 call to route_clarify ends the turn immediately (no third inference round consumed, clarify populated with flattened labels, conversation stays well-formed) and a malformed call (blank question) falls through to the normal executor path instead of being silently treated as a decision.
  • Full cargo test -p nodespace-agent --lib: 518 passed (up from 507), 0 failed.
  • cargo test -p nodespace-agent --test prompt_assembly_snapshot: 5/5 pass, unchanged — its stage2_tool_surface_matches_golden fixture only exercises the seeded Node Creation / Schema Creation skills (not Graph Editing), so no golden update was needed.
  • cargo clippy -p nodespace-agent --all-targets: clean.
  • cargo fmt --check: clean for everything in this diff (pre-existing, unrelated formatting drift on main in routing.rs/elsewhere confirmed via a clean checkout — not touched).
  • Full pre-push gate (bun run test:all + cargo build --bin nodespaced + bun run test:e2e + cargo test -p nodespace-app) passed locally before push.

🤖 Generated with Claude Code

route_clarify previously existed only as a Stage-1 routing tool
(routing::stage1_tool_definitions) — not in the Stage-2 tool registry, so no
Stage-2 skill could whitelist it and no Stage-2 turn could call it. The
corpus (dev-ambiguous-clarify.toml) measured that calling a clarify tool
mid-skill is more reliable than answering in prose, but today's only
mid-skill ambiguity path is skill_rules::AMBIGUITY_CLARIFY's imperative
text, with no structured tool call backing it.

Adds Tool::RouteClarify to the local_agent::tools registry, threaded
through the exhaustive Tool enum matches. Reuses Stage 1's tool NAME
(routing::ROUTE_CLARIFY_TOOL) but deliberately not its argument shape:
Stage 1 only ever asks "which capability" (no natural id — a query phrase
is the whole candidate), while Stage 2 clarification is almost always
"which of these specific records a prior tool result already named", so
options carries {id, label} pairs rather than bare strings — the shape
dev-ambiguous-clarify.toml already measured. A new parse_route_clarify_args
parses this Stage-2-specific shape; routing::parse_route_decision (Stage
1's parser) is untouched.

Whitelists route_clarify on Graph Editing, the only skill carrying
AMBIGUITY_CLARIFY, and retargets that rule's imperative text (plus the
parallel "multiple_matches" clause already inline in
graph_editing_guidance()) from prose ("ask one specific clarifying
question") to calling the tool.

agent_loop.rs intercepts a route_clarify call before it reaches the generic
tool executor, the same way the duplicate-write and second-create_schema
guards do — an executor can only return a tool result, it has no way to end
a turn or address the user, so the interception builds the tool result
(keeping the assistant tool-calls message well-formed) and, once every call
in that iteration is recorded, ends the turn immediately: surfaces the
question via the existing format_clarification/ClarifyPrompt path
(flattened to labels, matching Stage 1's existing frontend-facing shape),
runs no further inference round.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… fix duplicate-key chip collision

A route_clarify call could structurally arrive in the same iteration as a
real write (e.g. update_node) — nothing enforced route_clarify's own
description ("do not call another tool in the same turn"), only a soft
prompt instruction. If it happened, the write executed for real while only
the clarifying question reached the user, with no acknowledgment of the
side effect.

Pre-scan the iteration's tool calls (mirroring the same repair-then-parse
path the per-call loop uses, so the scan can't disagree with what that loop
decides for the same call) before executing anything. A well-formed
route_clarify anywhere in the batch now supersedes every other call in it:
each is reported as skipped ("superseded_by_clarification") rather than
executed, and the model's own tool-calls record still shows what it asked
for.

Also fixes a real frontend bug this PR exposed: chat-message.svelte keyed
clarify option chips by the label string itself. Stage-2 clarify's whole
point is disambiguating records that can share a display label (the id
that would prevent a collision is deliberately not sent to the frontend,
matching Stage 1's existing label-only contract) — two same-titled
candidates would collide on Svelte's keyed-each. Keyed by index instead.

Minor: ClarifyOption now denies unknown fields, matching its outer struct;
renamed a test that overclaimed what it asserts; added a direct assertion
that the "no further inference round" test proves what it claims to.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mstomar125
mstomar125 merged commit 1cd0f78 into main Aug 19, 2026
@mstomar125
mstomar125 deleted the worktree-issue-2149-route-clarify branch August 19, 2026 09:36
mstomar125 added a commit that referenced this pull request Aug 19, 2026
…ures (#2168)

* Trim #2161/#2164 tool-schema bloat; surface turn-level inference failures

Measured the actual assembled prompt for the failing ai-chat scenario via
NODESPACE_PROMPT_DUMP + the real tokenizer: on this machine the turn's
full-tool-surface prompt is 6932 tokens (713 resident prose + 6202 across
all 13 fail-open tools + 17 trailer), with create_schema (1341) and
update_schema (1034) — the two tools #2164 touched — together accounting
for over a third of the tool-schema budget. declare_write_tool_fields
contributes zero extra tokens for this scenario (no skill candidate clears
the score gate, so field declarations never fire).

Trims applied within the tool-schema/skill-guidance channels (ADR-064):
- create_schema's per-field name/friendlyName/description descriptions
  shortened to match update_schema's already-tighter phrasing instead of
  carrying two different-length explanations of the same argument shape.
- update_schema's rename_fields description tightened (identical facts,
  half the words) — it was restating, almost verbatim, what the
  RENAME_VS_RELABEL skill rule also says.
- RENAME_VS_RELABEL (skill_rules.rs) cut back to the procedural judgment
  call (which shape the user's intent maps to); the mechanical "from"/"to"/
  "friendlyName" explanation now lives only in the tool schema, its correct
  channel. Regenerated packages/skill/SKILL.md from the trimmed rule.
- route_clarify's (#2161) description tightened slightly.
- Fixed a pre-existing `cargo clippy --all-targets -D clippy::unused-async`
  failure in the same file: exec_route_clarify was declared async with no
  .await in its body (from #2161); made it a plain sync fn.

Net: 6932 -> 6810 tokens for the measured scenario (122 saved, confirmed
via the real tokenizer, not estimated). The prompt_assembly_snapshot goldens
were regenerated to pin the new tool-schema/skill-guidance text.

Also fixes the silent-failure half of this issue: local_agent_service.rs's
run_ai_chat_turn logged a WARN and reset the node straight to "idle" on any
inference failure (including ContextOverflow) with no new assistant message
and no way for a polling caller or the frontend to distinguish a failed turn
from one still in flight. It now appends an assistant-role message naming
the failure and reaching idle through the same path a normal reply uses,
matching ADR-062's "refuse loudly, don't clamp silently" principle applied
at the per-turn level. Added
failed_inference_turn_surfaces_a_visible_error_not_silent_idle as a
regression guard.

Closes #2167.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Address review: restore route_clarify disambiguation clause; document history tradeoff

Adversarial review of PR #2168 found no blockers. Two non-blocking items
addressed here:

- route_clarify's description had dropped "and nothing already said picks
  one" when trimmed — restored (a few tokens) since without it the text
  reads as license to clarify on any multi-match search result even when
  other conversational context already disambiguates.
- Documented, at the append_assistant_message call for a failed turn, why
  feeding the synthesized failure text back into the model's own future
  history as an ordinary assistant message is accepted rather than
  filtered/tagged: it can't trip the duplicate-write guard (empty
  completed_writes), unbounded growth is bounded by the existing
  maybe_summarize_history mechanism, and a model that sees its own stated
  failure has exactly the context needed to avoid blindly repeating it.

Also: the review noted this PR's first commit message states a net
6932 -> 6810 token result against the issue's reported 5120-token window
without reconciling that 6810 > 5120 — worth stating plainly here since
that commit's own text doesn't: the 5120 figure is this issue's reported
window on ITS reporting machine. On this machine, ADR-062's
`fit_n_ctx_to_budget` (packages/nlp-engine/src/chat/mod.rs) grants the
full configured 32768-token window given its total RAM, so the trim's
6810-token result already fits comfortably here regardless of the
5120-vs-6810 gap; the previously-failing test now passes for real (the
model generates and returns "OK", not a fallback/error path), independently
verified via NODESPACE_PROMPT_DUMP + the real tokenizer, not assumed. The
per-turn silent-failure fix in the same PR is what makes any machine whose
window IS smaller than its own prompt fail visibly instead of silently,
regardless of the exact number on that machine.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
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.

Wire a Stage-2-reachable route_clarify tool, so ambiguity resolution isn't prose-only

1 participant