Skip to content

common : support schema-constrained decoding for Gemma 4 tool calls - #23247

Open
rsauciuc wants to merge 3 commits into
ggml-org:masterfrom
rsauciuc:gemma4-strict-schemas
Open

rsauciuc wants to merge 3 commits into
ggml-org:masterfrom
rsauciuc:gemma4-strict-schemas

Conversation

@rsauciuc

Copy link
Copy Markdown

Overview

This adds support for Gemma 4's token-delimited tool calling dialect call:tool{key:<|"|>value<|"|>}.

Additional information

While testing Gemma 4 4B with llama-server and a custom harness (Android Studio), I noticed quite a few tool calls with incorrect arguments ("absolute.absolutePath"), taking the model a few turns to correct. This did not happen with LiteRT-LM, so I started looking into how they handled strings, and how the grammar was handled on the llama.cpp side.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES, navigating the llama.cpp codebase and tracing the code paths for a Gemma 4 run.

…calls

This adds support for grammar schema compilation for Gemma 4 tool calls,
using the non-standard string delimiter <|"|>.

- common/json-schema-to-grammar: added a common_schema_dialect to support
  a new GEMMA4 target with property keys formatted unquoted and string primitives
  referencing gemma4-string
- common/chat: the parser builder now compiles JSON schemas in the new
  dialect. gemma4-string and gemma4-string-content are defined as trigger rules
- common/peg-parser: exported trigger rules, for non-lazy grammar generation
@rsauciuc
rsauciuc requested review from a team and ggerganov as code owners May 18, 2026 03:28
@github-actions github-actions Bot added the testing Everything test related label May 18, 2026
@rsauciuc

Copy link
Copy Markdown
Author

Hi @aldehir , I'm not sure if you were already working on this, but if not, it would be great to get your thoughts on the approach, I'm new to the codebase. Thank you!

@aldehir

aldehir commented May 18, 2026

Copy link
Copy Markdown
Contributor

@rsauciuc thanks for your interest!

I think your approach is good and minimalistic.

One critique:

Rather than relying on the rules from the PEG generated grammar, it would be cleaner to duplicate the string rule instead. Similar to how the JSON rules are defined in json-schema-to-grammar.cpp. Then you can remove the awkward trigger rules, which are primarily intended to craft lazy grammars.

The string delimiter <|"|> is a good candidate for the token construct in GBNF, you can read about it in grammars/README.md.

Added gemma4-array|value|object to handle a failing test in
test-chat.cpp, because the 'todo_list' tool schema is not strict and
the actual items are not constrained to be strings.

- test-json-schema-to-grammar: added one more test where the strings
are nested inside an array, a very common pattern in our tool schemas.
- test-chat: added support for token-aware matching, by loading the
corresponding vocabulary (from e.g. models/ggml-vocab-gemma-4.gguf),
so the Gemma 4 tests don't throw "no vocab to parse token".
@rsauciuc
rsauciuc requested a review from pwilkin as a code owner May 27, 2026 03:40
@rsauciuc

Copy link
Copy Markdown
Author

Thank you so much for the pointers, @aldehir !

It took me a while to get the tests working again after adding the token-based string rule, and I took a detour through loading a vocabulary, but hopefully the latest commit is still conceptually simple. Please take a look when you get a chance!

@aldehir

aldehir commented May 27, 2026

Copy link
Copy Markdown
Contributor

Great, I'll take a look.

Out of curiosity, what issues are you seeing from tool calling that necessitates stricter grammar constrained decoding? At the moment the tool call notation is grammar constrained, but the keys and values are not. Applying stricter rules will introduce a couple of changes:

  • Strict ordering of arguments
  • Invalid regex -> grammar generation as the PR currently stands.

Trying to weigh the pros/cons, but I am largely in favor of this PR if it has a meaningful impact in tool calling. Some examples would help me better understand.

@bvisible

Copy link
Copy Markdown

Repro: HTTP 500 on tool_choice="required" + enum on the same property

Followed up after testing your two commits in isolation on b9426 (cherry-picked 04c74c40b and f05a29af8 separately, custom-built images deployed to a real harness — NORA / Hermes Agent).

Headline

  • commit-1 (04c74c40b schema-constrained decoding) alone resolves the peg-gemma4 infinite-loop issue Eval bug: Infinite repetition loop in llama-server with peg-gemma4 parser during tool calls #21375 without introducing any regression we could find on flat/array schemas. Multi-prop schemas, long string bodies (1 200 chars+), multi-tool tool lists, multi-turn with prior tool_result — all parse cleanly into structured tool_calls.
  • commit-1 + commit-2 (with Switch to token construct) introduces a second bug: with temperature=0, the model leaks its native <|tool_call>call:name{key:<|"|>val<|"|>} format into content instead of populating the structured tool_calls field. The harness (which only reads tool_calls) treats the response as "model declined to delegate" and proceeds without action.
  • Both commit-1 alone and the full PR hit a hard HTTP 500 as soon as a property has an enum AND tool_choice="required" is set.

500 repro (mono-shot, deterministic)

Setup: unsloth/gemma-4-26B-A4B-it-GGUF UD-Q3_K_XL, RTX 5090, llama.cpp b9426 + your branch (or commit-1 only), temperature=0.

