Skip to content

Implement route_multi for compound-intent routing, fix spurious firing under history (#1909) - #1916

Merged
malibio merged 9 commits into
mainfrom
issue-1909-stage1-compound-intent
Aug 3, 2026
Merged

malibio merged 9 commits into
mainfrom
issue-1909-stage1-compound-intent

Conversation

@malibio

@malibio malibio commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

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_clarify never 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:

  1. route_multi — a third typed Stage-1 tool (packages/agent/src/local_agent/routing.rs) taking an array of per-intent query strings, mirroring route_query's single-query schema. Each element re-enters retrieval independently; Stage-2's per-candidate trust boundary and score gating are unchanged.
  2. A labeling fix for a bug found while validating route_multi live: 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 raw parts.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_turns in agent_loop.rs) — build_retrieval_query's own output, used verbatim for schema retrieval's embedding query, is untouched.

Validation

Full traces and reasoning posted on #1909's comment history.

Test plan

  • cargo test -p nodespace-agent --lib / --tests — all non-ignored tests pass
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async — clean
  • bun run test:all — 171 test files / 4108 tests passed (frontend), 20/20 (skill package), all Rust suites green
  • Live golden-prompt harness (--ignored --nocapture, serial) — 4/4 pass
  • 3-rep live matrix gate — zero spurious route_multi firings; remaining gaps are pre-existing and separately tracked
  • Pre-push gate (test:all + cargo build --bin nodespaced + test:e2e) passed

Co-Authored-By: Claude [email protected]

@malibio

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review 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: git diff origin/main...HEAD --stat shows exactly the two files described (.gitignore +4, live_stage1_compound_intent.rs +310, new file). Build is clean (cargo test -p nodespace-agent --test live_stage1_compound_intent — 2 non-ignored tests pass, live test correctly #[ignore]'d), clippy is clean, and CI on the PR is green. The live run was executed and its findings (route_clarify never fires; route_query silently merges intents, sometimes dropping specificity) were posted to issue #1909 as a comment with a concrete route_multi recommendation consistent with ADR-038/ADR-064's discriminated-tool-choice doctrine — matching both acceptance criteria and the project's "don't commit ephemeral run artifacts" convention already established by routing-matrix-latest.txt.

This is a clean, well-scoped, net-positive change. No blocking issues found.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/agent/tests/live_stage1_compound_intent.rs:132-141 (run_stage1): production's Stage-1 call site (agent_loop.rs:1776) runs the user message through stage1_query(session, user_message), which blends prior conversation turns into the routing query before sending it. This test sends the raw user_message directly instead. For this probe that's a reasonable simplification — there's no session/conversation to blend since each prompt is a fresh, self-contained compound request — but it's worth naming explicitly in the module doc (alongside the existing "no retrieval, no Stage 2" scope note at line 17) so a future reader doesn't mistake this for an oversight or wonder whether it affects the finding. It doesn't: stage1_query with no prior turns reduces to the raw message.
  • mentions_both/keyword_pair_for (lines 217-234): the doc comments are appropriately hedged ("a heuristic... not a verdict"), but consider a unit test asserting keyword_pair_for returns Some for every label in COMPOUND_PROMPTS (similar in spirit to the existing every_compound_prompt_has_a_single_intent_control check). Today a typo'd or added label would silently fall through to None and drop the hint from the trace with no signal that it happened. Low stakes given the heuristic is explicitly advisory, but cheap to guard.

Nitpicks

  • Nit: Stage1Outcome::MultipleToolCalls and CalledButUnparseable are constructed correctly but never exercised by the two compile-time unit tests (understandably, since they require a live model). Not asking for a change — just noting the enum's non-Decided arms are only validated by eyeballing a live trace, consistent with the file's stated philosophy of human-judged raw output over asserted behavior.
  • Nit: report (the String accumulated across the loop, lines 249-276) duplicates what's already println!'d and is only used to build the gitignored trace file. This mirrors routing_latency.rs/live_openai_compat_routing.rs's pattern of writing a diffable local artifact, so it's consistent with house style — just flagging that the dual print+accumulate is slightly repetitive within this file itself (e.g. line is built once and both printed and pushed). Not worth restructuring for a throwaway diagnostic test.

Requirements Check (issue #1909)

  • Live reproduction confirming or refuting the compound-intent gap, with raw traces — delivered via the new test, run manually, traces posted to issue Stage-1 has no move for compound, unambiguous requests (multiple intents in one message) #1909.
  • If confirmed, a recommendation for the minimal extension consistent with ADR-038/ADR-064 — posted (route_multi, a third typed tool taking an array of per-intent queries, preserving the discriminated-choice pattern).
  • Explicitly out of scope respected: no ML classifier, no Stage-1 redesign, no production code touched at all.
  • Test reuses production constants/functions (STAGE1_SYSTEM_PROMPT, stage1_tool_definitions(), parse_route_decision, ROUTE_QUERY_TOOL/ROUTE_CLARIFY_TOOL) rather than reimplementing them — verified these are the actual pub symbols from routing.rs/agent_loop.rs, not lookalikes.
  • #[ignore] + graceful skip-when-model-absent, matching routing_latency.rs's convention exactly (same resolve_backend-style loader, same "GGUF not downloaded -> eprintln + return" pattern).
  • .gitignore entry for the per-run trace artifact mirrors the existing routing-matrix-latest.txt entry and rationale (per-run trace would otherwise look like a changed finding on every ordinary re-run).

Recommendation

APPROVE. 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 routing_latency.rs and live_openai_compat_routing.rs), imports real production symbols rather than reimplementing them, compiles and lints cleanly, and has already been run with its findings properly routed to the issue rather than committed to the repo. The two suggested improvements above are optional polish, not blockers, given this is a diagnostic/investigation artifact rather than shipped product code.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review recommendation: 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).

@malibio

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1916 (Add live Stage-1 compound-intent probe, #1909)

Scope reviewed: git diff origin/main...HEAD — 2 files, +314/-0. One new test file (packages/agent/tests/live_stage1_compound_intent.rs, 310 lines) plus a 4-line .gitignore entry. Initial review (no prior review comments on the PR).

Summary

This 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. STAGE1_SYSTEM_PROMPT, STAGE1_MAX_TOKENS, stage1_tool_definitions(), parse_route_decision(), and RouteDecision are all imported from production (local_agent::agent_loop / local_agent::routing) — nothing is copied inline, so the probe cannot silently drift from what ships. I verified against packages/agent/src/local_agent/agent_loop.rs:49,58 and routing.rs:75,89,91,114,164; the request shape at live_stage1_compound_intent.rs:132-141 is byte-for-byte the same construction as production's agent_loop.rs:1778-1785 and routing_probe.rs:104-112.

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:

  • cargo test -p nodespace-agent --test live_stage1_compound_intent --no-run — compiles clean, no warnings
  • cargo test -p nodespace-agent --test live_stage1_compound_intent — 2 passed; 0 failed; 1 ignored, 0.00s (the live test correctly self-excludes from default runs)
  • cargo clippy -p nodespace-agent --tests — clean
  • cargo fmt -p nodespace-agent -- --check — clean
  • git status --porcelain — empty; git check-ignore confirms the trace file is matched by the new .gitignore rule

1. Architectural Design & Integrity — Pass

The probe is correctly positioned as a tests/ integration artifact rather than production source. Worth noting the contrast with src/local_agent/routing_probe.rs, which is production code because its verdict feeds a runtime routing decision — this file has no such role and rightly stays out of src/. No duplication concern between the two: routing_probe.rs measures Stage-2 injection suppression with a deliberately minimal stand-in prompt, while this file measures Stage-1's own tool choice under the real prompt. Different questions, no overlap.

The resolve_locked_model() helper (lines 59-73) is a near-verbatim copy of routing_latency.rs:56-73's resolve_backend(). Normally I'd flag copy-paste under DRY, but here the duplication is ~15 lines of setup across two independent tests/*.rs integration binaries, which cannot share a private module without introducing a shared test-support crate or #[path] include. The doc comment at lines 51-58 explicitly names the pattern it mirrors and why. For two diagnostic probes, that's the right trade — YAGNI beats a test-support module for 15 lines.

Stage1Outcome (lines 116-130) is a genuinely good design choice. Modelling NoToolCall, MultipleToolCalls, CalledButUnparseable, and Errored as distinct variants — rather than folding everything into "didn't work" — is what lets the trace distinguish a harness failure from a model finding. That's exactly the distinction this project has been burned by before (see the ArmResult::Errored rationale in routing_probe.rs:93-100).

2. Functionality & Correctness — Pass

  • Tool-call accumulation (lines 144-163) correctly correlates ToolCallArgs fragments to their ToolCallStart by id rather than assuming a single in-flight call, and preserves call order. This is what makes the MultipleToolCalls variant trustworthy.
  • .expect("sink not poisoned") on the mutex (lines 151, 171) is appropriate here — a poisoned mutex in a test harness is a genuine bug, and panicking surfaces it rather than hiding it.
  • Trace-write failure is handled non-fatally (lines 278-286): a filesystem problem prints a message rather than failing a run whose real output already went to stdout. Correct priority for a diagnostic.
  • The deliberate absence of behavioural assertions (documented at lines 288-290) is correct, not a gap. Stage-1 has no move for compound, unambiguous requests (multiple intents in one message) #1909 asks for raw traces supporting a human judgement; encoding a pass/fail bar for a question not yet answered would be premature.

The two non-ignored unit tests are a nice touch and earn their keep. tool_name_constants_match_stage1_tool_definitions (line 300) is the one that actually protects something: it runs in the default suite and fails loudly if routing.rs ever reorders or renames its Stage-1 tools, so the probe's assumptions can't rot silently while the expensive live test sits ignored.

3. Security — Pass, nothing to flag

No secrets, no network egress, no user input. The only filesystem write is scoped to env!("CARGO_MANIFEST_DIR")/tests/ — repo-relative, no hardcoded machine paths. The model path resolves through GgufModelManager, the same mechanism production uses, so nothing is pinned to one machine's layout.

4. Maintainability & Readability — Strong

The module doc (lines 1-32) is the standout: it states the question, the ADR context, why native-in-process rather than served, why #[ignore], and the exact command to run it. Someone stumbling on this file in six months with no memory of #1909 can orient from the file alone — which is the bar for a diagnostic artifact that outlives its investigation.

The mentions_both doc comment (lines 209-216) deserves specific credit for explicitly labelling itself a heuristic hint rather than a verdict. Undersold diagnostics are far safer than oversold ones, and this is the difference between a printed hint and a false finding.

5. Testing Strategy — Pass

The single-intent control set (lines 104-113) is the methodological choice that makes this evidence rather than an anecdote. Without it, route_query("find notes and create task from content") losing "Q3 budget" is unattributable — it could be ordinary query-compression noise. With the control showing route_query("find notes about Q3 budget") retaining it on the same domain and phrasing, the loss is attributable to compounding specifically. That's the difference between a trace and a finding.

6. Performance & Scalability — Not applicable

#[ignore] gating keeps a ~9.6GB model load and 10 live generations out of test:all; confirmed by the local run finishing in 0.00s with 1 ignored. The graceful-skip on missing model (lines 239-245) returns early with an eprintln! rather than panicking, matching routing_latency.rs's convention.

7. Dependencies & Documentation — Pass

No new dependencies. The .gitignore addition mirrors the existing routing-matrix-latest.txt entry in both placement and rationale, and cross-references it ("Same rationale as the routing matrix above") rather than restating it. It is the only non-test change in the diff — no stray modifications.


Findings

Critical Issues

None.

Suggested Improvements

1. keyword_pair_for can silently go stale against COMPOUND_PROMPTS (lines 225-234). The label→keyword mapping is a match on string literals with a _ => None fallback. If someone adds a sixth compound prompt or edits an existing label, the mentions_both hint silently disappears for that prompt — no compile error, no runtime complaint, just a missing line in the trace that a reader is unlikely to notice is missing. Since every_compound_prompt_has_a_single_intent_control already establishes the pattern of guarding these tables with a cheap default-suite test, the same treatment fits here:

#[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 COMPOUND_PROMPTS as a third tuple element, which makes the mapping unmissable by construction and deletes keyword_pair_for entirely. Either way the principle is the same one the existing test already applies: a parallel-array invariant should be enforced by the compiler or a cheap test, not by whoever edits it next remembering to.

2. every_compound_prompt_has_a_single_intent_control only checks lengths (line 308). It asserts COMPOUND_PROMPTS.len() == SINGLE_INTENT_CONTROLS.len(), which catches an added prompt with no added control, but not a reordered or mismatched pairing — and the pairing is load-bearing for the comparison, since the control's value depends entirely on being the same domain as its compound counterpart. This one's harder to assert mechanically (semantic correspondence isn't checkable), so length may be the honest limit. If so, a one-line comment noting that ordinal correspondence is a convention the reader must maintain would close the gap that the test's name currently implies is covered. Low priority for a throwaway harness.

Nitpicks

Nit: The #[cfg(test)] mod tests wrapper at line 293 is redundant. In a tests/*.rs integration binary the whole file is already compiled only under cargo test, so the attribute is a no-op. Harmless and arguably good habit-consistency with src/ modules, but it can mislead a reader into thinking there's a non-test compilation mode for this file. routing_latency.rs doesn't use one.

Nit: display() (line 190) hand-formats each Stage1Outcome variant. A impl std::fmt::Display for Stage1Outcome would be the idiomatic Rust spelling and would compose with {outcome} in the format! calls at lines 255 and 264. Purely stylistic; the free function is perfectly readable and the enum is file-local.

Nit: LOCKED_NATIVE_MODEL is now duplicated across three probe files (here, routing_latency.rs:34, and referenced elsewhere). Each carries the same "measures only this model" doc comment. Not worth a shared constant today given they're separate integration binaries, but if a fourth probe appears, promoting it to a pub const in nodespace_agent would stop three files from needing a coordinated edit when ADR-056's lock changes.


Recommendation: APPROVE

The 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 route_multi recommendation is well-reasoned and consistent with ADR-038/ADR-064's discriminated-tool-choice doctrine, but it should carry that caveat into whatever issue implements it — the "sometimes drops specificity" finding rests on 1 of 5 prompts.

@malibio

malibio commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review recommendations

  • ✅ Documented run_stage1's session simplification (live_stage1_compound_intent.rs): added a doc comment noting it sends the raw user message rather than routing through stage1_query's prior-turn blending, since there's no session in this isolated probe.
  • ✅ Added every_compound_prompt_has_a_keyword_pair test: guards that every COMPOUND_PROMPTS label has a matching keyword_pair_for arm, so a future added/renamed label can't silently drop its mentions_both trace hint.
  • ⏭️ Skipped both nits (Stage1Outcome variants only exercised via live traces; report/println! duplication) — the review itself judged both acceptable for this throwaway diagnostic test, and I agree there's no real gap there.

cargo test -p nodespace-agent --test live_stage1_compound_intent passes (3 non-ignored tests, live test still correctly #[ignore]'d), clippy clean, pre-push gate (test:all + build + e2e) green.

Re-Review Decision

Decision: 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]

malibio added a commit that referenced this pull request Aug 2, 2026
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]>
malibio added a commit that referenced this pull request Aug 2, 2026
… 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]>
malibio and others added 8 commits August 2, 2026 20:23
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]>
@malibio
malibio force-pushed the issue-1909-stage1-compound-intent branch from 4386228 to e76fad6 Compare August 3, 2026 00:59
@malibio malibio changed the title Add live Stage-1 compound-intent probe (#1909) Implement route_multi for compound-intent routing, fix spurious firing under history (#1909) Aug 3, 2026
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1916 — Stage-1 route_multi (compound intent)

Review Type: Initial full-branch review (8 commits, 823/-39 across 5 files). Reviewed the complete origin/main...HEAD diff, not a delta against the stale 2026-08-02 COMMENTED review — that review predates the route_multi tool, the shared-surface prompt change, and the matrix validation.

Summary

This is a well-executed change and a clear net positive. The design follows ADR-038/ADR-064's channel doctrine faithfully: a third typed tool rather than free text or a bolted-on classifier, with the system retaining ownership of RETRIEVAL_TOP_K. The comments are unusually good — they explain why (the #1817 embedding-vs-chat distinction, the ADR-038 candidate bound, the "weakest measured channel" rationale) rather than restating mechanics. The mid-implementation discovery that route_multi fired spuriously on single-intent multi-turn conversations, and the decision to fix the shared prompt surface rather than paper over it in route_multi, is exactly the right call — and updating the golden-prompt harness so it exercises the fix instead of bypassing it closes a real fidelity gap.

I verified the specific concerns raised and found the two most-suspected areas to be sound. I have one Important finding on the retrieval merge that I did not see discussed anywhere, plus a test-coverage gap.

Requirements Check (issue #1909)

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 rest path),
  • 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_suffix removes 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 by build_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_TURNS priors → 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_score is 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 — the Multi(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 the agent_loop.rs:1944 match 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 that route_multi ships, a minimal regression assertion (e.g. single-intent controls never yield Multi) would convert this from a one-time investigation artifact into a standing guard. The golden-prompt file already does this well at live_stage1_golden_prompts.rs:263-268, where the scenario-6 Multi arm 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 malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review 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.

@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1916

Reviewed the full diff against main (5 files, 823 insertions / 39 deletions across all 8 commits, not just the latest), issue #1909's acceptance criteria, and the areas specifically called out for scrutiny: stage1_query_from_turns's suffix-stripping, route_multi's retrieval fan-out cost, RouteMultiParams validation, and whether stage1_query/stage1_query_from_turns can drift apart.

Verdict: APPROVE, with one should-fix (missing test coverage for the Multi fan-out path in agent_loop.rs) and two minor/non-blocking notes.

What's implemented

  • route_multi as a third typed Stage-1 tool (routing.rs), RouteDecision::Multi(Vec<String>), parsed via RouteMultiParams { queries: Vec<String> } with deny_unknown_fields.
  • agent_loop.rs's routing block fans out one retrieve_skills call per query for a Multi decision, merges by skill id, sorts by score, truncates to RETRIEVAL_TOP_K — same bound the single-Query path already respects.
  • A second, related fix: stage1_query_from_turns now wraps blended history with an explicit PRIOR CONTEXT / CURRENT REQUEST boundary, addressing a live-confirmed false-positive where route_multi fired on single-intent turns by reading blended prior-turn content as a second intent.
  • Live validation: 11/11 compound prompts route correctly post-fix (down from 45% lossy pre-fix), 18/18 single-intent controls unaffected, golden-prompt harness (4 cases) passes, 3-rep/36-trial matrix shows zero spurious route_multi firings.

stage1_query_from_turns's suffix-stripping — sound, one latent edge case

routing.rs:422-444. The function reconstructs blended via build_retrieval_query, then does blended.strip_suffix(current) to split prior-context from current-message, where current = user_message.trim(). This is safe by construction: build_retrieval_query computes current the identical way (current_message.trim(), same string), and only pushes it onto parts when non-empty — so whenever current is non-empty, it is provably the last thing appended to blended, and strip_suffix cannot fail to match.

Latent edge case (not introduced by this PR, low severity): when user_message is empty/whitespace-only and prior_turns is non-empty, current is "". str::strip_suffix("") always returns Some(unchanged) — a no-op match — so prior_blended becomes the entire blended prior-turn text, and the function emits PRIOR CONTEXT: <all prior turns> / CURRENT REQUEST: (empty). This mislabels history as "prior" that includes what would otherwise have been the (blank) "current" turn, though the net text content shown to the model is unchanged from what an unlabeled blend would have shown — just with a label that's technically wrong on this input. run_turn has no visible blank-message guard before this point. Not a regression this PR needs to fix (a blank routing turn was already a degenerate case before this PR), but worth a one-line guard or comment if it's ever hit in practice.

Can stage1_query and stage1_query_from_turns drift apart?

No — by construction. stage1_query (agent_loop.rs:393-405) does nothing but extract prior_turns: Vec<&str> from session.messages (filtering to User/Assistant roles, excluding the just-pushed current message) and delegates entirely to stage1_query_from_turns. There is no duplicated logic between them for drift to occur in. The doc comment on stage1_query explicitly calls out that stage1_query_from_turns was extracted as a free function specifically so the golden-prompt test harness can build the identical Stage-1 message without constructing an AgentSession — and the harness (live_stage1_golden_prompts.rs) was in fact fixed in this PR's history to call stage1_query_from_turns rather than build_retrieval_query directly, closing the exact gap that let the original bug (route_multi over-firing on blended history) slip past golden-prompt testing. This is a good design — single source of truth, and the PR fixed a real test-harness/production mismatch along the way.

route_multi's retrieval fan-out cost — works, but uncapped and sequential

agent_loop.rs:2001-2030. For a Multi decision with N queries, the loop calls self.tool_executor.retrieve_skills(query, RETRIEVAL_TOP_K) sequentially, once per query (no join_all/FuturesUnordered/spawn — confirmed via grep, none present in this file). Each retrieve_skills call is itself an embedding call plus a vector KNN search (skill_ops::find_skills → semantic_search_nodes). Results are merged by skill id into a HashSet, sorted by score, and truncated to RETRIEVAL_TOP_K — so the final candidate count is correctly bounded regardless of N, matching ADR-038's requirement that the system, not the model, owns K.

Two related gaps:

  1. No upper bound on N itself. RouteMultiParams.queries: Vec<String> has no maxItems in the JSON schema (routing.rs:192-206) and parse_route_decision only enforces a lower bound (queries.len() < 2 → reject). Nothing stops a pathological or adversarial model output from listing, say, 20 "intents," which would mean 20 sequential embedding+search round-trips before Stage-1 latency is even accounted for. In practice STAGE1_MAX_TOKENS: u32 = 256 puts a soft ceiling on how many queries the model can physically emit in one generation, and the tool description explicitly asks for "one short query per distinct intent," so this is unlikely to be hit organically — but it's an unenforced assumption, not a structural guarantee. A small queries.len() > K rejection (or silent truncation) in parse_route_decision, mirroring the < 2 guard already there, would close this cheaply.
  2. Sequential rather than parallel fan-out multiplies Stage-1's already-measured-and-documented latency overhead by N for genuinely compound requests. This is a reasonable v1 choice — retrieval fan-out for a compound request is inherently rarer than the single-query path, and correctness (dedup, capping) is simpler to reason about sequentially — but it's worth flagging as a known cost characteristic, not something this review demands be fixed now. If compound-intent routing becomes common, this is the first place to look.

Neither of these blocks merge; the PR's own goal (fix a confirmed 45%-lossy defect, add a third typed tool per ADR-038's doctrine) is achieved regardless. Flagging both as things worth a follow-up issue or comment rather than blocking changes.

RouteMultiParams validation — correct, well-tested for parsing

routing.rs:115-119, 238-255. serde(deny_unknown_fields) guards against the model sending unexpected keys. parse_route_decision trims each query, drops blanks, and requires 2+ non-empty entries after filtering — correctly treating a one-element "multi" (or an all-blank array) as "no decision" rather than trusting a degenerate compound call, falling through to unrouted retrieval on the raw message (consistent with the existing route_query/route_clarify "no decision" fallback philosophy). Well covered by routing.rs's unit tests: route_multi_parses_two_or_more_queries, route_multi_with_fewer_than_two_usable_queries_yields_no_decision, route_multi_trims_and_drops_blank_entries_among_valid_ones.

Should-fix: no non-live test exercises the Multi fan-out path in agent_loop.rs

This is the one finding I'd ask to be addressed (or explicitly deferred with a reason) before merge. Searched agent_loop.rs's test module directly: the RouteDecision::Multi arm of the routing block (lines 1944-1949) and the merge/dedup/cap loop that follows (lines 2001-2030) have zero coverage from a MockEngine-driven unit test. Compare to the Query path, which is exercised by routed_engine-based tests throughout the file (e.g. multi_skill_turn_invokes_skill_tools_between_searches, the duplicate-write guard tests, etc.) — there is an existing RoutingToolExecutor test double (agent_loop.rs:6591-6611) built exactly for asserting which queries retrieval was actually issued for, and it is never driven with a route_multi tool call.

Everything that does exercise the fan-out today is either:

  • routing.rs's unit tests — parsing only, never reach agent_loop.rs's merge loop, or
  • The #[ignore]d live tests (live_stage1_compound_intent.rs, live_stage1_golden_prompts.rs) — require a ~5-9GB GGUF on disk and are not part of cargo test -p nodespace-agent --lib / default test:all, so they don't run in CI-equivalent gates and wouldn't catch a regression in the merge/dedup/cap logic itself (e.g., an off-by-one in the RETRIEVAL_TOP_K truncate, a dedup key mistake, or the per-query error-continue behavior at line 2020 silently swallowing all failures).

A fast unit test using MockEngine + RoutingToolExecutor — model emits route_multi with 2-3 queries, assert queries_handle() recorded one retrieval call per query, assert the merged/deduped/capped candidate set matches expectations, assert a duplicate skill id across two queries counts once — would close this gap cheaply and would have been exactly the kind of test to catch a regression in the new code this PR actually adds (as opposed to the routing decision parsing, which is well covered). This is squarely "new code with no non-live test," which is the class of gap pragmatic-code-review treats as a should-fix rather than a nit.

Everything else

  • cargo test -p nodespace-agent --lib: 429 passed, 0 failed, 1 ignored — confirmed by direct run.
  • cargo clippy -p nodespace-agent --all-targets -- -D warnings -D clippy::unused-async: clean — confirmed by direct run.
  • .gitignore addition (stage1-compound-intent-latest.txt) mirrors the existing routing-matrix-latest.txt pattern and rationale — consistent, no issue.
  • The merge commit that resolved a conflict in live_stage1_golden_prompts.rs (adding Multi arms to 4 match blocks) looks mechanically correct — each arm either prints the parsed queries or (for scenario 6, a single-intent case) panics with a clear message if route_multi incorrectly fires, matching the existing pattern for the other two decision variants at each site.
  • Doc comments throughout routing.rs and agent_loop.rs are unusually thorough and specifically call out why (measured findings, prior regressions, ADR references) rather than just what — consistent with this codebase's existing style and genuinely useful for a future reader.
  • Scope match against Stage-1 has no move for compound, unambiguous requests (multiple intents in one message) #1909's acceptance criteria: the live-reproduction, recommendation, and sample-widening criteria were already checked off pre-PR; this PR closes "Implement route_multi as a third typed Stage-1 tool" and claims (in the PR description, not independently re-verified by this review beyond the unit/clippy checks above) the "full routing/retrieval matrix run before merging" criterion via the 3-rep/36-trial result described in the PR body. The optional repeat-run-for-variance criterion remains explicitly non-blocking per the issue text.

Summary

The core mechanism — route_multi, the labeled prior-context/current-request framing, and the fix to the golden-prompt harness that let the original bug slip past it — is well-designed, consistent with ADR-038/ADR-064's channel doctrine, and backed by real live-model validation with honest, appropriately-hedged findings. The suffix-stripping logic is correct by construction for all non-degenerate inputs. The retrieval fan-out correctly bounds the output (RETRIEVAL_TOP_K) but not the input (N queries), which is a minor unenforced assumption rather than a bug. The one thing I'd want addressed before/shortly after merge is unit-test coverage for the Multi fan-out path in agent_loop.rs itself, since that's genuinely new logic (not just new parsing) that currently has no non-live safety net.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Address review: fan-out/dedup unit test added

Addressed the one should-fix from the review: route_multi's retrieval fan-out and merge/dedup logic (agent_loop.rs's RouteDecision::Multi arm) was previously covered only by #[ignore]'d live tests, not in default test:all.

Added route_multi_issues_one_retrieval_per_query_and_merges_deduped_candidates, a mocked-engine test asserting: retrieval fires once per route_multi query, in order; a candidate matching both queries appears exactly once in Stage 2's injected prompt (not duplicated). Verified this actually catches a regression — temporarily removed the dedup check, confirmed the test failed, then reverted.

Not fixed (per the reviewer's own severity call, both were low-severity notes, not should-fix items):

  • The blank-current-message edge case in stage1_query_from_turns — pre-existing pattern, not introduced by this PR, and no blank-message path exists upstream in run_turn today.
  • route_multi's query count has no structural cap beyond STAGE1_MAX_TOKENS's soft limit — flagged as worth a follow-up if it proves a real problem, not blocking here.

bun run test:all and the pre-push gate both pass. Pushed as 99d2467e.

@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The single should-fix finding was a missing unit test for already-implemented, already-reviewed logic (route_multi's fan-out/merge/dedup) — no production code changed, no new behavior, no design change. The added test was verified to actually catch a regression (dedup temporarily removed → test failed; reverted → test passed) before committing, so it isn't resting on unverified trust. The two lower-severity notes from the review were explicitly left unaddressed per the reviewer's own severity call, not silently skipped.

Ready for merge, pending your go-ahead.

@malibio
malibio merged commit 2002fa8 into main Aug 3, 2026
2 checks passed
@malibio
malibio deleted the issue-1909-stage1-compound-intent branch August 3, 2026 01:18
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.

1 participant