Skip to content

Fix unique_case_insensitive wire key in schema tool JSON schemas - #2834

Merged
malibio merged 2 commits into
mainfrom
issue-2801-tool-schema-unique-key
Sep 22, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2801-tool-schema-unique-key

Conversation

@malibio

@malibio malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Closes #2801.

Problem

def_create_schema and def_update_schema declared the unique-field flag as unique_case_insensitive, but SchemaField carries #[serde(rename_all = "camelCase", deny_unknown_fields)] — so that key is rejected outright, not silently ignored.

Unlike #2788 (the same wrong spelling in skill_rules.rs doc text), this one is live and functional. These JSON Schemas are the literal contract handed to the tool-calling model, and exec_create_schema/exec_update_schema pass the model's raw tool-call arguments straight through to handle_create_schema/handle_update_schema, which serde_json::from_value them into CreateSchemaParams/UpdateSchemaParams. There is no key normalization anywhere in between. A model that faithfully followed its own tool schema and set the flag had its entire call rejected:

unknown field `unique_case_insensitive`, expected one of `name`, `friendlyName`, `type`, ... `uniqueCaseInsensitive`, `localOnly`

Changes

  • packages/agent/src/local_agent/tools.rs:1352, :1443 — both sites now declare uniqueCaseInsensitive.
  • The descriptions also named the wrong key inline ("Do not set both 'unique' and 'unique_case_insensitive'"), which the model reads too — corrected in the same edit.
  • New test schema_tool_field_keys_are_accepted_schema_field_wire_keys — walks every field-property key both tools declare, builds a minimal payload from each, and deserializes it through the real SchemaField. This generalizes past the one flag: any future declared key that can't survive deny_unknown_fields now fails at test time.
  • Golden stage2_tool_surface regenerated.

Verification

  • The regression test was confirmed to fail without the fix, with the identical unknown field error from the issue's CLI reproduction — it pins the real bug, not a tautology.
  • bun run rust:test:libsql-linked — 37 test binaries, 0 failures (646 agent lib tests).
  • bun run quality:fix — clean (clippy -D warnings, tsc, eslint, design tokens).
  • Full pre-push gate passed.
  • Golden diff reviewed: exactly the two key/prose changes, nothing incidental.

Why it survived this long

The existing unique_field_tool_descriptions_state_advisory_only_semantics checks these descriptions' wording but never the keys. And single-word keys like unique are spelled identically in both conventions — only a multi-word key exposes the drift. That is also the root cause documented in the companion docs work (#2809/#2810): field names are snake_case and field metadata keys are camelCase, and they sit side by side in one payload, so a wrong key can't be caught by eye.

🤖 Generated with Claude Code

 #2801)

`def_create_schema` and `def_update_schema` declared the unique-field flag
as `unique_case_insensitive`, but `SchemaField` is `rename_all =
"camelCase"` + `deny_unknown_fields`, so that key is rejected outright.

Unlike #2788's doc-text instance, this is a live functional defect: these
JSON Schemas are the literal contract handed to the tool-calling model,
and `exec_create_schema`/`exec_update_schema` pass the model's raw
arguments straight through to `handle_create_schema`/`handle_update_schema`,
which deserialize them into `CreateSchemaParams`/`UpdateSchemaParams` with
no key normalization in between. A model that faithfully followed its own
tool schema and set the flag got its whole call rejected with `unknown
field unique_case_insensitive`.

Both sites now declare `uniqueCaseInsensitive`. The surrounding
descriptions named the wrong key inline too ("Do not set both 'unique'
and 'unique_case_insensitive'"), which the model also reads, so those are
corrected in the same edit.

Adds `schema_tool_field_keys_are_accepted_schema_field_wire_keys`, which
walks every field-property key both tools declare, builds a minimal
payload from it, and deserializes through the real `SchemaField`. Verified
it fails without the fix, with the same `unknown field` error the CLI
reproduction hit. The existing
`unique_field_tool_descriptions_state_advisory_only_semantics` checks the
descriptions' wording but never the keys, which is why this survived while
the identical mistake was caught in the skill text -- single-word keys like
`unique` are spelled the same in both conventions, so only a multi-word
key exposes the drift.

Golden `stage2_tool_surface` regenerated; its diff is exactly these two
key/prose changes and nothing else.

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

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2834

Scope: 2 files, +74/−7. Single commit 5a0de353. Initial review (no prior reviews or comments).

Summary

This is a tight, correct, well-targeted bug fix and a clear net positive. It resolves a live functional defect exactly as issue #2801 specified, adds a regression test that genuinely pins the bug, and regenerates the golden with no incidental drift. The change is atomic — one cohesive purpose, no bundled unrelated edits.

I independently verified the central claims rather than trusting the description:

  • The bug is real and the fix is correct. exec_create_schema/exec_update_schema (📁 packages/agent/src/local_agent/tools.rs:3594, :3618) pass the model's raw args: Value straight into handle_create_schema/handle_update_schema with zero key normalization. SchemaField (📁 packages/nodespace-types/src/schema.rs:147-148) is rename_all = "camelCase" + deny_unknown_fields. A model that faithfully copied its own tool schema got the whole call rejected.
  • The regression test genuinely fails without the fix. I reverted only the two key renames and ran the new test in isolation. It failed at tools.rs:4461 with:
    CreateSchema declares field key "unique_case_insensitive" in its fields JSON Schema,
    but SchemaField rejects it: unknown field `unique_case_insensitive`, expected one of
    `name`, `friendlyName`, `type`, `protection`, `coreValues`, `userValues`, `indexed`,
    `required`, `extensible`, `default`, `description`, `itemType`, `fields`, `itemFields`,
    `unique`, `uniqueCaseInsensitive`, `localOnly`.
    
    That is the same error class as the CLI reproduction in skill_rules.rs documents the unique-field JSON key as unique_case_insensitive, but the wire form is uniqueCaseInsensitive, so the documented example is rejected verbatim #2788. The test is not vacuous, and the panic message is genuinely actionable — it names the key, the tool, and the repair. Working tree restored clean afterward.
  • The golden diff is exactly the two key/prose changes and nothing else — confirmed by reading git show on the .golden file directly.
  • The sweep is complete. I swept the whole repo (excluding target/) for all eleven snake_case spellings of SchemaField/EdgeField/SchemaRelationship keys in JSON/wire contexts, including a programmatic scan of all 21 def_* tool-definition bodies. No declared key anywhere is misspelled — def_create_schema/def_update_schema correctly carry friendlyName, coreValues, targetType, reverseName, reverseCardinality, edgeFields; skill_rules.rs:216-217 and the desktop TS types (src/lib/types/schema-node.ts:76,85,117,132) are correct too. Every remaining hit is a Rust struct-field initializer/accessor, a Rust doc comment, a deliberate negative test (📁 packages/nodespace-types/src/schema.rs:644, 📁 packages/core/src/schema/schema_test.rs:1727) asserting the snake_case form is rejected, an intentionally-different snake_case response contract that documents itself as such (📁 packages/core/src/ops/entity_types_block.rs:202), or a frozen ablation transcript under packages/agent/goldens/ablation/ that should not be rewritten (rewriting would falsify a recorded measurement). One genuine-but-minor prose instance remains — see finding 3.
  • No other tool reaches this deserialization. Only create_schema/update_schema feed SchemaField/EdgeField/SchemaRelationship; no other def_* declares schema-field- or relationship-shaped item properties.

Findings

🔴 Critical Issues

None.

🟡 Important

1. 📁 packages/agent/src/local_agent/tools.rs:4482 — the _ => json!("text") fallback is a latent false-failure trap for the next key added.

I enumerated what the tools actually declare today. Both tools declare only string/boolean/array-typed keys, so the fallback is currently harmless:

CreateSchema: coreValues(array) description(string) friendlyName(string) indexed(boolean)
              name(string) required(boolean) type(string) unique(boolean) uniqueCaseInsensitive(boolean)
UpdateSchema: coreValues(array) description(string) friendlyName(string)
              name(string) type(string) unique(boolean) uniqueCaseInsensitive(boolean)

But SchemaField has three more wire keys a future PR would plausibly want to expose — and two of them break this helper:

If someone declares… sample_value_for_declared_key yields Actual result
protection as "type": "string" "text" ❌ FALSE FAILURE — unknown variant \text`, expected one of `core`, `user`, `system``
itemType as "type": "string" "text" ✅ passes (correctly)
localOnly as "type": "boolean" true ✅ passes (correctly)
default with no "type" (as edgeFields.default already does) "text" ✅ passes (untyped serde_json::Value)

I verified each of these empirically against the real deserializer. The protection case is the live hazard: a correct, camelCase-spelled key would make this test fail with an error message that blames the key spelling — the one thing that would actually be right. Whoever hits that will burn time before realizing the test lied.

The comment at :4480-4481 also slightly misstates the mechanism. It says name/type "are overwritten with their own valid values by the caller's base object," but the data flow is the reverse: base is cloned first, then field[key] = ... overwrites the base value. For name the probe value becomes "text", and for type it stays "text" — both happen to deserialize fine, so the test is correct, but for a different reason than the comment gives. Since this comment is what the next reader will reason from, it's worth stating accurately.

Why this matters (fail-safe test design): a guard test whose failure mode is a misleading message is worse than one that's merely narrow. The principle is that a test should fail for the reason it claims to test. Two cheap options:

  • (a) Special-case the enum-shaped key, keyed off the declared enum array the JSON Schema would carry, or simply an explicit match arm:
    // `protection` is a closed enum on SchemaField; a generic string probe would
    // fail on the *variant*, not the key, and misattribute the blame.
    Some("string") if key == "protection" => serde_json::json!("user"),
    (this requires threading key into the helper, which is a one-line signature change)
  • (b) Leave the value logic alone but make the panic distinguish the two causes — if the error string contains unknown field, it's a key bug; otherwise it's a probe-value problem and the message should say so. This is arguably the better fix since it's key-agnostic and survives any future key:
    .unwrap_or_else(|e| {
        let msg = e.to_string();
        assert!(
            !msg.contains("unknown field"),
            "{tool:?} declares field key {key:?} ... {msg}"
        );
        panic!(
            "{tool:?} key {key:?} is a valid SchemaField key, but this test's probe \
             value was not accepted: {msg}. Teach sample_value_for_declared_key a \
             suitable value for this key — this is a test-harness gap, not a schema bug."
        )
    });

Either is fine. I'd lean (b): it keeps the helper dumb and makes the test self-diagnosing forever.

2. 📁 packages/agent/src/local_agent/tools.rs:1387, :1510 — edgeFields item schemas are structurally identical and equally exposed, but left uncovered by the new guard.

EdgeField (📁 packages/nodespace-types/src/schema.rs:224-226) carries the same #[serde(rename_all = "camelCase", deny_unknown_fields)] pair, reaches deserialization through the same handle_create_schema/handle_update_schema path (nested under SchemaRelationship::edge_fields), and its tool-declared keys (name, type, coreValues, required, default) are — I checked — all currently correct. So there is no bug here today.

But that's luck, not a guarantee: EdgeField also has targetType and indexed unexposed, and SchemaRelationship (camelCase + deny_unknown_fields) declares targetType/reverseName/reverseCardinality/edgeFields in the tool schema — four multi-word keys, every one a candidate for the exact drift this PR is fixing. The new test covers fields/add_fields items only.

Precisely, the new guard walks only properties["fields"]["items"]["properties"] (create) and properties["add_fields"]["items"]["properties"] (update). It does not cover:

  • relationships / add_relationships item properties → SchemaRelationship
  • nested edgeFields item properties → EdgeField
  • nested fields / itemFields recursion within a SchemaField

Given the loop is already written, extending it to recurse over the relationship and edge-field item schemas is a modest addition that would close the whole class rather than one instance. I'd call this the difference between fixing the bug and fixing the bug category — worth doing, but reasonable to take as a follow-up if you'd rather land this narrow fix now.

🟢 Suggestions

3. 📁 packages/agent/src/local_agent/tools.rs:1460 — add_field_values's description names user_values/core_values in snake_case, to the model.

"New values go to user_values; core_values is never written. … if any value string already exists in core_values or user_values."

These are model-facing prose, not declared keys, so nothing is rejected — strictly weaker than the bug being fixed, and lower severity still because both keys are server-owned on this path (a model never writes userValues in an add_field_values call, so a wrong spelling misinforms rather than breaks). But it's the identical drift pattern, and it's inconsistent within the same block — the sibling edgeFields descriptions at :1387 and :1510 say coreValues correctly.

The same two spellings appear in the shipped skill text at 📁 packages/skill/references/cli.md:384,386 (duplicated into the bundled copy at 📁 packages/desktop-app/src-tauri/resources/skill/references/cli.md:384,386), which is likewise self-inconsistent — lines 352, 355, 382, 419, 423 and 428 of that same file use coreValues/userValues correctly.

Both trace to a single source of truth: the imperative and prose fields of the add-field-values rule in 📁 packages/agent/src/skill_rules.rs (~:106-107). Fixing it there and regenerating propagates to all three surfaces. Worth a small follow-up rather than expanding this PR's scope — it would require another golden regeneration.

4. Nit: 📁 packages/agent/src/local_agent/tools.rs:4383 — pre-existing typo in a neighboring doc comment: "drifying" → "drifting". Not introduced by this PR; mentioning only because it's three lines above the code you touched.

5. Nit: the two tools' fields vs add_fields item schemas have diverged. create_schema declares required and indexed; update_schema does not. That asymmetry predates this PR and may well be deliberate prompt-surface tuning — but if it isn't, the new test's key-walking loop is exactly the place someone would notice. Worth a glance, not a blocker.

Standards & Process

  • ✅ No lint suppression, no #[allow(dead_code)], no #[deprecated], no backward-compat shim — the old key is deleted outright, correct for a pre-release codebase.
  • ✅ No new dependencies. No .md files added to this repo.
  • ✅ Test lives beside the code it guards, with a doc comment explaining why (the single-word-key blind spot) rather than what — exactly the comment standard CLAUDE.md asks for.
  • ✅ Golden regenerated rather than hand-edited; diff verified to contain only intended changes.
  • ✅ Commit message is unusually good: states the mechanism, the blast radius, why the existing test missed it, and that the failure was verified without the fix.
  • ✅ Requirements from create_schema/update_schema tool JSON schema declares unique_case_insensitive, but SchemaField requires camelCase uniqueCaseInsensitive #2801 fully satisfied, including the "Suggested fix" ask for both renames and a test that round-trips through the real deserializer. The PR actually exceeds the issue's ask by generalizing to all declared keys instead of hardcoding the one.

Recommendation

APPROVE

The fix is correct, minimal, verified, and complete for the defect as filed. Findings 1 and 2 are both about hardening the guard rather than the fix — neither affects runtime behavior, and neither should block a merge that removes a live defect from the model's tool contract. I'd suggest taking finding 1 (option b is a ~6-line change with real long-term value) in this PR since it's cheap, and filing finding 2 as a follow-up to extend the same guard to EdgeField/SchemaRelationship. Finding 3 is optional polish that costs a golden regeneration.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval on your own PR).

Full review: #2834 (comment)

Verdict: APPROVE. The fix is correct, minimal, and verified. I independently reverted the two key renames and confirmed the new regression test fails with the exact unknown field \unique_case_insensitive`error — it is not vacuous. The golden diff contains only the two intended key/prose changes. A full repo sweep across all 21def_*tool bodies, the skill text, the CLI/daemon, and the desktop TS types found no other misspelled declared key; onlycreate_schema/update_schema` reach this deserialization path.

Two non-blocking findings, both about hardening the guard rather than the fix:

  • 🟡 tools.rs:4482 — the _ => json!("text") fallback in sample_value_for_declared_key is a latent false-failure trap. I verified empirically that if protection were ever declared as "type": "string", a correctly-spelled key would fail with unknown variant \text`, blaming the spelling — the one thing that would be right. Cheap fix: assert the error contains unknown fieldbefore panicking, so the test distinguishes a schema bug from a probe-value gap. The adjacent comment aboutname/type being "overwritten by the base object" also has the data flow backwards (field[key] = ...` overwrites the base, not the reverse).
  • 🟡 tools.rs:1387,1510 — EdgeField and SchemaRelationship carry the identical camelCase + deny_unknown_fields pair and reach the same handler, but their declared keys (targetType, reverseName, reverseCardinality, edgeFields) are unguarded by the new test. All correct today; extending the loop to recurse would close the class rather than the instance.

