Skip to content

Split the two-linked-types ordering constraint out of the one-schema policy - #2818

Merged
malibio merged 4 commits into
mainfrom
issue-2812-schema-rule-split
Sep 22, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2812-schema-rule-split

Conversation

@malibio

@malibio malibio commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2812.

Problem

ONE_SCHEMA_PER_REQUEST packed two rules of different kinds into one paragraph: a policy about restraint and a mechanical ordering constraint. The policy led and owned both examples; the constraint arrived last, in a subordinate clause, framed as a side-effect prohibition.

An agent asked for "Customer and Invoice, linked" read the policy, correctly judged it didn't apply — both types were requested — and skimmed past the constraint that did. It planned a single call creating Customer with a relationship pointing at a not-yet-existent invoice.

The prose fix

  • ONE_SCHEMA_PER_REQUEST → "only the types asked for" — rescoped to the restraint policy alone, and now states explicitly that it governs restraint, not call count.
  • New CREATING_TWO_LINKED_TYPES — states the sequencing remedy the rules never assembled: create the target type first, then the referencing type declaring the relationship on the referencing side, whose required reverseName gives the other end its accessor for free. One stored edge, no schema update follow-up.
  • TARGET_TYPE_MUST_EXIST — "omit the relationship entirely" was the only escape offered, which silently delivers two unlinked types. Omission is now scoped to targets the user never asked for.
  • SCHEMA_ALREADY_EXISTS — said "do NOT call create_schema again", which renders immediately after the new rule and read as a stop signal right after being told to make a second call. Narrowed to that same type.
  • SKILL.md — a hand-written aside still said "one schema per request". It sits outside the generated markers, so regeneration would never have corrected it.

The runtime contradiction the review surfaced

Review of the prose change turned up something larger: the in-app agent could not follow the new rule. A structural guard in agent_loop.rs refused any second create_schema in a turn, and its refusal message told the model that a two-type request "needs its own follow-up request" — the direct opposite of the new guidance.

The existing test made it explicit. Its user message was "keep track of invoices and customers" — both types named — and it asserted the Customer call must be refused. That encoded the bug this issue reports, one layer down: ask for two linked types, silently get one.

The guard now turns on whether the user named the type, not on call count:

  • second_schema_should_be_refused() replaces the bare call-count check
  • user_message_names_type() does the matching — case-insensitive, tolerates plurals, requires every word of a multi-word name. Deliberately loose: a false positive only permits a type the user probably did ask for, while a false negative reinstates the bug being fixed
  • The refusal message no longer claims a cap the runtime doesn't enforce, and names the type it refused
  • Still blocks inventing an unrequested type, which is the guard's actual purpose

Tests

  • second_create_schema_in_one_turn_is_not_executed inverted and renamed to ..._for_a_type_the_user_named_executes — its own scenario names both types, so both must execute
  • New ..._for_an_unrequested_type_is_not_executed (a Sprint nobody asked for) — the policy keeps its teeth
  • New unit tests for the matching helper: case, plurals, multi-word, partial-word, and empty/punctuation names

Verified load-bearing. With the guard reverted, ..._user_named_executes fails its call-count assertion (only one create_schema reaches the executor, not two) while ..._unrequested_type_is_not_executed still passes. The new test fails without the fix rather than passing vacuously.

Two renderers

These constants feed the in-app agent prompt (imperative) and the generated skill markdown (prose). Both use explicit named-substitution templates, so adding a rule to SCHEMA_RULES renders it nowhere until it is interpolated into each:

  • schema_creation_guidance() — packages/agent/src/skill_pipeline.rs
  • render_schema_rules_block() — packages/cli/examples/gen_skill_md.rs

Both are guarded: schema_rules_are_wired_or_explicitly_excluded (agent) and every_schema_rule_reaches_the_skill (packages/cli/tests/skill_md_generation.rs:548). An earlier draft of this PR claimed the markdown-side guard was missing — it isn't; it lives in packages/cli tests, which cargo test -p nodespace-agent doesn't run.

Note on the issue's file path

The description cites packages/skill/src/skill_rules.rs; the real path is packages/agent/src/skill_rules.rs (line numbers are correct). Correction posted on the issue.

Verification

  • cargo test -p nodespace-agent — 645 passed, 0 failed
  • cargo test -p nodespace-cli --test skill_md_generation — 11 passed
  • bun run quality:fix — clippy / tsc / fmt / design-tokens clean
  • bun run skill:check — skill content up to date
  • Golden regenerated; diff reviewed

🤖 Generated with Claude Code

…policy (closes #2812)

The "one schema per request" rule packed a restraint policy and a mechanical
ordering constraint into one paragraph, with the policy leading and owning all
the examples. An agent asked for two explicitly-linked types correctly judged
the policy didn't apply, and skimmed past the constraint that did — then
planned a single call pointing at a type that didn't exist yet.

Three changes:

- Rescope ONE_SCHEMA_PER_REQUEST to the restraint policy alone, renamed "only
  the types asked for". It now says explicitly that it governs restraint, not
  call count, so a legitimately-requested pair doesn't read as forbidden.
- Add CREATING_TWO_LINKED_TYPES, stating the sequencing remedy the rules never
  assembled: create the target type first, then the referencing type declaring
  the relationship on the referencing side, whose required reverseName gives
  the other end its accessor for free. One stored edge, no schema update.
- Fix TARGET_TYPE_MUST_EXIST, where "omit the relationship entirely" was the
  only escape offered. That silently delivers two unlinked types when the user
  asked for linked ones; omission is now scoped to targets never asked for.

Wired into both renderers — the in-app agent prompt via schema_creation_guidance()
and the skill markdown via gen_skill_md — so the rule can't reach one surface
and not the other. Golden snapshot regenerated; the diff is the three edits above.

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

Review Type: Initial Review (no prior reviews on this PR)
Scope: 5 files, +37/−21. Model-facing prompt strings in packages/agent/src/skill_rules.rs, their two renderers, and the two generated artifacts.


Requirements Check (issue #2812)

Issue requirement Status
Split the ordering constraint out of the restraint policy so it stands on its own ✅ CREATING_TWO_LINKED_TYPES is a standalone rule with its own header in both renderers
Constraint must state the sequencing remedy, not just the prohibition ✅ "create the target type FIRST, then the referencing type, declaring the relationship on the REFERENCING side"
Include the worked example (Customer → Invoice with billed_to/reverseName: invoices) ✅ Verbatim, in both imperative and prose
Keep the restraint policy intact and separate ✅ Rescoped, examples ("ADR"/"Ticket"/"Sprint") retained
Fix the "omit the relationship" escape at TARGET_TYPE_MUST_EXIST ✅ Omission now scoped to targets the user never asked for
Fix "then stop and report it" implying a hard stop after one call ✅ Now "create exactly the types… then stop and report them" + explicit "NOT about call count"

Issue requirements are met.


Scrutiny Items You Raised

1. Does the new text fix the reported failure mode?

Reading the prompt in emission order (stage2_candidate_block.golden:35, 37, 51):

  • L35 ONLY THE TYPES ASKED FOR — the agent asked for "Customer and Invoice, linked" now reads "This is a rule about restraint, NOT about call count: when the user does ask for several types, create all of them (see CREATING TWO LINKED TYPES for the ordering)." The prior failure was the agent correctly judging the policy inapplicable and then having nowhere to go. It now has a forward pointer at exactly that moment.
  • L37 CREATING TWO LINKED TYPES — arrives immediately next, leads with the recognition trigger ("When the user asks for a linked pair (e.g. "Customer and Invoice, linked")") matching the failing prompt near-verbatim, and states the remedy as an imperative sequence.
  • L51 RELATIONSHIPS — the third read of the constraint now routes to the same section rather than to omission.

There is no remaining path I can find where the agent reads the policy and stops after one call. The three formerly-divergent surfaces now converge. Same structure holds in cli.md (368 → 370 → 415), where the pointer and the target are two lines apart. This fixes the reported failure mode.

2. Cross-reference resolution.

Verified both directions, both renderers:

  • Imperative: ONLY THE TYPES ASKED FOR → "CREATING TWO LINKED TYPES" resolves to the literal header at golden:37. TARGET_TYPE_MUST_EXIST → same string, same target. ✅
  • Prose: **Only the types asked for.** → Creating two linked types resolves to the bolded lead at cli.md:370. **Relationships vs. fields:** → same. ✅

Imperative/prose halves agree in substance on all three rules — I diffed them clause by clause. The only asymmetry is deliberate: the imperative adds create Customer (no relationship) where the prose says create Customer. That's a helpful disambiguation for the prompt surface, not a divergence.

3. Audit of the rest of skill_rules.rs for contradictions.

I grepped the whole file for "omit the relationship", "single … call", "one call", "then stop and report". Results:

  • GROUPING_IS_COLLECTIONS — no contradiction. Its "one call" claims are about collection path resolution, a different mechanism.
  • RELATIONSHIP_VS_FIELD — no contradiction (the targetType text lives in TARGET_TYPE_MUST_EXIST, which you fixed; they render as one joined paragraph).
  • DELETE_A_SCHEMA — no contradiction; it actively reinforces the new rule ("a relationship's target must EXIST to declare it, and must be ABSENT to delete the type it points at").
  • Self-reference text in TARGET_TYPE_MUST_EXIST — consistent. "no second call needed" is correctly scoped to the self-referential case, and CREATING_TWO_LINKED_TYPES explicitly carves self-reference out ("or be the type this very call is creating (self-reference)").
  • SCHEMA_ALREADY_EXISTS — one residual issue, see finding 🟡-1 below.

Outside skill_rules.rs, one stale phrase survives in hand-written content — see 🟡-2.

4. Technical correctness of the example — verified against source.

The example is not merely plausible; it is verbatim an existing passing test: packages/core/src/schema/schema_test.rs:3083 declared_reverse_fields_govern_the_inbound_group() creates Customer first, then Invoice with exactly {"name":"billed_to","targetType":"customer","direction":"out","cardinality":"one","reverseName":"invoices","reverseCardinality":"many"}, and asserts Customer's inbound group is labeled invoices with cardinality Many.

Point by point:

  • targetType must pre-exist — validate_relationship_targets_exist, packages/core/src/schema/mod.rs:397-426. Only two escapes: None, and pending_schema_id (the type being created in this call). Confirms the rule's claim, and confirms "Declaring invoices → invoice on Customer first is rejected."
  • reverseName/reverseCardinality required — non-Option in SchemaRelationship (packages/nodespace-types/src/schema.rs:291,306), plus a pre-serde friendlier check at mod.rs:902-978. ✅
  • Casing — RelationshipDirection is rename_all = "camelCase" → "out"; RelationshipCardinality is rename_all = "lowercase" → "one"/"many" (nodespace-types/src/schema.rs:253-266). The example's lowercase spellings are correct and required. deny_unknown_fields means the camelCase keys are also mandatory. ✅
  • reverseCardinality: "many" direction — the crux you flagged. Confirmed correct in three independent places: the type doc (nodespace-types/src/schema.rs:292-294, "how many sources may point at one target"), the validator message (core/src/schema/mod.rs:969-970), and the read path (core/src/ops/rel_ops.rs:626-630, "Reading from the inbound side, the reverse cardinality governs"). So cardinality: "one" = each Invoice has one billed_to; reverseCardinality: "many" = many Invoices per Customer. The example has it the right way round.
  • customer is the correct schema ID — normalize_schema_id, packages/core/src/services/node_service/mod.rs:820-830, with a unit test asserting normalize_schema_id("Invoice") == "invoice" at line 838. ✅
  • The invoices accessor materializes without a second declaration — resolve_relationship_name matches rel.reverse_name on inbound relationships (rel_ops.rs:254-261), and get_node_relationships emits the inbound group even when empty (rel_ops.rs:617-621), so the accessor exists from declaration time. ✅

No technical defect in the example.

5. Golden file.

stage2_candidate_block.golden diff is exactly three hunks matching the three source edits (-2/+4), with no drift elsewhere. cargo test -p nodespace-agent: 643 passed, 0 failed. cargo test -p nodespace-cli --test skill_md_generation: 11 passed, including checked_in_skill_md_is_up_to_date.


Code Review Findings

🟡 Important

🟡-1 📁 packages/agent/src/skill_rules.rs:64 (SCHEMA_ALREADY_EXISTS.imperative) — the SUCCESS rule still implies a hard stop after one create_schema

This is the last surviving instance of the exact framing the PR set out to remove, and it renders at stage2_candidate_block.golden:39 — two lines after CREATING_TWO_LINKED_TYPES:

SUCCESS: After create_schema returns a schema object (with fields, type_id, etc.), the schema was created. Respond to the user immediately — do NOT call create_schema again.

An agent that has just read "that is TWO create_schema calls, not one", then makes the first call and gets a schema object back, reads the very next rule as "do NOT call create_schema again" and "respond to the user immediately". That is a direct instruction to stop at exactly the point the new rule says to continue — and it arrives later in the prompt, which for a sequentially-read instruction block is the stronger position.

The rule's intent is clearly anti-re-try ("do not re-issue the same call to double-check"), the same intent SUCCESS_NO_REVERIFY carries. But the wording doesn't say "the same call"; it says "create_schema again", which is literally what the second call is.

This is the same class of defect as the one being fixed: two distinct meanings (don't re-verify vs. don't proceed) packed into one sentence, where the model picks the wrong one. Leaving it means the fix is complete at the planning stage but can still be undone at the execution stage — and the failure would be invisible, delivering one type where two were requested.

Suggested narrowing (both halves):

…the schema was created — do NOT re-issue that same create_schema call to confirm it. If the user asked for more types, continue with the next one (see CREATING TWO LINKED TYPES); otherwise respond to the user.

Principle: single-responsibility applied to instructions — one rule, one decision. It is also the precise defect class this PR exists to eliminate, so fixing it here keeps the change atomic rather than leaving a known instance of the same bug behind.

🟡-2 📁 packages/skill/SKILL.md:217 — hand-written comment still says "one schema per request"

# 1. Create the schema (one schema per request; `references/cli.md` covers field/enum/relationship shape)

SKILL.md has no BEGIN GENERATED markers, so this is hand-maintained and regeneration will never correct it. It now names a rule that no longer exists under that name (renamed to "Only the types asked for") and restates the exact misreading the PR removes — in a file a PTY agent reads before references/cli.md, i.e. earlier than the correction.

One-line fix: # 1. Create the schema (only the types asked for; …).

Principle: DRY / single source of truth. A hand-written paraphrase of a generated rule is a drift source by construction; here it has already drifted.

🟢 Suggestions

🟢-1 📁 PR description — the claimed test gap does not exist; the guard is already there

The PR body states:

schema_rules_are_wired_or_explicitly_excluded catches the prompt half; nothing currently guards the markdown half (worth a follow-up).

This is not accurate. every_schema_rule_reaches_the_skill at 📁 packages/cli/tests/skill_md_generation.rs:548 is exactly that guard. Its doc comment describes the failure you hit, nearly word for word:

"registering a rule in the SCHEMA_RULES array is NOT enough to publish it — a rule the template forgets to name is silently dropped, and checked_in_skill_md_is_up_to_date still passes because the generator and the checked-in copy agree on the same incomplete output. This test is the guard for that gap."

Its skill_md() helper (skill_md_generation.rs:38-63) concatenates SKILL.md and every references/*.md, so cli.md is in scope. I verified empirically: reverting the gen_skill_md.rs interpolation reproduces the failure, and the check fires. cargo test -p nodespace-cli --test skill_md_generation — 11 passed on this branch.

So: no follow-up issue is needed, and no new guard belongs in this PR. My recommendation on your question 5 is neither — the correct action is to delete that paragraph from the PR description so it doesn't seed a duplicate issue. (Answering your framing directly: had the guard genuinely been missing, it would have belonged in this PR, not a follow-up — the PR is the point at which the gap was proven to bite.)

Worth noting why it didn't save you during implementation: the guard lives in packages/cli's integration tests, so cargo test -p nodespace-agent — the natural command when editing skill_rules.rs — doesn't run it. It's the pre-push gate that would have caught it. That's a discoverability gap, not a coverage gap.

🟢-2 📁 packages/cli/tests/skill_md_generation.rs:552 — the guard's 60-char prefix has a latent collision

let needle: String = rule.prose.chars().take(60).collect(); For the two rules touched here the 60-char prefixes are distinct, so this PR is safe. But the match is prefix-based, so two rules whose prose opens with the same 60 characters would let the second pass on the first's text. Cheap hardening: match on rule.id-derived bold lead, or assert prefix uniqueness across SCHEMA_RULES in the existing skill_rules.rs structural test alongside the duplicate-id check at skill_rules.rs:332-335. Not blocking.

🟢-3 📁 packages/skill/references/cli.md:392 — pre-existing "above" that now points below

DELETE_A_SCHEMA.prose says "This is the mirror of the targetType rule above", but in rendered order TARGET_TYPE_MUST_EXIST lands at line 415 — below it. Pre-existing, not introduced by this PR, and it does not interact with the new rule. Flagging only because you asked for a DELETE_A_SCHEMA check. Fix separately (either reorder SCHEMA_RULES or drop the word "above") — out of scope here.

Nitpicks

  • Nit: 📁 skill_rules.rs:50 — the const is now ONE_SCHEMA_PER_REQUEST with id: "one-schema-per-request" while its rendered headers read "Only the types asked for". The identifier no longer describes the rule, and the id is what appears in SCHEMA_RULES_NOT_IN_PROMPT and test failure output. Greenfield rules say rename freely — ONLY_THE_TYPES_ASKED_FOR / "only-the-types-asked-for". I'd leave the id change out only if it's load-bearing somewhere I haven't checked; a grep showed the id appears only in the registry and tests.
  • Nit: 📁 skill_rules.rs:57 — the imperative writes the arrow as invoices -> invoice while the prose uses invoices → invoice. Intentional ASCII-for-prompt, presumably; harmless either way.

Standards Compliance

Check Result
No lint suppression / #[allow(dead_code)] / #[deprecated] ✅ none in diff
No backward-compat or migration code ✅ old text deleted outright, not deprecated
No GitHub issue numbers in docs/code content ✅ none in skill_rules.rs or cli.md; issue ref correctly confined to the commit message
Generated artifacts regenerated and committed ✅ skill:check clean, golden in sync
Tests ✅ nodespace-agent 643 passed; skill_md_generation 11 passed

Assessment

This is a well-executed, genuinely net-positive change, and the diagnosis in the issue and commit message is unusually sharp — the split between "policy" and "ordering constraint" is the right abstraction boundary, and pulling the constraint out so it owns its own worked example is the correct fix rather than a reworded patch. The example is not just correct but is a live test in schema_test.rs, which is the strongest possible grounding for model-facing documentation. Wiring into both renderers with the golden regenerated shows the two-surface hazard was taken seriously.

Two things keep this from a clean approve. SCHEMA_ALREADY_EXISTS (🟡-1) is the more important: it reintroduces the identical packed-instruction defect two lines after the new rule, at the execution stage rather than the planning stage, and an agent obeying it would silently deliver one type where two were asked for — the original bug's symptom, reached by a different route. SKILL.md:217 (🟡-2) is a one-line edit but sits in a hand-written file that regeneration cannot reach, and it names a rule that no longer exists. Both are small and belong in this PR, since the whole point of the change is that these instructions are read as a set.

🟢-1 is worth acting on before merge too, purely so the PR description doesn't seed a follow-up issue for a guard that already exists and already passes.

Recommendation: REQUEST CHANGES

Blocking on 🟡-1 and 🟡-2 (both one-paragraph edits; 🟡-1 needs the golden regenerated). 🟢-1 is a PR-description correction. 🟢-2, 🟢-3 and the nits are optional or out of scope.

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

Verdict: REQUEST CHANGES (posted via --comment — GitHub blocks self-approval/self-request-changes on one's own PR).

Full review: #2818 (comment)

Summary: Strong, correctly-diagnosed change. The policy/ordering split is the right abstraction boundary, the worked example is verbatim a passing test (packages/core/src/schema/schema_test.rs:3083), reverseCardinality: "many" is confirmed the correct direction against packages/core/src/ops/rel_ops.rs:626-630, customer/invoice are the correct normalized schema IDs, cross-references resolve in both renderers, and the golden diff is clean. Agent 643 passed / skill_md_generation 11 passed.

Two blocking items, both small:

  • 🟡 packages/agent/src/skill_rules.rs:64 (SCHEMA_ALREADY_EXISTS) still says "do NOT call create_schema again" and renders two lines after the new rule (golden:39). An agent told "that is TWO create_schema calls" makes the first, gets a schema object, and then reads a later, stronger-positioned instruction to stop. Same packed-instruction defect this PR exists to remove — anti-re-verify intent, but worded as anti-proceed. Needs narrowing to "that same call" plus the golden regenerated.
  • 🟡 packages/skill/SKILL.md:217 still reads "one schema per request". That file has no BEGIN GENERATED markers, so regeneration will never fix it, and it names a rule that no longer exists under that name.

One correction to the PR description (non-blocking): the claim that "nothing currently guards the markdown half" is not accurate — every_schema_rule_reaches_the_skill (packages/cli/tests/skill_md_generation.rs:548) is exactly that guard, its skill_md() helper covers references/*.md, and I reproduced the failure by reverting the gen_skill_md.rs interpolation. No follow-up issue needed and no new guard belongs in this PR — just drop that paragraph so it doesn't seed a duplicate. It didn't catch you during implementation only because it lives in packages/cli tests, which cargo test -p nodespace-agent doesn't run.

Remaining findings (60-char prefix collision in the guard, a pre-existing "above" that points below, two nits) are optional or out of scope.

Addresses review of #2818, plus a contradiction the review surfaced.

The prose fix in the previous commit told the agent that a linked pair is
two sequential create_schema calls. The in-app agent could not comply: a
structural guard in agent_loop.rs refused ANY second create_schema in a
turn, and its refusal message told the model the opposite — that a two-type
request "needs its own follow-up request". The prompt instructed an action
the runtime blocked.

The existing test made the defect explicit. Its user message was "keep
track of invoices and customers" — both types named — and it asserted the
Customer call must be refused. That encoded the very bug #2812 reports, one
layer down: the user asks for two linked types and silently gets one.

The guard now turns on whether the user named the type rather than on call
count, so it still blocks inventing an unrequested type (its actual purpose)
while permitting the second type of a legitimately-requested pair.

- second_schema_should_be_refused() replaces the bare call-count check
- user_message_names_type() does the matching: case-insensitive, tolerates
  plurals, requires every word of a multi-word name. Deliberately loose —
  a false positive only permits a type the user probably did ask for, while
  a false negative reinstates the bug being fixed
- The refusal message no longer claims a one-type-per-request cap, and names
  the type it refused
- second_create_schema_in_one_turn_is_not_executed inverted and renamed: its
  own scenario names both types, so both must now execute
- New test for an unrequested type (Sprint) still being refused
- New unit tests for the matching helper's case/plural/multi-word behavior

Verified the new tests are load-bearing: with the guard reverted, the
user-named test hangs (the refused call leaves the loop with no scripted
round) while the unrequested-type test still passes.

Also from review: SCHEMA_ALREADY_EXISTS said "do NOT call create_schema
again", which read as a stop signal immediately after being told to make a
second call — narrowed to that same type. SKILL.md's "one schema per
request" aside was stale and is hand-written, outside the generated markers.
Dropped a GitHub issue number from a code comment per CLAUDE.md.

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 #2818 (Re-Review)

Review Type: Re-Review
Reviewed: 6dd177b4 (new since last review) + one uncommitted working-tree change to packages/core/src/schema/mod.rs
Scope of new work: +240/−39 in agent_loop.rs, one prompt string, one golden line, one SKILL.md line, one data-layer error message.


Previous Review Summary

Finding Status
🟡-1 SCHEMA_ALREADY_EXISTS "do NOT call create_schema again" contradiction ✅ Addressed. Narrowed to do NOT call create_schema again FOR THAT SAME TYPE to re-verify or retry it, plus a forward pointer (If the user asked for other types too (see CREATING TWO LINKED TYPES), go straight on to the next one). The anti-re-verify intent and the anti-proceed misreading are now separated — exactly the single-responsibility split the rest of the PR performs. Golden regenerated (stage2_candidate_block.golden:39), one line, no drift.
🟡-2 packages/skill/SKILL.md:217 stale "one schema per request" ✅ Addressed. Now only the types asked for; a linked pair is two calls, target first — see references/cli.md. It does more than remove the stale name: it carries the new ordering constraint into the file a PTY agent reads before cli.md. Verified the desktop-app/src-tauri/resources/skill/ copies are byte-identical (diff clean on both SKILL.md and cli.md).
🟢-1 PR description false claim re: missing markdown-side guard ✅ Addressed. The description now reads "An earlier draft of this PR claimed the markdown-side guard was missing — it isn't; it lives in packages/cli tests, which cargo test -p nodespace-agent doesn't run." Correctly states both the fact and the reason it was missed.
🟢-2 60-char prefix collision · 🟢-3 DELETE_A_SCHEMA "above" · nits ⏸️ Not addressed — all were explicitly optional or out of scope. Still fine to defer.

All three actionable findings resolved. Nothing regressed.


The Test Inversion — Independent Scrutiny

You asked me to attack this rather than accept it. I went to the history and to the two mechanisms. The inversion is justified, and the reasoning is stronger than the version in the PR description — but it is stronger for a different reason than you gave, and the "hangs without the fix" claim is wrong. Details below.

Was the original test about a different scenario than its user message describes?

I traced the guard to its origin: db708a90, "Add structural backstop for legitimate multi-schema splits (closes #1905)". Reading the originating issue directly:

"Now that routing correctly reaches the Schema Creation skill for these prompts, nothing stops the model from still creating two schemas within one skill invocation and only populating one."
"In the original measurement, create_relationship errored (the target type didn't exist yet when the call was formed) and the model proceeded anyway, reporting success while leaving the second type empty and unlinked."

And its acceptance criterion, verbatim: "If a split is ever correct, the resulting types are actually linked and both are populated — no silently empty half."

This is decisive, and it cuts in your favour more sharply than your own argument does. The harm the original guard was written to prevent was a dangling/unlinked split, not two types existing. The issue text explicitly contemplates that "if a split is ever correct" — it never asserts one type per request as a safety property. The call-count cap was one of two mechanisms proposed in that issue ("either surface a stronger warning… or reject the second create_schema call outright"), and the issue itself flagged the mechanism as unsettled: "One approach to evaluate (not prescriptive — the actual mechanism needs its own investigation)."

So: the test's user message ("keep track of invoices and customers") was not a sloppy fixture that accidentally described a legitimate scenario. It described the exact scenario the parent issue called a possibly-correct split, and the implementation then refused it. Your reading is right — the test encoded the bug one layer down. The over-broad cap was an implementation shortcut against a criterion that never demanded it.

Is there harm the call-count cap prevented that the data-layer validation does NOT cover?

This is the question that would have blocked the PR, so I worked it independently rather than checking your answer.

The same commit db708a90 added both mechanisms. validate_relationship_targets_exist (packages/core/src/schema/mod.rs:397) is untouched by this PR and still fires from both call sites (mod.rs:1161 for create, mod.rs:1935 for add_schema_relationship). It rejects any targetType that is neither an existing schema nor the pending one. So the dangling reference half — the actual harm in the issue's reproduction — is fully intact.

I then looked for residual harm the cap alone covered:

  1. Model invents an unrequested related type. Still covered — second_schema_should_be_refused retains the refusal for any name the user didn't mention, and ..._for_an_unrequested_type_is_not_executed pins it.

  2. Runaway looping. Bounded independently by MAX_TOOL_ITERATIONS = 5 (agent_loop.rs:35) and by Schema Creation's max_iterations: 3. The cap was never the loop bound.

  3. Two types created but left unlinked — i.e. the model creates Customer, creates Invoice, and simply omits the relationship. This is the one real gap, and it is genuinely not covered by the data layer: validate_relationship_targets_exist skips targetType: None by design (mod.rs:402, and its doc comment says so), so omission is invisible to it. Under the old cap this was impossible-by-construction (you couldn't get a second type at all); now it is reachable.

    But I do not think this is blocking, for two reasons. First, the old cap did not prevent this failure — it converted it into a strictly worse one: the user asked for two linked types and got one type, silently. Two unlinked types is a smaller regression than half a request. Second, this is precisely the gap the prose now attacks from three directions: CREATING_TWO_LINKED_TYPES ("Do NOT omit the relationship here… omitting it silently delivers two unlinked types"), TARGET_TYPE_MUST_EXIST, and now the data-layer error message. Closing it structurally would mean tracking "did a relationship materialize between the two types created this turn" — a real feature, not a line of this PR. Worth a follow-up issue; not a blocker.

    Net: the protection the originating commit was written for survives; the residual gap is strictly less harmful than the behavior it replaces. Your two-mechanism argument holds.

Does the new pair of tests cover what the original single test covered?

Yes, and with better resolution. The original asserted one thing (second call refused) on a fixture whose message named both types — conflating "refuse unrequested" with "refuse second". The new pair separates them along the axis that now matters: ..._for_a_type_the_user_named_executes (2 calls reach the executor, second !is_error) and ..._for_an_unrequested_type_is_not_executed (1 call reaches the executor, second is_error). The second test keeps the original's exact assertions, only with "Sprint" and a message that doesn't name it. Nothing the original pinned is now unpinned — single_create_schema_executes still covers the first-call path.

Verdict on the inversion: legitimate. This is a test that was wrong, not a test bent to fit. The history supports it independently of the PR's framing.


Findings

🟡 Important

🟡-1 📁 packages/agent/src/local_agent/agent_loop.rs — the "hangs without the fix" claim is incorrect, and the PR description states it as verification

The PR description says:

"With the guard reverted, ..._user_named_executes hangs (the refused call leaves the loop with no scripted round)"

and you asked me whether a hang is a fragile failure mode. It would be — but it isn't what happens, and that matters because the claim is doing load-bearing work as evidence the test is non-vacuous.

MockEngine::generate (agent_loop.rs:3887-3900) explicitly handles exhaustion:

if idx >= responses.len() {
    // Return empty response if we run out of pre-configured ones
    on_chunk(StreamingChunk::Done { ... });
    return Ok(InferenceUsage { prompt_tokens: 0, completion_tokens: 0 });
}

It returns a clean empty Done, never blocks. And the ReAct loop is bounded: for iteration in 0..effective_max_iterations with MAX_TOOL_ITERATIONS = 5 (agent_loop.rs:35, 1841). There is no unbounded wait on either axis — an infinite hang is not reachable by this path.

So the real regression behavior is a clean assertion failure on assert_eq!(…count(), 2) — which is the good failure mode you were hoping for, not the bad one you thought you had. The test is better than you believe it is.

Two consequences, both small:

  • The PR description's "Verified load-bearing" paragraph asserts something that isn't true of the harness. Reword it (e.g. "fails the call-count assertion"). A future reader debugging this area will otherwise go looking for a hang that cannot occur.
  • Whatever you actually observed was most likely a slow run or a different local state, not this mechanism. Worth a second look only because a misdiagnosed symptom tends to get "fixed" later by someone adding a timeout that nothing needs.

I'd have raised this as 🟢 if it were only a wording slip, but a stated verification result that the code contradicts is the kind of thing that outlives the PR. No code change required.

Principle: claims in review artifacts are load-bearing documentation; an unfalsifiable-because-false verification claim is worse than none.

🟢 Suggestions

🟢-1 📁 packages/agent/src/local_agent/agent_loop.rs:659 — user_message_names_type false positives are broader than the doc comment admits, and one class is not benign

I compiled the function standalone and ran it against the cases you flagged plus the ones I could construct. Results that matter:

user message name result
"make a note of this and track my tasks" Note true your predicted false positive — confirmed
"track my tasks" Ask true substring of tasks
"keep a list of my books" Boo true substring of books
"for example a Sprint type is wrong; create an ADR" Sprint true name in a quoted example
"dont create a Sprint, just an ADR" Sprint true explicitly negated mention
"i want a report about bugs" Bug Report true words scattered, no phrase
"track my companies" Company false y→ies plural not handled
"track people" Person false irregular plural
"track my 顧客" 顧客 true CJK exact match works
"track my Kunden" Kunde true works incidentally (substring)

On your fail-open argument — "a false positive only permits a type the user probably asked for" — I think it is mostly right but stated too strongly, and the gap is the negation row. "don't create a Sprint, just an ADR" is a user who explicitly refused the type, and the guard permits it. That is not "probably asked for"; it is the opposite. Same for the quoted-example row.

I still land where you land, though, for a reason worth making explicit in the doc comment rather than the one that's there now: the guard is a backstop, not the primary control. The prose rule is the primary control, and a model that has just been told "only the types asked for" and then invents Sprint against an explicit refusal has already failed in a way no substring check was going to catch. The asymmetry that actually justifies fail-open is severity, not likelihood: a false negative silently delivers half a request (the bug being fixed, reproducible today), while a false positive creates a spurious type the user can see and delete. That holds even for the negation case. I'd amend the doc comment at agent_loop.rs:653-658 to say that, since "probably did ask for" is a claim the function's behavior doesn't support.

The substring rows (Ask/tasks, Boo/books) are the cheapest genuine improvement if you want one: matching on word boundaries rather than haystack.contains would eliminate that whole class without touching the plural tolerance you need. split(|c: char| !c.is_alphanumeric()) on the haystack and comparing word-to-word (with the same s-stem rule) is a few lines and strictly more accurate. Optional — the severity argument above means none of these are dangerous.

Non-ASCII: no defect. to_lowercase() is Unicode-aware, is_alphanumeric() is Unicode-aware, and CJK/umlaut names behave sensibly. The strip_suffix('s') pluralization is Anglocentric but fails closed into the exact-match path, so a non-English name just gets exact matching — degradation, not breakage.

🟢-2 📁 packages/agent/src/local_agent/agent_loop.rs:2534 — the "" fallback is correct, and I confirmed the shape concern you raised is unfounded

args.get("name").and_then(|v| v.as_str()).unwrap_or("") → user_message_names_type returns false on the empty name (the words.peek().is_none() early return, pinned by your test) → second call refused. That is the right direction: a create_schema whose name is absent or non-string is malformed, and refusing it loses nothing — the executor would reject it anyway.

On "can't wrongly refuse a valid call whose name field is shaped differently": I checked the tool schema (schema_executor, and the real create_schema surface) — name is a required top-level string. There is no nested or aliased shape for it. And repair_parsed_tool_arguments runs before this guard (agent_loop.rs:~2420), so the model's known malformed encodings are already normalized by the time args.get("name") runs. The fallback is only reachable for a genuinely malformed call. Correct as written.

One small note: the same args.get("name").and_then(...).unwrap_or("") expression is now evaluated twice — once in the guard condition, once to build the refusal message (second_schema_refused_result). Harmless (it's a &str borrow, no allocation), but binding it once above the else if chain would read better and remove the chance of the two drifting. Nit-level.

🟢-3 📁 packages/core/src/schema/mod.rs:414-424 (uncommitted) — the new error message is correct; wording has one soft spot

You asked for arity and wording.

Arity: correct. Four {} placeholders, four arguments (rel.name, then target_type ×3). I counted them in the assembled string, and cargo clippy -p nodespace-core --lib --all-features is clean (a format-arity mismatch is a compile error in Rust, so this was never able to ship broken — but the count is right regardless).

No test pins the removed sentence. I grepped for the removed phrases across all of packages/. The four assertions at schema_test.rs:3359, 3525, 3532, 3540 all match on "not an existing schema" / "targets 'X', which is not an existing schema", which you preserved verbatim as the opening clause. Nothing matches "omit the relationship entirely" or "inventing one" anywhere in the repo. bun run rust:test:lib: 1604 passed, 0 failed. Confirmed clean.

Wording — this is the right call and the highest-leverage placement in the whole PR. The model reads this at the exact moment it makes the mistake, which beats any amount of upfront prompt. Substance is correct and matches CREATING_TWO_LINKED_TYPES clause for clause.

The one soft spot: "create '{target}' first, then re-send this schema with the relationship." "Re-send this schema" is slightly ambiguous about what to re-send — the model has to infer it means the identical payload it just submitted, unchanged, after an intervening call. Compare the prompt rule, which is concrete about the sequence ("create Customer (no relationship), then create Invoice with {...}"). A model that misreads "re-send" as "send a correction" may start mutating the payload. Suggested tightening:

…create '{target}' first, then send this same create_schema call again unchanged — declaring the relationship on this side gives the other end its accessor via the required reverseName.

Minor; the current text is not wrong, just less concrete than its siblings.

Also worth noting for completeness: this message is reachable from add_schema_relationship too (mod.rs:1935), where "re-send this schema" is a slightly odd fit, since the caller is adding a relationship to an existing schema rather than re-sending a creation. The generic phrasing above ("send this call again unchanged") covers both sites.

🟢-4 📁 packages/agent/tests/golden_scenario6_sequence.rs:218 — stale "one schema per request" in a hand-authored prompt

Grepping for the old phrasing after your SKILL.md fix turned up one survivor:

let system = "You are a schema-design assistant. … Do not create more than one schema per request.";

This is not blocking and I am not asking you to change it: it is an #[ignore]d live-GGUF golden with a synthetic system prompt that deliberately does not go through the real prompt pipeline (the file's comments make clear the hand-authored prompt is the point). It cannot drift the product. Flagging only so the grep result isn't rediscovered later and mistaken for a missed edit.

Nitpicks

  • Nit: 📁 agent_loop.rs:2534 — bind the name lookup once rather than repeating the and_then(...).unwrap_or("") chain in both the condition and the message (see 🟢-2).
  • Nit: The ONE_SCHEMA_PER_REQUEST / id: "one-schema-per-request" naming nit from the last review still stands — the const now renders as "Only the types asked for", and after this commit the runtime no longer enforces anything resembling one-schema-per-request, so the identifier is now doubly misleading. Still optional, still a free rename under greenfield rules.
  • Nit: 📁 agent_loop.rs:653-658 — doc comment's justification ("a false positive only permits a type the user probably did ask for") is contradicted by the negation case; the severity argument in 🟢-1 is the one that actually holds.

Standards Compliance

Check Result
No lint suppression / #[allow(dead_code)] / #[deprecated] ✅ none in the diff
No backward-compat / migration code ✅ old guard and old message deleted outright
No GitHub issue numbers in code comments ✅ improved — the diff removes the // (see #1905) comment
Generated artifacts in sync ✅ golden regenerated; desktop-app/src-tauri/resources/skill/ copies byte-identical to packages/skill/
createLogger / no raw logging ✅ n/a (Rust; uses tracing::warn!, consistent with the file)
Tests ✅ nodespace-agent --lib 645 passed; nodespace-cli --test skill_md_generation 11 passed; bun run rust:test:lib 1604 passed; cargo clippy -p nodespace-core clean

Assessment

The follow-up commit is the stronger half of this PR. Tracing a prose contradiction into a runtime guard that made the new rule unfollowable is the kind of finding that justifies a review existing at all — the prose fix alone would have shipped a rule the in-app agent structurally could not obey, and nothing in the test suite would have said so.

On the inversion, which is the thing that needed to survive scrutiny: it survives. I went to db708a90 and to issue #1905 independently, and the originating issue is explicit that a split may be correct and that the mechanism was unsettled — its criterion was "no silently empty half", never "one type per request". The call-count cap was an over-broad implementation of a narrower requirement, and the data-layer validation it shipped alongside (validate_relationship_targets_exist, untouched here, both call sites live) is the mechanism that actually addresses the issue's harm. Your two-mechanism argument is correct. I found one residual gap the cap covered and the data layer doesn't — two types created but left unlinked, since targetType: None is deliberately unvalidated — but it is strictly less harmful than the behavior it replaces (half a request, silently), and closing it properly is a feature, not a line of this PR. Worth filing; not worth blocking.

The uncommitted mod.rs change is well-judged and arguably the highest-leverage edit in the set: the error message is what the model reads at the instant it errs, and it previously handed out the same misleading "just omit it" advice the prose rules were being fixed to remove. Arity is right, no test pinned the removed text, 1604/1604 green.

Everything from the previous review is addressed, and 🟡-1 was addressed well rather than minimally — the rewrite separates re-verify from proceed instead of just deleting the offending clause.

Nothing here blocks. The one 🟡 is a factual correction to the PR description (the "hangs without the fix" claim is contradicted by MockEngine's exhaustion branch and by MAX_TOOL_ITERATIONS = 5) — and it resolves in the PR's favour, since the true failure mode is the clean assertion failure you wanted. Fix the description text before merge; no code change needed. The two follow-ups worth filing are the unlinked-pair gap and, optionally, word-boundary matching in user_message_names_type.

Recommendation: APPROVE

Merge-ready once the "hangs" sentence in the PR description is corrected. 🟢-1 through 🟢-4 and the nits are optional. Two suggested follow-up issues: (1) structural detection of a linked-pair request that ends up unlinked; (2) word-boundary matching in user_message_names_type to drop the Ask/tasks substring class.

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

Verdict: APPROVE (posted via --comment — GitHub blocks self-approval on one's own PR).

Full re-review: #2818 (comment)

All three previous findings addressed. 🟡-1 (SCHEMA_ALREADY_EXISTS) was addressed well rather than minimally — it separates re-verify from proceed instead of deleting the offending clause. 🟡-2 (SKILL.md:217) now also carries the ordering constraint forward. 🟢-1 PR-description claim corrected.

On the test inversion — it survives scrutiny. I went to db708a90 and issue #1905 independently. The originating issue is explicit that a split may be correct ("If a split is ever correct, the resulting types are actually linked and both are populated") and that the mechanism was unsettled ("not prescriptive — the actual mechanism needs its own investigation"). Its criterion was "no silently empty half", never one-type-per-request. The call-count cap was an over-broad implementation of a narrower requirement, and the data-layer guard shipped in that same commit — validate_relationship_targets_exist, untouched here, both call sites live at mod.rs:1161 and :1935 — is what actually addresses the issue's harm. Your two-mechanism argument is correct.

One residual gap the cap covered and the data layer does not: two types created but left unlinked (targetType: None is deliberately unvalidated, mod.rs:402). Not blocking — it is strictly less harmful than the behavior it replaces (half a request, silently), and closing it structurally is a feature. Worth filing.

One 🟡, and it resolves in your favour. The PR description's "with the guard reverted, the test hangs" is not what happens. MockEngine::generate handles exhaustion explicitly (agent_loop.rs:3887-3900, returns an empty Done), and the ReAct loop is bounded by MAX_TOOL_ITERATIONS = 5 (agent_loop.rs:35). The real regression mode is a clean assert_eq! failure — the good failure mode you were hoping for. Just correct the description sentence; no code change.

Uncommitted mod.rs change verified. Arity correct (4 placeholders, 4 args). No test pins the removed sentence — all four assertions at schema_test.rs:3359,3525,3532,3540 match the preserved "not an existing schema" clause; nothing in the repo matches "omit the relationship entirely". rust:test:lib 1604/1604, clippy clean. Highest-leverage edit in the set. One soft spot: "re-send this schema" is less concrete than its sibling rules and reads oddly from the add_schema_relationship call site — suggest "send this same create_schema call again unchanged".

Heuristic probed empirically (compiled standalone). Confirmed false positives: Note/"make a note of this", Ask/"tasks", Boo/"books", Sprint/"don't create a Sprint" (negation), Bug Report/"a report about bugs". Your fail-open argument is mostly right but stated too strongly — the negation case is not "probably did ask for". The asymmetry that actually justifies it is severity, not likelihood: a false negative silently delivers half a request, a false positive creates a visible deletable type. Worth amending the doc comment at agent_loop.rs:653-658. Non-ASCII is fine (Unicode-aware lowercase/alphanumeric; the s-stem is Anglocentric but fails closed into exact match).

The "" fallback is correct — malformed call refused, and repair_parsed_tool_arguments runs before the guard so it is only reachable for genuinely malformed calls. Guard bypass is closed: user_message at the guard site is the raw run_turn parameter (no shadowing), sourced in the daemon from history.last() gated on m.role == Role::User (local_agent_service.rs:751) — model output cannot reach it.

Tests: agent lib 645, skill_md_generation 11, rust:test:lib 1604, clippy clean, skill resource copies byte-identical. Standards clean — the diff removes an issue-number comment.

Merge-ready once the "hangs" sentence is corrected. Suggested follow-ups: (1) structural detection of a linked-pair request that ends up unlinked; (2) word-boundary matching to drop the Ask/tasks substring class.

…ic's rationale

Addresses the re-review of #2818.

The data-layer validator that rejects a dangling targetType carried the same
"omit the relationship entirely" advice this PR removes from the prose — and
in the highest-leverage place, since the model reads it at the instant it
makes the mistake. It now tells the model to create the target type first and
send the same call again when the user asked for both types, and scopes
"omit" to types the user never asked for.

The re-review also falsified the justification in user_message_names_type's
doc comment. "A false positive only permits a type the user probably did ask
for" is wrong: substring matching also says yes to a negated mention ("don't
create a Sprint, just an ADR") and to incidental words ("make a note of
this"). The asymmetry that does justify matching loosely is severity, not
likelihood — a false positive creates a visible, deletable type, while a
false negative silently delivers half a request. Comment restated; behavior
unchanged, since the conclusion still holds.

Left alone deliberately: binding the args["name"] lookup once would mean
hoisting it above the if-chain and computing it on every tool call to save a
map lookup on a rare path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The suggested wording applied in the previous commit said "send this same
call again unchanged". That is right for create_schema, but
validate_relationship_targets_exist has two callers — create_schema
(mod.rs:1161) and update_schema's add_relationships path (mod.rs:1935) —
and re-sending an update_schema call unchanged after creating the target is
not the same operation the model just attempted. The message cannot assume
which caller it is under.

"Retry this call" is correct for both.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@malibio
malibio merged commit 475b3ac into main Sep 22, 2026
@malibio
malibio deleted the issue-2812-schema-rule-split branch September 22, 2026 12:11
mstomar125 added a commit that referenced this pull request Sep 23, 2026
* Flag a turn that creates two unlinked schemas

Relaxing the second-create_schema guard (PR #2818) made it possible for
a legitimately-requested linked pair to land as two sequential calls
that never declare a relationship to each other -- targetType: None is
intentionally unvalidated (a relationship-free schema is legitimate on
its own), so two unlinked types was a silent, valid outcome.

At turn end, re-fetch every schema created this turn and check whether
any relationship connects two of them. When two or more were created
and none do, append a short note to the assistant's response rather
than guess at user intent from phrasing.

Closes #2839.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Describe the guard gap directly instead of citing issue/PR numbers

Per repo convention, code comments describe behavior/constraints
directly rather than embedding GitHub issue or PR numbers.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Address review: per-schema orphan detection, log re-fetch errors

Address review: per-schema orphan detection instead of a single
existential check over the whole batch. With three or more schemas
created in a turn, two of them being linked to each other used to
suppress the note even when a third was a genuine orphan. Now every
created schema is checked individually against the set, and the note
names only the orphan(s) when the batch is partially linked.

Also log a genuine re-fetch failure (a real NodeService error, not
"schema not found") via tracing::warn!, matching this file's other
error arms, instead of collapsing it into the same silent return as
the benign case.

Addresses reviewer recommendations from PR review.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

one-schema-per-request rule buries the targetType ordering constraint under the don't-invent-types policy, and never states the sequencing fix

1 participant