Skip to content

Cover tool descriptions and parameter schemas in the eval-contamination guard (closes #1932) - #1952

Merged
malibio merged 2 commits into
mainfrom
issue-1932-tooldesc-contamination-guard
Aug 4, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-1932-tooldesc-contamination-guard

Conversation

@malibio

@malibio malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

guidance_is_not_contaminated_by_eval_prompts guards model-facing guidance against absorbing eval-scenario text, but guidance_corpus() hand-listed only the prose constants and seeded-node markdown. Tool descriptions and their parameter-schema descriptions were absent, so text in that channel was unguarded.

That channel is exactly where guidance is being moved: ADR-064 rule 1 assigns argument shape to tool schemas on the strength of measured 100% compliance, so the doctrine actively pushes instructional text into the one place the guard could not see. A worked example built on an eval scenario could be planted in a tool description with nothing failing.

Changes

  • guidance_corpus() now enumerates all_tool_definitions(), adding each tool's description and every description string in its parameters_schema. Deriving from the registry keeps tools added later covered automatically — the same property the fixture-side enumeration already has, and the reason its doc comment records a hand-maintained list as the anti-goal.
  • Descriptions are gathered by walking the whole schema value rather than reading only top-level properties.*.description. This goes beyond the issue's proposal deliberately: descriptions also sit on nested object properties and array items (update_schema's add_fields.items.properties.type, for one), and a fixed-depth read would recreate the same structural hole this enumeration exists to close.

Verification

The extended guard passes against the current fixtures, confirming the issue's read that the gap was structural rather than a live contamination.

Since a guard that passes proves nothing on its own, I checked it genuinely fires: temporarily planting the real fixture prompt "Do we have anything worth 90000 sitting out?" into search_semantic's query description failed the guard with the tool channel and the shared phrase both named. The plant was reverted.

New tests:

  • guidance_corpus_covers_tool_descriptions_and_parameter_schemas — asserts against real registry text, so a refactor that stops reaching all_tool_definitions() fails here rather than passing quietly.
  • schema_description_walk_reaches_arbitrary_nesting — pins the walk against nested properties, array items, and schema arrays, including shapes the registry does not use yet.
  • contamination_guard_detects_a_planted_example_in_a_tool_schema — mirrors the existing planted-example pin for the newly covered channel.

Testing

  • bun run test:all — frontend 172 files / 4112 tests passed (matches baseline exactly), browser 2/24 passed, no Rust failures
  • cargo clippy -p nodespace-agent --all-targets -- -D warnings — clean
  • Full pre-push gate passed

Note

quality:fix reformatted seven unrelated files workspace-wide; those were reverted to keep this PR scoped. A pre-existing cargo fmt drift in packages/agent/tests/golden_scenario6_sequence.rs is present on clean main independent of this change and was left alone.

Closes #1932

🤖 Generated with Claude Code

https://claude.ai/code/session_01FELy7rhqnKbDmmG9fuHALT

