Skip to content

Record skill, schema and operation selection as named decisions, with a measured Gemma baseline - #2842

Merged
malibio merged 9 commits into
mainfrom
issue-2802-decision-seam
Sep 22, 2026
Merged

malibio merged 9 commits into
mainfrom
issue-2802-decision-seam

Conversation

@malibio

@malibio malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Closes #2802.

Makes the three selections an agent turn performs — which skill, which schema, which operation — named, recorded, and scoreable, instead of leaving them implicit inside Gemma's generative pass.

Why

Both of ADR-056's recorded E4B failures are decision failures, not generation failures — a wrong operation, and a turn that stopped after the read without the write. Neither was separable from the scenario result containing it, and that ADR says plainly that the existing matrix scores "describe the harness as much as the model." There was no way to ask "how often does the agent pick the right schema?" except by inference from end-to-end pass/fail.

This does not change who decides. The model still makes every call exactly as before; removing this code would change no behaviour. What it adds is a record of what was on offer and what was chosen.

What's here

  • local_agent::decisions — a DecisionRecord carrying the candidate set alongside the outcome. An outcome alone is not scoreable: whether calling search_nodes was right depends on what else was offered.
  • Three decision kinds. skill is upstream of the other two and is not a model decision at all — it is deterministic retrieval plus a score bar — but it constrains them, so a turn routed to Node Creation never sees create_schema and reads as a wrong-tool failure when retrieval was what went wrong.
  • Harness plumbing — log markers → TurnRecord.decisions, parsed per ReAct round.
  • bun run eval:decisions — a fixture scoring each decision independently, so a failure names which of the three went wrong.
  • Stage-1 cost capture (routingMs) — the wall-clock of one generative pass whose entire output is a 3-way structural choice.

Not a third gate

ADR-038 establishes two independently-sourced gates and warns explicitly against "inventing a third number." Nothing here gates, filters, or rejects. The candidate sets recorded are the ones the pipeline already computed (stage2_tools, the retrieved schema metadata, find_skills' own output); the outcomes are the ones the model already produced. The existing score bars are untouched.

Measured baseline

3 reps, purged database between each, gemma-4-e4b-q4km, on this branch rebased onto current main:

Category pass^3
Skill routing 3/3
Operation selection 4/4
Instance-vs-type boundary 3/3
ADR-056 known failures 2/2
Schema selection 0/3
Off-menu type named 0
Stage-1 decision cost 1602 / 1638 / 1692 ms

Zero variance — every scenario passed 3/3 or failed 0/3. An earlier run against pre-#2815 code produced identical category scores, which is reassuring rather than coincidental: the failure is upstream of anything that fix touched.

All three schema failures are one failure, and it is not schema selection. Candidates were offered and the model called no tool at all, asking for a node ID instead:

"Add Northwind Trading to the companies we sell to."
  skill=Node Creation   candidates=company_sold_to, event_venue, sponsor
  operation=none  schema=none  tools called: []
  → "Could you confirm what you'd like me to do?"

It could not resolve the name "Northwind" to a node. That is a lookup, not a judgment — tracked as its own design problem in #2841, which this PR does not attempt.

What the instrumentation caught while being built

  • A schema named off-menu that retrieval never offered (delivery job vs the registered delivery_job) — a format error, invisible in end-to-end scoring.
  • Core seeded types are filtered out of schema candidates, so a turn acting on one records an empty candidate set — unconstrained generation, not a selection.
  • Two fixture bugs, each caught by the scorer's distinction between "the right option was never offered" and "the wrong option was chosen."

Review notes

  • decisions.rs is the substance; the rest is plumbing and fixture.
  • Marker format is a contract. decision_candidates is emitted last on each log line because tracing leaves string fields unquoted and a comma-separated list of names cannot be delimited by anything shorter than the line end — routed_skills is ordered that way for the same reason. A commit here fixes the mirror of that bug: selected was matched as a non-whitespace run, truncating "Schema Creation" to "Schema".
  • Fixture asserts on properties, not ids. create_schema derives ids from the model's phrasing ("companies we sell to" → company_sold_to), so an assertion naming company fails as a naming mismatch wearing a decision error's clothes. Two full 3-rep runs were spent learning that.
  • --between-runs is load-bearing. Without it rep 1's created schemas persist into reps 2-3 and the reps stop being independent observations.

🤖 Generated with Claude Code

malibio and others added 7 commits September 22, 2026 14:21
Both selections existed only as emergent properties of whatever tool call
the model emitted, so neither could be scored except through end-to-end
scenario pass/fail — which ADR-056 states "describe[s] the harness as much
as the model". Both of that ADR's own E4B failures are decision failures.

Adds local_agent::decisions: a DecisionRecord carrying the candidate set
alongside the outcome (an outcome alone is not scoreable — whether calling
search_nodes was right depends on what else was offered), and emits one
structured log line per decision per round.

No gate, no threshold, no behaviour change. ADR-038 warns against
"inventing a third number"; the candidate sets recorded are the ones the
pipeline already computed and the outcomes are the ones the model already
produced.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Scrapes the two "Agent decision" log lines into [decision ...] markers and
parses them onto TurnRecord, so a fixture can score the selections directly
instead of inferring them from end-to-end pass/fail.

decision_candidates is emitted LAST on each log line: tracing leaves a
string field unquoted when it can, and a comma-separated list of names
cannot be delimited by anything shorter than the line end. routed_skills is
ordered that way for the same reason, and a scrape that assumed otherwise
silently matched nothing.

Absent markers parse to undefined rather than [], so a results file from a
build predating them stays distinguishable from a turn that genuinely made
no decision.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Scores schema and operation selection directly rather than inferring them
from end-to-end pass/fail. Each scenario asserts on ONE decision, so a
failure says which of the two went wrong instead of collapsing both into
one verdict.

Scenarios run against a workspace carrying two overlapping types, because a
decision is only scoreable when there was something to decide between: a
single-schema workspace makes every schema selection trivially correct and
measures nothing. The setup turns that build it are marked `setup` so a
failure there is not counted many times downstream.

Covers ADR-056's two recorded E4B decision failures, the disambiguation
shape where several types plausibly match the wording, and the case where
the right answer is to call no tool at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two runs were spent measuring the fixture rather than the model. The cause
was assertions naming exact type ids: create_schema derives the id from the
MODEL's phrasing, so "companies we sell to" became company_sold_to and the
assertion on `company` failed as a naming mismatch wearing a decision
error's clothes.

Schema expectations now assert the property being scored — did it stay on
the retrieved menu, and which of two candidates did it pick — rather than an
id the fixture cannot predict.

Also drops core seeded types from the fixture entirely. Measured directly:
"How many projects do we have?" records `selected=project [off-menu]
candidates=` because parse_and_filter_non_core_schemas strips core types from
candidates. That is unconstrained generation, not a selection, and scoring it
would measure the is_core filter.

Adds [routing ms], capturing Stage-1's own latency — one generative pass for
a 3-way structural choice, measured at 1.5-1.7s. Kept separate from turn
latency because a decision-model comparison turns on cost and accuracy
independently.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The two decisions recorded so far sit downstream of the layer where the
observed failures actually happen. Stage-1 retrieval matches an embedding of
the message against skill descriptions (ADR-064 rule 3); by the time tool
descriptions matter, stage2_tools has already scoped the surface. A
type-definition request routed to Node Creation never sees create_schema at
all, so the turn reads as a wrong-tool failure when retrieval was what went
wrong — and the two have different fixes.

Records every retrieved candidate, including below-bar ones: "retrieved but
scored under its blast-radius bar" and "never retrieved" are different
failures, and a list filtered to gate-clearers cannot tell them apart.

Adds three instance-vs-type scenarios. A schema IS a node, so the boundary is
abstraction level rather than kind of thing, and it carries the larger blast
radius — a spurious type definition is worse than a spurious record. Both
skill descriptions already encode the distinction and retrieval still
misrouted the indirect phrasing during development, so these score embedding
similarity, not instruction quality.

One scenario was reworded after the contamination guard rejected it for
sharing five consecutive words with create_schema's own description.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both the log scrape and the results parser matched `selected` as a
non-whitespace run, so "Schema Creation" arrived as "Schema". tracing quotes
a string field when it contains a space, and skill names do — tool names and
type ids never do, which is why this was invisible until skill routing was
recorded.

Regression tests on both sides use a verbatim live daemon line.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The code-reference ratchet blocked the push: two module doc comments linked
ADR-056 and ADR-038 as relative paths into nodespace-docs. CLAUDE.md's
documentation standard is to reference decisions by ADR number and describe
the constraint directly, which is also what keeps a code comment from going
stale when a doc moves.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2842

Review Type: Initial Review
Scope: 12 files, +1317/-1 across packages/agent (Rust) and scripts/ (TS harness + fixture)
Verdict: APPROVE with one important finding — net-positive, well-tested, and the finding below is a one-line fix that does not block the instrumentation's value.


Summary

This is a genuinely good change, and unusually so for instrumentation. It does the hard part right: it records the candidate set alongside the outcome, which is the difference between a log line and a scoreable decision. The DecisionRecord doc comment argues that point explicitly and the fixture's scorer then uses it — "the right option was never offered" vs "the wrong option was chosen" produce different failure strings with different implied fixes. That distinction is the whole reason this earns its keep over the existing end-to-end matrix.

The behaviour-neutrality claim holds. I traced every call site: the three tracing::info! blocks sit between the "inference round completed" log and the if tool_calls.is_empty() branch, read only already-computed values (routed.candidates, tools, tool_calls), and write nothing back. decisions.rs exports no mutating API. Removing the module would change no behaviour, as claimed.

Discipline worth calling out: the PR reports a 0/3 category in its own description and then correctly diagnoses it as not schema selection (the model resolved no node id, called no tool) and routes it to #2841 rather than tuning the fixture until it went green. That is the instrumentation working as intended on its first use, and it is the strongest evidence that the seam was worth building.

Verification performed (not taken on faith):

  • 18/18 Rust unit tests in decisions.rs pass.
  • 92/92 TS tests pass (aichat.test.ts + runner.test.ts).
  • guidance_is_not_contaminated_by_eval_prompts passes, and I confirmed it enumerates scripts/eval/fixtures/ rather than naming files — so decisions.ts is covered automatically, as the fixture's header claims.
  • check-code-references.test.ts ratchet passes (the ADR-path violation fixed in 85caab02 is genuinely resolved).
  • cargo fmt --check clean, cargo clippy clean. No #[allow(...)], no #[deprecated], no any, no console.log.

Requirements Check — Issue #2802

Acceptance criterion Status
Schema selection is a named decision recording candidates + outcome ✅ record_schema / DecisionKind::Schema
Operation selection is a named decision recording candidates + outcome ✅ record_operation / DecisionKind::Operation
Both emitted on structured log, consistent with routed_skills ✅ Same comma-separated shape, same last-on-line placement, deliberately mirrored
Eval fixture scores both independently of end-to-end pass/fail ✅ scripts/eval/fixtures/decisions.ts, one assertion per scenario
Cases include ADR-056 Scenario 5 + Scenario 6, plus multi-schema cases ✅ op-list-by-type (adr056), op-read-then-write (adr056), schema-field-disambiguates / schema-shared-name-signed (ambiguous)
Fixture prompts independent of agent_guidance.rs ✅ Verified the guard runs against this file and passes
Recorded Gemma 4 E4B baseline with rep count stated ✅ 3 reps, purged DB between, per-category table in the PR body, zero variance
No new threshold or gate; score bars unchanged ✅ Confirmed — READ/MUTATING/DESTRUCTIVE_SKILL_SCORE_BAR untouched; record_skill reads clears_score_gate but never filters on it
Tests pass ✅
quality:fix clean ✅ fmt + clippy clean

Exceeded scope, justifiably: the issue asked for two decisions; this delivers three. The added skill decision is well-argued — it is upstream of the other two and constrains them, so without it a retrieval miss is indistinguishable from an operation miss, and the two have different fixes. Commit b289674c's message makes that case properly.


Findings

🟡 Important

📁 packages/agent/src/local_agent/decisions.rs:186-196 — record_skill reports a tool-less schema-typed candidate as the skill that led the turn

The doc comment states the selection is "the top gate-clearing candidate: the one whose whitelist leads stage2_tools." The implementation is:

selected: candidates
    .iter()
    .find(|c| super::routing::clears_score_gate(c))
    .map(|c| c.name.clone()),

Those two are not the same predicate, and the codebase already knows it. routing::stage2_permitted_names deliberately does not take the first gate-clearer — it uses top_tool_bearing_score, which filters on clears_score_gate(c) && !c.tools.is_empty(). That filter exists because of a named, twice-fixed bug, documented at routing.rs:361-376:

"a candidate that whitelists no tool must not influence which tool-bearing candidate wins … Today's producer of such candidates is schema-typed retrieval hits … One clears the gate unconditionally at the read rung while the lexical backstop pins it at a fixed confidence above any cosine-derived score a real skill can reach — so on every turn where a schema was named outright it took the top score away from a genuinely matching skill. Both consumers below were separately broken by exactly that."

This is the third consumer, broken the same way. Tracing the mechanism end to end:

  • skill_ops.rs:46 — const LEXICAL_SCHEMA_MATCH_CONFIDENCE: f64 = 1.0;
  • skill_ops.rs:377-378 — any non-core schema whose id or content is mentioned in the query is appended at that confidence.
  • skill_ops.rs:586-595 — the emitted candidate is { name: schema.content, kind: "schema", tools: [], confidence: 1.0 }.
  • agent_loop.rs:3304-3308 — candidates are sorted score-descending, so a 1.0 always sorts first.
  • SkillCandidate (agent_types.rs:596) carries no kind field, so record_skill cannot see it is a schema and reports name as though it were a skill.

The consequence is not hypothetical for this PR specifically: it lands on exactly the scenarios this fixture was built to score. Every schema scenario names its type outright by construction — "Add Northwind Trading to the companies we sell to", "Northwind can seat 200 people now" — which is precisely the trigger for the lexical backstop. So [decision skill] selected=… on those turns is likely to name the matched schema, not the routed skill, while stage2_tools scoped the surface from a different candidate entirely. The recorded skill decision and the actual tool scoping disagree, silently.

It also puts a latent false-negative in skill-instance-request, whose expectation is matches: /node creation|graph editing|organization/i. A schema named "Companies Sold To" would fail that regex and be reported as a routing failure that never happened — the exact class of "fixture bug wearing a model bug's clothes" the PR description says cost two full 3-rep runs to learn.

Principle: DRY over a safety invariant. routing.rs names this rule once, specifically so call sites cannot diverge by coincidence — its own doc comment says "which is why the rule is one named thing rather than a coincidence between call sites." A fourth reader of candidate ranking should reuse the rule, not re-derive it.

Suggested fix (one line, plus a regression test mirroring a_zero_tool_candidate_cannot_withhold_the_winning_skill_s_destructive_tool):

.find(|c| super::routing::clears_score_gate(c) && !c.tools.is_empty())

Better still, expose the rule from routing (e.g. pub fn leading_tool_bearing_candidate(&[SkillCandidate]) -> Option<&SkillCandidate>) and have stage2_permitted_names and record_skill both call it, so a fifth consumer inherits it for free.

One nuance to decide alongside the fix: the tool-less candidate arguably should still appear in candidates, since "a schema hit outscored every skill" is itself diagnostic. Only selected needs correcting.


🟢 Suggestions

📁 packages/agent/src/local_agent/decisions.rs:186-190 — the score-sorted precondition is relied upon but not asserted

.find() returns the first gate-clearer, which is the highest-scoring one only because agent_loop::route sorts descending (agent_loop.rs:3304) and single-query retrieval returns sorted. The doc comment says "in score order" descriptively but does not flag it as a precondition. top_tool_bearing_score faced the identical question and chose an explicit fold(max) with a stated rationale: "a safety property should not depend on another function's ordering staying that way." Recording is not a safety property, so .find() is a defensible cheaper choice — but the asymmetry deserves one sentence, e.g. "Relies on route's score-descending sort; an explicit max would be sturdier but this is a record, not a gate." Principle: make implicit preconditions explicit at the boundary that depends on them.

📁 packages/agent/src/local_agent/agent_loop.rs:2001-2012 — the iteration == 0 guard is fragile to an early-returning round

The skill decision emits only when iteration == 0. That is the right intent (one retrieval per turn), but it is coupled to round 0 always reaching this line. If a guard or error path ever returns before it, the turn silently records no skill decision — and the fixture then reports "either the daemon predates the [decision skill] marker, or the turn never reached retrieval", which would misattribute a code path to a stale build. Emitting it immediately after routing completes (next to the existing "two-stage routing overhead" line) would make it structurally unconditional rather than positionally so. Principle: prefer structural invariants to positional ones.

📁 scripts/eval/runner.ts:141-165 vs scripts/aichat.ts:254-284 — the marker format is a contract split across two regexes with no shared definition

The PR is right that decision_candidates must be last on the line, and the reasoning is sound: tracing leaves a string field unquoted when it can, and a comma-separated list of names admits no shorter delimiter. Commit a2efc692 is a good catch — quoting is value-dependent (tracing quotes on embedded spaces), so the selected field is quoted for skills and bare for tool names, and both forms must be handled. The fix handles both, and both sides carry verbatim-daemon-line regression tests. Good.

The residual risk is that the contract is asserted in three places (Rust emitter comment, aichat.ts scrape, runner.ts parse) and enforced in none. A single test that runs a real tracing line through both the scrape and the parse — i.e. an emitter→scrape→parse round-trip fixture — would pin it. candidates_field_is_comma_separated_like_routed_skill_names tests the Rust half only; the TS tests use hand-written strings that a future emitter change would not invalidate. Principle: a cross-language contract wants one executable specification, not three prose restatements.

Worth noting a latent edge the current format cannot express: a skill name containing a literal ", " would round-trip as two candidates. Not a problem today (skill names are curated), but if user-defined skills ever land, the format needs escaping. A comment recording the assumption would be enough for now.

📁 packages/agent/src/local_agent/decisions.rs:242-268 — schema_scoped's exhaustive match is right; two classifications are worth a second look

The design choice is correct and I'd defend it: enumerating both arms so a new Tool variant is a compile error, rather than _ => false silently answering "no", is the same discipline Tool::ALL_IS_COMPLETE enforces. I checked all 21 variants against the enum — the match is complete and compiles, so nothing is missing.

Two judgment calls to confirm rather than change:

  • ResolveQuery → schema-scoped. Reasonable if it takes node_type, but it is the one entry where "resolves a query" could plausibly carry no type argument. Worth a one-line confirmation that it does.
  • CreateNodesFromMarkdown → not schema-scoped. If that tool can create typed nodes, its turns make a real schema selection that is currently invisible to the record — and silent absence is the failure mode this module exists to eliminate. If it is genuinely untyped, a brief // note would stop a future reader re-litigating it.

📁 packages/agent/src/local_agent/decisions.rs:213-225 — schema_candidates() allocation per round is fine; noting it only to close the question

This runs once per ReAct round over at most RETRIEVAL_TOP_K (3) candidates, each holding at most MAX_SEMANTIC_SCHEMAS (5) descriptors — so ≤15 iterations with a linear seen.contains over a ≤15-element Vec. Against a 1.5-1.7s routing pass and multi-second inference rounds, this is unmeasurable. Vec + linear scan is also the correct choice over a HashSet here, because insertion order is load-bearing (presentation order is recorded deliberately, per the candidates doc comment) and at n≤15 a Vec scan beats hashing anyway. No change wanted. Principle: KISS — the simple structure is also the faster one at this cardinality.

📁 scripts/eval/fixtures/decisions.ts:1-6, 33-35 — module docstring is now stale on the three-decision count

The header says "scores the two selections the agent makes per round" and lists only schema / operation; the Expected union and the summary block both carry skill as a third. Same in decisions.rs:1-3 ("the two selections") and types.ts:157 ("The named schema/operation decisions"). Commit b289674c added the third kind and did not sweep the prose. Cosmetic, but these comments are unusually load-bearing in this codebase — they are the thing a future reader trusts over the code. Principle: comments explain intent, so a stale count misstates the intent.


Nitpicks

  • Nit: 📁 bun.lock:3 — this PR removes "configVersion": 0, which is unrelated to the change and looks like churn from a different Bun version (local is 1.2.16). Harmless but it makes the diff non-atomic; worth reverting to keep the commit's purpose single.
  • Nit: 📁 scripts/eval/fixtures/decisions.ts:352-357 — extra.routingMs sums routingMs across turns while the summary then means-averages those sums, so a multi-turn scenario contributes a larger "mean". With today's one-scored-turn scenarios the numbers are right; a mean-of-means would stay right if a scenario ever spans turns.
  • Nit: 📁 scripts/eval/fixtures/decisions.ts:236-246 — expected.oneOf.length === 0 implements an "expect no tool call" case that no scenario currently uses. Given CLAUDE.md's YAGNI stance, either add the scenario (the fixture header mentions "the case where the right answer is to call no tool at all", so one may have been intended) or drop the branch.
  • Nit: 📁 packages/agent/src/local_agent/decisions.rs:437-441 — kind_wire_names_are_stable asserts Schema and Operation but not Skill. The test's stated purpose is that a rename cannot silently break recorded baselines, so all three belong in it.

Recommendation

APPROVE — this is comfortably net-positive and should land. The architecture is sound, the behaviour-neutrality claim verifies, test coverage is strong on both sides of the language boundary, and the code-comment quality is genuinely above average for this kind of plumbing.

The 🟡 record_skill finding is worth fixing before merge rather than after — not because it endangers the system (nothing gates on this record), but because it corrupts the first numbers this instrumentation will produce, on precisely the scenarios it was built to measure. An instrumentation PR's whole value is the trustworthiness of its output, and a one-line predicate change plus a regression test buys that back cheaply. Everything else here is 🟢 or a nit and can follow at leisure.

🤖 Automated pragmatic-code-review

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

record_skill took the first gate-clearing candidate, which is not the same
predicate as "the candidate whose whitelist leads stage2_tools". A
schema-typed retrieval hit carries tools: [] and the lexical backstop pins it
at confidence 1.0 — above any cosine-derived score a real skill can reach — so
on every turn naming a schema outright it sorted first and was recorded as the
skill that led. It leads nothing: it contributes no tool to the offered
surface.

That is most of the decision eval's schema scenarios by construction, so the
defect corrupted the first numbers this instrumentation produced, on exactly
the cases it was built to measure.

routing.rs already held this invariant for two other consumers, both of which
had been separately broken the same way. Rather than re-deriving it a third
time, leading_tool_bearing_candidate is now exposed there, next to
top_tool_bearing_score and the doc comment explaining why the rule is one
named thing rather than a coincidence between call sites.

The tool-less candidate still appears in `candidates` — it was genuinely
retrieved, and "retrieved but contributed nothing" is worth seeing.

Regression test verified against the unfixed code: it reports the schema hit
as the winner without the fix, and the real skill with it.

Also from review: refreshed three docstrings still describing "the two
selections" after the skill decision was added, asserted the Skill wire name,
and documented why the empty-oneOf branch is retained rather than dead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review Summary

Commit: e255988e — Address review: a tool-less candidate cannot lead the turn

✅ Addressed

🟡 record_skill reports a tool-less schema hit as the skill that led the turn — decisions.rs

The finding was correct and the mechanism verified end to end:

  • skill_ops.rs:46 — LEXICAL_SCHEMA_MATCH_CONFIDENCE = 1.0
  • skill_ops.rs:586-595 — the emitted candidate carries "tools": [], "kind": "schema"
  • candidates are sorted score-descending, so a 1.0 always sorts first
  • SkillCandidate has no kind field, so record_skill could not see it was a schema

Fixed via the reviewer's second suggestion rather than the one-line predicate change: routing::leading_tool_bearing_candidate is now exposed and both consumers use it. That file's own doc comment (routing.rs:361-376) records that two prior consumers were "separately broken by exactly that, which is why the rule is one named thing rather than a coincidence between call sites" — re-deriving it a third time would have repeated the mistake the comment warns about.

The tool-less candidate still appears in candidates; only selected changed. "Retrieved but contributed nothing" is worth seeing.

Regression test verified against the unfixed code, not just asserted: reverting the fix makes a_tool_less_schema_hit_does_not_lead_the_turn fail with left: Some("Company Sold To"), right: Some("Node Creation"). Restored, passes.

Also added leading_candidate_is_the_highest_scorer_not_the_first, pinning that selection uses an explicit max rather than depending on the caller's sort order — the asymmetry the reviewer flagged in the 🟢 note about top_tool_bearing_score's fold(max).

🟢 Stale docstrings — three files still said "the two selections" after the skill decision landed: decisions.rs:1-3, fixtures/decisions.ts:1-6, types.ts:157. All updated.

🟢 kind_wire_names_are_stable omitted Skill — added.

🟢 Unused oneOf.length === 0 branch — kept, with a comment explaining why. It encodes "the right answer is to call nothing," which the record already distinguishes from "picked wrongly." The scenario that used it (op-plain-question) was removed because it never reached inference — a harness problem, not a wrong expectation. Deleting a correct capability to satisfy YAGNI would have to be undone when that scenario is fixed.

⏭️ Skipped, with reasoning

🟢 Emit the skill decision next to "two-stage routing overhead" instead of guarding on iteration == 0 — the concern (positional fragility) is fair, but moving it would split decision emission across two sites and two functions, so a reader looking for "where are decisions logged" finds one of three. The iteration == 0 guard is explicit and adjacent to its siblings. Revisit if the loop's structure changes such that iteration 0 is no longer guaranteed to run.

🟢 Emitter→scrape→parse round-trip test for the marker format — genuinely worth having; the format is asserted in three places and enforced in none. Skipped as scope creep for this PR: it needs a test harness that runs the Rust emitter and the TS parser together, which does not exist today. The three-way contract is at least documented at each site now. Worth its own issue.

🟢 Latent: a skill name containing ", " would split into two candidates — real but not reachable: all 11 seeded skill names are plain words. A user-authored skill could hit it. Not worth a format change (JSON-encoding the field) for a case that cannot currently occur; the round-trip test above is the better place to catch it if skills become user-authored.

Nitpick: bun.lock configVersion removal — not mine; it arrived via rebase from main and reverting it would fight the lockfile.

Nitpick: routingMs sums per scenario then means across — correct as written for single-turn scenarios, which is all of them today. A multi-turn scenario would skew it, but none exists and the fix would be speculative.

Verification

  • decisions:: 20/20 Rust tests pass (18 → 20, two added)
  • routing:: 64/64 pass — the new pub fn breaks no existing consumer
  • 110/110 TS tests pass (runner.test.ts, aichat.test.ts, check-code-references.test.ts)
  • cargo fmt + clippy clean via bun run quality:fix

Does the recorded baseline need re-measuring?

No — checked rather than assumed. The concern was that the baseline on #2802 was measured with the buggy record_skill, so skill-routing scores might have been recording schema hits. Scanning all 30 skill decisions across the 3 reps: zero non-skill candidates. The lexical backstop never fired in these scenarios, so the defect had no opportunity to mislabel anything. The recorded numbers stand.

Classification note

Reviewer marked this 🟡 Important rather than 🔴 Critical, correctly: nothing gates on the record, so no agent behaviour was affected. But it corrupted the first output of instrumentation whose entire purpose is producing trustworthy numbers, on exactly the scenarios it was built to score — which is why it was worth fixing before merge rather than as follow-up.

@malibio

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2842 (Re-Review)

Review Type: Re-Review
Scope: e255988e only — git diff 85caab02..e255988e, 4 files, +80/-11
Verdict: APPROVE — the 🟡 finding is correctly and completely fixed, the fix is better than the one suggested, and it introduces no new problem.


Previous Review Disposition

Count
Previous recommendations 1 🟡 + 5 🟢 + 4 nits = 10
Addressed 5 (the 🟡, two 🟢, two nits)
Skipped with stated reasoning 5
Not addressed / silently dropped 0
New issues introduced 0 blocking (one 🟢 below)

Every skipped item carries an explicit justification in the address-review comment, and I agree with four of the five. The exception is a factual correction, noted as a nit below rather than as a finding, since the outcome is unchanged:

  • bun.lock configVersion — the stated reason for skipping ("not mine; it arrived via rebase from main") does not hold. git log origin/main..HEAD -- bun.lock returns exactly one commit, e1872d81 — a branch commit on this PR — and git diff origin/main..HEAD -- bun.lock shows the single line - "configVersion": 0, is still present in the diff against main. It was introduced here, not inherited. That said, the decision to leave it stands: a one-line lockfile delta from a Bun version difference is noise either way, and reverting it risks re-churn on the next bun install. Skipping is fine; the reasoning just needs correcting so a future reader does not trust a false provenance claim.
  • oneOf.length === 0 retention — the reasoning is honest and the comment is accurate. I checked: no fixture scenario uses the branch today, and the comment says so in plain words rather than implying coverage. It records why dead-looking code is retained ("picked no tool" is a real decision distinct from "picked wrongly"), which is exactly the kind of intent a YAGNI deletion would destroy and a future reader would have to re-derive. This is the right call — YAGNI argues against speculative capability, not against a correct branch whose scenario was removed for a harness reason.

The iteration == 0 and round-trip contract test skips are also sound: the first trades a real fragility for locality of all three emissions (a defensible call either way, and the revisit condition is stated); the second is genuine scope creep needing a cross-language harness that does not exist.


Verification Performed

Not taken on faith — every claim in the address-review comment was independently re-run:

  • cargo test -p nodespace-agent --lib decisions:: → 20/20 pass (was 18, +2).
  • cargo test -p nodespace-agent --lib routing:: → 64/64 pass. Making leading_tool_bearing_candidate pub broke no existing consumer.
  • bun test scripts/eval/runner.test.ts scripts/aichat.test.ts scripts/check-code-references.test.ts → 110/110 pass, 200 assertions.
  • cargo fmt --check clean; cargo clippy -p nodespace-agent --lib --all-features clean, zero warnings.
  • Regression test verified against the unfixed code. I reverted record_skill to the original .find(|c| clears_score_gate(c)) and re-ran. Both new tests fail, with exactly the output the address-review claimed:
    a_tool_less_schema_hit_does_not_lead_the_turn
      left: Some("Company Sold To")   right: Some("Node Creation")
    leading_candidate_is_the_highest_scorer_not_the_first
      left: Some("Research")          right: Some("Node Creation")
    
    Restored; working tree confirmed clean (git status --porcelain empty). The tests pin the fix rather than merely accompanying it — including the second one, which I had not expected to fail and which turns out to pin the max-vs-first property independently.

Assessment of the Fix

The chosen fix is better than the one I suggested, and for the right reason. I offered a one-line predicate change as the minimum and leading_tool_bearing_candidate as the preferable alternative; the author took the latter. The justification given — that routing.rs:361-376's own doc comment records two prior consumers "separately broken by exactly that, which is why the rule is one named thing rather than a coincidence between call sites" — is the correct reading. A third re-derivation would have reproduced the documented mistake in the same file that warns against it. Principle: DRY applies most strongly to an invariant that has already been violated by duplication.

Correctness of leading_tool_bearing_candidate (routing.rs:413-418): the filter clears_score_gate(c) && !c.tools.is_empty() is character-identical to top_tool_bearing_score's, and max_by(total_cmp) is the right comparator — total_cmp is total over floats, so no NaN score can panic the way partial_cmp().unwrap() would. Returning Option<&SkillCandidate> rather than an owned clone keeps the allocation at the call site where it is actually needed. The None case correctly collapses "nothing retrieved" and "nothing tool-bearing cleared" into the same fail-open record, which matches what stage2_tools actually does on those turns.

Is pub justified? Yes. It is pub within local_agent's module tree, not exported from the crate — decisions.rs reaches it as super::routing::leading_tool_bearing_candidate, and nothing outside the crate can call it (grep confirms two references total, both in-crate). The alternative to widening it by one notch is duplicating the predicate, which is the defect being fixed. That is the right trade.

Docstrings are accurate. I checked each claim against the code: "three consumers have now been written against this predicate, and the two that re-derived it were both wrong in the same way" matches stage2_permitted_names (line 622) and declare_write_tool_fields (line 842), both of which carry their own historical comments describing exactly that breakage. The decisions.rs:173-189 rewrite describes the mechanism correctly down to tools: [] and the lexical backstop. The module header's "two selections" → "three selections" sweep also landed in fixtures/decisions.ts and types.ts, closing that 🟢.


Findings

🔴 Critical

None.

🟡 Important

None.

🟢 Suggestions

📁 packages/agent/src/local_agent/routing.rs:386-418 — the shared predicate is now named twice, and the two names disagree on ties

This is the residual of my original "or better still, have both call it" suggestion, and I want to be precise that it is not a correctness defect in this PR — the record is right on every input that can occur today.

The filter expression clears_score_gate(c) && !c.tools.is_empty() now appears at line 388 (top_tool_bearing_score) and line 416 (leading_tool_bearing_candidate), independently. That is one duplication fewer than before this commit (three sites → two), so the commit moves in the right direction; but the file's own thesis is that this rule should be "one named thing," and it is currently two.

The observable divergence is tie behaviour, and it is worth understanding rather than just noting:

  • top_tool_bearing_score returns a score, and both its consumers then apply c.score >= max_score — which retains every tied candidate. declare_write_tool_fields_unions_tied_top_scoring_candidates (line 1587) pins this deliberately: two candidates at 0.85 both contribute descriptors.
  • leading_tool_bearing_candidate returns one candidate, and max_by returns the last maximal element on a tie (per its contract).

So on a tie, stage2_tools scopes the surface from the union of tied candidates while the record names exactly one of them — the last in input order, which is an arbitrary artefact of route's sort stability rather than a modelled choice. DecisionRecord.selected is Option<String>, so it structurally cannot express "two skills tied for the lead"; recording one is the only option available, and it is the reasonable one. But the choice of which one is currently implicit.

Two things would close this cheaply, neither blocking:

  1. Factor the shared filter into one private predicate (fn leads_the_surface(c: &SkillCandidate) -> bool) that both functions call, so the third consumer inherits it structurally. This is what the file's doc comment already argues for.
  2. One sentence in leading_tool_bearing_candidate's docstring noting that ties resolve to the last maximal candidate and that this differs from top_tool_bearing_score's retain-all semantics — because the current docstring says "the same invariant [top_tool_bearing_score] holds," which is true of the filter but glosses the tie difference. A reader trusting that sentence would expect tie parity.

Principle: two functions holding the same predicate by coincidence is exactly the drift risk this file was written to eliminate; and where a doc comment claims equivalence to a sibling, the ways it is not equivalent should be the part that is written down.

📁 packages/agent/src/local_agent/decisions.rs:360-398 — two untested edges

The two added tests are well-chosen and both genuinely pin the fix (verified above). Two cases remain uncovered:

  • All candidates tool-less. record_skill(&[schema_hit_only]) should yield selected: None with the candidate still listed — i.e. the fail-open record on a turn where a schema hit outscored everything and nothing tool-bearing cleared. This is the most likely real-world shape of the bug that was just fixed, since the trigger is a query naming a schema outright, and it is the one input where the new code's None branch and the old code's Some(schema) differ most starkly. skill_with_no_candidates_records_none covers the empty slice, which is a different path.
  • Equal scores. Whatever tie semantics are settled on per the note above, a test would pin them rather than leaving them to max_by's documented-but-unasserted behaviour. routing.rs already sets this precedent with declare_write_tool_fields_unions_tied_top_scoring_candidates.

Neither is a gap in the fix — both are cheap additions to a test module that is otherwise thorough.

Nitpicks

  • Nit: 📁 bun.lock:3 — see the disposition table above. The line was introduced by branch commit e1872d81, not inherited from main, so the address-review's "not mine; it arrived via rebase" is inaccurate. Leaving it is still the right call; only the justification is wrong. Worth correcting because a provenance claim is the kind of thing a later reader acts on without re-checking.
  • Nit: 📁 packages/agent/src/local_agent/decisions.rs:181-183 — the docstring says the tool-less candidate outranks "every turn that names a schema outright — which is most of the schema scenarios in the decision eval, by construction." The address-review comment separately reports that scanning all 30 skill decisions across 3 reps found zero non-skill candidates, i.e. the backstop never actually fired in those runs. Both statements are true (one is about what the scenarios are constructed to do, the other about what retrieval did on a specific model run), but a future reader hitting the comment after reading the baseline may find them in apparent tension. Adding "by construction, though the backstop did not fire in the recorded baseline" would reconcile them.

Was the Baseline Correctly Left Un-remeasured?

Yes, and the reasoning is the right kind — checked rather than assumed. The claim is that all 30 recorded skill decisions across 3 reps contain zero tool-less candidates, so the defect had no opportunity to mislabel anything and the recorded numbers stand. That is the correct test to run: the bug can only alter a record on a turn where a tool-less candidate was actually retrieved and cleared. Verifying its absence in the captured data is strictly stronger than re-running, and it also explains why the original review's concern about skill-instance-request was a latent false-negative rather than an active one. Good discipline.


Recommendation

APPROVE — merge.

The 🟡 was real, the fix is complete, and it is the better of the two options I offered rather than the cheaper one. The regression tests were verified to fail without the fix — I re-ran that myself rather than accepting the claim, and both new tests fail on the reverted code with the reported output. No behaviour outside record_skill changed; 64/64 routing tests confirm the new pub fn disturbed nothing. Four of the five skipped items carry justifications I agree with; the fifth (bun.lock) reaches the right decision on an incorrect premise, which is a nit rather than a finding. The oneOf.length === 0 retention I checked most closely, and it is a case where the author was right and my original note was not.

The remaining 🟢 — one predicate still written twice, with an unstated tie difference — is a genuine but minor follow-up on an invariant that is now more centralised than before this commit, not less. It does not warrant holding the PR.

🤖 Automated pragmatic-code-review (re-review)

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

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

The re-review's 🟢: after the last commit the predicate
`clears_score_gate(c) && !c.tools.is_empty()` was still written out twice, in
top_tool_bearing_score and leading_tool_bearing_candidate. That is the shape
this file's own history warns about — the rule has drifted between call sites
three times — so it is now one named function, is_tool_bearing_contender,
that both filter on.

Documents the tie divergence the re-review found, which the previous docstring
glossed: top_tool_bearing_score returns a score and its consumers admit every
candidate matching it, so ties all contribute; leading_tool_bearing_candidate
returns one candidate because DecisionRecord has no shape for "these two
tied". Stable for a given input order, but not a modelled preference between
equals.

Adds the two untested edges the re-review named: all candidates tool-less
(the likeliest real shape of the bug just fixed, and distinct from the
empty-slice case), and a tie (asserting one of the tied top scorers wins,
never a lesser one — the property that matters, rather than which name
max_by happens to yield).

Reconciles a docstring the re-review flagged as overstated: it claimed the
backstop fires on "most of the schema scenarios", while the recorded baseline
observed 0 of 30. Now states the trigger condition and the observed zero
separately — reachable-in-principle and observed-in-practice are different
claims, and only the first justifies the guard.

bun.lock: the re-review correctly caught that the previous justification for
leaving the configVersion delta was wrong — it came from a branch commit here,
not from a rebase. Tested restoring it: `bun install` re-removes the line on
this Bun version, so it would churn back on every install. Left as-is, now for
a reason that holds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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.

Make schema and operation selection explicit, recorded decision points with a measured Gemma baseline

1 participant