Repository navigation
Description
Overview
Close the gap between ADR-038's Accepted routing decision and the shipped implementation, which is the alternative that ADR explicitly rejects.
Problem Statement
packages/agent/src/local_agent/agent_loop.rs:415-423 hands the model all 14 tools each turn with search_skills among them, commented "No pre-filtering". ADR-038 rejects this under Alternatives Considered: "Keeping retrieval as a model tool-call (single-turn pull) was also rejected: it removes the system's ability to bound K and enforce the trust boundary."
Missing:
- Stage-1 — the model's structural
queryvsclarifychoice. Not implemented; the model goes straight to tool calls - Stage-2 — two independently-sourced gates (retrieval score AND the model's judgment).
packages/core/src/ops/skill_ops.rs:22sets the score threshold to0.0, collapsing two gates into one - Blast-radius scaling — the confidence bar should be a property of the matched skill, higher for mutating skills than read-only ones
The 0.0 threshold is a reasoned choice, not an oversight. Its comment explains that a non-zero floor would silently hide the long tail from an LLM meant to judge confidence itself. That is correct under a single-gate design and only becomes wrong once the judged gate exists. Raising the constant without building Stage-2 would hide the long tail with nothing judging it — the two must land together.
This divergence is now recorded in ADR-038 itself so it is not rediscovered as a new finding. The scaling argument behind the decision still holds, so the decision stands and the code is what changes. (The comment at agent_loop.rs:415 also miscites ADR-036 for ADR-038; fix while there.)
Evidence
packages/agent/src/local_agent/agent_loop.rs:415-423and its commentpackages/core/src/ops/skill_ops.rs:22—SKILL_SEARCH_THRESHOLD: f32 = 0.0- ADR-038: two gates, blast-radius scaling, and the rejection of single-turn pull
Carried caveat on the supporting end-to-end measurement. A bundled "proposed stack" scored 75% against 50% for current. One scenario carries the entire gap (schema creation, 0/3 → 3/3) and two scenarios tie at 100%. The most parsimonious reading is that it measured the coreValues fix and little else. Do not cite that number as justification for this work — each component has independent evidence, and a bundled arm cannot attribute the delta.
Acceptance Criteria
- Stage-1 emits a discriminated
query | clarifyoutput — a structural choice, not a self-reported confidence number, which ADR-038 rejects explicitly - Retrieval runs as a deterministic system step rather than a model tool call, so K is bounded and the trust filter applies
- Stage-2 combines the retrieval score with the model's yes/no judgment — both gates, landed together with any threshold change
- The confidence bar is a property of the matched skill; mutating skills carry a higher bar
-
search_skillsis removed from the model-facing tool list - Clarification contract enforced: at most one per intent, then fall through to semantic search
- Latency measured. ADR-038 notes KV-cache reuse reduces but does not eliminate the extra-turn cost and requires it be measured rather than assumed
- The
agent_loop.rs:415comment's ADR miscitation corrected
Blocked by
- The instruction-delivery question — Stage-2's candidate-delivery mechanism is precisely what that resolves
- The resident-prompt reduction — building two-stage routing over unresolved channel conflicts yields a more expensive version of the same failures: more turns, same contradictions
- Verification depends on the agent eval being diagnostic
Architecture Impact
Completes the core of ADR-038. Sequenced last among behavioral changes deliberately.
Activity
malibio commentedon Jul 30, 2026
Baseline (worktree issue-1815-adr038-stage-gates): Frontend 171 test files passed, 4112 tests passed.
malibio commentedon Jul 30, 2026
Design questions before implementing the two-stage gates
Recording the open design decisions here rather than resolving them silently in code. Answers change the shape of the implementation, so they are worth settling on the issue.
Context established by reading the code:
packages/agent/src/agent_types.rs:287-296—InferenceRequestcarries exactlymessages,tools,temperature,max_tokens. There is no grammar, JSON-schema,response_format, ortool_choicesupport in either engine impl (inference.rsllama.cpp,openai_compat_inference.rsHTTP). The only forcing mechanism that exists today is settingtools: Noneto force a text reply (agent_loop.rs:1108).packages/agent/src/local_agent/tools.rs:1056-1103—Tool::write_semantics()already classifies every tool via an exhaustive match (Read/IdempotentWrite/SelfLimitingWrite/DuplicableWrite), withis_write()derived from it.tool_whitelist(skill_pipeline.rs:238-403), butskill_pipeline.rs:225-229notes the local agent currently ignores it — it is consumed only by external ACP agents.skill_pipeline.rsis seeding-only. The ADR-030 push pipeline is already deleted, so there is no legacy routing path to remove.available_tools()(tools.rs:2151) is DB-driven from seededtoolnodes, falling back to the hardcoded registry.Q1. Stage-2 candidate delivery — the blocker this issue names
Stage-2 must put the retrieved candidates (name + description + instruction subtree) in front of the model to be judged. That is exactly the channel ADR-064 leaves unresolved and marks ADR-038's delivery provision Provisional.
The evidence is split by channel, not by content:
create_schemacalls on both models.Options:
Proposed: option 1, on the grounds that it is the channel with supporting rather than adverse evidence.
Q2. How Stage-1 emits its
query | clarifychoiceADR-038 requires a structural discriminated output and explicitly rejects a self-reported confidence number. With no constrained-generation support at the inference boundary, there are two realistic mechanisms:
route_query(query)androute_clarify(question, options). Which tool the model calls is the discriminated output. Uses the channel measured strongest (tool schema 100% compliance vs prose 87.5%, ADR-064 Evidence), reuses the existingparse_chunkstool-call path, and needs no text parser.QUERY: …/CLARIFY: …and parse it. Relies on the weakest measured channel and adds a parser whose failures are hard to distinguish from model failures.Proposed: option 1.
Q3. Where the blast-radius bar lives
ADR-038 says the Stage-2 bar is "a property of the matched skill, not a single global constant". There is no
blast_radiusproperty on the skill schema today (core_schemas.rs:998-1055declares onlydescription,tool_whitelist,max_iterations).Options:
tool_whitelistviaTool::write_semantics(). A skill whose whitelist contains any write tool carries the higher bar; a read-only whitelist carries the lower one. No new hand-maintained field, no seed migration, and it cannot drift from the tools the skill can actually fire. This also givestool_whitelista real local-agent consumer for the first time.blast_radiusproperty to the skill schema and set it on all 8 seeds. More direct to read, but it is a second source of truth that can disagree with the whitelist.Proposed: option 1, deriving from the whitelist.
Q4. Threshold values
SKILL_SEARCH_THRESHOLD = 0.0(skill_ops.rs:24) is correct under the current single-gate design and must only move together with the judged gate — the issue is explicit on this. Once Stage-2 exists, the two bars need actual numbers. Absent a trustworthy eval (#1764), any specific pair is a guess.Proposal: introduce the two bars as named constants with the reasoning recorded at the definition site, keep them deliberately permissive to start, and treat tuning as work that follows #1764 rather than as part of this issue.
Q5. Plumbing — how retrieval reaches the loop
Retrieval must become a deterministic system step, but
LocalAgentLoopholds onlyengine,tool_executor, andprompt_assembler(agent_loop.rs:349-353).find_skillsneedsNodeEmbeddingService+NodeService, which live onGraphToolExecutorin thenodespace-agent→nodespace-coredirection.Options:
AgentToolExecutortrait with a retrieval method (e.g.find_skills(query, limit)), implemented byGraphToolExecutorand stubbed by mocks. Keeps the loop free of any directnodespace-coreservice dependency and preserves testability with the existing mock executors.LocalAgentLoopdirectly. Fewer indirections, but couples the agent loop to concrete core services and complicates every existing mock-based test inagent_loop.rs.Proposed: option 1.
Unless there are objections, implementation proceeds on the proposed options above.
malibio commentedon Jul 30, 2026
Verified the code claims underneath each proposal (
InferenceRequest's field set,write_semantics()'s exhaustive match,skill_pipeline.rs:227's "local agent ignores them" comment) — all hold. Proceed on all five as proposed. Two additions, no changes to the defaults themselves.Q1 (Stage-2 delivery channel) — agreed, option 1, with a measurement obligation attached. This is the one decision in the set that's actually resolving an open ADR-064 question rather than picking between two safe engineering options, so don't let it ship silently. Record the KV-cache-divergence cost ADR-038 asks for — even a rough before/after latency number — in this issue's closing comment. That's the input #1764's eventual matrix run needs to know whether the two-turn cost is a real regression or noise, and it's much cheaper to capture now than to reconstruct later.
Q2 (two typed tools for query/clarify) — agreed. Correctly avoids the parser-vs-model-failure ambiguity you flagged, and it's consistent with Q1 — both decisions land on "prefer the tool-schema channel over prose/parsing," which is the same channel ADR-064's evidence favors throughout. Worth naming that consistency in the PR description so a future reader sees the pattern rather than two independent choices that happen to agree.
Q3 (derive blast-radius from
tool_whitelist) — agreed, and this is the best of the five. Zero new state, cannot drift from what the skill can actually fire, and it resurrects a field that's been dead weight since the local agent started ignoring it. No notes.Q4 (threshold constants, deliberately permissive, tuning deferred to #1764) — agreed. Correctly declines to guess at numbers a broken eval can't validate. Make sure the constants' doc comments say why they're permissive (not yet tuned, blocked on #1764) so nobody "fixes" them to something stricter in the interim without knowing that's a regression against an untested target.
Q5 (widen
AgentToolExecutorover injecting services into the loop) — agreed. Keeps the loop's existing mock-based tests intact, which matters given how much of this workstream's evidence came from exactly that test-double pattern.Proceed on all five. Flag Q1's latency number specifically when you close this out — that's the one piece of data this decision owes the rest of the workstream.
malibio commentedon Jul 30, 2026
Implementation landed, plus a measurement result that contradicts my Q1 reasoning
The two-stage pipeline is built and the acceptance criteria are implemented. But the latency measurement turned up something that matters more than the latency number, and it argues against the Q1 decision you approved. Flagging it before merge rather than after.
The measurement caught a defect, not a win
The first benchmark run reported the routed arm 71% faster. That was not a win — the routed arm was making zero tool calls. It was faster because it was not doing the work. The wall-clock number alone would have been recorded as a success; the tool-round instrumentation is the only reason it wasn't.
This is exactly the failure mode #1764 describes: a clean, plausible number that reverses the conclusion once you look at raw output.
Isolating the cause
A four-arm diagnostic (
packages/agent/tests/routing_latency.rs,dump_one_routed_turn) on mistral:7b:create_nodecreate_nodeStage 1 is harmless. The extra routing turn costs latency but does not break tool-calling. The damage comes entirely from injecting the candidate block into the Stage-2 prompt — and a block containing only skill names, no instructions and no schema metadata, breaks it just as thoroughly as the full payload.
The operative variable is any injection at Stage 2, not payload size and not how procedural the payload is. ADR-064 predicts the opposite ("the operative variable is how procedural the payload is rather than how large"). On this model, that prediction does not hold.
On the locked production model it does not reproduce
Re-run against gemma4:e4b (ADR-056's locked model — the one that actually ships):
create_node×5create_node×3create_node×2create_node×5Every arm fires. The suppression is mistral-specific, not universal — so this does not block the design. Worth noting the secondary signal: the full instruction block cut redundant repeat calls from 5 to 2, while the names-only block did not. On Gemma the instructions appear to help it converge, which is the direction ADR-038 Finding 2 predicts.
Two real bugs fixed on the way
looks_like_narrated_tool_callonly detectedtool_name(...)— function-call syntax. Mistral emits the JSON form,[{"name":"create_node","arguments":{…}}], as text. The guard missed it, so the loop saw no tool call and the turn silently did nothing. Pre-existing gap, surfaced by this measurement; now detects both forms.Also: Stage 1 originally ran on every turn, taxing conversational turns that need no capability at all. It is now gated on retrieval actually being wired up (
routing_available()).What I'd like your call on
The Q1 decision (inject candidates into the Stage-2 prompt) is implemented as approved, and it works on the model we ship. But the evidence for it is now weaker than when we decided: I argued in-prompt injection was the channel with supporting rather than adverse evidence, and this measurement shows it carries its own adverse effect on at least one model — from the mere presence of the block, which neither ADR-038 nor ADR-064 anticipated.
Options as I see them:
My recommendation is 2. The design holds on the model we ship, and the mistral result is most useful as a regression guard on model changes rather than as grounds to redo the channel decision on a single-model result.
Latency numbers on the locked model to follow in the closing comment, per the obligation from your review.
malibio commentedon Jul 30, 2026
Latency measured (the obligation from your Q1 review) — PR #1826.
On
gemma-4-e4b-q4km(ADR-056's locked model), in-process, 3 prompts × 3 runs:Routing overhead: +419 ms (+13.0%).
Two things make this one believable where the earlier attempts were not:
tool rounds 1.00in both arms. Same work, done two ways. This is the check that invalidated the first result, where the routed arm scored −71% because it was making zero tool calls.N_CTX_MINIMUMof 16384).The prompt-token rise, 606 → 1121, is the injected candidate block — the KV-cache prefix divergence ADR-038 predicted, now with a number on it rather than an assumption.
For #1764's eventual matrix run: +13% is the cost of the extra turn on the shipped model, measured with same-work-both-arms enforced. The harness now panics rather than printing a number when turns fail to reach the model, so a repeat of the second failure mode cannot be recorded as a result.