Repository navigation
Implement route_multi for compound-intent routing, fix spurious firing under history (#1909) - #1916
Conversation
Code Review SummaryReview Type: Test-only addition for an investigation issue (#1909). No production code changes. Scope is exactly what the issue asked for: a live, in-process probe against the locked native model, producing raw traces for a human decision — not a fix, not a new classifier, not a Stage-1 redesign. Verified: This is a clean, well-scoped, net-positive change. No blocking issues found. FindingsCritical IssuesNone. Suggested Improvements
Nitpicks
Requirements Check (issue #1909)
RecommendationAPPROVE. This is a well-scoped, self-contained test-only PR that does exactly what an investigation issue's acceptance criteria asked for, follows the two existing live-test files' conventions faithfully (verified line-by-line against |
malibio
left a comment
There was a problem hiding this comment.
Review recommendation: APPROVE (self-approval blocked by GitHub on this PR since it's authored by the same account — see full report and recommendation in the PR comment above).
Pragmatic Code Review — PR #1916 (Add live Stage-1 compound-intent probe, #1909)Scope reviewed: SummaryThis is a well-executed diagnostic PR for an investigation issue, and it should merge. It does the one thing that makes or breaks a "live evidence" probe: it exercises the real Stage-1 path rather than a look-alike. Scope discipline is clean: zero production code touched, no new classifier, no Stage-1 redesign — exactly matching #1909's explicit out-of-scope list. Findings went to the issue as a comment (verified on #1909), not committed as a file; the per-run trace artifact is correctly gitignored and untracked. Verification run locally:
1. Architectural Design & Integrity — PassThe probe is correctly positioned as a The
2. Functionality & Correctness — Pass
The two non-ignored unit tests are a nice touch and earn their keep. 3. Security — Pass, nothing to flagNo secrets, no network egress, no user input. The only filesystem write is scoped to 4. Maintainability & Readability — StrongThe module doc (lines 1-32) is the standout: it states the question, the ADR context, why native-in-process rather than served, why The 5. Testing Strategy — PassThe single-intent control set (lines 104-113) is the methodological choice that makes this evidence rather than an anecdote. Without it, 6. Performance & Scalability — Not applicable
7. Dependencies & Documentation — PassNo new dependencies. The FindingsCritical IssuesNone. Suggested Improvements1. #[test]
fn every_compound_prompt_has_a_keyword_pair() {
for (label, _) in COMPOUND_PROMPTS {
assert!(keyword_pair_for(label).is_some(), "no keyword pair for {label}");
}
}Alternatively, fold the keyword pair into 2. NitpicksNit: The Nit: Nit: Recommendation: APPROVEThe probe faithfully exercises production Stage-1 rather than reimplementing it — the single check that determines whether this PR's evidence is worth anything — and it passed. Scope is exactly what #1909 asked for and nothing more: no production code, no classifier, no Stage-1 redesign. Compiles clean, clippy clean, fmt clean, default suite unaffected, trace artifact correctly gitignored, findings posted to the issue rather than committed. The two suggested improvements are both about parallel-array invariants in the throwaway harness and neither affects the validity of the evidence already gathered. Fine to address in this PR or wave through. One note beyond the code, for whoever picks up the follow-up: the issue comment's own caveat about sample size (5 prompts, one run each) is the right read, and this project has a standing lesson that single-run matrix numbers are not decision-grade. The |
Addressed review recommendations
Re-Review DecisionDecision: NO RE-REVIEW NEEDED Rationale: Both changes addressed were the review's own 🟢 suggestions — a doc comment and a new low-risk unit test, no logic changes to the probe itself or to any production code. Nothing architectural, nothing uncertain in how it addresses the feedback. Co-Authored-By: Claude [email protected] |
Per #1909's follow-up acceptance criterion, widen the compound-prompt sample to size the degradation rate rather than rely on the original 1-of-5 anecdote. Adds varied phrasing, 3-intent requests, and mutating/ read-only intent combinations, for 11 compound prompts total (up from 5) plus 18 matching single-intent controls (up from 5). Also folds each prompt's keyword set directly into a CompoundPrompt struct instead of a separate keyword_pair_for lookup, so the mapping is unmissable by construction (a suggestion from PR #1916's review). Live result (gemma-4-e4b-q4km, native, single run): - route_clarify called: 0/11 — structural finding holds at wider n - route_query, faithful: 6/11 - route_query, lossy (dropped/fabricated a detail): 5/11 Still a single run — per #1862's standing lesson, not decision-grade without a repeat to compare against. Co-Authored-By: Claude <[email protected]>
… started
## Completed in This Session
- [x] Live reproduction of the compound-intent gap against the locked native
model (gemma-4-e4b-q4km, in-process), not a served stand-in
(PR #1916, packages/agent/tests/live_stage1_compound_intent.rs)
- [x] Initial n=5 pass: route_clarify 0/5, lossy merge 1/5
- [x] Widened to n=11 (varied phrasing, 3-intent requests, mutating/
read-only combinations) + 18 single-intent controls: route_clarify
0/11, lossy merge 5/11 (45%)
- [x] Recommendation posted and folded into issue #1909's body: a third
typed Stage-1 tool, route_multi, taking an array of per-intent query
strings (mirrors route_query's single `query: string`, pluralized)
- [x] Pragmatic code review completed on PR #1916 (APPROVE, two suggestions
addressed: doc comment on run_stage1's session simplification, and a
keyword-coverage unit test)
- [x] Issue #1909 body and acceptance criteria updated to reflect all of the
above; all investigation-phase criteria checked off
## Remaining Work
- [ ] Implement `route_multi` as a third Stage-1 tool in
packages/agent/src/local_agent/routing.rs:
- Add `ROUTE_MULTI_TOOL: &str = "route_multi"` alongside the existing
ROUTE_QUERY_TOOL/ROUTE_CLARIFY_TOOL constants (line 89-91)
- Extend `RouteDecision` (line 75) with a `Multi(Vec<String>)` variant
(or equivalent) carrying per-intent queries
- Add its ToolDefinition to `stage1_tool_definitions()` (line 114) —
array-of-strings schema, mirroring route_query's single-string one
- Extend `parse_route_decision()` (line 164) to parse route_multi calls
- Update STAGE1_SYSTEM_PROMPT (packages/agent/src/local_agent/agent_loop.rs:58)
to describe the third option per ADR-064's channel doctrine (tool
descriptions own selection, not resident prose)
- Wire the caller in agent_loop.rs (~line 1776, the stage1_routing
block) to re-enter retrieval once per element of a Multi decision,
the same way it currently does once for a Query decision — Stage-2's
per-candidate trust boundary and score gating should not need to
change, only how many times retrieval runs per turn
- [ ] Before merging: full routing/retrieval matrix run (3+ reps vs. current
baseline), per the #1904/#1911 precedent — not just a re-run of the
compound-prompt probe. This is a hard requirement per #1909's own
acceptance criteria and #1917's operating rule 3.
- [ ] Optional, non-blocking: repeat the widened n=11 probe once to check the
45% lossy figure for run-to-run variance (per #1862) — proceeding with
route_multi does not need to wait on this.
## Current State
- Files modified this session: packages/agent/tests/live_stage1_compound_intent.rs
(new), .gitignore (+trace artifact entry) — both committed and pushed
- No production code touched yet — routing.rs/agent_loop.rs are unmodified
from origin/main plus whatever else has landed there since this branch
diverged
- Tests: all passing (cargo test -p nodespace-agent --test
live_stage1_compound_intent — 4 non-ignored unit tests pass; the live
#[ignore]'d probe was run manually twice, not part of default test:all)
- PR #1916 open against main, reviewed and approved, addressing its review
feedback is complete
- Issue #1909 fully up to date with findings, recommendation, and remaining
acceptance criteria
## Context for Next Session
This is a CONTINUING FROM WIP case (CLAUDE.md) for whoever picks this up
next — most likely #1917's autonomous orchestrator, per that issue's Step 0.
Do not create a new worktree; re-enter this one
(.claude/worktrees/issue-1909-stage1-compound-intent, branch
worktree-issue-1909-stage1-compound-intent) and continue its history.
The investigation is done and the fix shape is decided (route_multi, a
third typed Stage-1 tool). What's left is implementation plus the mandatory
full-matrix verification before merge — this is real work on shared routing
surface, not a mechanical follow-up. Read issue #1909's full comment history
for the raw traces behind the 45% figure before starting; the borderline
"search + create + reminder" case noted in the last comment is a heuristic
false-negative worth keeping in mind so it doesn't get miscounted again in
a future run.
## Acceptance Criteria Status
From issue #1909:
- [x] Live reproduction with raw traces
- [x] Recommendation for the minimal extension (route_multi)
- [x] Widen the compound-prompt sample past 5
- [ ] Optional repeat run of the widened sample (non-blocking)
- [ ] Implement route_multi as a third typed Stage-1 tool
- [ ] Full routing/retrieval matrix run before merging the implementation
Co-Authored-By: Claude <[email protected]>
Fires production's exact Stage-1 request against the locked native
model (in-process Gemma 4 E4B) for compound-but-unambiguous prompts
("log this expense and remind me Friday"), to check whether Stage 1
has a correct move when a request carries two distinct intents.
Measured: route_clarify is never called for these prompts. Stage 1
always calls route_query with a single merged query, which sometimes
silently drops one intent's specifics (e.g. "find notes and create
task from content" lost the "Q3 budget" detail entirely).
Ignored by default (loads a ~9.6GB GGUF, ~4 min), matching
routing_latency.rs's convention.
Co-Authored-By: Claude <[email protected]>
…eyword_pair_for coverage - Documented that run_stage1 skips stage1_query's prior-turn blending since each prompt is a fresh single-turn request with no session - Added a test asserting every COMPOUND_PROMPTS label has a matching keyword_pair_for arm, so a future label addition can't silently drop its mentions_both trace hint Skipped two nits from the review (Stage1Outcome variants only exercised via live traces; report/println duplication) — reviewer itself judged both as acceptable for this throwaway diagnostic test. Co-Authored-By: Claude <[email protected]>
Per #1909's follow-up acceptance criterion, widen the compound-prompt sample to size the degradation rate rather than rely on the original 1-of-5 anecdote. Adds varied phrasing, 3-intent requests, and mutating/ read-only intent combinations, for 11 compound prompts total (up from 5) plus 18 matching single-intent controls (up from 5). Also folds each prompt's keyword set directly into a CompoundPrompt struct instead of a separate keyword_pair_for lookup, so the mapping is unmissable by construction (a suggestion from PR #1916's review). Live result (gemma-4-e4b-q4km, native, single run): - route_clarify called: 0/11 — structural finding holds at wider n - route_query, faithful: 6/11 - route_query, lossy (dropped/fabricated a detail): 5/11 Still a single run — per #1862's standing lesson, not decision-grade without a repeat to compare against. Co-Authored-By: Claude <[email protected]>
… started
## Completed in This Session
- [x] Live reproduction of the compound-intent gap against the locked native
model (gemma-4-e4b-q4km, in-process), not a served stand-in
(PR #1916, packages/agent/tests/live_stage1_compound_intent.rs)
- [x] Initial n=5 pass: route_clarify 0/5, lossy merge 1/5
- [x] Widened to n=11 (varied phrasing, 3-intent requests, mutating/
read-only combinations) + 18 single-intent controls: route_clarify
0/11, lossy merge 5/11 (45%)
- [x] Recommendation posted and folded into issue #1909's body: a third
typed Stage-1 tool, route_multi, taking an array of per-intent query
strings (mirrors route_query's single `query: string`, pluralized)
- [x] Pragmatic code review completed on PR #1916 (APPROVE, two suggestions
addressed: doc comment on run_stage1's session simplification, and a
keyword-coverage unit test)
- [x] Issue #1909 body and acceptance criteria updated to reflect all of the
above; all investigation-phase criteria checked off
## Remaining Work
- [ ] Implement `route_multi` as a third Stage-1 tool in
packages/agent/src/local_agent/routing.rs:
- Add `ROUTE_MULTI_TOOL: &str = "route_multi"` alongside the existing
ROUTE_QUERY_TOOL/ROUTE_CLARIFY_TOOL constants (line 89-91)
- Extend `RouteDecision` (line 75) with a `Multi(Vec<String>)` variant
(or equivalent) carrying per-intent queries
- Add its ToolDefinition to `stage1_tool_definitions()` (line 114) —
array-of-strings schema, mirroring route_query's single-string one
- Extend `parse_route_decision()` (line 164) to parse route_multi calls
- Update STAGE1_SYSTEM_PROMPT (packages/agent/src/local_agent/agent_loop.rs:58)
to describe the third option per ADR-064's channel doctrine (tool
descriptions own selection, not resident prose)
- Wire the caller in agent_loop.rs (~line 1776, the stage1_routing
block) to re-enter retrieval once per element of a Multi decision,
the same way it currently does once for a Query decision — Stage-2's
per-candidate trust boundary and score gating should not need to
change, only how many times retrieval runs per turn
- [ ] Before merging: full routing/retrieval matrix run (3+ reps vs. current
baseline), per the #1904/#1911 precedent — not just a re-run of the
compound-prompt probe. This is a hard requirement per #1909's own
acceptance criteria and #1917's operating rule 3.
- [ ] Optional, non-blocking: repeat the widened n=11 probe once to check the
45% lossy figure for run-to-run variance (per #1862) — proceeding with
route_multi does not need to wait on this.
## Current State
- Files modified this session: packages/agent/tests/live_stage1_compound_intent.rs
(new), .gitignore (+trace artifact entry) — both committed and pushed
- No production code touched yet — routing.rs/agent_loop.rs are unmodified
from origin/main plus whatever else has landed there since this branch
diverged
- Tests: all passing (cargo test -p nodespace-agent --test
live_stage1_compound_intent — 4 non-ignored unit tests pass; the live
#[ignore]'d probe was run manually twice, not part of default test:all)
- PR #1916 open against main, reviewed and approved, addressing its review
feedback is complete
- Issue #1909 fully up to date with findings, recommendation, and remaining
acceptance criteria
## Context for Next Session
This is a CONTINUING FROM WIP case (CLAUDE.md) for whoever picks this up
next — most likely #1917's autonomous orchestrator, per that issue's Step 0.
Do not create a new worktree; re-enter this one
(.claude/worktrees/issue-1909-stage1-compound-intent, branch
worktree-issue-1909-stage1-compound-intent) and continue its history.
The investigation is done and the fix shape is decided (route_multi, a
third typed Stage-1 tool). What's left is implementation plus the mandatory
full-matrix verification before merge — this is real work on shared routing
surface, not a mechanical follow-up. Read issue #1909's full comment history
for the raw traces behind the 45% figure before starting; the borderline
"search + create + reminder" case noted in the last comment is a heuristic
false-negative worth keeping in mind so it doesn't get miscounted again in
a future run.
## Acceptance Criteria Status
From issue #1909:
- [x] Live reproduction with raw traces
- [x] Recommendation for the minimal extension (route_multi)
- [x] Widen the compound-prompt sample past 5
- [ ] Optional repeat run of the widened sample (non-blocking)
- [ ] Implement route_multi as a third typed Stage-1 tool
- [ ] Full routing/retrieval matrix run before merging the implementation
Co-Authored-By: Claude <[email protected]>
Per #1909's investigation: Stage-1 had exactly two moves (route_query, route_clarify), neither correct for a compound-but-unambiguous request ("log this expense and remind me to follow up Friday") — nothing is ambiguous, there are just two intents. Measured live against the locked native model: route_clarify never fired (0/11), and merging both intents into one route_query string dropped or fabricated a detail 45% of the time (5/11). Adds route_multi as a third Stage-1 tool taking an array of per-intent query strings, mirroring route_query's single string, pluralized. RouteDecision gains a Multi(Vec<String>) variant; parse_route_decision requires at least two non-empty queries (fewer falls through to no decision, since a one-element "multi" is really a route_query call the model over-triggered on). agent_loop.rs's routing block re-enters retrieve_skills once per query for a Multi decision — the same way it already does once for a Query — and merges the results by skill id, capped at the existing RETRIEVAL_TOP_K bound so a compound request cannot silently widen Stage 2's candidate count past what ADR-038 requires the system to own. Verified against the real model via the existing compound-intent probe (live_stage1_compound_intent.rs, extended to categorize Multi outcomes): all 11 compound prompts now call route_multi with faithful per-intent queries (11/11, 0% lossy — down from 45% lossy pre-fix), and all 18 single-intent controls still correctly call route_query with no false-positive route_multi calls. Co-Authored-By: Claude <[email protected]>
…ocks live_stage1_golden_prompts.rs predates route_multi (it landed on main via 83bdabe, before this branch's Multi variant existed) and its 4 match-decision blocks were exhaustive over the old 2-variant RouteDecision, breaking the build once this branch's Multi variant is in the mix. Adds a Multi arm to each, printing the parsed queries the same way the other golden tests already print their outcome — no behavior change to the existing 3 variants' handling. Co-Authored-By: Claude <[email protected]>
…tage1-compound-intent # Conflicts: # packages/agent/tests/live_stage1_golden_prompts.rs
…1909) route_multi fired on genuinely single-intent turns during multi-turn conversations, fabricating a second intent out of blended prior-turn content. Root cause: build_retrieval_query's unlabeled parts.join("\n") blob gives Stage 1 no way to tell "this happened before" from "this is the current request" — read as several things to do rather than one request in light of history. Wraps the Stage-1 chat message with an explicit PRIOR CONTEXT / CURRENT REQUEST boundary via a new stage1_query_from_turns, extracted so the golden-prompt test harness exercises the same code path production uses rather than calling build_retrieval_query directly (which would have missed this fix entirely). build_retrieval_query's own output, used verbatim for schema retrieval's embedding query, is untouched — the framing only changes what the Stage-1 chat turn sees. Validated: all 4 golden-prompt cases (8a, 8b control, scenario 4, scenario 6) pass under the new framing. 3-rep matrix gate shows zero spurious route_multi firings across 36 trials (up from a confirmed, reproducible defect); the aggregate 7.3/12 mean is unmoved because scenario 6 still fails on the separately-tracked Stage-2 resolve_query refusal gap, and the rep-to-rep score decline traces to already-tracked pre-existing issues (#1926, #1927) unrelated to this change. Co-Authored-By: Claude <[email protected]>
4386228 to
e76fad6
Compare
Code Review: PR #1916 — Stage-1
|
| Criterion | Status |
|---|---|
| Live reproduction with raw traces | Met (pre-existing on branch) |
| Recommendation consistent with ADR-038/064 | Met — third typed tool, no new classifier |
| Widen sample past 5 | Met — 11 compound + 18 controls |
| Optional: repeated run for variance | Met beyond ask — 3-rep matrix gate |
Implement route_multi |
Met |
| Full routing/retrieval matrix before merge (#1904/#1911 precedent) | Met per main agent (36 trials, zero spurious firings) |
The #1904/#1911 criterion is the one that most often gets skipped, and it's the one that caught the spurious-firing bug here. Good.
Findings
Critical
None.
Important
1. agent_loop.rs:1996-2030 — the per-query RETRIEVAL_TOP_K cap can starve a secondary intent, defeating the point of route_multi.
Each query retrieves its own top-3, results are merged, sorted by score globally, then truncated to 3. Because scores are compared across independent retrievals, one strongly-matching intent can occupy all three merged slots and evict every candidate for the second intent entirely.
Concretely: query A returns scores [0.9, 0.8, 0.7], query B returns [0.6, 0.5, 0.4]. Merged and truncated to 3, Stage 2 sees only A's candidates. The compound request has been silently reduced to a single-intent request — the exact failure mode the issue set out to fix, now relocated from Stage 1 into the merge step.
This is a real risk rather than a theoretical one, because cross-query cosine scores are not calibrated against each other. A short, well-matched intent ("find my notes") reliably scores higher than a longer or more unusual one, so the eviction is biased rather than random.
Worth noting: the comment justifies the global cap by citing ADR-038's system-owned bound, and that reasoning is correct — widening K for compound requests would be a real violation. The gap is that "cap the total at K" and "guarantee each intent gets representation" are both defensible, and only the first was implemented. A round-robin interleave before truncation (take the top candidate from each query, then the second from each, …) preserves the K bound exactly while guaranteeing every intent contributes at least one candidate when it has one. That's a small change to the same block and doesn't touch the score gates.
I'd also flag that the live matrix validation would not have caught this: it measured Stage-1 decisions (does route_multi fire when it should?), not the downstream candidate set after merge. The zero-spurious-firing result is real and reassuring, but it isn't evidence about this code path.
2. agent_loop.rs:1993-2030 — retrieval fan-out is unbounded in query count and strictly serial.
RouteMultiParams accepts any-length queries array; the schema says "two or more" in prose but sets no maxItems, and parse_route_decision enforces only the lower bound. The loop then awaits each retrieve_skills call sequentially, so latency scales linearly with whatever the model emits. A model that decomposes an unusual request into eight intents produces eight serial embedding round-trips on the turn's critical path — and ADR-038 specifically requires routing latency to be measured rather than assumed, which the existing routing_latency_ms instrumentation now under-describes for the multi case.
Two independent mitigations, either sufficient: add "maxItems": 4 (or similar) to the schema and enforce a matching truncation in parse_route_decision so the bound is structural rather than advisory; and/or run the retrievals concurrently via futures::future::join_all, since they're independent and the merge is order-insensitive after the sort. The cap is the more important of the two — an advisory prose bound on a model-controlled array is the kind of thing that holds until it doesn't.
3. Test coverage gap: the entire Multi fan-out/merge/dedupe path in agent_loop.rs has no unit test.
routing.rs has three solid new parse tests, and I verified they genuinely enforce what their names claim (cargo test -p nodespace-agent --lib routing — 53 passed; the two-or-more rule, blank-trimming, and empty-array rejection all hold). But every test on this branch stops at the parse boundary. Nothing exercises:
- that N queries produce N retrieval calls,
- that duplicate skill ids are deduped (
seen_ids), - that the merged set is truncated to
RETRIEVAL_TOP_K, - that one query's retrieval failure doesn't abort the others (the
continue with the restpath), - the starvation behavior in finding 1.
This matters because the merge block is where the genuinely novel logic lives — the parse layer is comparatively mechanical. The harness to test it already exists: RoutingToolExecutor (agent_loop.rs:6628) records every query into self.queries and returns configurable candidates, and skill_candidate(name, score, tools) builds fixtures with arbitrary scores and ids. A mock engine emitting a route_multi call at Stage 1 plus assertions on the recorded queries and outcome.candidates would cover all five bullets in one test with no new scaffolding. Given the #1904/#1911 precedent this issue explicitly invokes — a routing change validated only against its motivating scenario shipping a regression on a bystander — leaving the merge path to live-model testing alone is the weak spot in an otherwise well-validated change.
Verified as sound (raising because they were flagged for scrutiny)
stage1_query_from_turns's suffix-strip is correct. I extracted the real build_retrieval_query/trailing_chars implementations and ran the adversarial cases directly:
- Prior turn ending with the current message's exact text (
["please mark it paid"]+"mark it paid") → correct.strip_suffixremoves only the final occurrence, so the prior turn survives intact in PRIOR CONTEXT. - Prior turn identical to the current message → correct, both retained.
- Prior turn exceeding
MAX_CHARS_PER_BLENDED_TURN(500 chars) → correct; truncation applies to the prior turn only, and the current message is never truncated bybuild_retrieval_query, so the suffix always matches exactly. - All-blank prior turns → correctly falls through to the bare current message (the
prior_blended.is_empty()branch). - More than
BLENDED_HISTORY_TURNSpriors → correct, last two blended.
The key invariant making this safe is that build_retrieval_query never truncates the current message and always appends it last — so strip_suffix(current) cannot fail to match or match in the wrong place. The comment already states this ("split it back apart at that known boundary rather than re-deriving the trim/cap logic"), and the reasoning is sound: re-deriving would create exactly the drift risk the comment names.
One degenerate case: an all-whitespace user_message with non-empty priors yields a dangling CURRENT REQUEST (route this):\n with nothing after it. I traced run_turn and found no empty-message guard upstream, so it's reachable in principle — but an empty user turn is already degenerate everywhere else in the loop, and this produces a harmless prompt rather than a panic or a wrong route. Not worth a guard; noting it only because it was in scope.
stage1_query cannot drift from stage1_query_from_turns. Confirmed at agent_loop.rs:393-404: stage1_query only extracts prior_turns from the session and delegates. Zero duplicated framing logic. The doc comment explains why the split exists (test harness needs &[&str] without an AgentSession), which is a legitimate reason and not speculative generality.
RouteMultiParams rejection logic matches its test names. Verified in source, not inferred: trim → filter non-empty → len() < 2 → None. Single-element, all-blank, and empty arrays all correctly yield no decision, falling through to unrouted retrieval on the raw message. deny_unknown_fields is consistent with the sibling param structs.
Security: No new external input surface. queries elements flow into retrieve_skills (embedding retrieval) as data, not as instructions or interpolated queries. Stage 2's trust boundary and both score gates (READ_SKILL_SCORE_BAR / MUTATING_SKILL_SCORE_BAR, routing.rs:290-303) are untouched and still applied per-candidate after the merge — the claim in the diff comment that Stage 2's gating is unaffected is accurate. No secrets, no injection vector.
Nits
- Nit:
agent_loop.rs:2025-2029—top_scoreis computed as the max of each retrieval's first candidate. After the global sort and truncate,merged.first()is the true top score and is already available, making the separate accumulator redundant. Minor, but the two can disagree if a first-candidate score is beaten by a later candidate from another query. - Nit:
routing.rs— theMulti(Vec<String>)variant is the only tuple variant among struct-like siblings (Clarify { question, options }). A named field (Multi { queries: Vec<String> }) would read more consistently at theagent_loop.rs:1944match site. Purely stylistic. - Nit:
live_stage1_compound_intent.rs:485-487— the probe asserts nothing about model behavior by design, which is correct for an investigation harness. Now thatroute_multiships, a minimal regression assertion (e.g. single-intent controls never yieldMulti) would convert this from a one-time investigation artifact into a standing guard. The golden-prompt file already does this well atlive_stage1_golden_prompts.rs:263-268, where the scenario-6Multiarm panics with a genuinely useful message — that's the pattern worth extending.
Recommendation
COMMENT — approve-with-followups in substance; not blocking.
The architecture is right, the shared-surface bug fix is the correct call rather than a workaround, and the validation discipline (3-rep matrix, golden-prompt harness updated to exercise rather than bypass the fix) exceeds what the issue asked for. Findings 1 and 3 are the ones I'd want addressed — finding 1 because it can silently reintroduce the dropped-intent failure this PR exists to fix, and finding 3 because the merge block is the one piece of novel logic with no deterministic test behind it. Both are small, contained changes to code already on this branch. Finding 2's maxItems cap is a two-line schema addition worth taking while the file is open.
None of these require re-running the live matrix: findings 1 and 2 are deterministic code paths testable with the existing mock harness.
malibio
left a comment
There was a problem hiding this comment.
Review posted as a PR comment above. Recommendation: COMMENT (approve-with-followups in substance, not blocking). Two contained code findings worth addressing before merge — per-query top-K merge can starve a secondary intent, and the Multi fan-out/merge path has no deterministic unit test — plus an unbounded query-count nit. Suffix-strip logic and stage1_query delegation were both verified sound.
Pragmatic Code Review — PR #1916Reviewed the full diff against Verdict: APPROVE, with one should-fix (missing test coverage for the What's implemented
|
malibio
left a comment
There was a problem hiding this comment.
Full pragmatic code review posted above (all 8 commits reviewed against #1909's acceptance criteria; stage1_query_from_turns suffix-stripping, route_multi fan-out cost, RouteMultiParams validation, and stage1_query/stage1_query_from_turns drift risk all scrutinized as requested). Verdict: APPROVE (sound design, cargo test -p nodespace-agent --lib: 429 passed/0 failed, clippy clean). Note: gh pr review --approve is blocked here because the PR and reviewer share the same GitHub account (self-approval not permitted by GitHub) — recording as COMMENT instead. One should-fix noted: no non-live unit test exercises the Multi fan-out/merge/dedup/cap path in agent_loop.rs (only routing.rs's parsing is unit-tested; the fan-out itself is covered only by #[ignore]'d live tests).
The review on PR #1916 found route_multi's retrieval fan-out/merge/dedup path (agent_loop.rs's RouteDecision::Multi arm) was covered only by #[ignore]'d live tests, not run in default test:all. Adds a mocked-engine test exercising two route_multi queries against a fixed candidate set: asserts retrieval fires once per query in order, and that a candidate matching both queries is merged once in Stage 2's injected prompt, not duplicated. Verified the test actually catches a regression by temporarily removing the dedup check and confirming the test fails, then reverting. Co-Authored-By: Claude <[email protected]>
Address review: fan-out/dedup unit test addedAddressed the one should-fix from the review: Added Not fixed (per the reviewer's own severity call, both were low-severity notes, not should-fix items):
|
Re-Review DecisionDecision: NO RE-REVIEW NEEDED Rationale: The single should-fix finding was a missing unit test for already-implemented, already-reviewed logic ( Ready for merge, pending your go-ahead. |
Summary
#1909 identified that Stage-1 routing (ADR-038) has no move for compound, unambiguous requests — one message carrying two distinct intents. Live reproduction confirmed the gap (
route_clarifynever fires for a compound prompt, 0/5 then 0/11; the merged query silently drops or fabricates detail in ~45% of compound prompts at n=11).This PR implements the recommended fix and closes the loop found while validating it:
route_multi— a third typed Stage-1 tool (packages/agent/src/local_agent/routing.rs) taking an array of per-intent query strings, mirroringroute_query's single-query schema. Each element re-enters retrieval independently; Stage-2's per-candidate trust boundary and score gating are unchanged.route_multilive: it fired on genuinely single-intent turns in multi-turn conversations, fabricating a second "intent" out of blended prior-turn content. Root cause:build_retrieval_query's rawparts.join("\n")output gives Stage 1 no boundary between "this happened before" and "this is the current request." Fixed by wrapping the Stage-1 chat message with an explicit PRIOR CONTEXT / CURRENT REQUEST label (stage1_query_from_turnsinagent_loop.rs) —build_retrieval_query's own output, used verbatim for schema retrieval's embedding query, is untouched.Validation
live_stage1_golden_prompts.rs): all 4 named cases (8a, 8b control, scenario 4, scenario 6) pass under the new framing — no bystander regressions. The harness was also fixed to call the samestage1_query_from_turnsfunction production uses, rather thanbuild_retrieval_querydirectly, which would have bypassed this fix entirely.route_multifirings across 36 trials (3 reps × 12 scenarios) — the targeted defect did not reproduce once. Aggregate scores were 9/12, 7/12, 6/12 (mean 7.3/12); every failure traces to already-tracked, pre-existing issues unrelated to this change:create_schemaretry) — hit scenarios 3/8a/8b intermittentlycreate_nodepersists 0 properties on 8c)resolve_queryeven when available and correctly instructed — this is scenario 6's actual remaining blocker, and is unaffected by this PR (Stage 1 routes it correctly in all 3 reps; the failure is downstream).Full traces and reasoning posted on #1909's comment history.
Test plan
cargo test -p nodespace-agent --lib/--tests— all non-ignored tests passcargo clippy --all-targets -- -D warnings -D clippy::unused-async— cleanbun run test:all— 171 test files / 4108 tests passed (frontend), 20/20 (skill package), all Rust suites green--ignored --nocapture, serial) — 4/4 passroute_multifirings; remaining gaps are pre-existing and separately trackedtest:all+cargo build --bin nodespaced+test:e2e) passedCo-Authored-By: Claude [email protected]