Skip to content

Implement ADR-038 Stage-1 and Stage-2 gates; shipped loop is the rejected single-turn pull #1815

Closed

Description

@malibio

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 query vs clarify choice. 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:22 sets the score threshold to 0.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-423 and its comment
  • packages/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 | clarify output — 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_skills is 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:415 comment'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

  1. malibio commented on Jul 30, 2026

    @malibio
    CollaboratorAuthor

    Baseline (worktree issue-1815-adr038-stage-gates): Frontend 171 test files passed, 4112 tests passed.

  2. self-assigned this
    on Jul 30, 2026
  3. malibio commented on Jul 30, 2026

    @malibio
    CollaboratorAuthor

    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 — InferenceRequest carries exactly messages, tools, temperature, max_tokens. There is no grammar, JSON-schema, response_format, or tool_choice support in either engine impl (inference.rs llama.cpp, openai_compat_inference.rs HTTP). The only forcing mechanism that exists today is setting tools: None to 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), with is_write() derived from it.
    • All 8 seeded skills already carry a tool_whitelist (skill_pipeline.rs:238-403), but skill_pipeline.rs:225-229 notes the local agent currently ignores it — it is consumed only by external ACP agents.
    • skill_pipeline.rs is 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 seeded tool nodes, 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:

    • In-prompt injection is what ADR-038 Finding 2 actually measured — rendering the real Schema Creation subtree into the prompt produced flawless deeply-nested create_schema calls on both models.
    • Tool-result delivery is what currently ships, and is the channel measured to drop continuation from 100% to 44% and yield prose instead of tool calls. ADR-064 rule 4 reserves tool results for facts rather than procedures.

    Options:

    1. Inject candidates into the Stage-2 prompt. Matches the measured-good channel and ADR-064 rule 4. Cost: the Stage-2 prompt diverges from Stage-1's cached prefix at the injection point — which ADR-038 already anticipates and asks be measured rather than assumed.
    2. Keep tool-result delivery. Least code change, preserves current KV-cache behavior, but builds the new gate on the channel with the adverse measurement.
    3. Build both behind a runtime flag. Turns the ADR-064 open question into a measurable A/B against the real two-stage loop instead of a judgment call. More code, and the measurement is only trustworthy once Make the agent eval diagnostic before recording a baseline; revisit ADR-056's Scenario 5 claim #1764 lands.

    Proposed: option 1, on the grounds that it is the channel with supporting rather than adverse evidence.

    Q2. How Stage-1 emits its query | clarify choice

    ADR-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:

    1. Two typed tools — offer Stage-1 exactly route_query(query) and route_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 existing parse_chunks tool-call path, and needs no text parser.
    2. Prose convention + parser — instruct the model to emit 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_radius property on the skill schema today (core_schemas.rs:998-1055 declares only description, tool_whitelist, max_iterations).

    Options:

    1. Derive it from the matched skill's existing tool_whitelist via Tool::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 gives tool_whitelist a real local-agent consumer for the first time.
    2. Add an explicit blast_radius property 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 LocalAgentLoop holds only engine, tool_executor, and prompt_assembler (agent_loop.rs:349-353). find_skills needs NodeEmbeddingService + NodeService, which live on GraphToolExecutor in the nodespace-agent → nodespace-core direction.

    Options:

    1. Widen the AgentToolExecutor trait with a retrieval method (e.g. find_skills(query, limit)), implemented by GraphToolExecutor and stubbed by mocks. Keeps the loop free of any direct nodespace-core service dependency and preserves testability with the existing mock executors.
    2. Inject the services into LocalAgentLoop directly. Fewer indirections, but couples the agent loop to concrete core services and complicates every existing mock-based test in agent_loop.rs.

    Proposed: option 1.


    Unless there are objections, implementation proceeds on the proposed options above.

  4. malibio commented on Jul 30, 2026

    @malibio
    CollaboratorAuthor

    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 AgentToolExecutor over 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.

  5. malibio commented on Jul 30, 2026

    @malibio
    CollaboratorAuthor

    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:

    Arm Block injected at Stage 2 Tool call
    baseline (no routing) none ✅ create_node
    Stage-1 only, retrieval returns nothing none ✅ create_node
    routed + full instructions yes ❌ none
    routed + candidate names only yes ❌ none

    Stage 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):

    Arm Tool calls
    baseline create_node ×5
    Stage-1 only create_node ×3
    routed + full instructions create_node ×2
    routed + names only create_node ×5

    Every 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

    1. looks_like_narrated_tool_call only detected tool_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.
    2. Stage-1 token usage was dropped from the turn's reported total, hiding the cost of the extra turn from every consumer of that figure.

    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:

    1. Ship as-is. It works on the locked model, and the failure is confined to a model we do not ship. Record the mistral result as a known constraint on future model changes.
    2. Ship, and make it a gate. Add the four-arm diagnostic as a required check when the locked model changes, so a future model swap cannot silently reintroduce this.
    3. Reopen Q1. Treat the mistral result as evidence the injection channel is riskier than judged and re-evaluate against the tool-result channel — noting that channel has its own adverse measurement (100% → 44%).

    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.

  6. malibio commented on Jul 30, 2026

    @malibio
    CollaboratorAuthor

    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:

    Arm Mean Median Tool rounds Tokens
    single-turn (baseline) 3231 ms 3044 ms 1.00 606 in / 88 out
    two-stage (routed) 3650 ms 3534 ms 1.00 1121 in / 65 out

    Routing overhead: +419 ms (+13.0%).

    Two things make this one believable where the earlier attempts were not:

    • tool rounds 1.00 in 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.
    • Non-zero tokens in both arms. This is what invalidated the second, where a confident 299 ms vs 612 ms table came from a run in which all 18 turns had errored without reaching the model (Ollama was serving a 4096 context against the engine's N_CTX_MINIMUM of 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions