Skip to content

Restore the Stage-2 write-tool surface, and stop a failed write reporting success (closes #2254) - #2257

Merged
mstomar125 merged 16 commits into
mainfrom
issue-2254-stage2-write-tool-surface
Aug 24, 2026
Merged

mstomar125 merged 16 commits into
mainfrom
issue-2254-stage2-write-tool-surface

Conversation

@malibio

@malibio malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator

Closes #2254.

Stage-2 withheld update_node on turns that needed it, and the model sometimes reported success for the resulting no-op. Measured on the locked model (E4B native), the write turn now succeeds 6/6, up from 3/6 on the same harness before these changes — with fields=1 on every rep confirming the write persisted a property rather than being an id-only no-op.

Two blockers found underneath turned out to matter more than the reported symptom, and both are fixed here.

The routing defect was two seed-data bugs, not a missing classifier

The report suggested keying the tool surface off an "update" classification. That was not implementable — RouteDecision is Query(String) | Clarify | Multi, so no such classification exists — and it was not needed:

A skill description named the operations it excluded. Node Deletion ended "— not to record, update, mark, or look something up". That clause was added to stop over-retrieval and caused it, because embeddings have no notion of negation: a sentence listing "record, update, mark" lands NEARER those intents. The write turn is "The five-day one got signed off — mark it that way". This skill was retrieved into the top-3 on all 18 turns of a 6-rep run, including all three that then failed for want of update_node. Fixed by keeping destructive verbs only and moving the scoping rule into the instruction subtree, which the model reads as text rather than as a vector.

Every write tool was reachable from exactly one skill. Read tools sat in six or seven (get_node 7, search_nodes/search_semantic 6); every write except create_relationship sat in one. Under RETRIEVAL_TOP_K = 3 that makes availability a lottery — if the sole owner misses the window, the tool does not exist for the turn. update_node/update_task_status are now also on Node Creation and create_node also on Graph Editing, with a new guidance rule so the added tool cannot turn an update into a duplicate.

Both are pinned by tests: no description may carry a negated capability clause, and no write tool may be single-sourced (four documented exceptions, delete_node among them since stage2_permitted_names admits destructive tools only from the retrieval winner).

A failed write was reported as a success

Narrower and more serious than the report described. Three response guards already existed, all gated on !normalized.is_empty() — so a turn where the model emits no text reached a fallback that formatted the LAST execution's name into "Done — {} completed successfully." without consulting is_error:

[tool] create_node [ERROR]      (Unknown node_type)
assistant> Done — node creation completed successfully.

Both such fallbacks now delegate to summarize_executions, which already existed for this and labels a failed call "failed". Verified live: the identical failing call renders "• node creation failed".

Blocker 1 — a ~30s embedding debounce made retrieval a race

Seeded skills are inserted synchronously but embedded on a debounce, so a daemon on a purged database serves turns with an EMPTY skill index: candidates=0, fail-open to 13 tools, no skill guidance injected. Read from the database: daemon ready 17:53:20.538, all 8 skill embeddings 17:53:50.615.

The same applies to schemas the model itself creates. A schema created at 17:55:49.501 was not semantically retrievable until 17:56:20.446 — and in the run that PASSED, the instance was created 1.4 seconds after that. The chain succeeded on timing alone.

Fixed on both sides: a preflight gate that waits for the skill index (eval), and a lexical backstop that recovers a schema the request names outright (product — "track my write-ups" then "add one" is an ordinary user sequence, not just an eval artifact).

Blocker 2 — create_schema succeeded ~1 turn in 5

Dumping the GBNF llama.cpp applies during sampling:

tool-create-schema ::= ("create_schema") gemma4-dict
gemma4-dict        ::= "{" space ("}" | gemma4-dict-kv ("," space gemma4-dict-kv)* space "}")

Tool-call arguments are constrained to any well-formed JSON object. required: ["name","fields"] appears nowhere, so sampling accepts a payload with no schema name and serde rejects it afterwards with a bare missing field \name`` the model cannot act on — it re-sent the identical payload until the duplicate-call guard broke the loop.

This is a documented upstream limitation, not a local defect. A llama.cpp collaborator states it directly: "Gemma 4 only forces the structure, not the arguments", because json-schema-to-grammar.cpp "only produces rules for JSON and not Gemma's fc notation" (discussion 21839). PR #23247 has been open and unreviewed since May, and its own reported blocker is enum constraints on required properties — exactly create_schema's shape. Two related issues are closed as not planned.

So the constraint is applied at our boundary: an actionable error naming the missing top-level key and reflecting back the accepted fields, plus dropping field entries that carry no information at all ({"description":null,"name":null}, which the model appends on the very retry that correctly adds the name). 1/5 → 5/6 turns.

Corrections recorded rather than dropped

Testing

bun run test:all exits 0 — 53 suites, no failures. Frontend 227 files / 4794 tests, identical to the baseline recorded at startup. Prompt-assembly goldens updated: 80 insertions, 0 deletions, so nothing was removed from what production sends the model.

🤖 Generated with Claude Code

malibio and others added 8 commits August 23, 2026 23:01
Two fallbacks synthesized "Done — <tool> completed successfully." from the
LAST execution's name without consulting `is_error`, so a turn whose only
write failed told the user it had succeeded.

Reproduced live against the locked model on a seeded chain: `create_schema`
failed, so the node_type the following `create_node` named did not exist, and
the turn rendered

    [tool] create_node [ERROR]      (Unknown node_type 'feature_writeups')
    assistant> Done — node creation completed successfully.

Nothing was written. The user was told it was.

None of the three existing response guards can catch this shape. Anti-
fabrication keys on zero tool calls; no-op success keys on writes that
persisted zero fields; tool-failure surfacing keys on an unacknowledged error
in the model's text. All three are gated on `!normalized.is_empty()`, and this
is precisely the path where the model produced no text at all — so each
correctly stands down and the hand-rolled fallback speaks instead.

`summarize_executions` already exists for this and is already used by the two
other empty-text exits. It labels a tool "failed" when every call to it
errored, keeps per-tool verdicts, and collapses retries with a count. These
two sites were the outliers; they now delegate to it like the others.

The second site is the worse of the two: it is the inference-failed branch, so
the success claim is not even the model's — it is the loop asserting success
on its behalf about a call that may have errored.

Verified live on the same chain after the fix: the identical failing
create_node now renders "• node creation failed".

ADR-056 records a model "reporting a write that never happened" as a failure
mode worth taking seriously; this was a mechanism producing it deterministically
without the model's involvement.

Refs #2254.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG
Embeddings are generated on a 30-second debounce (`EmbeddingService`'s
`debounce_duration_secs`, which exists so rapid edits accumulate instead of
re-embedding repeatedly). Seeded skill nodes are INSERTED synchronously at
daemon startup but only become semantically retrievable when that worker runs.

So a daemon started against a purged database serves turns for ~30s with an
empty skill index. Stage-1 still emits a query, retrieval returns nothing, and
the daemon logs `candidates=0 routed_skills=` — `stage2_tools` fails open to
the full 13-tool surface with no skill guidance injected.

Measured on the locked model, first turn of a fresh chain:

    [tools offered] search_nodes, ..., delete_node, create_nodes_from_markdown
    [tool] create_schema [ERROR]   invalid params: missing field `name`
    [tool] create_schema [ERROR]   invalid params: missing field `name`

Without Schema Creation's guidance the model omits the required top-level
`name`, and the failure cascades through the group: `create_node` then names a
node_type that was never created, and `update_node` invents an id. One cold
turn reds out an entire group. The identical chain passes end to end once the
index is populated — schema created, instance created, update_node fired and
persisted.

This matters most for the documented setup, which makes it worse rather than
rarer: `--between-runs` is specified as "purge the database and restart the
daemon", so every rep after the first re-creates the cold window, and reps run
back-to-back with no wait.

The check waits rather than failing because the condition resolves itself; a
gate that only reported it would make each rep a manual retry. It probes via a
`--type skill` semantic search rather than counting rows, because the rows
exist from startup — embeddings are the thing in question, and a type-only
enumeration returns all eight the instant the daemon boots.

Requires all eight skills, not one: a partially-populated index is the same
defect in a quieter form. If the missing one is Graph Editing, every update
scenario scores against a surface that never offered `update_node` — which is
the shape #2254 is about.

Timing verified directly against the database: daemon ready 17:53:20.538, all
8 skill embeddings written 17:53:50.615 — a 30.1s window.

4 tests (probe injected so wait/timeout are testable without a daemon).
`bun run test:scripts` 221 pass.

Refs #2254.

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

Semantic schema retrieval (`context_ops`) is the second retrieval path subject
to the ~30s embedding debounce, and unlike skill retrieval it affects real
users, not only evals.

A type the user just defined is not semantically retrievable until the
embedding worker runs. There is no fallback below that point: an empty
`retrieved_hits` omits the EXISTING SCHEMAS block entirely, which tells the
model the type does not exist. It then invents a node_type or re-runs
create_schema. Measured on the locked model, create-then-use inside the window:

    [tool] create_node [ERROR]  Unknown node_type 'feature_writeups'

Measured lag, read from the database rather than inferred:

    feature write-up (schema)  created 17:55:49.501  embedded 17:56:20.446  30.9s
    Offline sync    (instance) created 17:56:21.887  embedded 17:56:51.925  30.0s

And in the run that PASSED, the instance was created 1.4s after its schema's
embedding landed. The chain succeeded on timing alone.

"Track my write-ups" followed by "add one" is an ordinary user sequence, so the
repair belongs in the product rather than the harness.

Adds a lexical backstop: any non-core schema the request names outright is
appended to whatever semantic retrieval found. Purely mechanical and already
precedented — `skill_ops::schema_named_in_query` matches non-core schemas
against the query with the same token-boundary matcher for the same reason;
`mentions_phrase` is now shared rather than duplicated.

Append rather than replace, because the two signals answer different questions
and a type named outright is the strongest available evidence of relevance.
Semantic order leads; dedup keeps a hit found by both from being injected
twice; core schemas stay excluded exactly as they are from the semantic path
(admitting one would reintroduce the ADR-063 violation
`parse_and_filter_non_core_schemas` exists to prevent).

Verified live: the fallback fired at 18:31:01.647 for a schema whose embedding
did not land until 18:31:30.033 — 28.4s inside the blind window — and the full
create → instance → update chain passed.

6 tests. `cargo test -p nodespace-core --lib` 1184 pass.

Refs #2254.

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

Two seed-data defects, both making a needed write tool unreachable.

## 1. A negative clause in an embedded description

`Node Deletion`'s description ended "— not to record, update, mark, or look
something up". That clause was added to stop it over-retrieving, and it did the
opposite, because embeddings have no notion of negation: a sentence listing
"record, update, mark, look up" lands NEARER those intents, not further from
them.

Measured on the locked model, 6 reps of one seeded chain on a warm index. The
write turn is "The five-day one got signed off — mark it that way", and the
word "mark" appears in the disclaimer. Node Deletion was retrieved into the
Stage-2 top-3 on ALL 18 turns, including all three where the turn then failed
for want of update_node.

The description now carries destructive verbs only — delete, remove, erase,
purge, discard, trash, drop, get rid of — with the scoping rule moved into the
guidance subtree, which the model reads as TEXT rather than as a vector.

Audited all 8 skills and all 15 tools for the same shape: this was the only
instance. `search_semantic` carries a "do not call get_node afterwards", but
that is a procedural follow-up rule, not a rival capability, so it cannot pull
the tool toward unrelated intents.

## 2. Every write tool was single-sourced

Read tools sat in six or seven skills (`get_node` 7, `search_nodes` 6,
`search_semantic` 6). Every write tool except `create_relationship` sat in
exactly one. With RETRIEVAL_TOP_K = 3 that makes a write tool's availability a
lottery: if its sole owner misses the window, the tool does not exist for the
turn and no amount of model reasoning recovers it.

That is the mechanism behind this issue. The two measured outcomes were:

    pass: Node Creation, Node Deletion, Graph Editing        -> update_node offered
    fail: Schema Creation, Node Deletion, Research & Search  -> no write tool at all

`update_node` and `update_task_status` are now also on Node Creation, and
`create_node` also on Graph Editing — "record this" and "change that" are one
user intent inflected two ways, and either skill can win retrieval on either
phrasing. Node Creation's guidance gains an explicit new-vs-existing rule so
the extra tool cannot turn an update into a duplicate.

Verified live after the change: a write turn routed to
`Node Creation, Node Deletion, Schema Creation` — Graph Editing OUTSIDE the
top-3, previously a guaranteed failure — called `update_node [fields=1]` and
persisted the change.

Blast radius is unchanged: both added tools are mutating, not destructive, so
Node Creation was already at the MUTATING bar via `create_node`, and
`stage2_permitted_names` still admits destructive tools only from the retrieval
winner.

`delete_node`, `create_schema`, `update_schema` and
`create_nodes_from_markdown` stay single-owner by design, each with its reason
recorded in the new test's exception list.

3 tests. `cargo test -p nodespace-agent --lib` 564 pass.

Refs #2254.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012A1ryuphm1PidSY1KTvcKG
`looks_like_narrated_tool_call` knew two shapes — `create_node(...)` and a
JSON call quoted as `"create_node"`. A third reached the user verbatim on the
locked model:

    call:create_schema{fields:[{"friendlyName":"Status", …}], name:"Feature Writeups"}

Name followed by a brace, behind a `call:` prefix. Matching neither pattern,
the guard stood down and the pseudo-code was persisted as the assistant's
answer while nothing executed — the exact failure this detector exists to
prevent, in a bracket style it did not cover.

A brace alone is not sufficient evidence: "create_node {" appears in ordinary
prose explaining a tool's arguments, and suppressing that would replace a
correct explanation with a summary. The brace shape therefore also requires the
prefix a narrated call carries (`call:`, `tool:`, `>>>`, or the start of the
text/line), keeping the detector as narrow as its parens case.

Found while investigating create_schema failures during the #2254 repro. The
other symptom seen there — `Decode Error -3` / `BackendDecodeFailed` — is NOT a
defect: it is a Metal command-buffer OOM under memory pressure on a 16GB
machine, and the "(context reset)" recovery from #2172/#2201 handled all three
occurrences correctly, tearing down and rebuilding the backend as designed.

5 tests on this detector now, including two false-positive guards for prose
that quotes an argument object.

`cargo test -p nodespace-agent --lib` 566 pass.

Refs #2254.

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

Tool-call arguments are NOT constrained to the tool's JSON schema on this stack.
Dumping the GBNF llama.cpp applies during sampling shows:

    tool-create-schema ::= ("create_schema") gemma4-dict
    gemma4-dict        ::= "{" space ("}" | gemma4-dict-kv ("," space gemma4-dict-kv)* space "}")

`gemma4-dict` is any well-formed JSON object. `create_schema`'s properties and
its `required: ["name", "fields"]` appear nowhere in the grammar, so sampling
accepts a payload with no top-level `name` and serde rejects it afterwards.

This is a documented upstream limitation, not a local defect. A llama.cpp
collaborator states it directly in ggml-org/llama.cpp discussion 21839: "Gemma 4
only forces the structure, not the arguments", because
`common/json-schema-to-grammar.cpp` "only produces rules for JSON and not
Gemma's fc notation". The PR that would add schema-constrained decoding for this
format (ggml-org/llama.cpp#23247) has been open and unreviewed since May, and
its own reported blocker is enum constraints on required properties — exactly
the shape create_schema has. Two related issues (#21384, #25072) are closed as
not planned. Nothing is arriving upstream, so the constraint has to be applied
at our boundary.

Measured on the locked model: 17 of 17 failing create_schema calls in one run
began `{"fields":[…]}` with a complete, correct fields array and no top-level
`name`. Serde's message for that is a bare "missing field `name`", which carries
no repair instruction — and the model re-sent the identical payload until the
duplicate-call guard broke the loop (the #1876 signature).

Adds `describe_missing_top_level_keys`, a sibling of the existing
`describe_malformed_fields`, which does the same job one level down. The new
error names the key, says it is top-level rather than a `fields` entry (the
model's actual failure mode), carries a worked example, and reflects back the
field names that were accepted so the caller extends its call instead of
rebuilding it.

Reports rather than repairs, deliberately. The four `repair_*` functions in
agent_loop fix malformations that are mechanical and unambiguous; a missing
schema name would have to be inferred from the user's prose, which is
interpretation. Naming the type wrongly is worse than asking again, because the
schema id derives from it and every later call must match.

MEASURED EFFECT, stated plainly: the error distribution changes completely —
"missing field `name`" disappears entirely and the model demonstrably acts on
the new message, visibly appending `, name: "Feat…` on its retry. The per-turn
success rate does NOT move (0/17 before, 0/17 after), because the retry corrupts
the JSON while making the edit:

    …"name":"feature_writeup\", \"type\": \"text\"}] , name: \"Feat

That is the #1876/#1926 escaped-quote corruption, and it breaks parsing outright,
so `repair_over_quoted_keys` cannot reach it — that repair operates on an
already-parsed Value. A separate defect, filed separately; this change is a
prerequisite for recovery, not sufficient on its own.

4 tests, including the verbatim payload observed live and a guard that a
complete call still succeeds.

`cargo test -p nodespace-core --lib` 1188 pass.

Refs #2254.

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

Completes the recovery loop the previous commit started. Measured on the locked
model, same prompt, purge between reps:

    before both fixes:  1 of 5 turns created the schema
    after  both fixes:  5 of 6 turns created the schema

The remaining failure is a single turn that never recovered; the other five all
show the intended shape — first call omits `name`, gets the actionable error,
retry adds it, schema created.

## What was actually happening

The previous commit's error message worked: the model reads it and repairs the
call correctly, adding `"name":"Feature Write-up"`. But that corrected retry was
then rejected for a DIFFERENT reason — it also appended a third field entry
carrying nothing:

    {"fields":[ …status…, …estimated_days…, {"description":null,"name":null}],
     "name":"Feature Write-up"}

Both real fields were well-formed. The schema name was right. The call failed
for the null entry, and the degradation cascaded: the next attempt added a stray
`field_values` key (a create_node parameter), and the one after abandoned
create_schema entirely and called create_node against a type that had never been
created.

One informationless entry cost the whole chain.

## Correction to the previous commit's stated diagnosis

That message reported the retry as "corrupting the JSON" with escaped quotes,
citing `…"name":"feature_writeup\", \"type\": \"text\"}] , name: \"Feat`. That
was wrong, and the error was mine: `args_preview` truncates at exactly 300
characters (`.chars().take(300)`), so I was reading a log cut off mid-string and
diagnosing the cut as corruption. Raising the cap showed well-formed JSON. There
is no escaped-quote corruption on this path, and #1876/#1926 are not implicated.

## The fix

`drop_empty_field_entries` removes entries whose every value is null (and empty
objects) before validation. Deliberately narrow: an entry with a real `name` but
no `type` is a genuine mistake the caller must see, and
`describe_malformed_fields` still reports it — a test pins that. This drops only
entries carrying no signal at all, so nothing the caller expressed is silently
discarded.

3 tests, including the verbatim payload observed live.

`cargo test -p nodespace-core --lib` 1191 pass.

Refs #2254.

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

Both changes are additive — 80 insertions, 0 deletions — so nothing was removed
from what production sends the model, which is the loss this golden exists to
catch.

`stage2_tool_surface`: `update_node`'s full definition now appears on a surface
built from a Node Creation match, because that skill's whitelist gained
`update_node` / `update_task_status`. That is the point of the change: a write
tool reachable from only one skill made its own availability a lottery under
RETRIEVAL_TOP_K = 3.

`stage2_candidate_block`: carries Node Creation's new NEW RECORD OR EXISTING ONE
rule, which keeps the added tool from turning an update into a duplicate.

Refs #2254.

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

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Initial review — no prior reviews or comments on this PR. Verified against git diff origin/main...HEAD (11 files, +1167/−30, 8 commits), issue #2254, and by executing the affected test suites locally (cargo test -p nodespace-core --lib schema:: → 71 passed; cargo test -p nodespace-agent --lib skill_pipeline:: → 22 passed).

I also built a standalone harness reproducing looks_like_narrated_tool_call's new branch to probe it adversarially rather than reading it. That produced the one blocking finding below.


Requirements Check against #2254

# Issue's stated problem Status
1 "Never scope away update_node on a request classified as an update" Addressed, correctly re-scoped. The PR is right that this was not implementable as stated — RouteDecision is Query(String) | Clarify | Multi, so no "update classification" exists to honour. Solving it as seed-data defects (pairing write tools, de-negating the description) attacks the actual mechanism. Rejecting a suggested direction with the reason it does not exist is better engineering than implementing it literally.
2 "Detect the contradiction and say so" Not implemented, and not claimed to be. No log fires when retrieved skills offer no write tool on a write-shaped request. Reasonable to defer — pairing makes the condition much rarer — but it is a stated acceptance item silently dropped rather than argued down. See 🟢 below.
3 "Do not let a turn report success when it called only read tools on a write request" Addressed, and the diagnosis is sharper than the issue's. The report framed this as read-tools-only; the real mechanism is that all three response guards are gated on !normalized.is_empty(), so the empty-generation path reached a fallback that formatted the last execution's name into "completed successfully" without ever consulting is_error. Both fallbacks now delegate to summarize_executions. Verified: agent_loop.rs:1139 picks failed when errored == count, per-tool, so a failed trailing write after a successful read keeps its own verdict.
4 "Consider whether tool-surface stability should be a property" Addressed as a pinned invariant, which is stronger than "considered" — no_write_tool_is_reachable_from_only_one_skill fails the build if a future skill split reintroduces the single point of failure, with four documented exceptions rather than a blanket allowlist.

Two blockers found underneath (embedding debounce, create_schema grammar) are outside the issue's scope but are genuine prerequisites, and the PR is explicit that they were discovered rather than planned.

Requirements: met, with item 2 deferred undeclared.


Code Review Findings

🔴 Critical

📁 packages/agent/src/local_agent/agent_loop.rs:1188-1196 — the brace branch false-positives on ordinary prose, and a false positive destroys a correct answer.

This was the area flagged for hard scrutiny, and the concern is real. I compiled the new predicate standalone and ran candidate assistant text through it. These all return true:

true  <= "Recall create_node {a} is one option."
true  <= "To do this I would call create_node {\"content\":\"Buy milk\"} but I need the id first."
true  <= "update_node {id, field_values} takes two arguments."
true  <= "create_node {\"content\":\"x\"} was already run earlier, so nothing to do."

Two independent defects produce these:

  1. prefix.ends_with("call") matches any word ending in "call" — recall, local… no, but recall, and critically the ordinary English verb in "I would call create_node {…} but I need the id first". That sentence is a correct, useful answer: the model is explaining it cannot act yet. There is no word-boundary check.
  2. prefix.is_empty() makes a response beginning with update_node {id, field_values} takes two arguments. fire, since before is empty at index 0. The committed test narrated_tool_call_ignores_a_brace_in_explanatory_prose only covers prose where the tool name is mid-sentence — it does not exercise the sentence-initial case, which is exactly where is_empty() bites.

The consequence is not cosmetic. At agent_loop.rs:1747 a positive verdict discards normalized entirely and substitutes CONFIRMATION_REQUEST; at :2426 it prevents a valid final answer from being returned at all. So a false positive silently replaces a correct answer with a canned prompt — a user-visible regression, and one in the same family as the silent-no-op this PR exists to fix.

The principle: a detector whose false-positive cost is destroying good output must be biased toward under-matching, and the surrounding doc comment states exactly that intent ("deliberately narrow… never a bare mention"). The implementation is currently wider than the comment claims. The paren branch is safe because name( is not a shape prose produces; name { demonstrably is.

Suggested fix — tighten the prefix test so it requires a genuine call marker rather than a trailing substring:

let call_prefixed = prefix.ends_with("call:")
    || prefix.ends_with("tool:")
    || prefix.ends_with(">>>")
    || prefix.is_empty()
    || prefix.ends_with('\n');

Dropping bare prefix.ends_with("call") removes both the recall and the I would call false positives while keeping every case the new tests assert (they use call:, tool:, and a bare start). If the bare-call form was actually observed live, gate it on a word boundary (prefix == "call" or preceded by whitespace) instead of a raw suffix. For prefix.is_empty(), consider additionally requiring that the brace content parse as JSON-ish, or that the text contain nothing after the closing brace — a real narrated call is the whole response, whereas prose continues into a sentence.

Please also add the two failing strings above as regression tests; they are the shapes the current tests miss.

🟡 Important

📁 packages/core/src/ops/context_ops.rs:407 and :426 — get_all_schemas() is now awaited twice per turn on the same path.

The flagged concern was the unconditional fetch. The fetch itself I would accept — but the duplication is a straightforward defect independent of that debate. Line 407 fetches the full hydrated schema corpus for the lexical backstop; line 426 fetches the same corpus again a few lines later to hydrate retrieved_hits. Two full-table reads and two Vec<SchemaNode> allocations where one would serve.

This is DRY at the I/O layer, and it is trivially fixable: hoist one get_all_schemas() above both, and pass the slice to append_schemas_named_in_query and the hydration block. That also removes the current oddity where the two sites have different error-recovery behaviour for the same failure.

On the "should it be conditioned on semantic retrieval being empty?" question — I'd argue no, and the code is right to fetch unconditionally: semantic_hits_keep_their_order_ahead_of_a_named_recovery pins the case where semantic retrieval found invoice and the backstop must still add venue. Conditioning on emptiness would break that. But once deduplicated, the cost question largely dissolves: the corpus was already being fetched on this path, so the backstop's true marginal cost is O(schemas × query tokens) of tokenization, not a DB round trip. Worth a brief comment saying so, since the current shape invites exactly the performance objection.

📁 packages/agent/src/skill_pipeline.rs:457 — issue reference #2240 in a code comment.

// record writes — the failure #2240 fixed, in the other direction.

CLAUDE.md: "Do not embed GitHub issue numbers in documentation content or code comments — describe the behavior/constraint directly, and reference decisions by ADR." This is the only occurrence in the diff (verified by grepping all added lines); everything else correctly cites ADR-038/ADR-056/ADR-063 or upstream llama.cpp discussions. Please describe the failure directly — e.g. "the over-retrieval failure that offering type-editing tools on ordinary record writes produces".

📁 packages/core/src/ops/context_ops.rs:236 — doc comment attached to the wrong item.

append_schemas_named_in_query's doc comment is appended directly onto the end of parse_and_filter_non_core_schemas's doc comment, with no blank line or item between them. The result is one 40-line /// block documenting parse_and_filter_non_core_schemas that ends by describing a different function, and parse_and_filter_non_core_schemas (now at :266) is left undocumented. Rustdoc will render the merged block under the wrong symbol. Almost certainly a paste that landed one item too early — move append_schemas_named_in_query and its doc below parse_and_filter_non_core_schemas, or insert the missing separation.

🟢 Suggestions

📁 scripts/eval/preflight.ts:171 — SEEDED_SKILL_COUNT = 8 is a hand-maintained duplicate of Rust seed data.

seed_skill_nodes() returns exactly 8 skills (verified). When a ninth is seeded, this constant does not move, awaitSkillIndex returns as soon as 8 of 9 are retrievable, and the gate silently under-waits — reintroducing the partial-index defect the constant's own doc comment says it exists to prevent, in the quieter form it explicitly calls out. Nit-adjacent, but the failure is silent rather than loud. If the CLI can enumerate seeded skills, deriving the count would close it; failing that, a comment at the Rust seed site pointing here would at least make the coupling discoverable.

📁 scripts/eval/preflight.ts:246 — the 120s hard timeout is the right failure mode; Bun.sleepSync is defensible here.

Flagged for scrutiny, and I think this one is fine as written. Against a documented ~30s debounce, 120s is 4× headroom, and the throw carries a genuinely actionable remedy (the exact sqlite3 query to distinguish "worker never ran" from "still warming"). Failing loudly is correct for a harness whose alternative is scoring a model against a surface that never offered the tool — a spurious hard failure is recoverable, a silently-wrong eval number is not, and this repo has already been burned by stale/invalid eval results. sleepSync blocking is acceptable in a single-purpose CLI gate, and the injected sleep/now seams mean the tests exercise the timeout without waiting in real time — the tests are well-built. No change requested.

📁 packages/core/src/schema/mod.rs:118 — drop_empty_field_entries is correctly scoped; one edge to note.

Flagged for scrutiny; I could not find a case where it discards expressed intent. The obj.values().any(|v| !v.is_null()) test keeps any entry with a single non-null value, and test_create_schema_still_reports_a_named_entry_missing_its_type pins that {"name":"city"} still errors. So an entry carrying any signal survives to describe_malformed_fields. Running it before validation is right — validating an all-null entry can only produce an error about information nobody supplied.

One boundary worth a thought: an entry that is only {"description":"how many days"} — description present, name and type null — is kept and then correctly errors. Good. Conversely {"name":null,"type":null,"unique":false} would be kept (because false is non-null) and then error on the missing name. That is arguably the right call (an explicit unique:false is a signal), but it is a shape the model plausibly emits, and it is neither tested nor mentioned. A one-line test pinning whichever behaviour is intended would stop it drifting.

📁 packages/agent/src/skill_pipeline.rs:305-315 — blast-radius claim is slightly overstated in the comment.

The comment says adding update_node means "this skill's Stage-2 bar rises from READ to MUTATING". I verified via seeded_skills_classify_by_blast_radius_as_expected (line 848) that Node Creation was already (mutating: true, destructive: false) before this change — create_node is a write tool, so skill_is_mutating was already true and the bar was already MUTATING_SKILL_SCORE_BAR. The change is a genuine no-op on the score bar, which is a stronger argument than the one the comment makes. Also confirmed neither skill gains a destructive tool, so stage2_permitted_names' winner-only rule for delete_node is untouched, and the existing blast-radius test passes unmodified — meaning no invariant assumed the old whitelists. Worth correcting the comment so a future reader does not go looking for a bar change that never happened.

📁 (process) Issue item 2 — the contradiction log was dropped without a note.

Items 1, 3 and 4 are each addressed and argued. Item 2 ("log it rather than letting the model discover it at generation time") simply is not present. With write tools now paired, the condition is much rarer — but "rarer" is when a diagnostic is most valuable, since it will no longer be obvious from failure rates. A line in the PR body saying it was considered and deferred would keep the record straight; the PR is otherwise exemplary about recording what was tried and abandoned.


What is notably good here

Worth stating explicitly, because it is unusual:

  • Two self-corrections recorded rather than quietly dropped — the args_preview 300-char truncation misdiagnosed as JSON corruption, and the "Node Deletion crowds out on top" claim shown false (never rank-1). A drafted slot-eviction fix was simulated against real whitelists, shown to evict the wrong candidate, and abandoned before commit. That is the discipline that keeps a measurement-driven codebase honest.
  • The negation finding is a genuine insight with a test behind it. "Embeddings cannot represent not, so a disclaimer listing rival intents pulls the skill toward them" explains a defect that prose review would pass on sight — the earlier wording reads as obviously correct. no_seeded_skill_description_names_operations_it_excludes pins it as a build-breaking invariant, and its paired test guards the opposite failure (a description narrowed until real deletion requests miss). Guarding both directions is the part usually skipped.
  • Tests pin real properties, not restatements. seeded_skills_classify_by_blast_radius_as_expected deliberately calls the production classifier instead of reimplementing the rule, with a comment explaining that a reimplementation would keep passing while the classifier regressed. The awaitSkillIndex tests inject clock and sleep so the timeout path is exercised in microseconds. test_create_schema_missing_name_says_what_to_add_and_where asserts the absence of the unhelpful serde message, not just the presence of the good one. These are not trivial passes.
  • The upstream constraint is cited, not assumed — grammar dump, collaborator quote, and the stalled PR's own blocker, establishing that the boundary check is necessary rather than a local workaround.

Recommendation: REQUEST CHANGES

Net-positive change with an unusually strong evidence trail, and the core architecture — fixing routing as seed-data defects and delegating both fallbacks to the existing error-aware summarizer — is right. I would not block on the 🟡/🟢 items.

The block is the single 🔴: the brace-form detector fires on legitimate prose ("…I would call create_node {…} but I need the id first", "Recall create_node {a}…", and any response starting with update_node {…}), and a false positive there discards a correct answer in favour of a canned confirmation request. Given this PR's own thesis — that a turn must never misreport what happened — shipping a guard that suppresses correct answers would undercut the fix it ships alongside.

Removing bare prefix.ends_with("call") and adding the two failing strings as tests is a small change. Everything else can land as-is or follow up.

@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: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

## Critical — the brace branch suppressed correct answers

Review found `looks_like_narrated_tool_call`'s new branch firing on ordinary
prose. Reproduced as tests before fixing; both now committed as regressions:

    "To do this I would call create_node {\"content\":\"Buy milk\"} but I need the id first."
    "update_node {id, field_values} takes two arguments."

Two admissions were wrong. `prefix.ends_with("call")` matched "call" as an
ordinary English VERB — the first string is a model correctly explaining itself,
and "Recall create_node {a}" matched on the same rule. `prefix.is_empty()` fired
on any response merely BEGINNING with a tool name, which is what documentation
looks like.

This mattered more than a normal false positive: a positive verdict DISCARDS the
model's text and substitutes a confirmation request, so it destroyed a correct
answer silently. That directly undercuts the thesis of this branch — a turn must
not misreport what happened.

Only marker prefixes survive: `call:`, `tool:`, `>>>`, or the call starting its
own line. The own-line test now reads `before` UNTRIMMED, because `trim_end()`
strips the very newline it looks for — caught when the fix made a passing test
fail.

Consequence, stated rather than hidden: a bare `create_node{…}` at the very
start of a response is no longer detected. It is genuinely indistinguishable
from documentation, and the errors are asymmetric — missing a narrated call
shows the user pseudo-code, which is visible and recoverable; a false positive
deletes a working answer. A test pins the decision so it is not silently
reverted.

## Important

`context_ops.rs` awaited `get_all_schemas()` TWICE on the same path — two
full-table reads per turn where one serves. Now fetched once and shared by both
consumers. The corpus-unavailable case is expressed once instead of in two
separate error arms, with identical behaviour (unhydrated hits kept, related
schemas omitted).

`append_schemas_named_in_query`'s doc comment had been fused onto the end of
`parse_and_filter_non_core_schemas`'s, leaving that function undocumented and
rustdoc rendering the text under the wrong symbol. The function is moved below
its neighbour so both comments attach correctly.

`skill_pipeline.rs` carried an issue number in a code comment, against
CLAUDE.md. Replaced with the behaviour it described.

## Suggestion

`SEEDED_SKILL_COUNT = 8` was a hand-maintained literal that would silently
under-wait the day a ninth skill is seeded — the gate would pass with the new
skill unembedded, which is the exact state it exists to prevent. The denominator
is now read from the database via a type-only enumeration (which does not depend
on embeddings, so it is correct immediately), falling back to the known count if
that fails. A test pins that 8-of-9 is still "not ready".

`bun run test:all` exits 0 — 53 suites. core 1191, agent 570, scripts 229.

Refs #2254.

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

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

All findings addressed in 62f46bf4. Every one was valid.

🔴 Critical — brace detector suppressed correct answers

Confirmed before fixing: I added both reported strings as tests and watched them fail against the committed code.

FAILED  "To do this I would call create_node {"content":"Buy milk"} but I need the id first."
FAILED  "update_node {id, field_values} takes two arguments."

The diagnosis was exactly right on both counts. ends_with("call") matched "call" as an ordinary English verb — the first string is a model correctly explaining itself — and it caught "Recall" too. is_empty() fired on any response merely beginning with a tool name, which is what documentation looks like.

You identified why this was worse than a normal false positive, and I want to underline it: a positive verdict discards the model's text and substitutes a confirmation request. So the guard destroyed correct answers silently — undercutting the exact thesis of the branch it shipped on.

Only marker prefixes now survive: call:, tool:, >>>, or the call starting its own line. Fixing it surfaced a second bug in my own code: the own-line check ran against a trim_end()-ed prefix, which strips the very newline it looks for. It now reads before untrimmed.

One consequence I chose deliberately rather than papered over: a bare create_node{…} at the very start of a response is no longer detected. It is genuinely indistinguishable from update_node {id, field_values} takes two arguments., and the two errors are asymmetric — missing a narrated call shows pseudo-code, which is visible and recoverable; a false positive deletes a working answer. A test pins that decision so it is not silently reverted later.

🟡 Important — all three fixed

Duplicate get_all_schemas() — you were right that it was two full-table reads, and right that conditioning the backstop on empty semantic results would break semantic_hits_keep_their_order_ahead_of_a_named_recovery. Fetched once, shared by both consumers; the corpus-unavailable path is now expressed once instead of two error arms, with identical behaviour.

Fused doc comment — correct, and worse than cosmetic: parse_and_filter_non_core_schemas was left undocumented with rustdoc rendering my text under its name. Moved my function below its neighbour so both comments attach to their owners.

#2240 in a code comment — removed, replaced with the behaviour it described. Only occurrence in the diff.

🟢 Suggestion — taken

SEEDED_SKILL_COUNT = 8 is now read from the database via a type-only enumeration, which does not depend on embeddings and is therefore correct the instant the daemon boots. Falls back to the literal if enumeration fails. A test pins that 8-of-9 still reads as "not ready" — the silent under-wait you described.

I did not act on the blast-radius comment note, and should say why: you are right that Node Creation was already mutating via create_node, so the score bar is unchanged. That is what the comment says ("this skill's Stage-2 bar rises from READ to MUTATING" is the part that is wrong — it was already MUTATING). Worth a follow-up correction, but it is a comment accuracy issue on an otherwise-correct change, and I would rather flag it than quietly rewrite history in a fixup.

Also noting item 2 of the issue ("detect the contradiction and log it") is deferred rather than done — you were right that I dropped it silently. It needs the same write/read signal that does not exist, and the seed-data fixes make the contradiction much rarer, but it is not implemented.

bun run test:all exits 0 — 53 suites. core 1191, agent 570, scripts 229 (+4 regressions from this review).

…mment

The comment said adding `update_node` makes "this skill's Stage-2 bar rise from
READ to MUTATING". That is wrong, and wrong in the direction that overstates the
change: Node Creation already whitelisted `create_node`, so `skill_is_mutating`
was already true for it and `score_bar_for` already returned MUTATING. Adding a
second mutating tool moves nothing.

The argument is stronger stated accurately — blast radius is UNCHANGED rather
than merely bounded — and a comment that misdescribes a safety property is worth
correcting even when the code it sits beside is right.

Comment only; no behaviour change. Raised in review and flagged in my response
rather than fixed silently, so this closes it.

`cargo test -p nodespace-agent --lib skill_pipeline` 22 pass.

Refs #2254.

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

malibio commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary

5 of 5 recommendations addressed. 0 skipped.

severity finding resolution
🔴 Brace detector false-positives on prose 62f46bf4 — both reported strings reproduced as failing tests first, then fixed; 2 regressions committed
🟡 get_all_schemas() awaited twice on one path 62f46bf4 — fetched once, shared; 2 calls → 1
🟡 Doc comment fused onto the wrong function 62f46bf4 — function moved below its neighbour
🟡 #2240 in a code comment 62f46bf4 — replaced with the behaviour described; 0 issue refs remain in the diff
🟢 SEEDED_SKILL_COUNT hand-maintained 62f46bf4 — derived from the database, with a test pinning that 8-of-9 reads as not-ready

Plus c4b6b009, which closes the blast-radius comment inaccuracy I flagged in my response rather than fixed at the time. The comment claimed Node Creation's bar "rises from READ to MUTATING"; it was already MUTATING via create_node, so the correct statement is that blast radius is unchanged — a stronger claim, accurately stated.

Nothing was skipped. The one item I deliberately did not implement is issue #2254's own suggestion 2 ("detect the contradiction and log it"), which is deferred, not addressed, and is called out as such in my review response — it needs a write/read signal that does not exist, and the seed-data fixes make the contradiction much rarer without removing the gap.

Verification: bun run test:all exits 0 — 53 suites. core 1191, agent 570, scripts 229. The pre-push gate ran in full on both pushes.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: The critical fix changed detection logic that gates whether a model's response reaches the user, and it deliberately narrows behaviour — a bare create_node{…} at text start is no longer detected, which is a judgement call about asymmetric error costs rather than a mechanical repair. The context_ops change also restructured control flow (two error arms collapsed into one match), which is exactly the shape where an unintended behaviour change hides. Both warrant a second look at the new commits rather than being taken on trust.

mstomar125 and others added 5 commits August 24, 2026 09:07
`summarize_executions` groups executions by tool name so a retry loop collapses
to one bullet with a count, and decided the verb by "did every call error?".
Two calls to the same tool with opposite verdicts therefore rendered as an
unqualified success:

    create_node(ok, record A), create_node(ERROR, record B)
    → "• node creation completed (2×)"

which is the failure mode this branch exists to close, one layer down from where
it was fixed. It matters now because both empty-generation fallbacks were newly
routed through this function precisely so a failed write could not read as a
completed one; a mixed group let it through anyway.

The verb now follows the rule the tool-failure-surfacing guard already applies —
the LAST call of a name decides, because that is the call the turn ended on.
Every call errored → "failed". Last call succeeded → "completed", since an
earlier error was a retry the model demonstrably recovered from and reporting it
would describe a transient with no action attached (the existing partial-failure
test pins that, unchanged). Last call errored after an earlier success → both
counts, so neither outcome is asserted over the other.

## The narrated-call detector's own-line branch declined at index 0 and fired one line down

`starts_its_own_line` admitted any tool name preceded by a newline anywhere in
the text. The branch immediately above it deliberately does NOT detect
`update_node {id, field_values} takes two arguments.` at the start of a
response — it is documentation, and a positive verdict discards the model's
whole reply. The same sentence one line further down was detected, which is
exactly the shape a model listing tools one per line produces.

The own-line form now also requires the brace ADJACENT to the name. A narrated
call writes `create_node{"content":…}` flush; documentation puts a space there.
The observed live shape and the existing own-line test both keep the brace
adjacent, so nothing real is lost.

`call:` was also an unanchored suffix test, so "recall:" satisfied it — putting
the English verb back one character narrower than the check removed last commit.
Markers must now stand as their own token.

`cargo test -p nodespace-agent --lib` 576 pass.

Refs #2254.

Co-Authored-By: Claude <[email protected]>
`drop_empty_field_entries` ran BEFORE `describe_malformed_fields`, and removing
an entry renumbers the array. A payload of

    fields: [{"name":null,"description":null}, {"type":"number"}]

came back as `fields[0] is missing "name"` — but the entry the caller got wrong
was at index 1. Sending an LLM to edit an element it had already written
correctly is the degrading-retry loop these located errors exist to break.

Worse, an array of ONLY informationless entries was reduced to `fields: []`,
which `handle_create_schema` reads as a deliberate relationship-only schema and
creates. The caller asked for a type with fields, got a fieldless one, and no
error to retry against.

Both come from doing the drop first, so the "declares nothing" rule now lives in
`describe_malformed_fields`, which skips such entries in place — positions
intact — and reports them when nothing else in the array declares anything
either. The drop runs afterwards, purely to keep them from reaching serde, and
can no longer empty a non-empty array.

`add_fields` gets the same drop. It is `fields` under another name, and leaving
it out reproduced on `update_schema` the exact failure `create_schema` was fixed
for — now with the added twist that the skip above would have let the null entry
through to a bare serde error.

## `null` counts as missing, at both levels

`Some(_) => false` treated a non-string value as present, so `{"name": null,
"fields": [...]}` bypassed the friendly error and fell through to
`invalid type: null, expected a string` — the bare, unlocatable message both
checks exist to replace, naming neither the key nor a repair. A model that
appends `"name": null` inside a field entry writes it at the top level too.

The top-level message now says what is actually wrong with the key (not sent /
sent as null / sent empty / sent as a number) rather than always "was not sent",
and the per-entry check treats a null `name`/`type` as absent.

`cargo test -p nodespace-core --lib schema::` 78 pass.

Refs #2254.

Co-Authored-By: Claude <[email protected]>
… registry

## The pairing was applied to the whitelists asymmetrically

Node Creation gained `update_node` and a NEW RECORD OR EXISTING ONE rule telling
the model when to reach for it. Graph Editing gained `create_node` and no rule
at all — its guidance still opens "CALL update_node NOW", which is now wrong for
the request shape the added tool was put there to serve. It gets the mirror
clause.

`update_task_status` was added to Node Creation with no mention in its guidance
either, while Graph Editing steers status changes to it explicitly. Without that,
a model handed both verbs sets status through `update_node`'s `field_values`,
where it does not move a task's status.

Two tests pin the property rather than the instance: a skill carrying both write
verbs must name both in its guidance, and a skill carrying `update_task_status`
must name it. The first fix was applied to one side only; the property makes
that visible next time.

## `no_write_tool_is_reachable_from_only_one_skill` could not see zero

The offender list was built by iterating the `owners` map, which only contains
tools some whitelist already mentions. A write tool removed from EVERY whitelist
has no entry, never appears, and the test named for catching unreachable write
tools passes green — on the strictly worse case than the single-owner one it was
written for.

Enumerated from `Tool::ALL` instead, so absence is a value the check can see; a
zero-owner tool is reported as "reachable from NO skill".

Golden updated for the new Node Creation clause: 2 insertions, 0 deletions.

`cargo test -p nodespace-agent --lib` 576 pass.

Refs #2254.

Co-Authored-By: Claude <[email protected]>
Sharing one `get_all_schemas()` between the lexical backstop and the hydration
step also made it unconditional, where the read it replaced was gated on
`retrieved_hits` being non-empty. A turn with no query and no hits — a resident
context build with nothing to retrieve against — went from zero full-table reads
to one, and neither consumer exists on that turn: the backstop has no query to
match names against and the hydration arm returns empty vectors regardless.

Gated on either consumer being live. The dedupe is unaffected: when a fetch does
happen it is still one, still shared.

`cargo test -p nodespace-core --lib context_ops` 39 pass.

Refs #2254.

Co-Authored-By: Claude <[email protected]>
…iting

`awaitSkillIndex` advertises a bounded wait, but its deadline is only consulted
between probes and `Bun.spawnSync` had no timeout. A daemon that stops
responding mid-request blocks the whole process indefinitely, so the eval hangs
rather than aborting with the diagnosis it was written to produce. Each probe
now has a ceiling; a killed probe reports `exitCode: null`, which the existing
`!== 0` test already reads as "no usable count".

`seededSkillCount` took the same fallback for a failed enumeration (`null`) and
for one that legitimately returned 0. Those are opposite facts. Skill rows are
inserted synchronously at daemon startup, so a successful enumeration of zero
means seeding never ran against this database — and substituting the fallback
made the gate poll for eight skills that cannot appear, burning the full 120s
before reporting a generic "index not ready". The real fault is knowable
immediately, so it is now reported immediately. A CLI failure still degrades to
the known seed count.

The enumeration is injectable, matching how `awaitSkillIndex` takes its probe,
so all three branches are covered without a daemon.

`bun run test:scripts` 232 pass.

Refs #2254.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type

Re-Review — scoped to the two commits since the prior review (62f46bf4, c4b6b009), verified against git diff 307cd4a1..HEAD. The prior review's 5 findings were re-checked against the code, not against the address-review write-up.

Previous Review Summary

5 recommendations, 5 addressed, 0 not addressed. 1 new issue found.

# severity finding verified resolution
1 🔴 Critical brace detector fired on ordinary prose Partially fixed — both named admissions removed, but the replacement starts_its_own_line reintroduces the same class of false positive on line 2+ (see below)
2 🟡 Important duplicate get_all_schemas() await ✅ Fixed, behaviour-preserving
3 🟡 Important fused doc comment ✅ Genuinely fixed, not relocated
4 🟡 Important issue number in code comment ✅ Fixed; zero issue refs remain anywhere in the PR
5 🟢 Suggestion hardcoded SEEDED_SKILL_COUNT ✅ Fixed; one gap in test coverage

Test results reproduced independently:

  • cargo test -p nodespace-agent --lib narrated_tool_call → 10 passed
  • cargo test -p nodespace-core --lib → 1191 passed, 0 failed
  • bun test scripts/eval/preflight.test.ts → 11 pass, 0 fail

Code Review Findings

🟡 Improvement — the brace detector's new starts_its_own_line prefix reproduces the defect it replaced

📁 packages/agent/src/local_agent/agent_loop.rs:1206-1213

The fix correctly removes ends_with("call") and is_empty(). But the surviving starts_its_own_line marker admits any line whose first non-whitespace token is a tool name followed by { — which is the identical shape the commit explicitly rejects one paragraph earlier:

is_empty() fired on any response merely BEGINNING with a tool name — "update_node {id, field_values} takes two arguments." is documentation, not a call.

That reasoning is right, and it does not stop applying at the second line. prefix.is_empty() was rejected because documentation-at-text-start is indistinguishable from a call; documentation-at-line-start is the same string with a \n in front of it. The new test narrated_tool_call_declines_an_unmarked_call_at_text_start asserts the text-start case is declined, while narrated_tool_call_detects_a_brace_delimited_call asserts the line-start case is accepted — the two tests encode opposite verdicts for the same evidence, separated only by position in the response.

I extracted the function body verbatim into a standalone harness (same 14 registered names from Tool::ALL) and ran realistic model outputs through it. These are all correct answers that get discarded and replaced with CONFIRMATION_REQUEST at agent_loop.rs:1766:

A. fenced JSON example      discarded=true
   "I created the task. For reference, the payload was:
    ```json
    create_node {\"content\":\"Buy milk\"}
    ```
    Anything else?"

B. soft-wrapped sentence    discarded=true
   "I was not sure whether to
    create_node {\"content\":\"x\"} or to update the existing one, so I asked."

C. indented example line    discarded=true
   "The signature is:
        create_node {content, node_type}
    and it returns the new id."

Case A is the one that matters. A fenced JSON block is the single most common way a model shows a payload, and trim_end_matches([' ', '\t']) walks straight past the fence line's newline to find it. This is a model correctly reporting a completed write — the exact turn this PR's sibling fix ("stop a failed write reporting success") is trying to make honest — and the guard throws the answer away.

Case C also shows trim_end_matches([' ', '\t']) is doing net harm: stripping leading indentation is what converts an indented documentation line into a "line start". The plain before.ends_with('\n') disjunct alone would decline it.

The severity is Improvement rather than Critical because the prior review's specific reported strings are fixed and the direction of travel is right — but the underlying principle ("a bare name + brace is not evidence of a call") is applied inconsistently, and the asymmetry argument in the new test's doc comment (a false positive is the expensive error, so err toward letting text through) argues against keeping this branch.

Two options, either acceptable:

  1. Drop starts_its_own_line entirely. The call: / tool: / >>> markers are the ones with observed live evidence behind them; the commit message justifies \n only as "a real observed shape", with no cited instance the markers don't already cover. This is the minimal change and matches the stated asymmetry.
  2. Require the line to contain nothing but the call — i.e. the brace-delimited call runs to the end of the line with no trailing prose. All three false positives above carry trailing prose or a closing fence; call:create_schema{fields:[…]} on its own line does not.

Answering the specific question asked: the trim_end()-vs-\n ordering bug is structurally fixed — reading before untrimmed is correct and the CRLF case works (\r survives trim_end_matches([' ', '\t'])... verified "Running now:\r\ncreate_node{…}" → detected). The problem is not the newline mechanics, it's that the newline marker itself is too weak.

🟢 Nit — seededSkillCount's fallback path has no test

📁 scripts/eval/preflight.ts:225-232

The claim that a --type skill search with an empty query enumerates without depending on embeddings checks out against the CLI contract, not just the comment — packages/cli/src/commands/search.rs:24-26 documents ""/"*" with --type as type-only listing, and #2252 (Honour sorting on a filterless search) is recent evidence that path is live. Good verification target, and it holds.

The gap is coverage: seededSkillCount and skillSearchCount are never imported by preflight.test.ts. The tests all inject expected explicitly, so the count === null || count === 0 → FALLBACK branch — the one that decides whether a CLI hiccup degrades safely or waves the gate through — is unexercised. Both functions are module-private, so testing them means exporting one or the other.

Worth noting the count === 0 case is doing real work: without it, an enumeration returning zero would make count >= expected trivially true and skip the wait entirely, which is precisely the failure the gate exists to prevent. That is the branch most deserving a test.

🟢 Nit — the default-parameter forward reference is correct but fragile

📁 scripts/eval/preflight.ts:268, 275

probe's default closure references expected, declared three parameters later. This works — the closure body evaluates on call, after all parameters are bound — and I confirmed it under Bun for both the all-defaults and expected-overridden paths. But it reads as a TDZ violation to anyone scanning it, and it would be one if probe's default were ever changed to a non-lazy expression. Reordering so expected precedes probe costs nothing and removes the trap. Optional.


Verified Claims

Each of the author's remaining claims was checked against the code rather than the write-up:

Finding 2 — schema fetch dedupe (context_ops.rs:411-443). The Option threading is correct, and I traced every branch combination against git show 307cd4a1 for equivalence:

corpus query hits empty old behaviour new behaviour
Ok non-empty no backstop + hydrate same
Ok empty/None no no backstop, hydrate same
Err any no no backstop, unhydrated hits, no related same
any — yes (vec![], vec![]) same

No schema is dropped in any combination. The (_, true) arm ordering is right — the empty-hits case must win before the corpus is consulted, and it does.

One deliberate behavioural change worth naming, since it isn't in the comment: the corpus is now fetched unconditionally, where the old code skipped the fetch when the query was empty and retrieved_hits was empty. That trades a saved read on a narrow path for one read instead of two on the common path — a clear net win, and the corpus is small — but the new all_schemas comment claims "one serves" without noting the case where previously zero served. Not worth changing the code; a half-sentence in the comment would make it accurate.

Finding 3 — fused doc comment (context_ops.rs:218-241). Genuinely fixed, not relocated. parse_and_filter_non_core_schemas now carries the full /// Parse semantic search results… block that describes it, and append_schemas_named_in_query has its own /// Append any non-core schema… block. Moving the function was the right fix — the alternative (splitting the comment in place) would have left the same adjacency hazard.

Finding 4 — issue number (skill_pipeline.rs:1030). #2240 is gone, replaced with a description of the failure mode rather than a pointer, which is exactly what the CLAUDE.md rule asks for. I swept the full PR diff (git diff origin/main...HEAD, all 11 files) for #[0-9]{3,5} in added lines: zero hits. Note #2254 still appears in commit messages, which the rule permits — it governs code comments and docs, not git metadata.

Finding 6 — the c4b6b009 blast-radius correction is correct. Verified from source, not from the claim:

  • git show origin/main:packages/agent/src/skill_pipeline.rs line 285 — Node Creation's pre-PR whitelist was ["create_node", "search_semantic", "search_nodes", "get_node"].
  • routing.rs:304 — skill_is_mutating is any(|t| Tool::from_name(t).is_none_or(Tool::is_write)), and create_node is a write.
  • routing.rs:336 — score_bar_for returns MUTATING_SKILL_SCORE_BAR on that.

So the skill was already at the MUTATING bar before this PR, and the old comment's "rises from READ to MUTATING" was wrong. The new comment is accurate. The destructive claim also holds: skill_is_destructive uses removes_user_data_tool, and neither update_node nor update_task_status removes user data (tools.rs:1749-1770 — a wrong status is "a write the user can see and correct").

Standards sweep (full PR diff, all 11 files): no lint suppression, no #[allow(dead_code)], no #[deprecated], no any types, no new .md files. The two console.error calls are in scripts/eval/preflight.ts — tooling, not production code, and they are the gate's user-facing progress output, which is correct there.


Recommendation

COMMENT

Four of the five prior findings are cleanly and verifiably fixed, and the self-caught blast-radius correction in c4b6b009 is accurate — the author was right to flag it. The dedupe refactor is behaviour-preserving under every branch combination I traced.

The brace detector is better than it was and no longer fires on the reported strings, so this is not a regression on the prior review. But starts_its_own_line still discards correct answers in the fenced-JSON case, which is a common enough model output shape to expect in practice, and it contradicts the reasoning the same commit uses to reject is_empty(). Dropping that one disjunct — option 1 above — is a two-line change that makes the branch internally consistent and costs only the ability to catch an unmarked call, which the commit's own asymmetry argument says is the cheap error to make.

Not a merge blocker on its own: worst case is an occasional correct answer replaced by a confirmation request, which is visible and recoverable, and the PR's net effect on this function is still positive. Worth one more pass before merge.

@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): COMMENT (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125

Copy link
Copy Markdown
Contributor

Adversarial re-review — 15 findings triaged, 13 real and fixed on this branch, 2 rejected

Per the standing core policy (self-authored PRs still get an independent adversarial pass), I ran a fresh review against c4b6b009 without reading the issue thread first, then verified every finding against the code rather than accepting the summaries. Five commits pushed to this branch; nothing merged.

bun run test:all exits 0 — frontend 227 files / 4794 tests (identical to your baseline), 53 Rust suites, scripts 232. Goldens regenerated: 2 insertions, 0 deletions, so the "nothing removed from what production sends the model" property still holds.


Confirmed and fixed

1. A same-tool failure could still hide behind an earlier success (agent_loop.rs) — the most important one

summarize_executions groups by tool name and picked the verb with "did every call error?". Two calls to the same tool with opposite verdicts therefore rendered as an unqualified success:

create_node(ok, record A), create_node(ERROR, record B)  →  "• node creation completed (2×)"

This is the exact defect the branch closes, one layer down from where it was fixed — and it matters now because both empty-generation fallbacks were newly routed through this function precisely so a failed write could not read as a completed one. A mixed group let it through anyway. The sibling tool-failure-surfacing guard already had the right rule and is gated on non-empty text, so it never applies here.

Fixed by adopting that guard's rule: the last call of a name decides, because that is the call the turn ended on. Every call errored → "failed". Last call succeeded → "completed" (an earlier error was a recovered retry — your existing partial-failure test passes unchanged, renamed to say what it actually pins). Last call errored after an earlier success → both counts reported, so neither outcome is asserted over the other.

2. describe_missing_top_level_keys treated a non-string name as present (schema/mod.rs)

Some(_) => false let {"name": null, …} through to invalid type: null, expected a string — the bare, unlocatable serde message the function exists to replace. A model that appends "name": null inside a field entry (the shape drop_empty_field_entries was written for) writes it at the top level too. The same Some(_) => false was in describe_malformed_fields one level down, so a null field name/type had the same hole.

Both now treat null as missing. The top-level message says what is actually wrong with the key — not sent / sent as null / sent empty / sent as a number — rather than always "was not sent".

3. An all-null fields array became fields: [] and silently created a fieldless type

drop_empty_field_entries on fields: [{"description":null,"name":null}] left [], which handle_create_schema reads as a deliberate relationship-only schema. The caller asked for a type with fields, got a fieldless one, and no error to retry against — a silent wrong success in place of a correctable error.

4. Dropping an entry renumbered the positions reported back to the caller

drop_empty_field_entries ran before describe_malformed_fields, so fields: [{"name":null,"description":null}, {"type":"number"}] came back as fields[0] is missing "name" — but the entry the caller got wrong was at index 1. Sending an LLM to edit an element it already wrote correctly is the degrading-retry loop these located errors exist to break.

(3) and (4) have the same root cause, so they took one fix: the "declares nothing" rule moved into describe_malformed_fields, which skips such entries in place (positions intact) and reports them when nothing else in the array declares anything either. The drop now runs afterwards, purely to keep them off serde, and can no longer empty a non-empty array. fields: [] sent explicitly is still valid.

5. starts_its_own_line fired on a tool name after any newline

The branch immediately above it deliberately declines update_node {id, field_values} takes two arguments. at index 0 — documentation, and a positive verdict discards the model's whole reply. The identical sentence one line down was detected, which is exactly the shape a model listing tools one per line produces. The added tests only covered idx == 0.

The own-line form now also requires the brace adjacent to the name. A narrated call writes create_node{"content":…} flush; documentation puts a space there. Your observed live shape and your own-line test both keep it adjacent, so nothing real is lost.

6. prefix.ends_with("call:") is an unanchored suffix test, and "recall:" ends with "call:"

That puts the English verb back one character narrower than the check you removed last commit — Recall: create_node {content} is the one you want. would have had its reply discarded. Your existing regression covers Recall create_node (no colon), which does not exercise this. Markers must now stand as their own token.

7 + 8. The write-tool pairing was applied to the whitelists asymmetrically

Node Creation gained update_node and a NEW RECORD OR EXISTING ONE rule. Graph Editing gained create_node and no rule at all — its guidance still opens "CALL update_node NOW", which is now wrong for the request shape the added tool was put there to serve. It gets the mirror clause.

update_task_status was added to Node Creation with no mention in its guidance either, while Graph Editing steers status changes to it explicitly; without that a model sets status through update_node's field_values, where it does not move a task's status.

Two tests pin the property rather than the instance — a skill carrying both write verbs must name both in its guidance, and a skill carrying update_task_status must name it — because the asymmetry is what recurs, not the specific omission.

9. update_schema's add_fields was left unpatched

Structurally identical to fields, same model behaviour, same failure. Note this became mandatory rather than merely consistent once (4) was fixed: describe_malformed_fields now skips informationless entries on both paths, so without the matching drop the null entry would reach serde and produce the bare error that check exists to replace.

10 (half). The corpus fetch became unconditional

The dedupe is right and the "two awaits here" claim is accurate — the daemon's own get_all_schemas() (local_agent_service.rs:2321) is pre-existing and outside this function, so I don't count it against the PR. But sharing one fetch also made it unconditional, where the read it replaced was gated on retrieved_hits being non-empty. A turn with no query and no hits went from zero full-table reads to one, and neither consumer exists on that turn. Now gated on either consumer being live; when a fetch does happen it is still one, still shared.

12 + 13. scripts/eval/preflight.ts

Both real, both fixed even though they are harness-only, because they defeat the diagnosis the new gate exists to produce.

Bun.spawnSync had no timeout, and awaitSkillIndex's deadline is only consulted between probes — so a daemon that stops responding mid-request hangs the run indefinitely instead of aborting with the message you wrote. Each probe now has a ceiling; a killed probe reports exitCode: null, which the existing !== 0 test already reads as "no usable count". Verified timeout is honoured by spawnSync on Bun 1.3.14.

seededSkillCount took the same fallback for a failed enumeration (null) and for one that legitimately returned 0. Those are opposite facts — skill rows are inserted synchronously at startup, so a successful enumeration of zero means seeding never ran, and substituting 8 made the gate poll for skills that cannot appear and burn the full 120s before reporting a generic "index not ready". Reported immediately now; a CLI failure still degrades to the known count. The enumeration is injectable, matching how awaitSkillIndex takes its probe, so all three branches are covered without a daemon.


Rejected

11. "append_schemas_named_in_query has no cap analogous to MAX_SEMANTIC_SCHEMAS"

Not fixed, deliberately. MAX_SEMANTIC_SCHEMAS was never a whole-context budget — related_one_hop_schemas already appends past it and did so before this PR, so the invariant the finding invokes did not exist. Each append requires a token-boundary match of a full schema id or display name in the query, so growth requires the user to actually name each type. And a cap has a real cost in the other direction: it would drop a type the request named outright, which is precisely the create-then-use case the backstop exists for. A speculative bound that can suppress the fix's own motivating case is worse than no bound.

8 (whitelist). "Node Creation lacks resolve_query/route_clarify"

Not a gap. The new guidance scopes Node Creation's update path to "a record already in this conversation" — where an id resolver is unnecessary by construction, because the id is already in context. Adding resolve_query/route_clarify would widen a creation skill's surface for a case its own guidance excludes, which is the same over-broad-surface failure this PR argues against in the Node Deletion direction. If the scoping ever loosens, the tools should come with it; as written they should not.


One observation, not a finding

append_schemas_named_in_query's comment says "There is no fallback below this point". On the production path there is one: local_agent_service::build_workspace_context already injects non-core schemas created in the last five minutes (capped at 5, skipped when relevant_schemas is already full) specifically as a debounce bypass. The two backstops overlap — yours additionally covers a type created longer ago that retrieval misses on threshold, which the recency one does not, so it earns its place. But the comment overstates the gap, and it's worth knowing the interaction exists (your uncapped append can now consume the recency injector's remaining_slots). Non-blocking; your call whether to reword or reconcile.

Filed separately

#2259 — clippy::collapsible_match fails bun run quality:fix on a clean main (packages/agent/tests/live_resolve_query_decomposition_shapes.rs:326, last touched by #2186, in no open PR's diff). Pre-existing toolchain drift under rustc 1.95.0, not caused by this branch; deliberately not folded in here. It blocks the mandatory quality step on every branch, not the pre-push gate. Everything else in quality:fix is clean on this branch — eslint 0/0, svelte-check 0 errors, tsc clean, cargo fmt clean, clippy clean across nodespace-agent and nodespace-core.

One note for whoever runs the gate on this branch

My first push failed on ai_chat_send_to_idle_test (300s, assistant_count=0) — which is #2224 exactly, and it was my own fault: a fresh worktree here inherits the primary checkout's target/, whose nodespaced is the 27 MB July binary, so cargo build --bin nodespaced is an mtime no-op and the gate spawns a month-old daemon that fails with ContextOverflow. rm target/debug/nodespaced + rebuild → 99 MB → the same test passes in 26.6s. Worth flagging because this branch's merge-base predates #2258, so it does not yet carry the fixture guard that would have said so in 0.01s instead of five minutes. Merging main in (or squashing onto current main) picks that up.


Not merging — this is your PR. From my side it is ready.

Re-review found the previous fix's surviving marker admitted the identical
shape it had just rejected, one line down. `is_empty()` was removed because a
tool name at the START of the text is documentation, not a call
("update_node {id, field_values} takes two arguments."). `starts_its_own_line`
admitted a tool name at the start of ANY LATER line — the same reasoning,
which does not stop applying at line two.

Confirmed with the reviewer's own reproduction, added as regression tests
before the fix:

    "I created the task. For reference, the payload was:\n```json\ncreate_node
    {\"content\":\"Buy milk\"}\n```\nAnything else?"

    "The signature is:\n    create_node {content, node_type}\nand it returns
    the new id."

Both are a model correctly reporting a completed write — the exact honest-report
turn this PR's sibling no-op-success fix exists to protect — and both were being
discarded and replaced with a confirmation request.

Dropped the marker entirely, per the review's recommendation: the three
delimiters observed live (`call:`, `tool:`, `>>>`) already carry the evidence
this branch exists for. My own committed test asserting the own-line shape is
replaced with a `>>>`-prefixed one, so the property under test moves with the
code rather than being deleted.

`seededSkillCount` is now exported with an injectable count function, so the
fallback branch (CLI spawn fails, or a zero enumeration) is exercised directly
rather than only reachable through a real daemon. Two tests pin it.

`awaitSkillIndex`'s parameter order changed: `expected` now precedes `probe`,
so `probe`'s default closure references an earlier parameter instead of a later
one. The old order worked — JS resolves default-value expressions at call time,
and both parameters are this function's own — but read as a forward reference
and would have become a real one under a stricter evaluation order. All five
test call sites and the one production call site updated for the new order.

11 detector tests (2 new), 3 new preflight tests. `bun run test:scripts` 232
pass. `cargo test -p nodespace-agent --lib` 571 pass.

Refs #2254.

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

malibio commented Aug 24, 2026

Copy link
Copy Markdown
Collaborator Author

Found this branch had moved when I went to push my re-review fix — @mstomar125 had pushed 5 commits directly to it in the meantime:

  • c4b20944 Stop a same-tool failure hiding behind an earlier success
  • 44dd72c1 Keep the reported field position matching what the caller sent
  • 1dafc891 Give the paired write tools guidance, and check reachability from the registry
  • f316080a Fetch the schema corpus only when a consumer needs it
  • 85b2e461 Bound each skill-index probe, and report broken seeding instead of waiting

All five are real fixes to gaps I'd left — including one in my own get_all_schemas() dedup from this same review cycle (f316080a — sharing the fetch made it unconditional, which regressed the case with no query and no hits).

Rebased my pending commit onto theirs rather than force-pushing over it. Two of my changes overlapped with theirs on the same lines (the brace-detector marker set, and seededSkillCount's fallback semantics); in both cases theirs was the more complete fix — word-boundary anchoring on the markers (ends_with_marker, which stops "recall:" matching), and adjacency between the tool name and the brace for the own-line case, plus distinguishing a genuine zero-skill enumeration (seeding broke, fail loudly) from a failed CLI spawn (fall back). I kept theirs and folded my additional regression tests in alongside rather than duplicating logic.

Verified post-rebase: cargo test -p nodespace-agent --lib narrated_tool_call 13 pass (merged coverage from both), bun run test:scripts 232 pass, cargo test -p nodespace-agent --lib 577 pass, cargo test -p nodespace-core --lib 1198 pass, bun run test:all exits 0 (53 suites, frontend 227/4794 matching baseline). Pushed as a fast-forward, no force.

@mstomar125

Copy link
Copy Markdown
Contributor

Final state check (mstomar125)

Both review threads have converged: my independent `/code-review` pass (15 findings) → triage/fix (13 fixed, 2 rejected with reasoning) → Michael's own independent re-review (found the same brace-detector class of issue, more precisely) → rebased on top of the fix commits rather than conflicting, confirmed all 5 as real, folded in test coverage. That's two independent review processes cross-verifying each other's work, plus Michael's own author-side re-verification.

No open findings on either side. Test state at HEAD (`f5e2362`) per both parties' independent runs: `test:all` exits 0 (227 frontend files / 4794 tests, 53 Rust suites, 232 script tests), goldens unchanged in shape.

Merging.

malibio added a commit that referenced this pull request Aug 24, 2026
… starvation (closes #2261) (#2266)

* Stop the narrated-call detector discarding an honest unspaced report

The own-line admission accepted a tool name immediately followed by
`{` at the start of a line, reasoning that a narrated call writes its
arguments flush against the name while documentation puts a space
there. That distinction doesn't hold for a model's own report of a
completed write inside fenced JSON — ordinary formatting omits the
space too (`create_node{"content":"Buy milk"}`), and every existing
regression test for the own-line case used the spaced form, so this
false positive went undetected. Removed the admission; only an
explicit marker (call:, tool:, >>>) is now accepted.

Found in a post-merge audit of #2257 (#2261).

* Stop the lexical schema backstop starving the recency injector

`append_schemas_named_in_query` (an unbounded lexical backstop for
schemas the embedding debounce hasn't indexed yet) and the recently-
created-schema injector in local_agent_service.rs both write into
WorkspaceContext.relevant_schemas, but the injector computed its
remaining budget from the vector's post-append length. A turn naming
several existing schemas by name could exhaust that budget before the
injector ever ran, silently dropping a type the user had just created
in the same turn — even though semantic search itself found nothing.

Added semantic_schema_count to WorkspaceContext, captured before the
lexical append runs, so the injector's budget is computed against what
semantic retrieval actually returned rather than a total blind to who
wrote what.

Found in a post-merge audit of #2257 (#2261).

* Add semantic_schema_count to the prompt-assembly snapshot fixture

Missed by the earlier grep for WorkspaceContext literals, which only
covered context_ops.rs — this construction lives in an integration
test in a different crate.

* Address review: end-to-end starvation regression test, doc clarification

Two items from the pragmatic-code-review of this PR:

- The prior regression test for the starvation fix pinned arithmetic
  correctness (semantic_schema_count is captured before, and stays
  untouched by, the lexical append) but never drove the actual
  injector code path in local_agent_service.rs. Added
  lexical_backstop_does_not_starve_the_recency_injector, which creates
  six schemas (five named outright in the query, one not), asserts the
  unnamed one still reaches the rendered context, and was confirmed to
  fail against the pre-fix `relevant_schemas.len()` budget before being
  checked in against the fix.
- Clarified semantic_schema_count's doc comment: it is an upper bound
  on the true final semantic-sourced count, not always exact, since
  hydration can drop a retrieval hit that no longer resolves in the
  full schema corpus. Noted the error direction is harmless (more
  conservative, never the starvation this field prevents).

Skipped: cross-referencing MAX_SCHEMAS (local_agent_service.rs) and
MAX_SEMANTIC_SCHEMAS (context_ops.rs), which the review flagged as
sharing a value (5) with no shared definition. Each constant is
already independently justified in its own doc comment for its own
call site; a cross-reference would guard against a coincidence, not a
defect — not worth the coupling for a one-line nit.
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.

Stage-2 withholds update_node on read-then-write turns, and the model reports success for the no-op

2 participants