Tool with enum on a required property:

{"name":"kanban_create","parameters":{"type":"object","properties":{
  "assignee":{"type":"string","enum":["ventes","compta","support","rh"]},
  "body":    {"type":"string"}
},"required":["assignee","body"]}}

Request body adds "tool_choice":"required".

Server response:

HTTP 500 — "Failed to parse input at pos 41:
  <|tool_call>call:kanban_create{assignee: "compta", body:<|"|>Créer une facture...<|"|>}<tool_call|>"

The server generates a perfectly well-formed tool call (all delimiters closed, JSON-ish payload sane) and then fails to parse its own output. Confirmed across 5 variants:

  • 4-value enum, multi-value enum
  • 1-value enum (sanity)
  • enum on a different property (kind instead of assignee)
  • enum + required vs enum + auto
  • with vs without trailing whitespace around :

What works (so we don't drop the baby with the bath water)

The combination that ships cleanly to a real orchestrator harness:

  • Image: b9426 + cherry-pick commit-1 only.
  • Client sends tool_choice="required" whenever tools is non-empty.
  • No enum in tool schemas (works around the 500). Allowed values are listed in plain text in the system prompt; the model still respects them.

Side effects checked:

  • Trivial prompts (e.g. "bonjour") with tool_choice="required" still return free-form text. The model does not force a meaningless tool call. So required can be unconditional client-side without UX cost.
  • Mono-shot prompts that include safety-triggering words (e.g. firearms vocabulary) still trigger Gemma's safety refusals — that's the model, not the parser, and it manifests as finish_reason="length" with a polite refusal in content. Unrelated to this PR.

What I think is happening on the 500

The GBNF grammar generated for enum properties under the strict required regime seems to constrain the token stream into a state that the PEG parser can't replay, because the generated text re-uses the strict tokens (<|"|>, <tool_call|>) verbatim instead of the looser fallback. The parser then fails at the very first key — pos 41 is exactly after {. Without enum, the same grammar produces a sequence the parser accepts.

Standing offer

I have three small Python repro scripts (≤ 80 lines each):

  • probe_safety.py — 7 scenarios isolating the leak trigger (temperature, tool_choice, SOUL strictness)
  • test_multi_props.py — flat / array / array sweep
  • test_500_enum.py — 5 enum + required variants, exact request bodies
  • Happy to drop them in a gist or paste inline, and to test a fix patch against my running setup (custom build pipeline already in place — I can have a new image deployed in ~5 min). Thanks for the work on this PR — commit-1 alone is already a meaningful win for #21375.

@aldehir aldehir self-assigned this May 31, 2026
@rsauciuc

Copy link
Copy Markdown
Author

@aldehir we've been seeing issues like https://issuetracker.google.com/issues/498987211#comment11 on the Android Studio side, when the model sometimes fails to make edits. Our tool schemas are quite similar to Antigravity's, e.g. the replacementChunk nested object is the same, so I would rather not touch the schemas.

I will try to run some of our agentic evals and get more concrete results for tool calling failures. As yet another anecdote, for all other OpenAI-compatible remote backends we've enabled strict tools (with additionalProperties always set to false), so the switch to a local model is even more jarring when users don't expect to see these kinds of failures anymore.

@bvisible this is an amazing investigation, thank you so much for doing this! I think I know where the bug is, I'm sorry I didn't test this out as thoroughly as you did. We do have 2 tools with enums in their schemas in Android Studio, so I'll work on a fix.

PS. Our official recommendation for the temperature is 1.0, so I'm not sure about this other failure mode you've encountered.

@rsauciuc

Copy link
Copy Markdown
Author

I'll get back to this shortly, sorry for the delay, I want to do some more local testing.

@bartlettroscoe

Copy link
Copy Markdown

Can't we just lift the implementation for this from vllm? It should have a compatible license that you can just adapt that code and use it for llama.cpp?

I'm debating having a proxy layer that can fix these tool calls in a more inference provider agnostic way.

It's unfortunate you have to wait months to get these new models to call tools properly.

mstomar125 added a commit to NodeSpaceAI/nodespace-core that referenced this pull request Aug 24, 2026
…ting success (closes #2254) (#2257)

* Stop reporting a failed write as a completed one on an empty generation

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

* Wait for the skill index before scoring an eval rep

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

* Recover a schema named in the request when its embedding has not landed 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

* Stop a skill description from naming what it excludes; pair every write 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

* Detect a narrated tool call written with braces instead of parens

`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

* Make create_schema's missing-name error actionable, since the grammar 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

* Ignore an informationless field entry instead of failing the whole create_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

* Update prompt-assembly goldens for the paired write tools and new guidance

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

* Address code review: narrow the brace detector, dedupe the schema fetch

## 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

* Correct an overstated blast-radius claim in the Node Creation seed comment

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

* Stop a same-tool failure hiding behind an earlier success

`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]>

* Keep the reported field position matching what the caller sent

`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]>

* Give the paired write tools guidance, and check reachability from the 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]>

* Fetch the schema corpus only when a consumer needs it

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]>

* Bound each skill-index probe, and report broken seeding instead of waiting

`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]>

* Address re-review: drop the own-line marker, close two test gaps

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: mstomar125 <[email protected]>

This branch has not been deployed

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

Labels

testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants