Skip to content

Gate destructive tools behind winning retrieval and a destructive score bar - #2244

Merged
malibio merged 2 commits into
mainfrom
issue-2240-deletion-skill-scoping
Aug 22, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2240-deletion-skill-scoping

Conversation

@malibio

@malibio malibio commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator

Closes #2240.

What was wrong

stage2_tools scoped the turn's tool surface to the union of every gate-clearing candidate's whitelist. So Node Deletion contributed delete_node merely by placing in the top-3 — and when no candidate whitelisted create_node, the turn simply could not perform the write the user asked for.

Two things worth correcting from the issue's framing:

The union, not rank-1, is the mechanism. In the Laguna 8c repro the candidates were Node Deletion, Bulk Import, Research & Search. create_node was absent because none of the three whitelisted it — not merely because Deletion ranked first. A fix aimed only at rank-1 would have left 8 of the 11 observed turns untouched.

The invariant was already agreed, just under-enforced. stage2_tools_are_scoped_to_eligible_candidate_whitelists already asserts "a read-only skill must not put a destructive tool in reach" — but passes a single candidate, so the union path was never covered.

ADR-038 says the expensive error should be "gated hardest"; riding along in retrieval cost a destructive skill nothing.

What changed

# Change Fixes
1 stage2_tools admits destructive tools only from the candidate that won retrieval the 8 rank-2/3 turns (scenarios 6, 10b, 11d)
2 DESTRUCTIVE_SKILL_SCORE_BAR — a third rung on ADR-038's ladder the 3 rank-1 turns (incl. 8c)
3 Reworded Node Deletion seed description retrieval signal, fresh installs only
4 Log line when scoping withholds a destructive tool observability

Tool::removes_user_data is an exhaustive match (like write_semantics), a strict subset of is_write, and deliberately distinct from the existing duplicate_is_destructive — that one is about repeating a call across turns; this is about what one call does.

An unrecognised tool name is mutating but not destructive — the opposite of skill_is_mutating's unknown handling. A typo'd or externally-registered whitelist entry must not attract the strictest bar in the system. Pinned by test so a later "consistency" cleanup can't quietly flip it.

Please read these caveats rather than skimming them

  • DESTRUCTIVE_SKILL_SCORE_BAR = 0.45 is an untuned placeholder, chosen structurally (clearly above the mutating bar, well below what a genuine "delete X" match earns) — not measured against live embeddings. This is a deliberate departure from ADR-038 line 159, which defers threshold tuning until an eval can separate model failure from harness failure. The ordering is the load-bearing property and is asserted at compile time. If a real deletion request is ever seen failing to route, this constant is the first thing to revisit.
  • The reworded description does not reach existing installs. Seeding skips by node type, so it only applies to a fresh DB. Changes 1 and 2 are what actually ship to current users; the reword is not claimed to fix the reported behaviour on its own.
  • Verification is unit-test-driven, by design. The defect is a deterministic pure function — (candidates, all_tools) -> Vec<ToolDefinition> — so tests pin it exactly with no GPU contention or run-to-run variance. No agent-matrix run was performed; real retrieval scores are therefore not exercised.

Verification

  • The Node Deletion skill is retrieved for creation and query requests, scoping away create_node #2240 regression test was confirmed to fail without the fix (delete_node present alongside create_node) and pass with it.
  • cargo test -p nodespace-agent — 558 lib tests pass, incl. 10 new.
  • Frontend matches baseline exactly: 227 files / 4794 tests.
  • Full pre-push gate (test:all + cargo build + test:e2e) passed.
  • ai_chat_send_to_idle_test — a real end-to-end inference turn against a daemon built from this branch — passes in 57s. (It first failed against a stale Aug-17 debug sidecar copied in to satisfy the fresh-worktree gap; rebuilding the daemon resolved it. Worth flagging since that trap is easy to misread as a real failure.)

🤖 Generated with Claude Code

https://claude.ai/code/session_0178cDupAoxb6oHW8WsmQxgp