…on guard (closes #1932)

`guidance_is_not_contaminated_by_eval_prompts` guards model-facing guidance
against absorbing eval-scenario text, but `guidance_corpus()` hand-listed the
prose constants and seeded-node markdown only. Tool descriptions and their
parameter-schema descriptions were absent, so text in that channel was
unguarded.

That channel is exactly where guidance is being moved: ADR-064 rule 1 assigns
argument shape to tool schemas on the strength of measured 100% compliance,
so the doctrine actively pushes instructional text into the one place the
guard could not see. A worked example built on an eval scenario could be
planted in a tool description with nothing failing.

Extend the corpus from `all_tool_definitions()`, so a tool added later is
covered automatically — the same property the fixture-side enumeration already
has, and the reason its doc comment records a hand-maintained list as the
anti-goal.

Descriptions are collected by walking the whole `parameters_schema` value
rather than reading only top-level `properties.*.description`: they also sit
on nested object properties and array `items` (update_schema's
`add_fields.items.properties.type`, for one), and a fixed-depth read would
recreate the same structural hole this enumeration exists to close.

Not a live contamination fix — the extended guard passes against the current
fixtures, confirming the gap was structural. Verified it genuinely fires by
temporarily planting a real fixture prompt into `search_semantic`'s query
description; the guard failed with the tool channel and shared phrase named.

Tests: corpus coverage asserted against real registry text (so a refactor that
stops reaching the registry fails), the schema walk pinned against nesting
shapes including ones the registry does not use yet, and a detector test
mirroring the existing planted-example pin for the tool channel.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FELy7rhqnKbDmmG9fuHALT
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1952

Review Type: Initial Review
Scope: packages/agent/src/agent_guidance.rs (+168, test module only), commit 01af4eb2


Summary

This is a net positive and lands the structural fix #1932 asked for. I independently verified the implementer's claims rather than taking them at face value, including re-running the plant/revert experiment and running a differential against origin/main. The headline result:

With the same contamination planted in search_semantic's query description, origin/main's guard passes (0 failures) and this PR's guard fails naming the tool channel and the shared phrase.

That is the definitive answer to "does this add real protection, or is it self-satisfying?" — it is real. The guard genuinely could not see this channel before and can now.

The recursive walk (deviating from the issue's proposed top-level-only read) is the right call and I'd have flagged the issue's narrower version as a defect: update_schema carries model-facing text at add_fields.items.properties.type.description and at enum_values.description (a full validation rule: "REQUIRED and must be non-empty when type="enum""), neither of which a top-level properties.*.description read reaches. A fixed-depth read would have re-created the exact hole the enumeration exists to close.

There is one substantive gap worth addressing (a second model-facing tool registry is still unguarded), and some smaller polish. None of it blocks merge on its own, but the gap is the same class of miss as #1932 itself.


Requirements Check (issue #1932)

Requirement Status Evidence
Corpus includes every all_tool_definitions() tool description ✅ 93 of 127 corpus entries now come from the tool channel; guidance_corpus_covers_tool_descriptions_and_parameter_schemas asserts per-tool
Corpus includes parameters_schema property description strings ✅ Covered, and exceeded — recursive rather than top-level-only
Derived from the registry function so later-added tools are covered automatically ✅ Iterates all_tool_definitions(); no hand-listed def_* constants
Guard still passes against current fixtures (structural, not live, gap) ✅ 14/14 pass, cargo test -p nodespace-agent --lib agent_guidance
Guard demonstrably fires on tool-channel contamination ✅ Verified by plant/revert (details below)
No lint suppression / #[allow] / #[deprecated] / back-compat ✅ cargo clippy -p nodespace-agent --all-targets -- -D warnings clean
No issue numbers in code comments ✅ Comments reference ADR-064, which is the correct convention. Issue number appears only in the commit subject, which is fine

Independent Verification

Claim 2 — recursion is necessary, not gold-plating: CONFIRMED.
update_schema's schema carries descriptions at depth well past properties.*.description, including a load-bearing validation rule on add_fields.items.properties.enum_values.description. The issue's proposed shape would have missed them.

Claim 3 — guard passes on current fixtures: CONFIRMED. 14/14 green in 0.06s.

Claim 4 — the guard genuinely fires: CONFIRMED, and I strengthened the evidence.
I planted the real fixture prompt "Do we have anything worth 90000 sitting out?" (from scripts/eval/fixtures/agent-matrix.ts:403) into search_semantic's query description:

local_agent::tools parameters_schema the ENTIRE prompt appears (8 consecutive words)
from scripts/eval/fixtures/agent-matrix.ts prompt "Do we have anything worth 90000 sitting out?"
      shared phrase: "do we have anything worth 90000 sitting out"

I then ran the same plant against origin/main's version of agent_guidance.rs — it passed. So this is a differential improvement, not a test that only proves itself. Both files were restored; git status is clean in this worktree and in the primary checkout.

Brittleness measurement (the key flakiness signal).
I instrumented guidance_corpus() to report the maximum shared run across all 127 corpus entries × 33 eval prompts:

  • Observed max shared run: 3, against MAX_SHARED_RUN = 4.
  • The top-3 offenders are split between old and new channels — TOOL_STRATEGY_RULES ("i want to"), seed_agent_guidance_nodes ("i want to"), and the new tool channel ("create a new", "due date to").

Conclusion on false-positive risk: acceptable. The new channel does not raise the observed ceiling above what the pre-existing corpus already produced — both max out at 3. The margin is one word, but that margin was already one word before this PR; adding 93 entries did not consume it. This is not a change that turns the guard into a flaky tripwire. Worth noting the margin is thin in absolute terms, but that is a property of the pre-existing threshold, not a regression this PR introduces.

quoted_whole risk: acceptable. The shortest fixture prompts are "Hi there" (2 words — below the >= 3 floor, correctly exempt) and then 4-word prompts ("What can you do?", "organize my client contacts"). A tool description reproducing "organize my client contacts" verbatim genuinely is contamination and should fire. "what can you do" is the one plausible false-positive shape, but no current description contains it and the phrase is unnatural inside a tool schema. Not worth pre-emptive complexity.

Test quality: non-tautological — verified by simulated regression. I removed the all_tool_definitions() loop from guidance_corpus() and re-ran: guidance_corpus_covers_tool_descriptions_and_parameter_schemas FAILED as designed (13 passed / 1 failed). The coverage test does real work.


Findings

🟡 Important

📁 packages/agent/src/agent_guidance.rs:203 — A second model-facing tool registry, stage1_tool_definitions(), remains outside the corpus.

all_tool_definitions() is not the only set of tool definitions sent to a model. packages/agent/src/local_agent/routing.rs:128 defines stage1_tool_definitions() (route_query / route_clarify / route_multi), and agent_loop.rs:2283 passes it straight to the model as the Stage 1 tool surface. I confirmed all three are absent from the corpus:

PROBE stage1 tool route_query   description_in_corpus=false
PROBE stage1 tool route_clarify description_in_corpus=false
PROBE stage1 tool route_multi   description_in_corpus=false

This matters more than a generic "you missed a registry", because route_query's parameter description already contains a worked example built on eval-scenario material:

…e.g. 'update the equipment record worth 2400 to returned', not just 'equipment items'…

against fixture scenarios "The 2400 one came back — set it to returned" and "Log a laser cutter checked out on the 12th, replacement cost 2400" (agent-matrix.ts:390, :375). It currently measures a shared run of only 2, so it would not fail the guard today — but it is exactly the drafting pattern the guard exists to catch, sitting in exactly the channel this PR set out to close, and it is one rewording away from being real contamination that nothing reports.

The issue text said all_tool_definitions(), so this is arguably out of the literal ask. I'm raising it because the principle of #1932 — "derive from the registry so nothing is unguarded by default" — is only half-applied while a second model-facing registry is enumerated nowhere. Leaving it means a follow-up issue reporting the identical structural gap.

Suggested fix, mirroring the existing loop:

for def in crate::local_agent::routing::stage1_tool_definitions() {
    if !def.description.is_empty() {
        corpus.push(("routing::stage1_tool_definitions description", def.description));
    }
    collect_schema_descriptions(
        &def.parameters_schema,
        "routing::stage1_tool_definitions parameters_schema",
        &mut corpus,
    );
}

I measured this addition: max shared run against the fixtures is 2, so it passes today with margin to spare and adds no flakiness. If you'd rather keep this PR scoped to the issue, that's defensible — but please open the follow-up rather than dropping it.

Principle: completeness of a derived enumeration. A guard whose value proposition is "derived, so nothing is missed by default" is undermined by a second source it doesn't derive from — this is the same failure mode the guard's own doc comment calls out about hand-maintained lists.

📁 packages/agent/src/agent_guidance.rs:203-207 — all_tool_definitions() vs model_facing_tool_definitions(): right choice, but worth a one-line note.

model_facing_tool_definitions() (tools.rs:1352) filters out search_skills as system-only. Using the broader all_tool_definitions() is the correct call for a guard — over-inclusion here costs nothing (worst case you guard text the local model never sees, and search_skills is still model-facing to external MCP agents per its own doc comment). But a reader who knows both functions exist will wonder whether the broader one was chosen deliberately or by accident. One clause in the existing comment — "deliberately the unfiltered set: search_skills is withheld from the local loop but still model-facing to external MCP agents" — removes that doubt permanently.

Principle: comments should record the "why" behind a non-obvious choice between two similar APIs.

🟢 Suggestions

📁 packages/agent/src/agent_guidance.rs:510-520 — the nested-description assertion is a mild maintenance landmine, but an acceptable one.

.parameters_schema["properties"]["add_fields"]["items"]["properties"]["type"]["description"]

Six chained index operations plus two .expect()s, pinned to one tool's internal schema shape. If update_schema's add_fields is ever restructured, this test fails with a message about the walk not reaching nested properties — which would be a misleading diagnosis, since the real cause is that the fixture moved.

That said, I don't think this should change. The failure is loud, the message is nearby, and asserting against real registry text rather than a constructed value is what makes this test meaningful (schema_description_walk_reaches_arbitrary_nesting already covers the synthetic case). The one cheap improvement: enum_values.description is a more stable target and is more obviously instructional text, if you want a less shape-coupled anchor. Optional.

Principle: tests coupled to fixture internals should fail with a message that points at the real cause.

📁 packages/agent/src/agent_guidance.rs:203-206 — violation messages name the channel but not the tool.

The failure I reproduced reads local_agent::tools parameters_schema the ENTIRE prompt appears…. With 93 entries now flowing from this channel, that tells you which registry but not which tool or which parameter. Grepping the shared phrase gets you there, so this is minor — but since corpus entries already carry a label, threading def.name into it (format!("local_agent::tools {} description", def.name)) would make the diagnosis immediate. This requires widening the label type from &'static str to String, which is a real (if small) cost — reasonable to decline.

Principle: error messages should minimize the distance from failure to root cause; the value scales with corpus size, and the corpus just grew 4x.

Nit: 📁 packages/agent/src/agent_guidance.rs:227-247 — the walker double-visits description values.

When key == "description" and the child is a string, it's pushed and then also passed to collect_schema_descriptions, which no-ops on Value::String. Harmless and arguably the more robust shape (it correctly handles the pathological case of a description key whose value is an object). Not worth changing — noting only so a future reader doesn't mistake it for an oversight.

Nit: 📁 packages/agent/src/agent_guidance.rs:230 — for (key, child) in map iterates serde_json::Map by reference already; the code is idiomatic. No change needed. The recursion is clean, allocation-light, non-generic, and correctly matches only Object/Array with a _ => {} fallthrough. Rust idiom quality here is good.


Observation (pre-existing, not introduced by this PR)

eval_prompts() is picking up doc-comment prose as "prompts". Two of the 33 parsed entries are multi-hundred-character blocks of the fixture files' own header comments (they contain the literal text prompt: followed by a quote inside prose). They're harmless — they inflate the check count slightly and can't realistically collide — but they mean checked > 0 and the prompts.len() == sites coverage assertion are counting a couple of non-prompts. Worth a follow-up issue at most; explicitly out of scope here and not a reason to hold this PR.


Verification Performed

cargo test -p nodespace-agent --lib agent_guidance      → 14 passed, 0 failed (0.06s)
cargo clippy -p nodespace-agent --all-targets -- -D warnings → clean
plant real fixture prompt in tool schema → PR guard FAILS (correct)
same plant against origin/main            → guard PASSES (proves the gap was real)
remove all_tool_definitions() loop        → coverage test FAILS (proves non-tautological)
max shared run across 127 corpus × 33 prompts = 3 (threshold 4)
git status: clean in worktree AND primary checkout

Recommendation

APPROVE — with the stage1_tool_definitions() gap (🟡) tracked either in this PR or as an immediate follow-up.

The change does exactly what #1932 asked, the deviation from the issue's proposal is a correct engineering judgment rather than scope creep, the tests are meaningful and I proved they fail on regression, and the differential-against-main experiment shows the protection is real rather than self-satisfying. The false-positive analysis says this won't become a flaky tripwire that someone later weakens — the new channel doesn't push the observed shared-run ceiling above where the pre-existing corpus already sat.

The one thing I'd genuinely like to see resolved is Stage 1. Not because it's contaminated today (it isn't — run of 2), but because shipping "the corpus is now derived from the registry" while a second model-facing registry is derived from nothing invites the exact same issue to be filed again in a month.

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

One tracked item: stage1_tool_definitions() (routing.rs:128) is a second model-facing tool registry still absent from guidance_corpus(). Not contaminated today (max shared run 2), but it is the same structural gap #1932 describes. Address here or as an immediate follow-up.

…tool in violations

Addresses the 🟡 finding from the PR review.

stage1_tool_definitions() (routing.rs) is a second model-facing tool
registry — agent_loop.rs hands it straight to the model as that turn's tool
surface — and it was enumerated nowhere. Shipping "the corpus is derived from
the registry" while a second registry is derived from nothing would leave the
same structural hole one registry over, and invite this issue to be refiled.

This is not hypothetical drafting risk: route_query's query description
already carries a worked example built on eval-scenario material
('update the equipment record worth 2400 to returned', against the fixture
prompts "The 2400 one came back — set it to returned" and "...replacement
cost 2400"). It measures a shared run of only 2 so it does not fail today,
but it is exactly the pattern the guard exists to catch, previously in a
channel nothing watched.

Both registries now flow through one loop, so they cannot drift and a third
registry is a one-line addition. Verified the new coverage genuinely fires by
planting the real fixture prompt into route_query's description: the guard
failed naming the registry, tool, and channel. Reverted after.

Measured the flakiness cost independently rather than assuming it: across
134 corpus entries x 33 fixture prompts the max shared run is 3 against
MAX_SHARED_RUN = 4, and Stage 1's own worst case is 2 — the pre-existing
corpus already sat at 3, so this consumes no margin.

Also from the review:
- Violation labels now name the specific tool, not just the registry
  ("routing::stage1_tool_definitions route_query parameters_schema" rather
  than the registry alone). With the corpus 4x larger, this removes a
  grep-the-shared-phrase step from every future diagnosis. Costs widening
  the label to String, which is contained to this test helper.
- Recorded why all_tool_definitions() is deliberately preferred over
  model_facing_tool_definitions(): search_skills is withheld from the local
  loop but stays model-facing to external MCP agents, and over-inclusion in
  a guard costs nothing.
- Coverage test now asserts both registries and fails if only the main one
  is checked.

Declined, per the reviewer's own guidance on both: swapping the nested
assertion's anchor to enum_values (the reviewer recommended keeping the
current one — asserting against real registry text is what makes it
meaningful), and the walker's harmless double-visit of description values
(the current shape correctly handles a description key holding an object).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FELy7rhqnKbDmmG9fuHALT
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Review Addressed — commit fbc3d783

Thanks for the differential-against-main experiment and the shared-run measurement — both went straight to the questions that mattered.

✅ Addressed

🟡 stage1_tool_definitions() gap — fixed in this PR rather than deferred.

You were right that this is the same class of miss as #1932 itself. I verified it independently: agent_loop.rs:2283 hands the registry straight to the model, and route_query's description does carry the 'update the equipment record worth 2400 to returned' example against fixtures agent-matrix.ts:390 / :375.

Both registries now flow through a single loop, so they cannot drift and a third registry is a one-line addition.

Verified it genuinely fires — planted the real fixture prompt into route_query's description:

routing::stage1_tool_definitions route_query parameters_schema the ENTIRE prompt appears
(9 consecutive words) from scripts/eval/fixtures/agent-matrix.ts
prompt "The 2400 one came back — set it to returned"

Reverted after; both checkouts clean.

Flakiness re-measured independently (not assuming your number): across 134 corpus entries × 33 prompts the max shared run is 3 vs MAX_SHARED_RUN = 4, and Stage 1's own worst case is 2 ("kind of"). Matches your finding — the pre-existing corpus already sat at 3, so Stage 1 consumes no margin.

🟡 model_facing_tool_definitions() note — added the clause explaining all_tool_definitions() is deliberately the unfiltered set (search_skills is withheld from the local loop but stays model-facing to external MCP agents; over-inclusion in a guard is free).

🟢 Violation labels now name the tool, not just the registry — routing::stage1_tool_definitions route_query parameters_schema rather than the registry alone. You flagged this as reasonable to decline given the String widening, but with the corpus 4x larger it removes a grep step from every future diagnosis, and the cost stayed contained to this test helper.

Coverage test now asserts both registries and fails if only the main one is checked.

⏭️ Declined (both per your own guidance)

  • enum_values anchor swap — you recommended keeping the current assertion, and I agree: type is equally real registry text, and schema_description_walk_reaches_arbitrary_nesting already covers the synthetic case.
  • Walker double-visit nit — you noted it's harmless and arguably more robust; the current shape correctly handles a description key holding an object.

Out of scope

The eval_prompts() doc-comment parsing observation is pre-existing and unrelated to this change — agreed it's a follow-up at most.

Verification

cargo test -p nodespace-agent --lib agent_guidance      → 14 passed, 0 failed
cargo clippy -p nodespace-agent --all-targets -D warnings → clean
cargo fmt (agent_guidance.rs)                            → 0 diffs
bun run test:all → frontend 172/4112, browser 2/24, no Rust failures (matches baseline)
plant in route_query → guard FAILS naming registry + tool + channel
max shared run: 3 of 4 (stage1 worst case: 2)
git status clean in worktree AND primary checkout

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: The Stage 1 fix is a functional change to guidance_corpus() (new registry enumerated, both registries restructured through one loop) plus a type change threaded through every corpus call site — not a trivial edit. A second pass should confirm the restructure didn't drop coverage of any pre-existing channel.

@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

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

Review Type: Re-Review
Scope: delta 01af4eb2..fbc3d783 (+88/−31, test module only), plus cumulative origin/main...HEAD sanity check


Previous Review Summary

# Prior finding Severity Status
1 stage1_tool_definitions() is a second model-facing registry, unguarded 🟡 ✅ Addressed — fixed in-PR, verified
2 Note why all_tool_definitions() over model_facing_tool_definitions() 🟡 ✅ Addressed
3 Nested assertion anchor could use enum_values 🟢 ⏭️ Declined — per my own recommendation to keep
4 Violation messages name channel but not tool 🟢 ✅ Addressed — accepted despite being declinable
5 Walker double-visits description values (Nit) Nit ⏭️ Declined — per my own note that it isn't worth changing

5 recommendations → 3 addressed, 2 declined on my explicit guidance, 0 outstanding. No new issues found.


Top Risk Check: Did the restructure drop pre-existing coverage?

This was the stated top risk, and it's the right one to worry about — the loop was restructured and the label type threaded through every call site. I verified it empirically rather than by reading the diff.

I instrumented guidance_corpus() with a dump test, built it against both commits, and diffed the resulting corpora by text:

01af4eb2: 127 entries      fbc3d783: 134 entries
DROPPED TEXTS: 0
ADDED TEXTS:   7   (all routing::stage1_tool_definitions)

Per-channel histogram, before → after:

Channel 01af4eb fbc3d78
SCHEMA_CREATION_RULES 1 1
TOOL_STRATEGY_RULES 1 1
NODE_REFERENCE_FORMAT 1 1
skill_rules::SCHEMA_RULES 11 11
skill_rules::INTERACTION_RULES 7 7
skill_pipeline::seed_skill_nodes 8 8
prompt_assembler::seed_agent_guidance_nodes 5 5
local_agent::tools description + parameters_schema 14 + 79 = 93 93
routing::stage1_tool_definitions — 7
Total 127 134

Zero coverage lost. Every pre-existing channel is present at identical cardinality, and the 93 main-registry entries survived the restructure exactly. The delta is purely additive: the 3 Stage 1 tool descriptions plus 4 of their schema descriptions.


Independent Verification

Claim: "both registries flow through a single loop so they can't drift" — CONFIRMED and complete.
I grepped for every tool-definition producer in packages/agent/src/. There are exactly two registries — tools.rs:1331 all_tool_definitions() and routing.rs:128 stage1_tool_definitions() — plus model_facing_tool_definitions() (a filter over the former, subset by construction) and prompt_templates.rs format_tool_definitions() (a formatter, not a registry). The enumeration is now exhaustive, not merely "one more".

Claim: "verified it fires" — CONFIRMED, reproduced independently with a different plant site.
The implementer planted in route_query. I deliberately planted in a different tool — route_clarify's top-level description — using the real fixture prompt from agent-matrix.ts:

routing::stage1_tool_definitions route_clarify description the ENTIRE prompt appears
(9 consecutive words) from scripts/eval/fixtures/agent-matrix.ts
prompt "The 2400 one came back — set it to returned"

This confirms two things at once: the guard reaches Stage 1, and the new label genuinely resolves to registry + tool + channel. Plant reverted; git status clean.

Claim: "134 × 33, max shared run 3; Stage 1 worst case 2" — CONFIRMED exactly.
Re-measured from scratch against the real fixtures (33 prompts parsed, matching):

MAX SHARED RUN OVERALL: 3   (threshold MAX_SHARED_RUN = 4)
  run=3  TOOL_STRATEGY_RULES                          "i want to"
  run=3  prompt_assembler::seed_agent_guidance_nodes  "i want to"
  run=3  local_agent::tools update_node               "due date to"
  run=3  local_agent::tools create_node/create_schema "create a new"
STAGE1 MAX: 2  ("of the")
quoted_whole violations: 0

Stage 1's ceiling is 2 — it consumes none of the margin. The pre-existing corpus already sat at 3, and adding a 7th channel did not move the ceiling. Note the implementer reported Stage 1's worst phrase as "kind of" and I measured "of the"; both are run=2, so the number that matters is identical and the discrepancy is just which of several tied 2-runs sorts first. No concern.

Coverage test is non-tautological — verified by simulated regression.
I removed only the Stage 1 tuple from guidance_corpus(), leaving the coverage test untouched:

FAILED: tool route_query's description is absent from guidance_corpus()

It fails at the per-tool assertion (:548), correctly and with a message that names the offending tool.

Hygiene: git status clean in the worktree and in the primary checkout (git -C /Users/malibio/nodespace/nodespace-core status --short → empty), both before and after all experiments.


Requirements Check (issue #1932)

Requirement Status Evidence
Corpus includes every tool description ✅ 93 + 7 entries; per-tool assertion across both registries
Corpus includes parameters_schema descriptions ✅ Recursive walk, exceeds the issue's top-level-only proposal
Derived from registry functions, later-added tools covered automatically ✅ Both registries iterated; a third is one tuple
Guard still passes against current fixtures ✅ 14/14, max run 3 vs threshold 4
Guard demonstrably fires ✅ Reproduced on a plant site of my own choosing
No lint suppression / #[allow] / #[deprecated] ✅ Grepped: none. cargo clippy --all-targets -- -D warnings clean
No issue numbers in code comments ✅ Grepped #[0-9]{3,}: none. Comments cite ADR-064, the correct convention
No back-compat / dual-mode code ✅ Old shape deleted outright, not kept alongside

Code Review Findings

🟢 Suggestions

📁 packages/agent/src/agent_guidance.rs:560-564 — the tools_checked count assertion is sound but is the weaker half of a belt-and-braces pair.

assert!(
    tools_checked > crate::local_agent::tools::all_tool_definitions().len(),
    "both tool registries must be checked — only the main one was..."
);

You asked whether this is fragile or tautological. It is neither, but it is also not the assertion doing the real work. Assessment:

  • Not tautological: tools_checked is incremented inside the loop over registries, while the bound is computed from a fresh independent call. The two sides have genuinely different provenance — it is not n > n-k by construction.
  • Not fragile in the failure direction: it can only false-pass if Stage 1 were ever to become empty (vec![]), which would make tools_checked == len() and trip the assertion. It cannot false-fail.
  • But it is redundant: I proved by simulated regression that removing Stage 1 fails at the per-tool assertion on line 548 first, with a far better message (tool route_query's description is absent…). The count assertion is unreachable in that scenario. Its only unique coverage is the exotic case where someone replaces stage1_tool_definitions() with an empty vec — and there, assert!(!defs.is_empty()) per registry would say so more directly.

I'd keep it. It's three lines, costs nothing, and defends a real if unlikely shape. Just noting that the per-tool loop is the load-bearing assertion, so nobody later mistakes the count check for the primary guarantee and "simplifies" the wrong one away.

Principle: layered assertions are fine, but their relative strength should be legible — the strongest one should be the one a reader reaches for.

📁 packages/agent/src/agent_guidance.rs:157-171, 232-241 — the String widening is correct Rust, with a small amount of unavoidable verbosity.

You asked specifically about allocation and awkwardness. Assessment: no unnecessary allocation, mild syntactic cost, right trade.

  • The three leading constants now need .to_string() on the label as well as the text — 12 lines where 5 sufficed. Unavoidable given a homogeneous Vec<(String, String)>, and rustfmt is responsible for most of the vertical growth.
  • format!("{label} parameters_schema") allocates once per tool, then label.to_string() clones it once per description found. That's ~86 small allocations in a test that runs in 0.06s. Correct call — a Cow<'static, str> would remove them at the price of noise in a test helper, which is the wrong optimization.
  • collect_schema_descriptions taking &str instead of &'static str is a strict generalization; the two synthetic tests still pass "test" unchanged.
  • .map(|(name, text)| (name.as_str(), normalize(text))) at :441 borrows rather than clones — the right pattern, and it type-checks only because corpus outlives tokenized.

The mixed inline-{label}/positional-{} in format!("{registry} {}", def.name) is idiomatic (you can't inline a field access), so nothing to flag.

Principle: in test-support code, prefer clarity over allocation-avoidance; the widening buys diagnosis quality at a cost that never reaches a hot path.

📁 packages/agent/src/agent_guidance.rs:222-231, 543-547 — the comments carry the rationale well.

Worth calling out positively since it was finding #2: the added note explains both non-obvious choices (why two registries, why the unfiltered set) and explains them as why, not what. The "guarding only one registry would leave the very hole this enumeration exists to close, one registry over" line is exactly the framing that stops a future reader from re-litigating the decision. The doc comment on the coverage test was updated in step rather than left stale — an easy thing to miss in a rename-heavy diff.


Verification Performed

corpus diff 01af4eb2 → fbc3d783   → 127 → 134, 0 dropped, +7 (all stage1)
per-channel histogram              → all 9 pre-existing channels identical
registry enumeration exhaustive?   → yes, exactly 2 registries exist in packages/agent/src
plant in route_clarify (my own)    → guard FAILS naming registry + tool + channel
remove stage1 from corpus          → coverage test FAILS at per-tool assertion
max shared run 134 × 33            → 3 (threshold 4); stage1 worst case 2; quoted_whole 0
cargo test -p nodespace-agent --lib agent_guidance      → 14 passed, 0 failed (0.06s)
cargo clippy -p nodespace-agent --all-targets -D warnings → clean
cargo fmt -p nodespace-agent -- --check                  → 0 diffs in agent_guidance.rs
fmt drift in golden_scenario6_sequence.rs → PRE-EXISTING; file not in this PR's diff
git status → clean in worktree AND primary checkout

On the fmt drift: I confirmed it is not attributable to this PR — git diff --name-only origin/main...HEAD returns packages/agent/src/agent_guidance.rs and nothing else, so golden_scenario6_sequence.rs was never touched here.


Recommendation

APPROVE

The delta does what it claims and I verified the risky part empirically rather than by inspection. The headline result: the restructure dropped zero pre-existing coverage — all 127 prior entries survive byte-identical, and the change is purely the +7 Stage 1 additions.

Three things raise my confidence above the initial review:

  1. The gap is now closed exhaustively, not incrementally. I checked for other registries myself; there are exactly two, and both are in. "A third registry is one line" is true, but there is no third.
  2. The fix was verified on a plant site the implementer didn't use. Reproducing on route_clarify rather than route_query shows the coverage is structural, not tuned to one demonstration.
  3. The declined items were declined for the stated reason. Both 🟢/Nit declines match my own recommendation to keep the current shape; neither was quietly dropped, and Enhanced BaseNode with Hierarchical Circle Indicators + TextNode Implementation #4 was accepted despite my saying it was reasonable to decline — the resulting label (routing::stage1_tool_definitions route_query parameters_schema) demonstrably improves diagnosis, as my own plant experiment showed.

Remaining findings are 🟢 observations about assertion layering and Rust verbosity. Nothing blocking, nothing requiring another pass.

No re-review needed.

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

@malibio
malibio merged commit f06874f into main Aug 4, 2026
2 checks passed
@malibio
malibio deleted the issue-1932-tooldesc-contamination-guard branch August 4, 2026 05:29
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.

Eval-contamination guard does not cover tool descriptions or parameter schemas

1 participant