Repository navigation
create_schema paths disagree on whether field names carry a namespace prefix - #1788
Conversation
The description path namespaced inferred fields with `custom:` while the
explicit-fields path stored caller-supplied names verbatim, so the same user
intent produced different stored keys depending on the call shape. Stored names
are user-visible — titleTemplate tokens, CEL selectors, query filters, frontend
lookups — so the divergence surfaced later as templates that render empty and
filters that match nothing.
Per ADR-063, namespace prefixes scope to types NodeSpace owns:
- Fields of user-defined types are stored bare on both routes. create_schema
only ever creates user-defined types (isCore is hardcoded false), so dropping
the inference-time prefix cannot weaken core-property protection.
- Extending a core type now requires a prefix. update_schema's add_fields path
rejects a bare name there, which is where a future core property could collide.
The field-name validator cannot enforce this — it sees a name with no
indication of the type it belongs to.
Also fixes two defects found while implementing:
- The reserved-core-property warning was never delivered. Warnings were
snapshotted before normalization, which is the step that appends it, so every
collision was silently dropped. Warnings are now collected after.
- Title-template tokens matched `\w+` in TypeScript but any run of characters in
Rust, so `{custom:capacity}` and `{first-name}` resolved on the backend and
passed through literally in the UI, leaving optimistic and persisted titles
disagreeing. Both evaluators now share one pattern mirroring the Rust scanner.
The path-agreement test was verified to fail against the pre-fix behavior.
Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
e30d898 to
57152c8
Compare
Review TypeInitial review — PR #1788, 2 commits ( Requirements Check (issue #1785)
1 — ADR ✅. 2 — Paths agree ✅, verified by execution. 3 — Validator ✅. The chosen direction makes neither form invalid at the name level, so no code change to 4 — Agent side ✅, independently verified. 5 — Test ✅ and it is a real guard. I re-ran the new tests against reverted implementations:
No trivially-passing tests found among the new additions. Verification of the Two Bundled FixesWarning delivery (defect 4) — correct. The old code snapshotted Title-template parity (defect 5) — correct, and parity is exact. I diffed the two implementations against three edge cases:
They agree on all three, including the pathological nested case. On the specific Shared-regex
Code Review Findings🟡 Important📁 The guard is placed in the I confirmed this empirically: A bare Principle — an invariant enforced at one entry point is not an invariant. The rule "core schemas carry no unprefixed user fields" is a property of the schema's post-state, but it's currently checked against one input channel. The robust placement is a single post-state validation after Phase 1 and Phase 2 have both been applied — validate the final I'd note this is a pre-existing gap being newly exposed rather than something this PR broke — before this PR there was no guard at all. It's a net improvement either way. But since #1785's stated goal is "the divergence cannot silently return," leaving the cheapest bypass open undercuts the guarantee the PR is claiming. 🟢 Suggestions📁 I checked whether it can be fooled and mostly it can't: 📁 The doc comment says "Kept in one place so both template evaluators stay in sync," which is the right instinct, but a shared 📁 The unit tests cover 📁 That file says "User-defined properties MUST use namespace prefixes" with 📁 "The validator accepts a prefix only where the target type is core, and rejects an unprefixed name there" describes behavior the implementation deliberately does not have — the Verification section three paragraphs later correctly states the opposite ("enforced where the target schema is known, not in the field-name validator"). Since the whole point of the ADR's own Consequences note is that this distinction "will be re-litigated," the one sentence that misstates it is worth deleting. Docs-repo follow-up, not a blocker here. Nits
What This PR Does WellWorth stating explicitly, since the findings above are all secondary:
RecommendationCOMMENT — approve-with-followup in spirit. This is a clear net improvement: it closes a real correctness divergence, records the reasoning durably, and fixes two adjacent defects with tests I verified are genuine guards rather than tautologies. Nothing here is a security issue or an architectural regression, and I would not hold the merge over the suggestions. The one item I'd want a decision on before merge is the Everything else is a follow-up: the |
malibio
left a comment
There was a problem hiding this comment.
Initial pragmatic code review posted as a PR comment. Summary: net improvement, recommendation COMMENT. Verified all 5 acceptance criteria and confirmed the new tests are real guards (they fail against reverted implementations). One item worth a decision before merge: the core-type prefix guard in update_schema's add_fields path is bypassable via rename_fields, which runs in Phase 1 before the guard and never checks is_core — reproduced empirically.
The guard added in the previous commit only inspected add_fields, so a bare
name could still reach a core schema in two calls: add custom:effort, then
rename it to effort. rename_fields is exposed to the agent and its tool
description actively recommends it, and because renames migrate property data
the bare key would land on every existing node instance.
Moving the check to a post-state validation would not work: rename_schema_field
rewrites the schema and migrates node data per rename as it goes, so validating
afterwards returns an error with the offending rename already committed. The
check therefore runs before any rename executes, covering both routes that can
introduce a name — add_fields directly, and rename_fields turning an already
prefixed field bare.
Also from review:
- Replace contains(':') with has_namespace_prefix, which requires exactly one
':' with non-empty segments either side. The old check was correct only
because validate_schema_field_name rejects the malformed forms first; a guard
that depends on validation order in another module is one refactor away from
admitting the names it exists to exclude.
- Assert the reserved-core-property warning reaches the response JSON. The
defect fixed earlier was that it never reached callers, which a unit test on
the normalization function alone would not have caught.
- Rename the stale namespaced_fields binding to stored_fields.
Both new guards were verified to fail against the unguarded behavior.
Co-Authored-By: Claude <[email protected]>
The token pattern was a module-level `/g` RegExp shared by both evaluators. That is safe only while every call site uses String.replace, which resets lastIndex — the first .test() or .exec() a later change adds would start returning alternating results, a failure mode that is hard to trace back to a regex declared in another function. A factory removes the hazard rather than documenting it, at no cost: both call sites now get a fresh instance. Completes the review recommendations from the initial review of this PR. Co-Authored-By: Claude <[email protected]>
Review recommendations addressedAll findings from the initial review are addressed. Nothing skipped. 🟡 Important —
|
| Finding | Resolution |
|---|---|
contains(':') a loose proxy |
Replaced with has_namespace_prefix — exactly one :, non-empty segments either side. Unit-tested against :capacity, custom:, a:b:c, :, "". No longer depends on validation order in another module. |
/g regex singleton lastIndex hazard |
Commit 874a8635. Took the factory option (templateTokenRe()) rather than the comment option — removes the hazard instead of documenting it, at no cost. |
| No test that the warning reaches the JSON response | Added test_create_schema_reserved_property_warning_reaches_response, asserting on result["warnings"] from handle_create_schema. This guards the actual reported symptom. |
schema-management.md states superseded rule |
Fixed in nodespace-docs e828106 — scoped table (core → prefix, user-defined → bare) plus ADR-063 link. |
| ADR-063 internally inconsistent sentence | Fixed in nodespace-docs e828106 — removed; replaced with what the implementation actually does. |
Nit: namespaced_fields binding |
Renamed to stored_fields. |
Follow-up filed
#1789 — the description route folds the type keyword into the inferred name ("capacity number" → capacity_number). Separate from namespacing, noted in ADR-063, and why test_create_schema_paths_agree_on_stored_field_names uses "capacity".
Tests
Frontend 4106 / 170 files · browser 20 · Rust 1026 + 309 + 3. Zero failures. Rust core is up from 1022 — four new tests. Full pre-push gate passed.
Review TypeRe-review — PR #1788, delta Previous Review Summary
Every item was verified by execution or by reading the landed source, not taken on the summary's word. Verification of Prior Recommendations🟡 Important —
|
| Route | Result |
|---|---|
add_fields: [{name: "effort"}] |
✅ Rejected |
rename_fields: [{to: "effort"}] |
✅ Rejected |
remove_fields: ["status"] + add_fields: [{name: "status"}] (same call) |
✅ Rejected — add_fields is checked regardless of removals |
| Multi-rename batch, one bad entry | ✅ Rejected atomically, zero partial application |
add_relationships |
⚪ N/A — relationships are a separate namespace, not validated by validate_schema_field_name, and explicitly outside ADR-063's scope |
create_schema remains unreachable: it hardcodes "isCore": false (📁 mod.rs:301) so it cannot target a core schema.
🟢 contains(':') was a loose proxy → Addressed
Replaced with has_namespace_prefix (📁 packages/core/src/schema/mod.rs:101). I checked it against validate_schema_field_name (📁 behaviors/mod.rs:1266) and the two use structurally identical split(':') triple-match logic, so they agree by construction rather than by coincidence — which was the entire point of the finding. has_namespace_prefix is deliberately the weaker check (it does not test the alphanumeric charset), which is the right relationship: it may pass a name that the validator later rejects, but it can never pass one the validator would consider unprefixed. No name is accepted that should be rejected. The doc comment states exactly why it doesn't lean on the other module.
test_has_namespace_prefix covers :capacity, custom:, a:b:c, :, and "".
🟢 /g regex lastIndex hazard → Addressed
📁 packages/desktop-app/src/lib/utils/title-template.ts:32 — took the factory option (const templateTokenRe = () => /\{([^}]*)\}/g), which removes the hazard rather than documenting it. Verified:
grep -rn "TEMPLATE_TOKEN_RE" packages/→ zero hits, no stale references.- Both call sites (
:46,:97) use the factory. - 26/26 title-template tests pass. Behavior unchanged — each
replacenow gets a fresh instance.
🟢 No test that the warning reaches the JSON response → Addressed, and it is a real guard
test_create_schema_reserved_property_warning_reaches_response asserts on result["warnings"] from handle_create_schema. I independently confirmed it fails when the delivery is broken by forcing the handler to elide warnings:
panicked: warnings should be present in the response when a field collides
It guards the reported symptom, not just the extracted function.
🟢 schema-management.md stated the superseded universal rule → Addressed
nodespace-docs e828106. Now carries the scoped table (core → prefix required, user-defined → bare name) plus the ADR-063 link, and explicitly documents the rename route: "update_schema rejects an unprefixed name on a core type, both when adding a field and when renaming one to a bare name." Matches the implementation.
🟢 ADR-063 Decision section contradicted its own Verification section → Addressed
nodespace-docs e828106. The sentence "The validator accepts a prefix only where the target type is core…" is gone (grep confirms). The Decision section now states what the implementation actually does, and agrees with the Verification section at line 68.
Nit: namespaced_fields binding → Addressed
Renamed to stored_fields at both use sites (📁 mod.rs:259, :303, :343).
New Test Verification
Both remaining new tests independently confirmed as real guards, not tautologies:
test_update_schema_core_type_rename_cannot_drop_namespace_prefix — disabling the rename check reproduces exactly the bypass from the initial review:
panicked: renaming a core-schema field to a bare name should be rejected:
Object {"fieldsRenamed": Number(1), "schemaId": String("task"), "success": Bool(true)}
It also asserts the negative — that custom:effort survives the rejected rename and effort never appears — so it guards against a rejection that still mutates.
test_update_schema_user_defined_type_allows_bare_names — forcing schema_is_core to always return true makes it fail:
panicked: bare names on a user-defined type should be accepted:
InvalidParams("Field 'address' added to core schema 'venue' must carry a namespace prefix…")
This is the test I most wanted to see, because it pins the over-rejection direction. Without it, a future tightening of schema_is_core would break every user-defined type silently.
cargo test -p nodespace-core --lib schema:: → 61 passed, 0 failed on restored source.
Over-rejection analysis
I checked whether the guard can fire on something legitimate:
- Can a user-defined type have
is_core == true? No.is_core: trueis written only by NodeSpace's shippedmodels/core_schemas.rs; every user-reachable creation path hardcodesfalse(📁mod.rs:301). A user-defined type cannot trip the guard. - Can
schema_is_corereturnfalsefor a genuinely core schema? Only via the missing-schema →falsemapping, which is unreachable: the pre-existing Phase 0 already returns"Schema '{id}' not found"before this call. The fallback is defensive, and the doc comment says so.
Code Review Findings
🟢 Suggestions
📁 packages/core/src/schema/mod.rs:613 and :682 — two consecutive blocks both labelled "Phase 0".
The pre-existing block (// --- Phase 0: Verify schema exists, validate renames, run playbook impact check ---) and the new one (// --- Phase 0: Reject unprefixed field names on a type NodeSpace owns ---) are separate blocks under the same number, separated by ~70 lines. The numbering exists to convey ordering, and two things sharing a number defeats that — the next reader has to determine whether these are one phase interrupted or two independent ones, and the answer isn't visible locally.
The placement is correct (both must precede Phase 1); only the label is ambiguous. Cheapest fix is to fold the heading into the existing one — // --- Phase 0: Validate everything that must be checked before any mutation --- — or number the new block Phase 0b. Cosmetic; not worth another round-trip on its own.
📁 packages/core/src/schema/mod.rs:682 — schema_is_core re-fetches a schema the function already fetched.
The pre-existing Phase 0 at :613 calls get_schema_node(¶ms.schema_id) and discards the result (it only needs the existence check); schema_is_core then fetches the same row again. That is one redundant read on every update_schema call.
Not a correctness concern — update_schema is a low-frequency agent-driven operation, both reads happen before any mutation so there is no TOCTOU window that matters, and the value is re-fetched again at Phase 2 anyway. It is genuinely also a readability win as written: schema_is_core(node_service, &id) states the question at the call site far better than threading a SchemaNode binding down from :613 would. Binding the existing fetch and reading .is_core off it would save the read but couple the two blocks. I'd leave this as-is — flagging only so the trade-off is recorded rather than looking like an oversight.
What the Delta Does Well
- The deviation was reasoned from the code, not from convenience. The implementer investigated my suggestion, found it would corrupt data, and said so explicitly with the mechanism named. Pushing back on a reviewer with evidence is the correct outcome here — and the batch-rename probe shows their design is strictly stronger than mine, not merely equivalent.
- The fix is placed where the invariant actually holds. My original framing ("an invariant enforced at one entry point is not an invariant") was right about the problem and wrong about the remedy. Phase 0 enforces it across all input channels in one block, which achieves the same robustness property — a future mutation kind added to
update_schemaneeds its check added here, and the co-located block makes that obvious. - Comments carry the reasoning forward. The Phase 0 comment explains why it isn't a post-state check — precisely the question the next reader (or reviewer) will ask, pre-answered. Same for
has_namespace_prefix's note on not depending on validation order, and thetemplateTokenRefactory's note onlastIndex. - Tests assert the negative direction too.
test_update_schema_user_defined_type_allows_bare_namesand the "original field survives a rejected rename" assertions guard against over-rejection and partial application, not just the happy path.
Recommendation
APPROVE
All 7 prior recommendations are addressed, verified by execution rather than by claim. The one deviation from my guidance was correct, well-reasoned, and produces a stronger guarantee than what I suggested — Phase 0 rejects a mixed rename batch atomically where post-state validation would have committed the legal renames first.
The 🟡 Important finding that held the previous review at COMMENT is closed: the rename_fields bypass is shut, remove_fields + re-add is covered, no partial application is possible, and the three new tests all fail when their guards are disabled. The two remaining findings are cosmetic and I would not hold a merge for either.
Working tree left clean; all probe edits reverted and verified with git status --porcelain.
malibio
left a comment
There was a problem hiding this comment.
Re-review posted above: all 7 prior recommendations addressed and verified by execution. The deviation from my suggested post-state validation was correct — Phase 0 rejects mixed rename batches atomically where post-state validation would have committed the legal renames first. APPROVE.
Resolves an import-block conflict in local_agent_service.rs: main added ChatModelSpec (#1791) while this branch added PriorWrite and the agent_loop imports for the duplicate-write guard. Both are needed, so the resolution is the union of the two import lists. No logic conflict. The SelfLimitingWrite doc's claims about handle_update_schema were re-verified against the merged schema/mod.rs (#1788 touched that file): adds still error on an existing name, removes are still retain() calls that converge. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
Closes #1785