…re bar (closes #2240)

Stage-2 scoped the turn's tool surface to the UNION of every gate-clearing
candidate's whitelist, so `Node Deletion` contributed `delete_node` merely by
placing in the top-3. Measured across 6 runs / 3 models, it was a retrieved
candidate on 11 turns spanning 5 scenarios whose prompts recorded a decision,
marked a status, set a due date, and asked a question — none asked to remove
anything. When no candidate whitelisted `create_node`, the turn could not
perform the write the user asked for, and the model had no evidence a better
tool existed.

- `Tool::removes_user_data` — an exhaustive-match classifier for tools that
  irreversibly remove user data, a strict subset of `is_write`. Distinct from
  the existing `duplicate_is_destructive`, which is about repeating a call
  across turns rather than what one call does.
- `stage2_tools` admits a destructive tool only from the candidate that won
  retrieval; the union is unchanged for everything else. The winner is picked
  by explicit max so this safety property does not depend on the caller's
  sort order.
- `DESTRUCTIVE_SKILL_SCORE_BAR` adds a third rung to ADR-038's blast-radius
  ladder (read < mutating < destructive), so a weak destructive match cannot
  win rank-1 on a non-destructive request. The ordering is asserted at compile
  time; the value is an untuned placeholder, like the two bars below it.
- `Node Deletion`'s seeded description drops its generic "a node or record"
  tail, which made it an attractor for anything node-shaped.
- A log line when scoping withholds a destructive tool, so this failure stops
  looking like a model that declined to call a tool.

An unrecognised tool name is mutating but NOT destructive — the opposite of
`skill_is_mutating`'s unknown handling, so a typo'd whitelist cannot attract
the strictest bar in the system. Pinned by test.

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

malibio commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2244

Review Type: Initial Review (no prior reviews or comments on this PR)


Requirements Check (issue #2240)

# Requirement Status
1 delete_node must not reach the surface when Node Deletion merely places in the top-3 ✅ stage2_permitted_names admits destructive tools only from the top-scoring eligible candidate. Pinned by a_destructive_skill_that_only_places_cannot_put_delete_node_in_reach.
2 The turn's needed write tool must not be crowded out ✅ The union is unchanged for every non-destructive tool; the runner-up's search_nodes still lands.
3 A genuine deletion request must still be able to delete ✅ a_destructive_skill_that_wins_retrieval_still_offers_delete_node.
4 Rank-1 weak destructive matches ✅ DESTRUCTIVE_SKILL_SCORE_BAR closes this — verified consistent across all five clears_score_gate call sites (see below).
5 Retrieval signal (description reword) ✅ Implemented; correctly caveated as fresh-installs-only in the PR body.
6 Observability ✅ destructive_tools_withheld + tracing::info!.

📝 The PR body's correction of the issue's framing — that the union, not rank-1, is the primary mechanism, and that a rank-1-only fix would have left 8 of 11 observed turns untouched — is accurate and is the right diagnosis. stage2_tools_are_scoped_to_eligible_candidate_whitelists did assert the invariant but passed a single candidate, so the union path was genuinely uncovered. That is an honest account of a test that looked like coverage and wasn't.

Verification of the accepted limitations: all three are stated correctly, not mis-stated. Seeding does skip by node type (skill_pipeline.rs), so the reword genuinely does not reach existing installs. 0.45 genuinely is unmeasured. 558 passed and cargo clippy clean both reproduce locally.


Code Review Findings

I checked the specific areas raised, and the three highest-risk ones come back clean. Recording that explicitly, because "I looked and found nothing" is a different result from "I didn't look."

✅ Verified clean: NaN, ties, and the fail-open branches

📁 packages/agent/src/local_agent/routing.rs:530-548

fold(f32::NEG_INFINITY, f32::max) with c.score >= top_score is correct here, and each sub-case holds for a real reason rather than by luck:

  • NaN. A NaN score cannot reach the fold at all: clears_score_gate is score >= bar, which is false for NaN, so a NaN candidate is filtered out upstream. Even if one did reach it, f32::max returns the non-NaN operand regardless of argument order (I confirmed both orderings). The dangerous combination — NaN becoming top_score and then NaN >= NaN admitting a destructive tool — cannot occur, since NaN >= anything is false. Fails closed.
  • All candidates ineligible. top_score becomes -inf, but the flat_map runs over the same empty filtered set, so permitted is empty and stage2_tools takes the existing fail_open_surface branch. Reachable and correct.
  • Ties. >= keeps every tied top scorer, deliberate and matching declare_write_tool_fields. Worth naming the security shape: a tie widens destructive admission slightly. That is the right call — a tie means two skills matched equally well, and treating it as "nobody wins" would strand a genuine deletion request — but it is the one branch where the property is permissive rather than restrictive.
  • Float equality. No epsilon concern: top_score is drawn from the very set being compared, so the winner compares bit-identical to itself. This would only be fragile if top_score came from a different arithmetic path.

Picking the winner by explicit max rather than candidates[0] is the right instinct, and destructive_admission_does_not_depend_on_candidate_order pins it. A safety property should not depend on a caller's sort order remaining incidental — that is exactly the coupling that survives review and then breaks silently two refactors later.

✅ Verified clean: the deliberate mutating/destructive asymmetry

📁 packages/agent/src/local_agent/tools.rs:1880-1895, routing.rs:311-327

The reasoning is sound and is not merely defensible — it is the only correct choice. The two unknowns answer different questions:

  • skill_is_mutating asks "could this cause a write?" Unknown ⇒ assume yes, because an unknown blast radius must not get the lower bar. ADR-038 line 154 states this explicitly.
  • removes_user_data_tool asks "do I affirmatively know this deletes?" Unknown ⇒ no, because an unknown name is already captured as mutating by the first classifier. Flipping it would apply the strictest bar in the system to any skill with a typo'd whitelist entry — an availability failure with no corresponding safety gain, since an unknown tool is not in all_tools and cannot be offered anyway.

The insight that makes this safe, which the doc comments state correctly, is that the two classifiers compose: nothing falls through to the read-only bar. Documentation and testing are adequate — an_unrecognised_tool_name_is_mutating_but_not_destructive asserts all three properties including the resulting bar, and both doc comments explicitly warn against a future "consistency" cleanup flipping it. That is the right defensive move for a non-obvious asymmetry.

✅ Verified clean: clears_score_gate consistency across all five call sites

I traced every one, since an inconsistency would mean the new bar closes some rank-1 paths but not others:

Call site Line Consistent?
routed_skill_names 373 ✅
render_candidates_for_prompt 392 ✅
tools_with_available_guidance 498 ✅
stage2_permitted_names 538/544 ✅
declare_write_tool_fields 708 ✅

All five call the same clears_score_gate, which routes through the same score_bar_for. Because change 3 raised the bar inside score_bar_for rather than at any call site, all five inherit it atomically — a sub-bar destructive candidate is invisible everywhere at once. This is the right place to have made the change; adding the check per call site would have created exactly the drift the question was probing for. a_destructive_skill_below_its_bar_is_ineligible_everywhere pins three of the five.

One detail worth calling out as deliberately right: score_bar_for checks destructive first. Since a destructive skill is necessarily also mutating, the reverse order would short-circuit at the lower rung and silently render the new bar dead. The comment says so.

✅ Verified clean: no stage2_permitted_names / declare_write_tool_fields inconsistency

Both compute "the turn's global top score" over clears_score_gate candidates and both use >= for ties, so they agree on who won. They seed the fold differently (NEG_INFINITY vs MIN) but that is unobservable — both are below every real score, and both empty cases are guarded. The two also gate different things (tool availability vs schema content), so even a divergence would not produce an unsafe surface. See the nit below on the seed value.


🟡 Important: the seeded blast-radius test was not extended to the new rung

📁 packages/agent/src/skill_pipeline.rs:782-793

seeded_skills_classify_by_blast_radius_as_expected pins skill_is_mutating against the real seed data for all eight seeded skills, with a comment explaining that the point is to fail "if a seed's whitelist gains or loses a write tool without that being an intentional change to its Stage-2 bar."

That guard now has a hole. The PR adds a third rung, but the test still has only a should_mutate column. Nothing pins that Node Deletion is the only destructive seed. Concretely: if someone adds delete_node to Organization's or Bulk Import's whitelist, that skill silently jumps to the strictest bar in the system and starts losing destructive admission to whoever wins retrieval — and every existing test still passes, because should_mutate was already true for both.

removing_user_data_is_a_strict_subset_of_writing pins the registry side (destructive == ["delete_node"]), but not the seed side, which is where the coupling actually bites. Suggested fix — extend the tuple to a third column:

let expected = [
    // (title, mutating, destructive)
    ("Node Creation", true, false),
    ("Node Deletion", true, true),
    ("Bulk Import", true, false),
    // ...
];
// then also assert skill_is_destructive(&candidate) == should_destroy

Engineering Principle: A test that pins a derived classification against real data must be extended whenever the classification gains a dimension — otherwise it keeps passing while covering less than its own doc comment claims. This is the same failure mode the PR body correctly identified in stage2_tools_are_scoped_to_eligible_candidate_whitelists, which passed a single candidate and so never exercised the union path. Worth not reintroducing it one file over.


🟡 Important: the 0.45 bar and the reword push the same quantity in opposite directions

📁 packages/agent/src/local_agent/routing.rs:67-89, packages/agent/src/skill_pipeline.rs:350-362

I am not re-reporting the documented "untuned placeholder" caveat — that is disclosed, and shipping an ordering-correct untuned bar is a reasonable call. This is about an interaction between changes 2 and 3 that the PR body does not connect, and which the caveat therefore does not cover:

  • Change 3 makes the description more specific (drops the generic noun tail, adds an exclusion clause).
  • Change 2 raises the score a deletion match must clear, to 0.45.

A narrower description embeds further from an indirectly-phrased real deletion request ("get rid of that old meeting note", "I don't need the Q3 draft anymore") — exactly the indirect phrasing ADR-038 names as its load-bearing unverified assumption. The reword lowers the score a genuine deletion earns at the same moment the bar demanding it went up.

For context: 0.45 is 3× the read bar and 1.5× the mutating bar, and the observed spurious matches scored ~0.35–0.5. The PR's own regression test uses 0.5 as the "placed but did not win" score — a score above 0.45 chosen to represent a spurious match. That leaves a fairly narrow band for a genuine match to land in.

The failure mode is also asymmetric: a below-bar deletion does not degrade gracefully. It is excluded from render_candidates_for_prompt too, so the model is not shown deletion as an option it could have picked — the user asks to delete something and the agent behaves as though deletion is not a capability.

I would not block on this, and I would not guess at a different number — replacing one unmeasured constant with another is not progress. Two things would help:

  1. The tracing::info! currently fires only when scoping withholds a destructive tool from an eligible candidate. The case above — a destructive candidate rejected by the bar — is silent. Logging that too makes the risk observable in the field rather than only reportable by a confused user. Small addition to code this PR already touches, and it converts an unknown into a measurement.
  2. Consider noting the reword/bar interaction in DESTRUCTIVE_SKILL_SCORE_BAR's doc comment. It already says "if a real deletion request is ever seen failing to route, this constant is the first thing to revisit" — the description is the second thing, and the next reader has no way to know the two moved together.

Engineering Principle: When two changes in one PR affect the same measured quantity in opposite directions, the combined effect needs stating even when each is individually justified — otherwise the caveat on one reads as covering both. Bias observability toward the failure you cannot currently measure.


🟢 Suggestion: log line is correct; one detail

📁 packages/agent/src/local_agent/agent_loop.rs:1311-1328

The tracing::info! is at the right level and has no leak risk — I checked. It emits session.id, tool wire names, and skill names: all system-controlled identifiers, no user message content, node titles, or query text. session_id = %session.id matches the established pattern at five other sites in this file. info over warn is right: withholding is designed behaviour, and warn for a working system trains readers to ignore the channel.

The reasoning for destructive_tools_withheld re-reading stage2_permitted_names rather than reimplementing the rule is exactly right — a log that can disagree with the behaviour it reports is worse than no log, because it actively misleads during the incident it exists to explain.

Nit: withheld_tools = %withheld.join(", ") allocates a String on every turn where something is withheld. Negligible (rare path, ≤1 element today), and it matches routed_skill_names' shape, which the codebase documents as a scraper contract. Fine as-is.


🟢 Nit: fold seed inconsistency

📁 packages/agent/src/local_agent/routing.rs:540 vs :709

stage2_permitted_names seeds with f32::NEG_INFINITY; declare_write_tool_fields seeds with f32::MIN. Both are correct and unobservable. NEG_INFINITY is the better idiom — f32::MIN is the most-negative finite value and reads like a bug to anyone who has met the i32::MIN analogue. Since the new code already uses the better one, aligning line 709 would remove a "why do these differ?" moment. Optional, and arguably out of scope.


Assessment

A well-constructed change and a clear net improvement to code health. The parts it gets right are worth naming, because they are the ones most often skipped:

  • It fixes the actual mechanism, not the reported symptom. The PR body corrects the issue's own framing and explains why a rank-1-only fix would have missed 8 of 11 turns. I verified that correction against the code.
  • It ships the regression test that fails without the fix and confirms that it does.
  • It scopes narrowly. Only destructive admission is narrowed; the union is untouched for everything else, so the fix's own blast radius is small.
  • The asymmetry is documented on both sides and pinned by a test that names the future refactor most likely to break it. Unusually good defensive commenting for a non-obvious invariant.
  • The caveats are disclosed rather than buried, and all three check out under scrutiny.

The two Important findings are additive — a test-coverage gap and an observability gap — not defects in the shipped logic. I found no correctness bug in the top-score selection, no inconsistency across the five gate call sites, and no security or logging concern.

Recommendation: APPROVE

Worth doing before merge (both small, neither blocking): extend the seeded blast-radius test with a destructive column, and consider logging bar-rejected destructive candidates so the 0.45 risk becomes measurable in the field rather than waiting on a user report.

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

…ed deletions

Both 🟡 Important findings from the PR #2244 review. Neither was a defect in
the shipped logic — a test-coverage gap and an observability gap.

1. `seeded_skills_classify_by_blast_radius_as_expected` pinned only
   `should_mutate`, so the new destructive rung was unguarded on the seed
   side. `removes_user_data` pins that `delete_node` is the only destructive
   *tool*, but nothing stopped a second *seed* from whitelisting it — and
   every seed with a write tool already had `should_mutate: true`, so such a
   change would have moved that skill to the strictest bar in the system with
   the whole suite still green. Added a third column. Verified it fails on the
   reviewer's exact scenario (adding `delete_node` to `Organization`).

2. `destructive_candidates_below_bar` + a log line for a destructive skill
   retrieval surfaced that the bar rejected outright. This is the failure mode
   in the opposite direction from the withheld-tool line: not "a destructive
   tool leaked onto the surface" but "a real deletion request may have been
   dropped".

   The reviewer's point behind (2) is worth recording: changes 2 and 3 of this
   PR push the same quantity in opposite directions — the bar a deletion match
   must clear went up, while the description was narrowed, and a narrower
   description embeds further from an indirectly-phrased real request. Both
   moves are individually justified and the bar is a documented placeholder,
   but the interaction was not stated in the PR body and neither side was
   measured. Logging the rejects with their scores turns that unknown into
   something readable from ordinary logs rather than a user report.

Deliberately NOT changed: the value of DESTRUCTIVE_SKILL_SCORE_BAR. Swapping
one unmeasured constant for another is not progress; the log line is what
makes a future choice evidence-based.

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

malibio commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — both 🟡 Important findings

Commit bb939cd4. Both were additive gaps rather than defects, and both are now closed.

✅ 1. Seeded blast-radius test extended to the new rung

📁 packages/agent/src/skill_pipeline.rs

Correct catch, and the reasoning was exactly right: removes_user_data pins that delete_node is the only destructive tool, but nothing pinned which seeds are destructive — and every seed with a write tool already had should_mutate: true, so a seed gaining delete_node would have jumped to the strictest bar in the system with the whole suite still green.

Extended the tuple to (title, mutating, destructive).

I verified the guard actually works rather than assuming it: adding delete_node to Organization's whitelist (your exact scenario) now fails with

skill 'Organization' gained or lost the ability to irreversibly remove user data;
whitelist is [..., "delete_node"]. This changes its Stage-2 score bar AND whether
it may contribute destructive tools when it is not the retrieved winner.

The old should_mutate-only version passed that same mutation.

✅ 2. Bar-rejected destructive candidates are now logged

📁 packages/agent/src/local_agent/routing.rs, agent_loop.rs

destructive_candidates_below_bar + a log line, distinct from the withheld-tool line: that one reports "a destructive tool leaked onto the surface", this reports the opposite failure — a real deletion request may have been dropped entirely. Scores are logged alongside names so the distribution is readable from ordinary logs rather than requiring a dedicated eval run.

Your framing of the underlying interaction was the most useful part of the review and I've recorded it in the commit message: changes 2 and 3 push the same quantity in opposite directions — the bar a deletion match must clear went up, while the description was narrowed, and a narrower description embeds further from an indirectly-phrased request. Both moves are individually justified and the bar is a disclosed placeholder, but that interaction was not stated in the PR body, so the caveat genuinely didn't cover it.

⏭️ Deliberately not changed: the value of DESTRUCTIVE_SKILL_SCORE_BAR

Agreeing with your reasoning — swapping one unmeasured constant for another isn't progress. The log line is what makes a future choice evidence-based. Left at 0.45.

Verification

  • cargo test -p nodespace-agent --lib — 559 passed, 0 failed (up from 558; one new test, one extended).
  • The extended seed test confirmed to fail on the injected regression and pass after revert.
  • bun run quality:fix clean; full pre-push gate (test:all + cargo build + test:e2e) passed.

No re-review needed — one new test, one extended test, one additive log line. No change to the routing logic that was already reviewed and approved.

@malibio
malibio merged commit b5c892b into main Aug 22, 2026
@malibio
malibio deleted the issue-2240-deletion-skill-scoping branch August 22, 2026 20:44
malibio added a commit that referenced this pull request Aug 23, 2026
…s as model failures (#2256)

* Stop the agent matrix scoring an unreachable assertion as a model failure

Three defects surfaced while evaluating candidate models for #2239, all found
by reading traces rather than scores.

## Asserted tool never offered

Stage-2 scopes each turn's tool surface to the retrieved skills' whitelists, so
a retrieval miss can remove the tool a scenario asserts on. The scenario then
reds out for "not calling" a tool the model was never given, which measures
skill retrieval and reports it as tool use.

Observed live: "Put down that we went with event-based cache clearing, Priya's
call" retrieved Node Deletion as rank-1, scoping the turn to delete/search
tools with no `create_node` present. Filed as #2240 and fixed separately in
#2244; the same shape recurs for `update_node` in #2254.

`EvalFixture.requiredTools` names the action tools a scenario's expectation
makes reachable, and the runner excludes a turn whose asserted tool was absent
from `toolsOffered` — on the same grounds as a degenerate empty generation: the
assertion was unreachable, so neither a pass nor a fail is a statement about
the model. Still recorded, so the rate stays visible. `noTools` and `noRetry`
require nothing, since neither becomes unreachable when a tool is withheld.

## NODESPACE_HOME did not isolate provider configs

`assembly.rs` built the `daemon.toml` path from `dirs::home_dir()` rather than
`nodespace_dir()`, so an isolated daemon served a temp database while reading
OpenAI-compat provider configs — and WRITING routing-probe verdicts — into the
user's real `~/.nodespace`. Same class as the `NODESPACED_DB_PATH` trap ADR-053
warns about: one component honouring the isolation while another quietly does
not. It also blocks every served-model eval arm, which is how it was found.

## Clarification scored as a pass where the prompt underdetermines the write

A scenario whose prompt cannot supply every required field leaves a model three
options: fabricate the missing value, send an incomplete call and be rejected,
or ask the user. Asking is the best of the three and was the only one scoring
zero — a clarification writes nothing, so `assertEndState` finds no created or
updated node and fails it.

The inversion is measured. Scenario 8d says "New cycle: Harbour, it wraps up on
the 30th" — an end date, no start date, against a type the model itself defined
one turn earlier:

  Laguna-XS  asked for the start date              -> FAIL
  E4B        guessed, write REJECTED by backend    -> passed on tool name

So the suite rewarded a model that guessed and corrupted nothing only by luck,
over one that checked. In a product that writes to the user's own knowledge
graph that is the wrong way round.

`scoreOutcome` is pure over the diff by design, and a clarification is invisible
in a diff — nothing changed. The scored turn is therefore threaded through to
it rather than smuggling turn state into `GraphDiff`, which would make the diff
mean two things. `turns` is optional so a caller holding only a diff (unit
tests, or a future consumer re-scoring a recorded run) still gets the graph
assertions.

Recognised two ways: a `route_clarify` call, or no action tool plus a reply
containing a question mark. The text check is deliberately narrow — it requires
BOTH conditions, so a turn that acted and merely ended on a question cannot be
credited. `route_clarify` is the robust signal; the prose check is a fallback
for models that ask without routing.

Opt-in per scenario, following `noRetry`'s `minCalls` precedent: changing shared
scoring semantics silently re-scores every existing scenario. Only 8d opts in,
and only because its required fields come from a type the model defines at run
time, so no fixed prompt can guarantee completeness. A fully determined prompt
should still fail a clarification — there a question is evasion, not care.

A capture error still wins over `clarifyOk`, so this cannot mask a dead daemon.

7 new tests. `bun run test:scripts` 224 pass, `bun run test` 227 files pass.

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

* Let a served-model eval pace its turns past a per-minute rate limit

Free tiers on hosted endpoints cap requests per MINUTE, and a matrix turn
issues several back to back — Stage-1 routing, then one per ReAct iteration.
The burst trips the cap even when the sustained average sits far below it.

Measured on OpenRouter's `free-models-per-min`: 20/20 requests succeeded when
curl's own round-trip latency spaced them ~2.6s apart, while a real run took 10
rate-limit errors in its first 11 requests. Two full Nemotron 550B attempts and
two Laguna-S attempts were lost to this before the cause was clear — the tell is
that a single smoke request always passes, so the endpoint looks healthy right
up until a rep starts.

`NS_TURN_DELAY_MS` pauses before each turn. Opt-in, so local arms pay nothing:
they have no such limit, and a delay there would only lengthen an already
GPU-bound run. At 4000ms a Nemotron 550B run went from 10 rate-limit errors in
11 requests to 1 in 78 turns.

This paces the TURN boundary rather than individual requests inside a turn.
Coarser, but it needs no reach into the inference engine's retry path, and the
burst it flattens is the one that actually trips the cap.

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

* Retry a throttled OpenAI-compat endpoint instead of failing the turn

A 429 is a transient condition, but the engine treated any non-2xx as terminal:
the turn failed, the scenario scored as "no tools called", and the run became a
measurement of the provider's capacity rather than the model. That failure is
also quiet in the worst way — a turn that calls no tools scores GREEN on every
negative assertion, so a throttled run reports a plausible partial result.

Measured across six served eval runs while evaluating candidates for #2239,
only one was clean:

  Laguna-S       unpaced   40 of 63 turns rate-limited
  Laguna-S       unpaced   48 of 78
  Laguna-S       2s        23 errors against 20 requests
  Laguna-S       8s        39 of 81
  Nemotron Ultra 4s         1 of 78   <- clean
  Nemotron Super 4s        62 of 81

External pacing (NS_TURN_DELAY_MS) was the first attempt and it does not
generalise: the same 4s that left Ultra clean left Super at 77% contaminated,
because Super is faster and bursts harder at the same delay. The delay has to
be re-tuned per provider and per model, and three attempts to guess it were
wrong. Backoff adapts without being told.

Retries 429 and 5xx, honouring `Retry-After` when the server sends one and
otherwise doubling from 2s. Bounded at 4 attempts and a 60s per-wait ceiling —
roughly two minutes total. A turn that cannot get through in that window is a
real outage, and hanging on it would trade a bad number for a run that never
finishes; `retry_policy_is_bounded` pins that.

Non-retryable statuses (4xx other than 429) still fail immediately: a bad
request will not become valid by being sent again.

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

* Address code review: four blocking defects, three of them self-inflicted

All four blockers from the review on #2256, plus two of the important findings.
Three were introduced by this branch's own rebase and were invisible to every
gate that ran, which is the part worth recording.

## types.ts was not valid TypeScript

A union-merge during the rebase concatenated both conflict sides and swallowed
the `/**` opening two doc blocks, leaving bare ` * ` lines inside the interface
bodies. `tsc` rejects the file (TS1131/TS1005/TS1434).

It escaped every gate because `types.ts` is imported type-only: Bun elides it
at runtime, so `test:scripts` never parses it. A type-only file needs `tsc`,
not a test run, to be checked at all — and as a consequence the two new fields
were not part of their interfaces as parsed, which is exactly why the next
defect produced no type error.

## The requiredTools guard could never fire

The runner reads `fixture.requiredTools?.(scenario)`, but no fixture
implemented the hook — the implementation was lost when this branch took
upstream's rewritten fixture wholesale during the same rebase. `required` was
always `[]`, so the guard was unreachable and the headline claim was not in
effect. Restored in the matrix fixture.

## clarifyOk turned a dead daemon into a pass

The `clarifyOk` early return sat ABOVE the `captureError` guard, so a turn
whose snapshot failed scored PASS whenever its reply happened to contain a
question mark. That is precisely the confusion the harness exists to prevent —
an environment fault filed as a model verdict — and this branch introduced it.

Environment faults now outrank outcome grading, as they did before. The test
covering this passed `askedForClarification: false` and so passed vacuously; it
now passes `true`, which is the only case that can distinguish the orderings.

## rust:lint failed on this branch's own test

`clippy::assertions-on-constants` fires on `retry_policy_is_bounded`, which
compares compile-time constants. Moved into `const { assert!(..) }` per
clippy's own suggestion — strictly stronger than a runtime assert, since a
violation becomes a compile error. An `#[allow]` would have violated the
project's no-lint-suppression standard.

The earlier claim that this failure was pre-existing and caused by a missing
`resources/skill/` was wrong. `RETRY_MAX_ATTEMPTS` does not exist on
origin/main; the failure arrives with this branch. The earlier check used
`cargo clippy --lib`, which does not compile test targets.

## Retry bound was 240s, not the ~120s claimed

`Retry-After` REPLACES the backoff and was capped only by `RETRY_MAX_DELAY`, so
four waits of 60s was the real worst case. The test recomputed the exponential
path (30s) and asserted against that, never touching the branch that governs
the bound.

`RETRY_MAX_DELAY` lowered to 20s, putting the true worst case at 80s. The test
now asserts over the `Retry-After` path and cross-checks that the exponential
path stays under it. Also corrected the request count: retries follow the
initial send, so N retries means N+1 requests.

## The new exclusion was invisible

It left the scored set but appeared in no count and had no glyph, so totals
stopped reconciling and the comment's promise that "the rate stays visible" was
false. Added `toolNotOfferedCount` and a distinct `⊗` marker — kept separate
from `⊘` because an empty generation is an inference bug and this is a routing
miss, and collapsing them would hide which one a run is suffering from.

Verified: `bun run rust:lint` clean, `cargo fmt --check` clean,
`tsc --noEmit scripts/eval/types.ts` clean, `bun run test:scripts` 224 pass,
`cargo test -p nodespace-agent --lib openai_compat` 17 pass.

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

* Address review finding 7: stop counting the pacing delay as turn latency

`NS_TURN_DELAY_MS` slept inside `aichat.ts`, which is the subprocess `runTurn`
times, so every recorded `latencyMs` carried the delay. A 45s Gemini pause put
turn latencies at ~49s and made a fast model look slow — and those served-vs-
local comparisons were reported as a decision input on #2239, so the defect
reached a conclusion, not just a log line.

Moved into the runner ahead of the clock. `runTurn` is synchronous and the
harness is serial, so this blocks with `Atomics.wait` on a throwaway buffer
rather than making the whole call chain async purely to await a sleep.

Also documents why `resolve_model_path` keeps reading the real home (review
finding 11), rather than changing it. That path resolves a multi-GB read-only
model meant to be shared across instances, and has its own
`NODESPACED_MODEL_PATH` override; making it follow NODESPACE_HOME would force
every isolated run to re-download a model for no benefit. The config path was
not analogous — `daemon.toml` is WRITTEN to by the routing probe, which is why
resolving it against the real home was a genuine bug.

Findings 8, 9 and 10 needed no action: each validated an existing decision
(the prose fallback is adequately fenced, threading `turns` through
`scoreOutcome` is the right call, and the exclusion trade is sound).

Verified: `bun run rust:lint` clean, `cargo fmt --check` clean,
`bun run test:scripts` 224 pass.

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

* Record why the model path always defaults to ~/.nodespace/models

The rationale was abstract ("models are multi-GB"); the concrete number makes
the decision obvious. A dev machine mid-evaluation held 9 GGUFs totalling 39 GB
in that directory — resolving it against NODESPACE_HOME would have every
isolated run start from an empty directory and re-download.

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

* Make the unrouted-turn exclusion visible, and fix three misleading comments

Re-review finding 12: the previous fix added `⊗` to `markerFor` and
`toolNotOfferedCount` to the results JSON, and both were real — but neither sat
on a path a human reads. `markerFor`'s only caller runs AFTER this branch
`continue`s, so the excluded turn printed its own hardcoded `⊘`, the very glyph
`⊗` was added to be distinguishable from; and the count reached the JSON but no
summary line, so the denominator shrank with nothing on screen to explain it.

That is the same shape as the three self-verification failures before it —
checking that a mechanism EXISTS rather than that the property HOLDS. The
struct field was there; nobody could see it. Now the emitted line carries `⊗`
and the summary prints an `Unrouted:` count beside the other exclusions.

Three comment corrections, each of which would mislead a future reader:

- `pauseBeforeTurn` had been inserted BETWEEN `runTurn`'s doc block and
  `runTurn`, so the `sendFailed` rationale — the one explaining why a dead
  daemon must not pass a "no tools" assertion — documented the sleep helper.
- The `requiredTools` comment claimed `noRetry` is exempt because it is
  "satisfied by a turn that never called the tool". Untrue since `minCalls`
  was added (scenario 11 uses it). No scoring bug today because this fixture
  grades on outcome, but the stated reason is what a reader would rely on, so
  it now says the real one and names what would change if it mattered again.
- The retry doc still claimed "near two minutes"; the real worst case is 80s
  after `RETRY_MAX_DELAY` dropped to 20s.

Verified: `bun run rust:lint` clean, `cargo fmt --check` clean,
`tsc --noEmit scripts/eval/types.ts` clean, `bun run test:scripts` 224 pass.

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

---------

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.

Node Deletion skill is retrieved for creation and query requests, scoping away create_node

1 participant