🟢 tools.rs:1460 plus packages/skill/references/cli.md:384,386 still say user_values/core_values in model-facing prose — same drift pattern, much lower severity (server-owned keys, misinforms rather than breaks). Both trace to skill_rules.rs ~106-107; worth a small follow-up.

None of these block a merge that removes a live defect from the model's tool contract.

Review finding (Important): `sample_value_for_declared_key`'s string
fallback is a latent false-failure trap. Every key the two tools declare
today is a string, boolean or array, so it is harmless right now — but a
key whose value is more structured than "any string" would get the probe
value "text" and fail deserialization for a reason having nothing to do
with its spelling, while the panic message blamed the spelling: the one
thing that was actually correct.

The round-trip now asserts the error is an `unknown field` before
indicting the key. Anything else reports as a test-harness gap naming the
offending probe value and pointing at the helper to extend.

Verified both branches empirically:

- Reverting the two key renames still fails with the key-spelling message
  and the real `unknown field unique_case_insensitive` error, so hardening
  the guard did not weaken what it catches.
- Temporarily declaring `protection` as a plain string reproduces the
  predicted false failure (`unknown variant \`text\`, expected one of
  \`core\`, \`user\`, \`system\``) and now surfaces as the harness message
  instead of a spelling accusation.

Also corrects two comments the review flagged: the helper's note had the
data flow backwards (it claimed `name`/`type` are overwritten by the base
object, but `base` is cloned and the probe overwrites the clone), and a
pre-existing "drifying" typo three lines above the touched code.

