Repository navigation
Implement ADR-038 Stage-1 and Stage-2 gates; replace the rejected single-turn pull - #1826
Conversation
… Stage-2 blast-radius bar Implements the routing flow ADR-038 decided, replacing the single-turn pull that ADR explicitly rejects under Alternatives Considered. - Stage 1 emits a structural query|clarify choice as one of two typed tools (route_query / route_clarify), not a self-reported confidence number - Retrieval runs as a deterministic system step via AgentToolExecutor:: retrieve_skills, so K is bounded and the trust filter applies - Stage 2 combines the retrieval score with the model's judgment; the score bar is derived from the matched skill's tool_whitelist, so mutating skills carry a higher bar than read-only ones - Candidates are delivered in the Stage-2 prompt, not as a tool result (ADR-064 rule 4) - search_skills is withheld from the model-facing surface while staying in Tool::ALL for the external MCP surface Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
…rose and prompt Stage-1 costs a full model generation, so it now runs only when retrieval is actually wired up (routing_available). Without the gate every turn paid for a routing call whose query nothing consumed — including conversational turns that need no capability at all. Also removes search_skills from guidance prose and skill instructions: the tool is no longer offered to the model, so instructing it to call one is the channel contradiction ADR-064 warns about. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
… total The usage test caught real under-reporting: Stage-1's tokens were recorded but never added to the turn's total, hiding the cost of the extra turn from every consumer of that figure. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Skill routing is no longer observable as a search_skills call in the trace: Stage 1 emits route_query/route_clarify and the system performs retrieval itself. routing.ts asserted the retrieval call directly and would have failed every skill case; it now observes routing through its effect. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Both arms run the same production loop against the same engine and request, differing only in whether routing_available() reports true, so the delta is the routing overhead alone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
These tests script multi-round tool dispatch, which is still valuable, but they asserted a call sequence the production loop can no longer produce. Renamed and repointed at tools the model is actually offered. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Tuning the bar values is expected; inverting their ordering is not, so the check now fails the build rather than a test run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
The first run showed routing FASTER than baseline, which is counterintuitive enough that reporting it unattributed would risk recording a false conclusion. Rounds and tokens make the wall-clock delta explainable. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
The clarification path returned early to Idle without ever announcing Thinking, so a UI would show idle while Stage 1 was generating. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Derivation was only tested against stub candidates; this checks it agrees with what the 8 seeds actually declare, and fails if a whitelist gains or loses a write tool without that being an intentional bar change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
A inside the loop meant one entry missing type_id dropped every remaining type from the injected block, instead of skipping that entry. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Measurement caught a real defect the aggregate latency number hid. The routed
arm looked 71% FASTER — because it made zero tool calls. It was not doing the
work.
Two causes, isolated with a three-arm diagnostic (baseline / scoped-tools-only
/ scoped+instructions):
1. The candidate block opened with "Pick the ONE that fits and carry out its
instructions", framing the turn as a selection exercise. The model answered
in kind, narrating which tool it would use instead of calling it. Reworded
to direct action and to forbid restating the reference text.
2. Pre-existing gap this surfaced: looks_like_narrated_tool_call only detected
function-call syntax, tool_name(...). The model emits the JSON form,
[{"name":"create_node",...}], as text — so the guard missed it and the
turn silently did nothing. Now detects both.
The benchmark's tool-round instrumentation is what made this visible; the
wall-clock number alone would have been recorded as a win.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Isolates which part of two-stage routing suppresses tool-calling: baseline (no routing) -> create_node OK stage-1 only, no candidates -> create_node OK routed + full instructions -> none routed + names only -> none Stage 1 is harmless. Any candidate block injected into the Stage-2 prompt suppresses the tool call on mistral:7b, regardless of payload size or how procedural it is. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
A result on an incidental endpoint model does not describe what NodeSpace ships. Prefers gemma when served, with NODESPACE_BENCH_MODEL to override for cross-model comparison. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
A Gemma run reported a confident 299ms vs 612ms table in which EVERY turn had failed with 'model produced empty response'. Zero tokens in, zero out — the 11-second run never reached the model, and error-return time was being averaged as turn time. Errors are now counted, excluded from the timings, and cause the benchmark to panic with the ok/failed split rather than print a number. A benchmark that silently reports error-path timings is worse than no benchmark. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
The local OpenAI-compatible endpoint served gemma with a 4096 context window against the engine's N_CTX_MINIMUM of 16384, so every turn returned empty, and later degraded to returning empty on its native API too. This forces the in-process llama.cpp path so a measurement does not depend on that server. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
The harness resolved a backend by asking a local OpenAI-compatible endpoint first and taking whatever it served. That is not how NodeSpace runs its native agent (ADR-056: Gemma 4 E4B in-process via llama.cpp), and it produced two bad results on this issue: a tool-call suppression finding on mistral, a model we do not ship, and a full table of error timings when the server served a 4096-token context against the engine's N_CTX_MINIMUM of 16384. The HTTP path, its imports, and the model-override env var are removed. The locked model or nothing. Re-measured on the in-process-only path: +394ms (+12.0%), tool rounds 1.00 in both arms — matching the +419ms/+13.0% measured before, so the number never depended on the removed path. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
|
Review Type: Initial Review SummaryThis is a well-executed implementation of ADR-038's routing design. The structure is right: the discriminated Stage-1 output rides the tool-schema channel rather than a parser, retrieval is genuinely a system step behind a trait method the model cannot reach, and blast radius is derived from What raises this above "correct implementation" is that the measurement work found two real defects (Stage-1 usage dropped from the turn total; Findings below are two Important and three Suggestions. None of them is a merge blocker; the two Important ones are behavioral gaps worth a follow-up rather than a rework. Requirements Check
Also verified: Code Review Findings🟡 Important — Stage 1 routes on the bare user message, ignoring conversation history📁 let messages = vec![
ChatMessage::text(Role::System, STAGE1_SYSTEM_PROMPT.to_string()),
ChatMessage::text(Role::User, user_message.to_string()),
];
This is the exact failure mode already characterized and fixed one layer over, for schema retrieval: Stage-1 routing now has the same shape and the same silent-degradation profile: a pronoun-only follow-up gives the model nothing to describe, so it either emits a weak query that retrieves the wrong skill or calls It is also self-reinforcing with the clarification contract: a clarification is answered by a short user reply ("the first one"), which is precisely the message with the least standalone routing signal, and Stage 1 sees only that reply on the turn that has to succeed without clarifying again. Recommendation: blend the preceding user/assistant turns into the Stage-1 user message, the same way Principle: consistency of context construction. Two retrieval steps in the same turn deriving from different amounts of conversational context will disagree, and the disagreement surfaces as unattributable routing quality rather than as a bug. 🟡 Important — the clarification contract is scoped by the last clarification, so it never re-arms within a conversation📁 let last_clarification = session.messages.iter().rposition(|m| {
matches!(m.role, Role::Assistant) && m.content.starts_with(CLARIFICATION_OPENER)
});
match last_clarification {
Some(idx) => session.messages[idx + 1..]
.iter()
.any(|m| matches!(m.role, Role::User)),
None => false,
}The doc comment above it claims the scope is "messages after the last unclarified user turn, so a clarification early in a long conversation does not permanently disable clarifying for every later request." The code does not do that. It anchors on the last clarification and asks only whether any user message follows it — so once a clarification has been asked and answered, ADR-038 scopes the contract "per intent". A conversation is many intents. The test at Note the failure is graceful — it falls through to retrieval on the raw message, which is the ADR's own degraded path — so this is a quality regression, not a break. But the comment asserts a property the code lacks, which is the more dangerous half: a future reader will trust it. Recommendation: either implement intent scoping (e.g. treat a clarification as consumed once the turn following it completed with a non-clarification answer, so the mechanism re-arms), or — cheaper and honest — narrow the comment to describe the latch that is actually implemented and record why permanently-off-after-one is acceptable. Add a test asserting whichever behavior is chosen, with the conversation extended a few turns past the clarification. Principle: comments must describe the code, not the intent that motivated it. A doc comment stating a property the implementation lacks is worse than no comment. 🟢 Suggestion — an unregistered tool in a whitelist silently downgrades a skill's blast radius📁 pub fn skill_is_mutating(candidate: &SkillCandidate) -> bool {
candidate.tools.iter().any(|t| is_write_tool(t))
}
// is_write_tool: Tool::from_name(tool).is_some_and(Tool::is_write)
For the 8 seeded skills this cannot bite: Note this composes safely with Recommendation: treat an unrecognized whitelist entry as mutating for bar purposes — Principle: fail-safe defaults. Where a classification gates a safety bar, the unknown case belongs on the restrictive side; where it gates availability (as 🟢 Suggestion —
|
malibio
left a comment
There was a problem hiding this comment.
Initial pragmatic code review posted as a PR comment: #1826 (comment)
Recommendation: COMMENT — no blocking defects. All 8 acceptance criteria met with verifiable evidence; implementation matches the five approved design decisions with no divergence.
Two Important findings worth addressing before this becomes the baseline for the diagnostic eval, since both degrade routing quality silently:
- Stage 1 routes on the bare user message, ignoring conversation history — the same silent-degradation failure already fixed one layer over in
schema_retrieval_query. session_already_clarifiedpermanently latches after the first answered clarification; the doc comment claims per-intent scoping the code does not implement.
Three Suggestions: unregistered whitelist tools fail open to the lower blast-radius bar; CLARIFICATION_OPENER prefix protocol lacks a round-trip test; the routing_available() early return is untraced.
Merge is the repo owner's call.
…contract Addresses reviewer recommendations from PR #1826 review. - 🟡 Stage 1 routed on the bare user message, ignoring history. Same silent degradation already fixed one layer over for schema retrieval: a follow-up naming its subject by pronoun ('mark it paid') gives the model nothing to describe, so it emits a weak query or clarifies a request the conversation had already disambiguated. Worst right after a clarification, whose answer is the shortest message on the turn that must not clarify again. Now shares context_ops::build_retrieval_query with schema retrieval so the two cannot drift; the current message is excluded from the blend to avoid double weighting it. - 🟡 session_already_clarified latched permanently: it anchored on the last clarification, so once one was answered the contract never re-armed for the rest of the conversation, and the doc comment claimed per-intent scoping the code did not implement. Intent now ends at an assistant turn that ANSWERED rather than asked, so a resolved turn re-arms the mechanism. - 🟢 An unregistered whitelist tool now counts as mutating. is_write_tool answers false for an unknown name, which put the LOWER bar on a skill of unknown blast radius — the opposite of ADR-038's bias. stage2_tools still fails open in the other direction on purpose: that gates availability, not a safety bar. - 🟢 Round-trip test: format_clarification output must be recognised by session_already_clarified. The contract rides user-visible text, so a rewording would silently stop it enforcing; tests that hand-build the marker from the constant would not have caught it. - 🟢 The unrouted early return now opens a stage1_routing_skipped span. Routing availability is a live per-turn property, so nothing distinguished 'embedding still warming' from 'this executor never routes' — which would misattribute an eval run started before the service warmed. Both amber fixes are mutation-tested: reverting either makes its new test fail. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Review addressed — 5/5, none skippedCommit 🟡 Stage 1 routed on the bare user message📁 The reviewer's framing was right and I'd missed the compounding case: a clarification is answered by a short reply, i.e. the message with the least standalone routing signal, arriving on the turn that must succeed without clarifying again. The current message is excluded from the blend ( 🟡 The clarification contract latched permanently📁 Chose to implement the scoping rather than narrow the comment: an intent now ends at an assistant turn that answered rather than asked, so a resolved turn re-arms the mechanism. A clarification isn't a resolution, so the state still survives the user's reply to it. 🟢 Unregistered whitelist tool → mutating📁 🟢 Round-trip test for the clarification marker📁 🟢 Trace the unrouted path📁 VerificationBoth 🟡 fixes are mutation-tested — reverting either makes its new test fail, so neither test passes vacuously:
370 agent tests (up from 365), 1,067 core, full workspace green. Carried forward, not fixed hereTwo reviewer observations I'm deliberately leaving as notes for #1764 rather than acting on now, since both are about the eval rather than this code:
Re-Review DecisionDecision: RE-REVIEW NEEDED Rationale: The clarification-latch fix is a behavioral change to control flow, not a comment correction — |
|
Review Type: Re-Review (delta — commit Previous Review Summary
Verification of each previous finding🟡-1 Stage 1 routed on the bare user message — ✅ properly addressed📁 let prior = session.messages.split_last().map(|(_, rest)| rest).unwrap_or(&[]);
let prior_turns: Vec<&str> = prior.iter()
.filter(|m| matches!(m.role, Role::User | Role::Assistant))
.map(|m| m.content.as_str())
.collect();
nodespace_core::ops::context_ops::build_retrieval_query(&prior_turns, user_message)I verified each property the fix summary claims rather than taking it: The shared helper is genuinely the same one. The role filter matches. The No panic path. Ordering vs. summarization is fine. Mutation-tested (verified independently, not taken on trust). Replacing the helper call with 🟡-2
|
Sequence (U=user, A=assistant, T=tool) |
Result | Correct? |
|---|---|---|
U — first turn |
false |
✅ can clarify |
U, A:CLARIF — just asked, awaiting reply |
false |
✅ not a second attempt |
U, A:CLARIF, U — clarification answered |
true |
✅ contract holds within the intent |
U, A:CLARIF, U, A:"Done.", U — resolved, then new ambiguous request |
false |
✅ re-arms — this is the fix |
U, A:CLARIF, U, T, A:"Done.", U — same but via a tool-calling turn |
false |
✅ tool results don't close an intent; the assistant answer does |
U, A:CLARIF, U, A:ans, U, A:CLARIF, U — second clarification in a later intent, answered |
true |
✅ each intent gets its own one |
A:CLARIF, U — history rebuilt starting mid-conversation |
true |
✅ conservative: suppresses rather than loops |
U, U — history starts with a user reply, no assistant turn |
false |
✅ nothing was asked |
Why intent_start is the right anchor rather than "last user turn". A clarification is deliberately not a resolution, which is what lets the "already clarified" state survive the user's reply to it (the A:CLARIF, U row) while still clearing once a turn actually completes (the A:"Done.", U row). Those two rows are the whole contract, and they are the two the old code could not separate. The old implementation anchored on the last clarification and asked only whether any user message followed, so every row below the third returned true forever.
Interaction with the suppression path. When suppression fires (agent_loop.rs:1601-1610), the turn falls through to retrieval and completes with a normal assistant answer — which is precisely an intent boundary, so the mechanism re-arms on the next turn. That composes correctly and is the behavior ADR-038 wants.
Residual edge, and it fails safe. If maybe_summarize_history compacts history such that the resolving assistant turn is drained but the clarification survives ([System summary], A:CLARIF, U, U), the function returns true and suppresses a clarification that would have been legitimate. That requires compaction to land on exactly that boundary, and the consequence is the ADR's own documented degraded path (fall through to retrieval on the raw message) rather than the clarification loop the contract exists to prevent. Erring toward suppression is the correct direction here; not worth code.
One theoretical false-positive. A genuine assistant answer that happens to begin with the literal string "I can take that a couple of ways" reads as a clarification. That is inherent to the in-band marker, was already noted in the initial review as 🟢-4's underlying fragility, and the round-trip test below is the agreed mitigation. Not a new defect.
Mutation-tested (verified independently). Collapsing intent_start to 0 — i.e. restoring whole-conversation scope — makes the_clarification_contract_re_arms_on_a_new_intent fail with a resolved turn starts a new intent; clarifying must be possible again. The test genuinely pins the new behavior, and the assertion sequence at 5789-5819 covers both sides (asserts true mid-intent before asserting false after resolution), so it would also catch a fix that over-corrected into never latching.
🟢-3 Unregistered whitelist tool downgraded blast radius — ✅ properly addressed
📁 packages/agent/src/local_agent/routing.rs:204-209
.any(|t| Tool::from_name(t).is_none_or(Tool::is_write))The unknown case now takes the higher bar. stage2_tools still fails open in the other direction (availability, not a safety bar) — the distinction the initial review drew is preserved and now documented at the definition site.
is_none_or is stable, not nightly. Stabilized in Rust 1.82 (Option::is_none_or); the workspace toolchain is 1.94.1 and there is no rust-version MSRV pin in any Cargo.toml. It is the only occurrence in the workspace, but it is a stable-API choice, not an accident. cargo clippy -p nodespace-agent --all-targets is clean.
Test pins it correctly. an_unrecognised_whitelist_tool_is_treated_as_mutating (routing.rs:443-453) asserts both halves — skill_is_mutating is true and !clears_score_gate at 0.2, a score that clears the read bar. Asserting the downstream consequence rather than just the classifier is what makes it a real regression guard.
🟢-4 No round-trip test for CLARIFICATION_OPENER — ✅ properly addressed
📁 packages/agent/src/local_agent/agent_loop.rs:5822-5839
The test composes via the real format_clarification rather than hand-building the marker, which is exactly what the finding asked for.
I mutation-tested this one too, because a round-trip test is easy to write in a way that still passes through a rewording. Prefixing format_clarification's output with "Just checking — " (a plausible tone edit, leaving CLARIFICATION_OPENER itself untouched) makes a_composed_clarification_is_recognised_as_one fail. The pre-existing tests that hand-build the marker from the constant all still passed under that mutation — so this test adds coverage the others genuinely did not have. That is the finding closed properly.
Minor scope note, not worth changing: the test exercises only the with-options branch (format_clarification line 343). The no-options branch (line 336) shares the same prefix construction, so a rewording breaking one breaks both and this test catches it either way.
🟢-5 Unrouted early return untraced — ✅ properly addressed
📁 packages/agent/src/local_agent/agent_loop.rs:1518-1530. The tracer binding was correctly hoisted above the gate (1511) so the skipped path can open stage1_routing_skipped with routing.available=false, plus a tracing::debug!. A trace now distinguishes "embedding still warming" from "this executor never routes" — the misattribution risk for the follow-up diagnostic work.
New Findings
Both are documentation-only. Neither affects behavior; fold into the next commit that touches the file or ignore.
🟢 Nit — the new skill_is_mutating doc paragraph has no separator and reads as one run-on block
📁 packages/agent/src/local_agent/routing.rs:193-194
/// no second field to keep in sync.
/// An unrecognised tool name counts as mutating. `is_write_tool` answers
The /// blank line between the pre-existing paragraph and the appended one is missing, so rustdoc renders them as a single paragraph and the two distinct ideas (derivation, then the unknown-name policy) run together. Every other paragraph break in this doc comment has one. One-line fix.
Principle: consistency of documentation formatting — rustdoc treats /// line adjacency as semantic.
🟢 Nit — the doc now names a function the code no longer calls
📁 packages/agent/src/local_agent/routing.rs:195
The comment explains the fix in terms of is_write_tool ("is_write_tool answers false for a name not in the registry"), but the body no longer calls it — it inlines Tool::from_name(t).is_none_or(Tool::is_write). The sentence is accurate as history but describes a call that isn't there, which is the same class of read-the-comment-trust-the-wrong-thing that finding 🟡-2 was about. Rephrasing to "an unregistered name has no write classification, so it is treated as mutating" describes the code as written.
Principle: comments should describe the code, not the diff that produced it.
(For the record, and not a finding: is_write_tool is still live at skill_pipeline.rs:625 and local_agent_service.rs:1432, 2870, so nothing is dead. Worth noting that seeded_skills_classify_by_blast_radius_as_expected reimplements the old classification via is_write_tool rather than calling skill_is_mutating. The two agree today because all_skill_whitelist_tools_are_registered guarantees every seed name resolves, so this is not a bug — but that test no longer pins the production function. Switching it to skill_is_mutating would be strictly better if the file is touched again.)
Verification performed
| Check | Result |
|---|---|
cargo test -p nodespace-agent --lib |
370 passed, 0 failed — matches the claimed count (365 → 370) |
cargo clippy -p nodespace-agent --all-targets |
Clean |
Mutation: revert intent_start scoping |
the_clarification_contract_re_arms_on_a_new_intent FAILED ✅ |
Mutation: revert stage1_query blending |
stage1_blends_prior_turns_into_its_query FAILED ✅ |
Mutation: reword format_clarification prefix |
a_composed_clarification_is_recognised_as_one FAILED ✅ (my own addition — the other clarification tests survived it) |
session_already_clarified state machine |
8 sequences simulated, all match the doc comment |
| Working tree after mutation testing | Restored clean, git status empty |
| Standards | No #[allow], no #[deprecated], no lint suppression, no .md added, no issue numbers in comments |
Recommendation
APPROVE
All five findings are properly addressed, and the two that mattered were addressed by fixing the behavior rather than by narrowing the claim — which was the harder and better call on 🟡-2, since the honest-comment option was explicitly on the table.
The session_already_clarified rewrite is the change I scrutinised hardest, and I did not find a hole. The anchor choice — an intent ends at an assistant turn that answered, and a clarification pointedly does not count as one — is what separates the two states the old implementation conflated, and it holds across first turns, unanswered clarifications, tool-calling turns, sessions rebuilt mid-conversation, and repeated clarifications in later intents. The one residual edge (history compaction draining the resolving turn) resolves toward suppression, which is the safe direction.
The mutation testing claimed in the fix summary is real — I reproduced both, and added a third against the round-trip test, which was the one most likely to have passed vacuously. It didn't.
Merge is the repo owner's call.
malibio
left a comment
There was a problem hiding this comment.
Re-review of 7cfb2e7a: APPROVE — all 5 previous findings properly addressed. (Submitted as a comment rather than an approval: GitHub does not permit approving your own PR.)
Both amber fixes verified by independent mutation testing, plus a third mutation I added against the new round-trip test — which the pre-existing clarification tests survived, so it adds real coverage. Walked the session_already_clarified rewrite across 8 message sequences (first turn, unanswered clarification, answered, resolved-then-new-intent, tool-calling turns, mid-conversation rebuild, repeated clarifications); no hole found. 370 tests pass, clippy clean. Two documentation-only nits, non-blocking.
Full report: #1826 (comment)
- routing.rs: restore the missing doc separator, and stop describing the fix via is_write_tool — the body no longer calls it. A comment describing the diff rather than the code is the same drift the clarification-comment finding was about. - skill_pipeline.rs: the seed blast-radius test reimplemented the rule instead of calling skill_is_mutating, so it would have kept passing while the production classifier regressed. Now exercises the real function; verified by mutation (stubbing skill_is_mutating to always-false fails the test). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
Re-review nits addressed —
|
…mpty-generation exclusion, guidance provenance (closes #1764) The eval could not tell "the model failed" from "the harness failed" — both rendered as a low score, and the two known false results on record (a contaminated 11/12 baseline, and "no tools called" scenarios passing while every turn died on context overflow) were only caught by reading raw model output. This makes the harness diagnostic before any future baseline gets recorded against it: - Raw generation per ReAct iteration is now captured to a .trace.jsonl file alongside the results JSON (agent_loop.rs logs it at debug level so production's default info verbosity is unaffected). - A uniform 0%/100% pass rate across 4+ scored scenarios now aborts as an environment failure rather than writing a plausible results file. - The documented degenerate-empty-generation failure mode (model emits neither text nor a tool call) is now excluded from the pass/fail denominator instead of silently scoring as a model failure. - Provenance now records which seeded prompt/skill content a run actually measured (_seed.key/_seed.version read back via `node query`), since seeding only reseeds on daemon startup and a long-running daemon can silently serve stale guidance. - Stage 1's routing decision (query/clarify/clarify_suppressed/none/ unavailable/failed) and whether Stage 2's prompt actually carried a candidate block are now logged on every code path and surfaced per turn, closing the gap where a silently-skipped routing attempt looked identical to one that matched nothing. Verified the tool-call-parsing regression flagged during scoping (narrated JSON-array calls slipping past detection, per #1826) is already fixed in the production loop with its own unit coverage; no separate eval-side parsing gap exists since the eval only counts executed-tool log lines, never re-parses raw text itself. ADR-056's Scenario 5 claim and the honest 9/12 baseline were already addressed in earlier sessions on this issue; recording a fresh baseline remains gated on #1800 (create_schema description-inference deletion). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs
…DR-056's Scenario 5 claim (#1831) * Make the agent eval diagnostic: raw-output trace, uniformity guard, empty-generation exclusion, guidance provenance (closes #1764) The eval could not tell "the model failed" from "the harness failed" — both rendered as a low score, and the two known false results on record (a contaminated 11/12 baseline, and "no tools called" scenarios passing while every turn died on context overflow) were only caught by reading raw model output. This makes the harness diagnostic before any future baseline gets recorded against it: - Raw generation per ReAct iteration is now captured to a .trace.jsonl file alongside the results JSON (agent_loop.rs logs it at debug level so production's default info verbosity is unaffected). - A uniform 0%/100% pass rate across 4+ scored scenarios now aborts as an environment failure rather than writing a plausible results file. - The documented degenerate-empty-generation failure mode (model emits neither text nor a tool call) is now excluded from the pass/fail denominator instead of silently scoring as a model failure. - Provenance now records which seeded prompt/skill content a run actually measured (_seed.key/_seed.version read back via `node query`), since seeding only reseeds on daemon startup and a long-running daemon can silently serve stale guidance. - Stage 1's routing decision (query/clarify/clarify_suppressed/none/ unavailable/failed) and whether Stage 2's prompt actually carried a candidate block are now logged on every code path and surfaced per turn, closing the gap where a silently-skipped routing attempt looked identical to one that matched nothing. Verified the tool-call-parsing regression flagged during scoping (narrated JSON-array calls slipping past detection, per #1826) is already fixed in the production loop with its own unit coverage; no separate eval-side parsing gap exists since the eval only counts executed-tool log lines, never re-parses raw text itself. ADR-056's Scenario 5 claim and the honest 9/12 baseline were already addressed in earlier sessions on this issue; recording a fresh baseline remains gated on #1800 (create_schema description-inference deletion). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs * Fix multiline/embedded-marker corruption in raw-output log scraping (review fixes for #1764) Code review on PR #1831 caught two bugs in the raw-output-trace plumbing added for #1764, both stemming from the same root cause: treating a field that can contain arbitrary model text as if it were bounded by ordinary line/marker delimiters. 1. scripts/aichat.ts split the daemon log slice on "\n" before scanning for the raw-generation marker. tracing's %-Display formatter writes the field verbatim, embedded newlines included, so any multiline generation was silently truncated at its first newline. 2. scripts/eval/runner.ts's regex used "\n[tool]" as a lookahead terminator, which broke if the model's own raw text happened to contain that literal substring (e.g. narrating "I'll use [tool] create_node..."). Fixed at the source: agent_loop.rs now JSON-encodes response_text before logging it, so the field is guaranteed to be exactly one line regardless of content. aichat.ts and runner.ts parse it back with JSON.parse instead of fragile lookahead regexes. While fixing this, found and fixed a related bug the review didn't catch: the tool-call-counting regex in runner.ts wasn't anchored to line start, so a [raw] line's embedded model text mentioning "[tool] create_node" was miscounted as a real tool call. Same fix applied to every other marker regex in parseTurnOutput for consistency, since all of them now share stdout with arbitrary model text. Extracted parseTurnOutput (runner.ts) and formatTurnLogLines (aichat.ts) as pure, exported functions so this parsing logic — where the bugs actually lived — is directly unit-testable without a daemon. Added 21 regression tests across two new test files covering multiline output, embedded markers, and the marker/tool-call interaction. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs * Rename seed_prompt_nodes to seed_agent_guidance_nodes; fix eval's stale seeded-type list seed_prompt_nodes seeds nodes with root_node_type "agent-guidance", not "prompt" — the type was renamed under ADR-064/#1699's markdown-children refactor but the function name was never updated to match, which is exactly what caused a real bug: scripts/eval/preflight.ts's SEEDED_GUIDANCE_TYPES still listed "prompt" as a seeded type to verify guidance provenance against, so readGuidanceProvenance silently found zero prompt nodes on every run (the type genuinely doesn't exist anymore) while correctly finding the 8 seeded skills. Caught while running the actual Phase B baseline for #1764 against a fresh isolated daemon, where zero results for a type that should exist is exactly the "can't tell if this is the harness or reality" ambiguity #1764 exists to eliminate. Fixed both: the function now matches what it actually seeds, and the eval now checks "agent-guidance" (verified against a live daemon — 5 nodes: Core Identity, Workspace Context Template, Tool Strategy Guide, Response Formatting Rules, Tool Call Formatting) instead of a type that seeds nothing. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs * Record the honest post-ADR-064 baseline: 9/12 (6/9/8 across 3 runs), superseding the pre-#1800 e4b-1775-r3 figure Recorded against a purged, freshly-seeded isolated daemon (commit 57bf108) now that both remaining ADR-064 workstream gates have closed: #1811 (already resolved as a side effect of #1820) and #1800 (create_schema description-inference deletion, merged as #1833). Ran three full trials for variance characterization, as the issue requires, plus two routing-eval trials. Headline: 9/12 (median of 6/12, 9/12, 8/12 — mean 7.7/12), consistent with this suite's previously-documented 10/9/8 variance band. The committed file records run 2 with the other two summarized in other_runs_this_session and full detail in caveats, per the issue's "report enough repetitions to characterize variance, not a single number" requirement. Findings from reading the raw-output traces this issue's diagnostic harness now captures, not just the aggregate: - Scenario 6 (Update via indirect reference) failed in all three runs — the model asks the user for a node ID instead of calling resolve_query, despite resolve_query being confirmed present in the offered tool list every time. A genuine comprehension gap, not a routing or harness defect. Tracked by #1637. - create_schema JSON-truncation errors recurred across scenarios 3/8a/8b at 2/3 frequency each — the model emits genuinely malformed JSON on complex multi-field schemas ("EOF while parsing a value"), a real generation defect distinct from the #1800/coreValues class of prose-contradiction bug this suite previously found. - Zero "widget" placeholder leakage across all three runs' raw output and the full daemon log, per the issue's specific ask. Scenarios 4/8c/8d show no systematic INSTANCE-vs-TYPE regression. - Zero empty-generation exclusions and no uniformity-guard trips in any run — nothing here reads as a harness artifact. - Routing eval: 10/15 twice, with an IDENTICAL failure set both runs (not committed as a separate file here, but noted in caveats since the consistency across independent runs suggests systematic causes, and at least one failure looks like a scoring-heuristic gap rather than a model failure). scripts/results-e4b.trace.jsonl is the raw-output trace for the committed run, so any of the findings above can be re-verified from the actual model text without re-running the eval. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs * Correct #1637 misattribution in the baseline; fix a stale doc-comment reference results-e4b.json's scenario-6 caveat wrongly cited #1637 (closed) as already tracking the model-never-calls-resolve_query failure. #1637 was about resolve_query's return contract once called (fixed, confirmed working in this code — its own evidence cites 100% success on this exact phrasing when the tool IS called); the failure this baseline actually measured is the model not calling the tool at all, which #1637 did not observe under its own measurement conditions. Filed as its own issue, #1835, and corrected the caveat to explain the distinction plus separate run 1 (a cascade from scenario 4, a different failure) from runs 2-3 (the clean repro). Also fixes a doc comment in preflight.ts left referencing the old seed_prompt_nodes name after the prior commit renamed the function in prompt_assembler.rs but missed this comment — caught in re-review. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012qFMbS5rEGLQL6CCkg6Xjs --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
Implements the routing flow ADR-038 decided, replacing the single-turn pull that ADR explicitly rejects under Alternatives Considered.
Closes #1815.
What changed
AgentToolExecutor::retrieve_skills, a deterministic system step. K is bounded by the system (RETRIEVAL_TOP_K), not the model.tool_whitelistviaTool::write_semantics(): any write tool in the whitelist raises that skill's bar. Mutating > read-only is a compile-time invariant.delete_nodein reach.search_skillsis withheld from the model-facing surface but stays inTool::ALL, because the MCPfind_skillshandler shares its implementation and the seeded tool node backs that external surface.One channel decision, applied twice
Q1 (Stage-2 candidate delivery) and Q2 (Stage-1 output) were settled independently but land on the same principle: prefer the tool-schema channel over prose and parsing. That is the channel ADR-064's evidence favors throughout — tool schema 100% compliance vs prose 87.5%, and instructions rendered into the prompt (Finding 2) rather than returned as a tool result (measured to drop continuation 100% → 44%).
Concretely: Stage 1 uses two typed tools instead of a
QUERY:/CLARIFY:prose convention, and Stage 2 receives candidates in the prompt instead of as a tool result. These are the same decision seen from two directions, not two coincidentally-aligned choices.This resolves the ADR-064 Provisional question for the Stage-2 path specifically. It is a reasoned choice on existing evidence, not a new measurement.
Threshold values
SKILL_SEARCH_THRESHOLDstays at0.0— deliberately. Retrieval still returns the long tail so the judged gate can see it; the new bars decide what is actionable. One gate filters, the other judges.The two bars are deliberately permissive and not yet tuned, and their doc comments say why: tuning needs an eval that can distinguish a model failure from a harness failure (#1764). Tightening them before that would hide the long tail against an untested target, with no measurement showing the loss.
Latency
ADR-038 requires the extra turn's cost be measured, not assumed.
packages/agent/tests/routing_latency.rsruns both arms through the same production loop against the same engine, differing only in whetherrouting_available()reports true.On gemma-4-e4b-q4km (ADR-056's locked model), in-process, 3 prompts x 3 runs:
Routing overhead: +419 ms (+13.0%).
tool rounds 1.00in both arms is what makes this comparable — same work, done two ways. The prompt-token rise (606 -> 1121) is the injected candidate block, i.e. the KV-cache prefix divergence ADR-038 predicted.Three earlier attempts were rejected rather than reported, and the harness now refuses error-dominated runs instead of printing a confident number from error paths.
A model-specific failure worth knowing about
A four-arm diagnostic (
dump_one_routed_turnin the same file) isolates which part of routing affects tool-calling:On the locked model every arm fires. On mistral over the OpenAI-compatible endpoint, any injected block suppresses the tool call — even one containing only skill names, no instructions and no metadata. Stage 1 alone is harmless in both.
That does not block this change, since the failure is confined to a model we do not ship. It is worth keeping as a regression guard when the locked model changes, and it is a data point against ADR-064's prediction that the operative variable is how procedural the payload is: here, payload content did not matter, only the block's presence.
Two bugs the tests caught
looks_like_narrated_tool_callonly detectedtool_name(...)syntax; a model emitting the JSON form[{"name":"create_node",...}]as text slipped past it, so the loop saw no tool call and the turn produced nothing. Pre-existing gap, surfaced by the latency measurement; now detects both forms.?inside a loop in schema-metadata rendering discarded every remaining type when one entry lacked atype_id.Also fixed: Stage 1 originally ran on every turn, taxing conversational turns that need no capability. It is now gated on retrieval actually being wired up.
Not in scope
The three blockers #1815 names remain open — the resident-prompt reduction (#1813) and the diagnostic eval (#1764). This was built at Michael's direction with verification explicitly deferred to #1764; the acceptance criteria that depend on a trustworthy eval cannot be closed until it lands.
Testing
quality:fixclean (ESLint, svelte-check, tsc, fmt, clippy)agent_loop.rs:415is corrected🤖 Generated with Claude Code