Test-only and comment-only; the golden is deliberately untouched, since
no model-facing text changed.

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

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — c8ea7166

✅ Addressed (3)

🟡 Finding 1 — sample_value_for_declared_key false-failure trap. Fixed. The round-trip now asserts the error is an unknown field before indicting the key; anything else reports as a test-harness gap naming the offending probe value and pointing at the helper to extend.

Verified both branches empirically rather than assuming:

  • Reverting the two key renames still fails with the key-spelling message and the real unknown field \unique_case_insensitive`` error — hardening the guard did not weaken what it catches.
  • Temporarily declaring protection as a plain string reproduces exactly the false failure you predicted (unknown variant \text`, expected one of `core`, `user`, `system``), and it now surfaces as the harness message instead of a spelling accusation.

🟢 Finding 4 — "drifying" typo. Fixed.

Comment correction. You were right that the helper's note had the data flow backwards — base is cloned and the probe overwrites the clone, not the other way round. Replaced with an accurate note on why the string fallback is deliberately naive.

📋 Filed as follow-up (1)

🟡 Finding 2 — EdgeField/SchemaRelationship guard gap → #2836

Confirmed your analysis independently: EdgeField (packages/nodespace-types/src/schema.rs:224-226) carries the same camelCase + deny_unknown_fields pair and reaches the same handler. Out of scope here because all keys on those surfaces are correct today — this is preventive hardening, not a live defect, and folding it in would expand a two-file bug fix into a test-infrastructure change. Issue includes the nested fields/itemFields recursion gap you noted.

⏭️ Skipped (2)

🟢 Finding 3 — user_values/core_values prose in skill_rules.rs. Skipping — I believe this is a false positive, and changing it would make the text wrong.

That prose describes where values land in storage ("New values land in user_values; core_values is never touched"), not a wire key the model types. I checked FieldValueAddition (packages/core/src/schema/mod.rs:1340-1347): the add_field_values payload accepts only field and values — userValues/coreValues are not input keys on that path. Renaming them to camelCase would imply a wire key the payload rejects, and would cost another golden regeneration for a net-negative change.

The coreValues references elsewhere in cli.md that you flagged as "correct" are a different thing: those are genuine create_schema input keys, which is why both spellings coexist legitimately. Happy to revisit if you read that prose differently.

🟢 Finding 5 — required/indexed asymmetry between the two tools. Skipping as out of scope: pre-existing, unrelated to this fix, and plausibly deliberate prompt tuning. Changing either tool's declared properties would alter model-facing text and require a golden regeneration — not something to fold into a wire-key bug fix on a hunch.

Verification

  • cargo test --lib -p nodespace-agent — 645 passed, 0 failed
  • bun run quality:fix — clean (clippy -D warnings, tsc, eslint, design tokens)
  • Full pre-push gate passed
  • Golden deliberately untouched — these changes are test-and-comment-only, so no model-facing text changed

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The one code change is confined to test-harness error discrimination, with both its branches verified empirically. No production code, no model-facing text, no golden change. The remaining items were either filed as a tracked follow-up or skipped with reasoning. Nothing here alters the behavior the initial review approved.

@malibio
malibio merged commit 535ec36 into main Sep 22, 2026
@malibio
malibio deleted the issue-2801-tool-schema-unique-key branch September 22, 2026 12:02
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.

create_schema/update_schema tool JSON schema declares unique_case_insensitive, but SchemaField requires camelCase uniqueCaseInsensitive

1 participant