Skip to content

Resolve extends-chain fields in Play condition path validation - #2826

Merged
mstomar125 merged 9 commits into
mainfrom
issue-2819-validate-play-extends-chain
Sep 22, 2026
Merged

mstomar125 merged 9 commits into
mainfrom
issue-2819-validate-play-extends-chain

Conversation

@mstomar125

@mstomar125 mstomar125 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

validate_schema_path (packages/core/src/playbook/validation.rs, called from validate_play) checked a Play condition's path segments against a single schema's own directly-declared fields/relationships (schema.fields/schema.relationships) — it never walked the ADR-078 extends chain. A field or relationship genuinely inherited from an ancestor schema (declared there, not redeclared on the subtype — the normal, intended extends usage) was therefore rejected with PlayValidationError::BrokenPath, blocking a legitimate Play from ever being saved or activated at all. validate_relationship_action (an add_relationship/remove_relationship action's relationship_type param) had the identical gap.

This is the same root-cause class as the extends-chain gap fixed separately in workflow_state.rs's diagnostic candidate enumeration (core#2769/PR#2817), but more severe: it sits in the save-time validation path rather than a diagnostic query, so it's a real functional blocker rather than a misreported diagnostic.

Fix

  • validate_schema_path and validate_relationship_action now resolve the effective field/relationship set per hop via NodeService::resolve_field_owners/resolve_relationships (own directly-declared plus everything inherited across the extends chain), instead of a single schema's own declarations. validate_relationship_action also gained the is_reserved_relationship_name skip its sibling already had, fixing a pre-existing (not introduced here) misclassification of built-in relationship names (has_child, member_of, ...) as unknown.
  • Field/relationship precedence: a name can be a field on one schema in the chain and a relationship on another. Rather than checking "is it a member of the whole merged field set" unconditionally before ever checking relationships, validate_schema_path compares chain position between resolve_field_owners's and resolve_relationships's owner maps — the nearer declaration (of either kind) wins, matching ADR-078's per-name shadowing rule.
  • No silent degradation on a resolution error: a resolve_field_owners/resolve_relationships failure (e.g. a transient DB error) is surfaced as a new PlayValidationError::SchemaResolutionFailed rather than silently falling back to a narrower, un-merged view — that fallback would reintroduce the exact under-reporting bug this PR closes, just gated on infra flakiness instead of being always-on.
  • SchemaResolutionFailed is not treated as a genuine failure by any of the 4 engine.rs callers that react to validate_play's Err (handle_schema_updated's schema-drift re-validation, handle_play_created, handle_play_updated, load_active_plays) — a new PlayValidationError::has_genuine_failure helper gates all four. Only handle_schema_updated (re-checking an already-active, previously-confirmed play in reaction to an unrelated schema edit) leaves state unchanged on an inconclusive-only result. The other three all (re-)activate with the current rules instead: they're reacting to a fresh save/first-activation/re-enable, where there's no prior lifecycle-manager entry for "leave state unchanged" to preserve — skipping activation there would make the play permanently invisible to all future re-validation (a "ghost" play showing active on the node while silently never running), which is worse than proceeding on an unconfirmed verdict. The primary create/update gate (NodeService::validate_play_rules) still rejects the write on any error including SchemaResolutionFailed, by design: a transient failure there is honestly retryable (the Display text says so), unlike the deterministic misclassification bug this PR fixes.
  • Also merged origin/main mid-PR to pick up core#2769/PR#2817, which independently fixed a related resolve_relationships gap (excluding the extends/extended_by type-system relationship from the merge, so a condition literally named extends can't misresolve as traversable).

Relationships and fields are both now extends-chain-aware; workflow_state.rs's own diagnostic path walker (walk_path_against_schema) is a different function/PR's territory and is intentionally left untouched here — it inherited the chain-merge from PR#2817 but not this PR's field/relationship precedence fix, tracked separately.

Known follow-ups (non-blocking)

Raised across 6 review rounds and intentionally left out of scope for this fix:

  • resolve_field_owners/resolve_relationships are called uncached per path segment (each independently re-walks the extends chain), and the two calls for one segment aren't resolved atomically — a narrow TOCTOU under concurrent schema edits. A shared, cached "effective schema" primitive across validate_schema_path, validate_relationship_action, and workflow_state.rs's walker would remove both the duplication and the race window.
  • log_validation_errors tags every validation error, including the new SchemaResolutionFailed, as PlayErrorType::CompileError when writing a persistent log node — pre-existing imprecision (every error kind was already tagged this way before this PR), not something this PR introduces, but worth a dedicated error-type mapping at some point.
  • is_genuine_failure treats every resolution error as transient; there's currently no way to distinguish a one-off DB hiccup from a deterministic, permanent resolution failure, so a persistently-failing resolution would loop as "inconclusive" indefinitely rather than escalating.

New tests

  • test_inherited_field_through_relationship_passes_validation / test_inherited_relationship_through_relationship_passes_validation — the issue's exact scenario, for a field and a relationship respectively.
  • test_own_relationship_shadows_inherited_field_of_same_name — the precedence fix: a subtype's own relationship must shadow a same-named field on a farther ancestor.
  • test_inherited_relationship_type_in_action_passes_validation / test_builtin_relationship_type_in_action_passes_validation — the extends-chain gap and the built-in-name gap in validate_relationship_action.
  • has_genuine_failure_distinguishes_schema_resolution_failed_from_real_errors — locks in the SchemaResolutionFailed-vs-genuine distinction directly (the underlying DB failure isn't fault-injectable in this test harness).

All schema-path/action tests verified to fail with the pre-fix error (BrokenPath/UnknownRelationshipType) before their respective fix and pass after, via manual revert/re-apply.

Test plan

  • cargo check --workspace --all-targets — clean
  • cargo clippy -p nodespace-core --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo test --workspace --lib — all crates green
  • cargo test -p nodespace-core --lib — 1615/1615 passing
  • cargo test -p nodespace-core --test playbook_engine_integration_test — 12/12
  • cargo test -p nodespace-core --test playbook_invariant_integration_test — 28/28
  • bun run quality:fix — clean
  • Pre-push gate (test:all + cargo build --bin nodespaced + test:e2e) — all green

Closes #2819

🤖 Generated with Claude Code

mstomar125 and others added 3 commits September 22, 2026 12:40
validate_schema_path checked a Play condition's path segments against
a single schema's own directly-declared fields (schema.fields), never
walking the ADR-078 extends chain. A field genuinely inherited from an
ancestor schema (declared there, not redeclared on the subtype) was
therefore rejected with PlayValidationError::BrokenPath, blocking the
Play from ever being saved or activated.

Resolve the effective field set per hop via
NodeService::resolve_field_owners (own fields merged with everything
inherited across the chain) instead of schema.fields, matching the
fix PR#2817 applied to the identical gap in workflow_state.rs's
diagnostic candidate enumeration. Relationships are unaffected —
schema relationships aren't part of the extends merge, so the
relationship check still reads the schema's own declarations.

Adds a regression test reproducing the issue scenario (a subtype
schema extending a base with an inherited, non-redeclared field,
referenced via a relationship path in a Play condition), verified to
fail with BrokenPath before the fix and pass after.

Closes #2819

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The pre-push code-reference ratchet rejects embedded issue/PR numbers
in code comments (CLAUDE.md: describe behavior directly, cite ADRs
instead). Rewrite the regression test's doc comment to describe the
extends-chain gap and its fix without citing specific issue/PR
numbers.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
validate_schema_path's relationship lookup still checked only the
current schema's own directly-declared relationships, reproducing the
same extends-chain gap this PR fixes for fields: a relationship
inherited from an ancestor (not redeclared) was never recognized,
wrongly rejecting a condition that traverses it as BrokenPath.

Add NodeService::resolve_relationships (the relationship counterpart
to resolve_field_owners, same nearest-first merge across the chain)
and use it here, falling back to the schema's own relationships on a
resolution error rather than an empty set. Adds a regression test for
the inherited-relationship case, mirroring the existing
inherited-field one; verified to fail with BrokenPath before this fix
and pass after.

Also: use the file's existing `tracing::{debug, warn}` import instead
of a fully-qualified `tracing::warn!` call, for consistency with the
rest of the module.

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

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (initial)

Recommendation: REQUEST CHANGES (one 🔴 critical finding)

🔴 Critical: Relationship lookup still checks only the schema's own declarations, not the extends chain

📁 packages/core/src/playbook/validation.rs:758 (pre-fix)

validate_schema_path fixed the extends-chain gap for fields but left the relationship check (schema.relationships.iter().find(...)) reading only the current schema's own directly-declared relationships — reproducing the identical bug class for a relationship inherited from an ancestor and not redeclared. A condition traversing such a relationship (e.g. node.owner.manager.status, where manager is declared on an ancestor of owner's target type) was wrongly rejected as BrokenPath.

Engineering principle: the fix pattern (resolve the effective/merged set across the extends chain, not the current schema's own fields) needs to be applied uniformly everywhere a schema's declarations are consulted in this function, not just for the field branch — a sibling PR (workflow_state.rs's walk_path_against_schema) hit and fixed this exact same asymmetry in its own review pass.

🟡 Other findings (evaluated, addressed or intentionally skipped)

  • No memoization of resolve_field_owners/resolve_relationships per path segment — matches the established pattern in the sibling workflow_state.rs fix (also uncached per-segment). Skipping: consistency with the just-reviewed, accepted sibling pattern; a caching layer would be a follow-up affecting both call sites together, not scope creep on this fix alone.
  • Fallback on resolution error reverts to the schema's own fields/relationships — this is correct, not a bug: it matches the sibling's own review-fix (falling back to the current schema's own fields is strictly better than an empty set, since it can't misreport a field/relationship that unambiguously exists on the node's own schema).
  • Test naming uses vp_ prefix instead of the module's documented vt_ convention — the immediately-surrounding pre-existing tests in this same "Schema-aware path validation tests" section already consistently use vp_, so this test matches its actual local neighbors. Skipping.
  • Test's inherited field is literally named priority, which shadows a reserved core property — deliberate: this reproduces the issue's exact literal repro (node.epic.priority). create_schema only warns (doesn't reject), so there's no functional impact. Skipping.
  • tracing::warn! fully-qualified instead of reusing the file's use tracing::debug; import — addressed: added warn to the same import, changed both call sites to bare warn!.

Fix applied

  • Added NodeService::resolve_relationships (packages/core/src/services/node_service/schema.rs) — the relationship counterpart to resolve_field_owners, same nearest-first merge across the extends chain.
  • validate_schema_path's relationship lookup now uses it, with the same current-schema fallback pattern on a resolution error.
  • New regression test test_inherited_relationship_through_relationship_passes_validation, verified to fail with BrokenPath before the fix and pass after (same manual-revert methodology as the field-side test).

Verification: cargo test -p nodespace-core --lib playbook::validation — 90/90 passing. cargo test -p nodespace-core --lib playbook:: — 450/450. cargo test -p nodespace-core --lib — 1607/1607. bun run quality:fix clean. Pre-push gate green on the latest push (003267cb).

🤖 Generated with Claude Code

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor 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: initial pass found 1 critical finding (relationship extends-chain gap), now fixed in commit 003267c — see review comment above for full findings and resolution. Posted as a comment — GitHub blocks self-approval.

mstomar125 and others added 3 commits September 22, 2026 13:54
…rors

Two follow-up fixes to the extends-chain merge, both from review:

- validate_schema_path checked "is this a member of the whole merged
  field set" unconditionally before "is this a member of the whole
  merged relationship set" — two independently pre-merged sets checked
  in a fixed field-then-relationship order. A subtype's own
  relationship could be shadowed by a same-named field on a farther
  ancestor (the reverse of the intended shadowing rule: nearer
  declarations should win regardless of kind), silently misresolving
  a valid relationship-traversal path as a terminal field and
  rejecting it as BrokenPath. resolve_relationships now returns an
  owners map (relationship_name -> owning_schema_id), mirroring
  resolve_field_owners, so the two can be compared by chain position
  instead of by a fixed check order.

- Both resolve_field_owners's and resolve_relationships's error
  fallbacks degraded to the current schema's own directly-declared
  set on a resolution failure, with only a log — silently
  reintroducing the exact under-reporting bug this fix exists to
  close under nothing more than a transient DB error. Save-time
  validation cannot safely guess here the way a read-only diagnostic
  can, so a resolution failure is now surfaced as a new
  PlayValidationError::SchemaResolutionFailed instead of silently
  degrading.

Adds a regression test for the precedence bug (a subtype's own
relationship shadowing an inherited field of the same name), verified
to fail with BrokenPath before this fix and pass after.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…alidate-play-extends-chain

# Conflicts:
#	packages/core/src/services/node_service/schema.rs
…lidation too

validate_relationship_action (validates the relationship_type param of
add_relationship/remove_relationship Play actions) still checked
schema.relationships directly against the trigger schema's own
declarations, un-merged — the same extends-chain gap
validate_schema_path fixes for condition paths, left live in this
sibling function. A relationship_type genuinely inherited from an
ancestor schema (declared there, not redeclared) was wrongly rejected
as UnknownRelationshipType.

Now resolves the effective relationship set via resolve_relationships,
with the same SchemaResolutionFailed surfacing on a resolution error
as validate_schema_path, instead of silently falling back.

Adds a regression test, verified to fail with UnknownRelationshipType
before this fix and pass after.

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

Copy link
Copy Markdown
Contributor Author

Address review (round 2)

Two independent review passes surfaced 3 more real, high-confidence findings, all fixed:

🔴 Critical: field/relationship precedence

validate_schema_path checked "is this a member of the whole merged field set" unconditionally before ever checking relationships — two independently pre-merged sets checked in a fixed field-then-relationship order, instead of comparing which declaration is nearer in the extends chain. A subtype's own relationship could be wrongly shadowed by a same-named field on a farther ancestor.

Fix: resolve_relationships now returns an owners map (relationship_name -> owning_schema_id), mirroring resolve_field_owners. validate_schema_path compares chain position between the two instead of a fixed check order — nearer declaration (of either kind) wins. Regression test test_own_relationship_shadows_inherited_field_of_same_name, verified to fail with BrokenPath before the fix and pass after.

🔴 Critical: silent error-fallback

Both resolve_field_owners's and resolve_relationships's error fallbacks degraded to the current schema's own directly-declared set on a resolution failure, with only a log — silently reintroducing the exact under-reporting bug this PR exists to close under nothing more than a transient DB error.

Fix: added PlayValidationError::SchemaResolutionFailed, surfaced instead of silently degrading, at every resolve_field_owners/resolve_relationships call site in this file (including validate_relationship_action, see below).

🟡 Important: validate_relationship_action had the identical extends-chain gap

A sibling function (validates an add_relationship/remove_relationship action's relationship_type param) still checked schema.relationships directly, un-merged. A relationship_type genuinely inherited from an ancestor was wrongly rejected as UnknownRelationshipType.

Fix: now uses resolve_relationships, same SchemaResolutionFailed surfacing on error. Regression test test_inherited_relationship_type_in_action_passes_validation, verified fail-before/pass-after.

Also: merged main

core#2769/PR#2817 merged upstream in the meantime and independently fixed the same resolve_relationships "extends"/"extended_by" leak (a condition segment literally named extends could pass as a real, traversable relationship). Merged origin/main, resolved the resolve_relationships conflict by combining both fixes (kept the owners-map for precedence, took upstream's is_type_system_relationship filter), fixed the resulting workflow_state.rs call-site break.

Verification

  • cargo check --workspace --all-targets — clean
  • cargo test --workspace --lib — all crates green (nodespace-core: 1613/1613)
  • cargo test -p nodespace-core --lib playbook:: — 456/456
  • bun run quality:fix — clean
  • Pre-push gate — green on the latest push (35b025f6)

🤖 Generated with Claude Code

The new SchemaResolutionFailed error was, until now, treated identically
to a genuine validation failure (BrokenPath, UnknownRelationshipType,
etc.) at every consumer of validate_play's result in engine.rs
(handle_schema_updated's schema-drift re-validation, handle_play_created,
handle_play_updated). A transient DB error during extends-chain
resolution could therefore silently disable an already-active, correctly-
configured Play — the exact failure mode SchemaResolutionFailed exists to
make visible, reintroduced one layer up instead of fixed.

Add PlayValidationError::is_genuine_failure/has_genuine_failure, and gate
all three disable_play call sites on it: a SchemaResolutionFailed-only
result now logs a distinct "inconclusive, leaving state unchanged"
warning and returns without disabling anything, rather than treating an
unconfirmed verdict as a confirmed break.

Also corrects an overclaiming comment on the field/relationship
precedence tie-break: schema creation does not actually guard against a
single schema declaring both a field and a relationship under the same
name (only field-vs-field redeclaration across the extends chain is
checked), so the tie-break's "moot" framing was wrong — documented as a
real, reachable edge case instead, with the field-wins choice explained
as deterministic rather than harmless.

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

Copy link
Copy Markdown
Contributor Author

Address review (round 3)

One more re-review pass surfaced a real, critical regression introduced in round 2, now fixed:

🔴 Critical: transient resolution failures were silently disabling working Plays

Every consumer of `validate_play`'s result in `engine.rs` (`handle_schema_updated`'s schema-drift re-validation, `handle_play_created`, `handle_play_updated`) treated the new `SchemaResolutionFailed` identically to a genuine failure (`BrokenPath`, `UnknownRelationshipType`, etc.). A transient DB error during extends-chain resolution could therefore silently disable an already-active, correctly-configured Play — the exact failure mode `SchemaResolutionFailed` was added to make visible, reintroduced one layer up.

Fix: added `PlayValidationError::is_genuine_failure`/`has_genuine_failure`, gated all three `disable_play` call sites on it. A `SchemaResolutionFailed`-only result now logs a distinct "inconclusive, leaving state unchanged" warning and returns without disabling anything.

🟢 Also fixed: an overclaiming code comment

The field/relationship precedence tie-break's comment claimed schema creation guards against a single schema declaring both a field and a relationship under the same name. Verified against `schema/mod.rs` — no such guard exists (only field-vs-field redeclaration across the extends chain is checked). Corrected the comment to document this as a real, reachable edge case with a deterministic (not "harmless") tie-break, rather than adding a broader schema-creation-time guard (out of scope for this fix).

Verification

  • `cargo check -p nodespace-core --lib` — clean
  • `cargo test -p nodespace-core --lib playbook::` — 456/456
  • `cargo test -p nodespace-core --lib` — 1613/1613
  • `cargo test -p nodespace-core --test playbook_engine_integration_test` — 12/12
  • `cargo test -p nodespace-core --test playbook_invariant_integration_test` — 28/28
  • `bun run quality:fix` — clean
  • Pre-push gate — green on the latest push (`df85a376`)

🤖 Generated with Claude Code

… too

load_active_plays (the daemon-startup path that loads and activates
every previously-active play) was missed by the has_genuine_failure
gating applied to handle_play_created/handle_play_updated/
handle_schema_updated: it still skipped activation unconditionally on
any validate_play error, including a SchemaResolutionFailed-only one.

Unlike the other three call sites, this one has no later event to
retry validation on — a play skipped here at startup stays
un-activated for the rest of the process's life. On an
inconclusive-only result, activate the play anyway rather than leave
it off indefinitely: the user already set it active in a previous
session, so optimistically honoring that over an unconfirmed
transient failure is the safer default here (unlike the other three
sites, which leave state unchanged since they can rely on a future
event to re-validate).

Also rewrote the PR description, which still described the
now-superseded pre-SchemaResolutionFailed fallback approach from the
first commit.

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

Copy link
Copy Markdown
Contributor Author

Address review (round 4)

Another re-review (10 finder angles + direct verification) found the `has_genuine_failure` gating from round 3 was applied to only 3 of 4 relevant `validate_play` call sites, plus flagged a stale PR description.

🟡 Fixed: `load_active_plays` missed the same gating

The daemon-startup path that loads and activates every previously-active play still skipped activation unconditionally on any `validate_play` error, including a `SchemaResolutionFailed`-only one. Worse than the 3 sites fixed in round 3: this one has no later event to retry validation on, so a play skipped here at startup stays un-activated for the rest of the process's life.

Fix: on an inconclusive-only result, activate the play anyway rather than leave it off indefinitely — the user already set it active in a previous session, so honoring that over an unconfirmed transient failure is the safer default specifically here (the other 3 sites correctly leave state unchanged, since they have a future event to retry on).

Evaluated, not changed (with reasoning documented in the PR description)

  • `NodeService::validate_play_rules` (the primary create/update gate, `crud.rs`) still rejects the write on any error including `SchemaResolutionFailed`. This is intentional, not a miss: the original issue's bug was a deterministic misclassification (fails forever, any number of retries); `SchemaResolutionFailed` is transient by construction and its own `Display` text tells the caller to retry. Fail-closed on an unconfirmed verdict at the one synchronous, transactional, first-line gate is a defensible, different policy than "don't disable an already-working play" at the async re-validation sites — applying `has_genuine_failure` uniformly everywhere would mean creating possibly-broken plays whenever validation is merely inconclusive, which is worse.
  • `workflow_state.rs`'s `walk_path_against_schema` still lacks this PR's field/relationship precedence fix (it picked up the chain-merge from core#2769/PR#2817, but not the "nearer wins" logic added here). That's a different function in a different, already-merged PR's territory — out of scope for validate_play rejects a legitimate Play condition referencing an inherited (extends-chain) field as BrokenPath #2819's stated scope (`validate_play`'s write path). Called out explicitly in the PR description as a known, intentionally-untouched gap.

Also rewrote the PR description top-to-bottom — it still described the original, now-3-rounds-superseded fallback-to-own-schema approach from before `SchemaResolutionFailed` existed.

Verification

  • `cargo check -p nodespace-core --lib` — clean
  • `cargo test -p nodespace-core --lib playbook::` — 456/456
  • `cargo test -p nodespace-core --lib` — 1613/1613
  • `cargo test -p nodespace-core --test playbook_engine_integration_test` — 12/12
  • `bun run quality:fix` — clean
  • Pre-push gate — green on the latest push (`b939cefb`)

🤖 Generated with Claude Code

…hip gap

handle_play_created and handle_play_updated's inconclusive-validation
branches returned without ever calling activate_play/reenable_play —
unlike handle_schema_updated (a re-check of an ALREADY-active play,
where "leave it running" is a real, meaningful choice), these three
transitions have no prior lifecycle-manager entry that "leaving it
unchanged" preserves:

- A brand-new play (None -> active) was never in the lifecycle at all,
  so skipping activation makes it permanently invisible to
  plays_referencing_schema and therefore to every future schema-drift
  re-validation too — a ghost play, showing "active" on the node but
  silently never running, with nothing to retry it short of a manual
  re-edit or a daemon restart.
- A disabled play being re-enabled (Disabled -> active) stayed
  disabled with the same no-retry problem.
- An active play being edited (Active -> active) kept its OLD,
  pre-edit rules running silently instead of either applying the edit
  or disabling — the user's change was dropped with only a log line.

All three now fall through and (re-)activate with the new rules on an
inconclusive-only result, matching load_active_plays' identical
reasoning (already fixed in the prior commit) — only
handle_schema_updated keeps its "leave state unchanged" policy, since
it's the one case actually re-checking an already-confirmed-valid,
untouched play rather than reacting to a fresh save.

Also: validate_relationship_action — the exact function this PR made
extends-chain-aware — was still missing the is_reserved_relationship_name
skip its sibling validate_schema_path has, so an add_relationship/
remove_relationship action naming a built-in structural relationship
(has_child, member_of, ...) was wrongly rejected as
UnknownRelationshipType. Pre-existing gap, not introduced by this PR,
but reachable in the same function this PR already rewrote.

New tests: a pure unit test locking in has_genuine_failure/
is_genuine_failure's SchemaResolutionFailed-vs-genuine distinction
(the DB-level failure itself isn't fault-injectable in this harness),
and a regression test for the built-in relationship type fix.

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

Copy link
Copy Markdown
Contributor Author

Address review (round 5)

🔴 Critical: "ghost plays" — my own round-3 fix's blind spot

`handle_play_created`/`handle_play_updated`'s "don't disable on inconclusive validation" branches returned without ever calling `activate_play`/`reenable_play`. That's correct for `handle_schema_updated` (re-checking an already-active, previously-confirmed play — "leave it running" is meaningful there), but wrong for these: a brand-new play, a just-re-enabled one, or a just-edited active one was never (re-)registered in the lifecycle manager on this path, so "leaving it unchanged" actually meant "leave it permanently invisible to all future re-validation" — a play showing "active" on the node while silently never running, with no retry path short of a manual re-edit or daemon restart. Same failure class as round 4's `load_active_plays` fix, in the 2 sites that one round hadn't reached yet.

Fix: all 3 transitions (new play, re-enable, edit-while-active) now fall through and (re-)activate with the new rules on an inconclusive-only result — only `handle_schema_updated` keeps "leave state unchanged," since it's the one case not reacting to a fresh save.

🟢 Also fixed: pre-existing gap in the touched sibling function

`validate_relationship_action` was missing the `is_reserved_relationship_name` skip its sibling `validate_schema_path` has, so an action naming a built-in relationship (`has_child`, `member_of`, ...) was wrongly rejected. Pre-existing (not introduced by this PR), but reachable in the exact function this PR already rewrote — fixed while there.

New tests

  • Pure unit test locking in `has_genuine_failure`/`is_genuine_failure`'s behavior directly — the underlying DB failure itself isn't fault-injectable in this test harness, so this is the practical coverage ceiling for that path.
  • Regression test for the built-in relationship type fix.

Verification

  • `cargo check -p nodespace-core --lib` — clean, `cargo clippy` — clean
  • `cargo test -p nodespace-core --lib` — 1615/1615 (one flaky SQLite DDL test on first run, confirmed pre-existing/unrelated — passed in isolation and on rerun)
  • `cargo test -p nodespace-core --test playbook_engine_integration_test` — 12/12
  • `bun run quality:fix` — clean
  • Pre-push gate — green on the latest push (`cf76a1bb`)

This is the last planned review round — running one final pass now to confirm no similarly-severe findings remain before merge.

🤖 Generated with Claude Code

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review (round 6 — final)

Final pass (10 angles + direct source verification) found no new correctness bugs of the same severity as rounds 3–5. All findings are either already addressed/documented, already-tracked from prior rounds, or pre-existing/out-of-scope:

  • `workflow_state.rs` precedence divergence, `crud.rs`'s primary gate not gated on `has_genuine_failure` — both re-raised, both already evaluated in rounds 4–5 with reasoning now in the PR description (`workflow_state.rs` is a different PR's territory; the primary gate's fail-closed behavior is an intentional, different policy from the async re-validation sites).
  • TOCTOU between the two independent chain resolutions, uncached per-segment resolution — the same efficiency/race class flagged and explicitly deferred since round 2.
  • `log_validation_errors` tags `SchemaResolutionFailed` as `PlayErrorType::CompileError` — verified directly: this is pre-existing behavior (every error kind was already bucketed this way before this PR touched anything), not a regression this PR introduces. Added as a follow-up note.
  • No permanent-vs-transient distinction in `is_genuine_failure`, flat `Result` type doesn't force callers to handle the distinction, duplicated gating logic across 4 call sites — real architectural observations, but each is a design/refactor decision beyond this issue's scope (extends-chain field/relationship resolution in save-time validation), not a correctness bug in what this PR changed.
  • Corrupt schema node silently dropped from the merged set — traced to `resolve_field_owners`'s own pre-existing, documented design ("a missing mid-chain schema contributes nothing... deletion with a live chain is out of scope"), inherited unchanged by this PR.

Added a "Known follow-ups (non-blocking)" section to the PR description covering the 3 items worth remembering. No further code changes this round.

Final verification

  • `cargo check --workspace --all-targets` — clean
  • `cargo clippy -p nodespace-core --all-targets -- -D warnings -D clippy::unused-async` — clean
  • `cargo test -p nodespace-core --lib` — 1615/1615
  • `cargo test -p nodespace-core --test playbook_engine_integration_test` — 12/12
  • `cargo test -p nodespace-core --test playbook_invariant_integration_test` — 28/28
  • `bun run quality:fix` — clean
  • Pre-push gate — green on `cf76a1bb` (current HEAD)

Six review rounds, all real findings addressed (extends-chain gap for both fields and relationships, precedence, silent-degradation-to-error-surfacing, and two "ghost play" regressions introduced across the fix's own iterations, all caught and fixed before merge). Ready to merge.

🤖 Generated with Claude Code

@mstomar125
mstomar125 merged commit c0c8664 into main Sep 22, 2026
@mstomar125
mstomar125 deleted the issue-2819-validate-play-extends-chain branch September 22, 2026 13:45
malibio added a commit that referenced this pull request Sep 22, 2026
Round 8 found the failure I had asked it to look for: having swung from a
blanket walk to key-targeted helpers, the new risk was a MISSED id-bearing
key, and `trigger.property_key` was one. It is namespaced as
`<node_type>.<field>`, so its leading segment is a schema id. Rewriting
`node_type` beside it and not it left the pair jointly incoherent.

One correction to the review's severity. It predicted both invariant gates
would silently fail open, since the trigger index would register
`{issue_2, "issue.status"}` while real events carry `"issue_2.status"`.
Reproducing it showed better: upstream's #2762 rejects a mis-namespaced
property_key at SAVE time, with a diagnostic naming the exact correction. So
the install fails loudly rather than the gates failing open. Still a blocker —
the recipe cannot install into a workspace where `issue` is taken — but the
graph is never left holding two dead guards.

Read the authored node_type before mutating it: the namespace is compared
against the type the rule was written with, so rewriting node_type first
leaves nothing to match. Guarded on the namespace equalling that type,
mirroring `lifecycle::renamespace_property_key` — a key namespaced to some
other type is not this rename's business.

`rewrite_rule_ids`' doc now enumerates TriggerDefinition's five fields and
ActionDefinition's three, classifying each, the way the create/update helpers'
docs already do. Round 8's point stands: that doc's value is being an
auditable enumeration, and this one had argued its case instead of listing the
fields — which is how `property_key` passed unmentioned.

Rebased onto main first, as round 8 recommended, since upstream had moved
through four playbook commits. Three conflicted, and the resolutions were
genuinely three-way rather than mechanical:

- engine.rs: #2817 now ACTIVATES a play whose validation was inconclusive
  rather than disabling it. My side disabled and returned. Took upstream's —
  undoing a deliberate behavior change would have been the wrong call.
- validation.rs: #2826 added `resolve_relationships`, an effective-set
  resolver spanning the extends chain, which supersedes my
  `resolve_forward_segment` wholesale. Deleted mine; the dead-code warning
  confirmed nothing else used it.
- Mayank's #2796 fixed the forward-before-reverse precedence I had skipped as
  I6. My first resolution put reverse first, reintroducing it. Caught and
  reordered: forward from the effective set, reverse as fallback.

Final shape is upstream's effective forward set, Mayank's precedence, my
reverse branch. 94 validation tests pass across all three.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
malibio added a commit that referenced this pull request Sep 22, 2026
…or Settings (closes #2596) (#2777)

* Declare play as a core schema

`architecture/playbook-system.md` ("Built-in Node Types") specifies `play`
as an isCore schema registered at startup, but get_core_schemas() had no
entry -- the engine's query_nodes_by_type("play", "active") ran against an
undeclared type.

This is about declared identity, not rule correctness: validate_play_rules
(services/node_service/crud.rs) already parses every rule, compiles its CEL
conditions and runs the full save-time validation pipeline before a play
node is persisted, which is stricter than an `array` field could express.
Declaring the type is what makes it queryable and schema-validated for its
scalar properties, the same way `skill` is.

`rules` is typed `array` with no item_type deliberately: element shape lives
in playbook::types::RuleDefinition, and restating it here would be a second
source of truth that could drift from the parser.

Backend only -- `play` is NOT added to SIDENAV_CORE_TYPES; there is no GUI
surface for Plays yet, and a test pins that absence so a later GUI change is
deliberate rather than incidental.

A second test pins that neither `log` nor `playbook_log` is a graph type,
ahead of moving engine diagnostics to a log file.

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

* Move Play engine diagnostics out of the graph and into tracing

Play errors were written into the user's knowledge graph as `playbook_log`
nodes, with SHA-256 fingerprinting, dedup and occurrence counting behind
them. That was 765 lines of machinery serving one consumer: the
`nodespace playbook logs` CLI verb. Nothing branched on a log node, nothing
recovered from one, and all seven engine call sites discarded the result
(`let _ = ...`).

It was also actively wrong in three ways:

- A Play error is operational telemetry, not knowledge. The graph is for
  why a system was built, not for which rule failed to compile.
- Nothing excluded `playbook_log` from Play triggers, so the engine wrote
  into the substrate it watches, bounded only by MAX_CHAIN_DEPTH.
- It corrupts under sync. `localOnly` is per-property and these nodes have
  no schema, so nothing marks them local. The fingerprint deliberately
  excludes node ids and timestamps, so two devices logging the same failure
  produce the same fingerprint with independently-incremented `occurrences`
  -- a counter that is neither a sum nor a max, just whichever write landed
  last.

So the seven call sites become `warn!`/`info!` carrying the same fields, and
logging.rs is deleted outright. MAX_CHAIN_DEPTH moves to types.rs, where the
cycle-detection machinery it actually serves lives -- it was in logging.rs
only by accident of history. `log_validation_errors` survives its three
callers but loses the ordinal-disambiguation logic, which existed purely to
avoid fingerprint collisions.

`nodespace playbook logs` is removed rather than repointed: the daemon log
is already the general log, `tracing` already writes to it, and grep already
filters it.

Tests: the four dedup regression tests covered a bug that cannot recur
without fingerprints, so they go with the mechanism. The non-activation
property they also exercised is independently covered by
`reject_on_reactive_rule_bypassing_save_time_validation_is_not_activated_at_load`.
The seeded-play warning test is rewritten to capture tracing output rather
than query for a node -- verified to fail when the warning is suppressed, so
it pins the behavior rather than the mechanism.

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

* Add the Linear-style methodology recipe, and fix Play path validation

The recipe: `issue` (extends task, owns a points `estimate`), `cycle`
(start/end dates, duration_days, a tasks relationship mirroring project's),
the extended status and priority vocabularies, four Plays, and three narrow
seeded skills. Content only -- no sample instances, and nothing joins
seed_agent_nodes, because a methodology is opt-in and a workspace has at most
one.

Two corrections to the issue's spec, both forced by what the code actually
declares. Core task.status is open/in_progress/done/cancelled -- there is no
`todo` -- so backlog and triage map to `open`, not to a value that does not
exist; add_field_values would have rejected the mapping outright. And the
JSON key is `mapsTo`, not `maps_to`.

Writing an integration test that really installs the recipe (rather than
only asserting the shape of its JSON) immediately paid for itself: it caught
two pre-existing bugs in `validate_schema_path`, both of which made
save-time validation stricter than the engine that executes the rules.

1. Built-in structural edges were rejected. `has_child` and its three peers
   are legal between any two nodes and declared on no schema, so looking them
   up in `schema.relationships` never found them -- but GraphResolver walks
   them by name like any other segment. A condition over an issue's
   sub-issues was refused despite being executable. Both spellings are now
   accepted, and the walk stops there since these edges are untyped and name
   no schema to continue into.

2. Inherited and reverse relationship names were rejected. The walk consulted
   only the concrete type's own declarations, so `blocked_by` -- the reverse
   half of task.blocks, reaching `issue` through extends -- resolved as
   neither field nor relationship. Forward and reverse lookups now both walk
   the extends chain via resolve_type_chain, mirroring how rel_ops and
   GraphResolver already resolve either end of an edge.

Neither was reachable before: no shipped Play traversed a structural edge or
a reverse name, so the gap between what validation accepted and what the
engine could run had nothing to surface it.

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

* Generate the Linear recipe's CLI reference, and fix a no-op rollover

The recipe is typed Rust executed in-process by the desktop app. An external
agent has no access to that, so the same content is rendered as literal
`nodespace` verbs into references/linear-recipe.md, joining the existing
gen_skill_md region registry -- same marker splice, same --check/--write, same
skill:check gate. Generated rather than hand-written because drift here fails
silently in the worst way: an agent follows a stale doc, installs a schema
subtly different from the one the GUI installs, and the two workspaces diverge
with nothing to flag it.

Reading the generated output immediately caught a real bug the tests could not.
The rollover Play's add_relationship used `{trigger.node.id}` as its source --
the cycle that is ENDING -- so it re-added each unfinished task to the cycle it
was already in. Work never moved. Every structural check passed, because
`{trigger.node.id}` is a perfectly valid binding resolving to a real cycle;
nothing failed, it just did nothing.

The fix merges cycle-creation and rollover into one Play with two actions. The
successor's id is only reachable as `{actions[0].result.id}` -- nothing in the
binding context can name "the cycle starting tomorrow" -- so a separate
rollover Play has no way to address the node it is meant to move work into.
Running both on the end date also drops a cross-day dependency, where a
next-morning rollover would silently no-op if creation had not run.

Pinned by a test asserting the reassignment targets the created successor, and
the recipe is three Plays now rather than four.

Also: --check named a fixed pair of source files, which would have sent anyone
hitting recipe drift to the wrong place. It now reports the source_note of the
regions that actually went stale -- verified by drifting the recipe and reading
the message.

SKILL.md gains a pointer with the two conditions that matter: install only on
request, and stop rather than install over an existing issue/cycle.

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

* Add the recipe installer, with disclosed collision re-keying

`install_recipe` executes a recipe against a live NodeService and returns a
per-step report. It lives in core rather than the Tauri layer because the
collision logic belongs next to the recipe it protects, and because the
desktop app reaches core through the in-process gRPC daemon rather than
calling it directly -- so a core-side installer is reachable from the GUI, the
CLI and tests alike.

Collisions are re-keyed and disclosed, never resolved silently. A workspace
may already hold something called `cycle`; adopting it would be wrong, since a
schema sharing a name need not share a shape and the recipe's Plays would then
read fields that do not exist. Overwriting it would be worse. So a taken id
moves to the first free deterministic suffix and the report names both ids,
which is what lets the GUI say what landed where without a blocking dialog.

Re-keying rewrites later references within the same install, walking the JSON
rather than matching known key names -- a schema id appears as `schema_id`, as
a trigger's `node_type`, as a relationship `targetType`, and nested inside a
Play's rules, and missing one would leave a step pointing at exactly the
stranger's schema the re-key existed to avoid. Only exact string matches are
rewritten, so prose mentioning a cycle survives.

Tests cover the case that matters: a pre-existing unrelated `cycle` survives
untouched, with none of the recipe's fields written into it, while the
recipe's own cycle lands under a new id and the rollover Play follows the
rename.

One test assertion was wrong rather than the code -- a second install re-keys
five things, not two, because the three play nodes collide as well as the two
schemas. That is correct behavior; the assertion now states it.

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

* Expose methodology install over gRPC and Tauri

ListMethodologies and InstallMethodology on the node service, plus the two
Tauri commands over them. The desktop app proxies through the in-process gRPC
server rather than calling packages/core directly, so a core-side installer
needs an RPC to be reachable from the GUI -- and the same RPC is available to
the CLI later without duplicating anything.

One RPC rather than the client driving CreateSchema/UpdateSchema/CreateNode
itself: the steps are ordered, and a collision on any id has to re-key every
later reference to it. That logic belongs beside the recipe, not copied into
each client that wants to install one.

The picker carries no steps -- a client chooses by id and the daemon executes
-- so the step sequence never crosses the wire and cannot be edited in flight.

A partial install returns Ok with `success: false`, not a Status. By then the
install has really half-happened, and the report is the only record of how far
it got; a Status would discard exactly that at the moment it matters most.
Only transport and decode failures surface as errors.

The report's wire shape is now a contract pinned from both ends: core asserts
what it serializes (camelCase, outcome internally tagged on `kind`, with a
deliberately-provoked collision so the data-carrying variants are exercised
rather than just the happy one), and the Tauri layer asserts it decodes that
shape. A drift in either side's serde attributes would otherwise surface as a
decode error at install time, with the install already done and the report
lost.

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

* Offer methodology install from onboarding and Settings

Both consumers call `methodology-service`, not Tauri directly. The issue notes
onboarding will be reworked, so the execution path deliberately does not live
inside the wizard: a Settings install and a wizard install are the same call,
and the wizard can be rewritten around this without the install logic moving
with it.

The wizard step is its first non-binary one -- the others are act-or-skip,
this asks the user to choose. Nothing is preselected and Install stays
disabled until a choice is made, because picking a methodology for someone is
worse than asking. The step is dropped entirely when the backend offers
nothing, rather than shown with generic wording the way the skill step is:
there is no sensible generic phrasing for an empty choice.

A partial install resolves rather than throwing, so both consumers branch on
`report.success` rather than on reaching a catch. Treating a resolved promise
as done would report a half-finished install as a clean one.

Re-keying is stated plainly in the summary -- "cycle -> cycle__2 ... Your
existing types were left unchanged" -- rather than buried. A user whose own
`cycle` survived needs to know the new one is called something else, or they
will look for fields on the wrong type.

`listMethodologies` normalizes a non-array response to an empty list. Without
it, every existing wizard test would need to mock the new command: they fall
through to a catch-all `Promise.resolve()`, and `undefined.length` crashed the
step sequence. Degrading to "no recipes" is also the honest answer when the
backend gave us none.

Verified the 7 wizard tests fail without the step (6 of 7 -- the seventh
asserts the step is absent, so it correctly still passes), so they pin
behavior rather than mechanism.

Frontend suite: 258 files / 5231 tests, up from the 256 / 5214 baseline.

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

* Embed linear-recipe.md in the PTY session's skill copy

write_skill_md embeds each references/*.md individually, so a new reference
file is linked from SKILL.md but never written next to it until it is wired
in here. An external agent following the pointer would have found nothing.

Caught by write_skill_md_also_writes_the_references_tier, which enumerates the
references directory and asserts every file is both linked and written -- it
exists for exactly this omission.

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

* Keep SKILL.md's body under its token budget

SKILL.md is capped at ~5000 tokens by
skill_md_body_is_within_spec_size_recommendations, which exists to stop the
body absorbing detail that belongs in references/. main sits at 4995 -- five
tokens of headroom -- so the recipe pointer put it over at 5009.

Reclaimed the space where the body restates what its own examples already
show: the collections section's closing paragraph re-explained the mechanism
the three preceding commands demonstrate. Merged the Play and methodology
pointers under one heading while here, since both are one-line references to
the same tier.

Deliberately did not trim the deletion-safety or preflight sections. Those
carry consequences a reader needs in the body, not one file away.

`member_of` stays in that paragraph: every_seeded_skill_is_represented keys
the "Organization" seeded skill on exactly that term, so dropping it would
have silently orphaned a skill from its external-agent counterpart. The test
caught it; the phrase is load-bearing, not decorative.

Net 4990 tokens -- under the cap, and marginally leaner than before.

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

* Address review: make inherited relationships actually work

The review found four criticals, all install-clean and runtime-wrong. Chasing
the third to its root showed the problem was bigger than the recipe: inherited
relationships were broken end to end, and this recipe is simply the first
content to need one.

ADR-078 says an `issue` IS a `task`. Four places disagreed, each comparing a
concrete node type against a declared type with no chain awareness:

- `get_inbound_relationships` matched `target_type` exactly, so `task.blocks`
  was invisible from `issue` and `blocked_by` resolved to nothing.
- `create_relationship`'s declaration check (both the plain and tx paths)
  looked only at the node's own schema, so creating a `blocks` edge from an
  issue was REJECTED outright -- an issue could not have a blocker at all.
- The target-type check (both paths) rejected an `issue` target for a
  relationship declaring `target_type: "task"`.
- `graph_resolver`'s reverse-traversal narrowing filter kept only nodes whose
  type equalled the declarer's, dropping every subtype instance.

Fixed by resolving the extends chain at each. No regressions: 36 core test
binaries green, including the relationship and resolver suites these touch.

Two more bugs in the recipe itself, found while tracing:

- The CEL conditions used `.any(bare_field)`, which `playbook-system.md`
  documents but the engine does not implement. The working form is the
  comprehension `.exists(c, c.status ...)`, as `core_plays.rs` uses.
- `property_key` needs the namespaced `"issue.status"`; `compute_property_changes`
  emits `"{node_type}.{field}"`, so a bare `"status"` matched nothing.

The four criticals:

C1 -- rollover added the task to the successor without removing the old edge.
Only FORWARD cardinality is enforced on write, so a `many` forward side means
nothing rejects the second edge and the idempotency check, keyed on
(source, target, name), misses. Tasks accumulated one edge per cycle forever
and estimate sums double-counted. Now add-then-remove, in that order, so a
failure between the two leaves the task in both cycles rather than neither.

C2 -- `for_each` has no per-item filter, so rollover moves completed work too.
`ActionDefinition` carries only action_type/params/for_each and rule conditions
cannot see `item`, so this cannot be fixed by authoring. Fixed the CLAIMS
instead: the Play description and the "Working with Cycles" skill now say what
the engine does. The skill mattered more -- it is content agents retrieve and
act on.

C3 -- see the resolver work above.

C4 -- the generated CLI reference emitted unparseable shell: CEL string
literals carry bare single quotes inside a single-quoted `--params` argument.
Now POSIX-escaped, with a test that round-trips every bash block through a
shell splitter. Checked against the rendered artifact, not the generator,
because `--check` only proves doc and generator agree -- a broken pair stays
happily in sync.

Also: I1, `nodespace logs` now exists rather than being silently unticked. It
resolves the path itself, which is the point -- the interim `grep` guidance
named the desktop app's path and was wrong for a Homebrew install, exactly the
audience `references/cli.md` serves. I2, the doc promised a first cycle that
would never arrive; the guidance now says to create it. I3, a re-key now
reaches the seeded skills, which named schema ids in prose and would otherwise
point at the stranger's schema the re-key existed to avoid.

The test gap was the real finding. Every test in the PR passed with three
criticals live, because install-time assertions cannot see a rule that saves
and then misbehaves. The new execution suite runs the engine and inspects the
graph; it failed on its first run and drove every fix here.

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

* Actually apply the rollover fix, and close the gap that hid its absence

The previous commit claimed to fix C1 and did not. A scripted edit asserted on
five anchors in sequence; the fourth failed, Python raised before the write, and
every edit to linear.rs was discarded -- including the remove_relationship
action. I saw the AssertionError, fixed the anchor it named, and never checked
whether the earlier edits had landed.

A separate script DID succeed, so the seeded "Working with Cycles" skill shipped
asserting "added to the new cycle and removed from the old one, so a task
belongs to exactly one cycle" -- a false statement about a data invariant,
written into the user's graph, that an agent would act on. The commit message
and PR comment asserted the same thing.

Every edit here reads the file back and asserts the change is on disk.

The reason a commit claiming to fix the rollover passed the full gate is that
nothing executed the rollover. The execution suite covered the two validation
gates and stopped -- in precisely the place I had just changed. Adding
`rollover_moves_a_task_rather_than_leaving_it_in_both_cycles` immediately found
a SECOND defect in the same Play: `for_each: "node.tasks"` is condition syntax.
Action bindings know only `trigger.node.*`, `item.*` and `actions[N].*`, so the
iteration failed at runtime with `unknown binding root: 'node'`. Both for_each
paths now use the action-binding root.

N2: the C3 work missed a fifth site, and making `get_inbound_relationships`
subtype-aware is what activated it. `get_node_relationships` narrowed each
inbound group with `retain(|r| r.node_type == source_type)`, so `task.blocks`
correctly surfaced for an `issue` and then every issue on the far end was
dropped -- the viewer rendered a confident "blocks: 0" rather than a visibly
missing group. A wrong count reads as truth; an absent group reads as absent.
Now matched against each node's chain, memoized per node_type since a traversal
usually returns many nodes of one type.

N4: two stale claims survived the C2 correction, including `cycle.end_date`'s
field description -- persisted into the schema node and returned by
`schema get`, so it is graph content rather than a comment.

Also: the generated doc's closing summary was wrong three ways (two scheduled
Plays, four Plays, extensions on `task`); `rename_note` said "the text above"
while being appended to a subtree with no guaranteed order; and the shape test
still asserted the pre-fix `for_each` value, which would have shipped a red
suite. It now documents that it pins shape only, and points at the execution
test that pins behavior.

I4-I7 filed as #2792 rather than left recorded only in a PR thread.

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

* Add the rel_ops verdict cache the last message claimed, and gate the rollover test on its condition

Round 3 caught that "memoized per node_type" was true of graph_resolver.rs and
false of rel_ops.rs, which had no cache at all. `resolve_type_chain` is
resolved live and issues a parent-map query per call, so the narrowing cost one
round trip per inbound edge per group where the previous exact-match `retain`
cost none. Same pattern as the round-2 miss in milder form: the message
described what I meant across both sites rather than what I wrote at each.

The cache is hoisted above the group loop so it amortizes across groups, not
just within one.

While adding it I nearly shipped a second unsupported claim. I wrote a
two-group test asserting it pinned the cache key, then checked by replacing
`source_type` in the key with a constant -- and it stayed green, as did the
single-group test. `collect_related` scopes each group's candidates by
relationship name before narrowing, so a `tasks` edge never reaches the
`blocks` group and there is nothing for a wrong key to confuse. The
`source_type` component is defensive, not load-bearing. Both the cache comment
and the test's doc now say that rather than implying coverage neither has.

Also closes the condition gap round 3 named: `run_rollover` executed actions
without ever evaluating `end_date == today()`, so a condition that was broken,
malformed, or resolved to an empty set would have been invisible -- the
silent-no-op mode that hid C3. It now evaluates conditions the way
`rule_processor_loop` does, and a negative test proves a cycle that is not
ending today is left alone, which is what makes the positive case mean
something.

Execution suite: 8 tests. Core: 36 binaries, 0 failures.

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

* Correct the last stale rollover claim, in the recipe doc's intro

Found by grepping every claim in the previous commit message against the code
rather than asserting it. The hand-written intro of references/linear-recipe.md
still described "Cycles that roll unfinished work forward" -- the same false
promise corrected in the Play description, the seeded skill, the schema field
description and the doc's closing summary, surviving in the one place none of
those greps had reached.

Rollover moves every task in the ending cycle, completed ones included, because
`for_each` has no per-item filter. Three rounds of review have now corrected
five separate statements of the opposite; this was the last.

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

* Fix four latent defects in methodology install and Play path validation (#2796)

* Fix four latent defects in methodology install and Play path validation

Structured `MarkdownError::AlreadyExists { id, message }` replaces
substring-matching "already exists" in install.rs's is_already_exists,
which would misfire if any other schema rejection (e.g. a duplicate
enum value from add_field_values) ever grew the same phrase.

create_node_resolving_collisions now attempts the create directly
instead of checking existence first, mirroring create_schema_resolving_collisions
directly above it: the write path is the authority, and a rejection is
interpreted by reading back the id, not assumed from a stale pre-write
check. A failed read is reported, never treated as "not found".

validate_schema_path now resolves a segment's forward relationship
before its reverse spelling, matching rel_ops::resolve_relationship_name's
documented forward-first precedence, so validation and the runtime
resolver never disagree on a same-spelled forward/reverse pair.
resolve_reverse_segment takes the same schema_cache resolve_forward_segment
already does, so a schema either check touches is fetched once per path
walk instead of twice.

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

* Address review: fix overclaiming doc comment and collapse duplicate error match

resolve_reverse_segment's doc comment claimed warming schema_cache meant
"no second fetch needed" for its own work, but the function never reads
what it cached — get_inbound_relationships is always a fresh, uncached
call. Corrected the comment to describe what the cache warming actually
buys (the cheap single-schema lookup other callers in the same walk make
for the same scope), not the expensive part it doesn't touch.

export_markdown hand-rolled its own inline MarkdownError match instead of
routing through the markdown_error_to_status helper its two sibling
handlers already use. Collapsed it to match them, removing the duplicate
arm list the new AlreadyExists variant would otherwise need updating in
two places.

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

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>

* Fix a timezone flake and correct a wrong claim about the cache key

Round 4 found two blockers. Both were mine.

The rollover test built `end_date` from `Utc::now()` while CEL's `today()`
uses `Local::now()`. The mismatch was inert until the previous commit added
the condition gate, which turned it into a real failure -- reproduced under
TZ=Pacific/Auckland, now passing there and under Pacific/Honolulu.

The second is worse, because I asserted it after testing for it. I claimed the
`source_type` half of the verdict cache key was defensive rather than
load-bearing, on the grounds that `collect_related` already scopes each group's
candidates. But it scopes by relationship NAME, not by declarer. Two schemas
may declare the same forward name toward the same target, so both groups
receive both declarers' nodes and only the per-group narrowing separates them.
`graph_resolver.rs` documents this as "live, not hypothetical: `tasks` is
declared both on `project` and on `person`" -- a comment I had already read in
this session.

My test picked `tasks`/`blocks`: different names, disjoint candidate sets, so
the key could never collide. I degraded the key, saw the test stay green, and
generalized from a case that could not have failed.

The code was always correct. What was wrong were two comments telling the next
maintainer the key component was optional -- an invitation to reintroduce a
silent correctness bug. Both now say it is load-bearing and why.

The test is re-pointed at same-named declarers, and there are three rather than
two: `project`, `person`, and this recipe's own `cycle`. That this PR ADDS a
third declarer of `tasks` is precisely why the key matters more after it than
before. Verified the corrected test fails when the key is degraded, with the
wrong-node symptom the reviewer reproduced.

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

* Address round 5: pin the reverse-segment branch, rewrite schema params on re-key

I1 — `resolve_reverse_segment` had no unit-level coverage: disabling it left
all 83 tests in its own module green, because the only thing pinning it was
the Linear recipe's integration suite. The sibling precedence test does not
help, since it asserts the FORWARD name wins and passes either way. Added a
unit test routed through an `extends` chain, which is the shape the recipe
needs and the one that was silently rejected before the chain walk. Verified:
disabling the branch now fails its own module (83 pass / 1 fail).

I3 — `create_schema_resolving_collisions` passed `step.params` raw while the
three sibling loops applied `rewrite_schema_ids`. Schema params carry ids too
(`extends` names a parent, a relationship's `targetType` names a target), so a
recipe whose second schema extends its first would silently extend whatever
stranger's schema squatted the id. The suffix-retry now starts from the
rewritten params as well, or the rewrite would be undone on retry.

My first test for I3 was worthless and I nearly shipped it. It called
`rewrite_schema_ids` directly, so it passed — and still passed when I reverted
the fix, because it exercised the helper rather than the call site I changed.
That is the round-4 mistake exactly: a test that cannot fail for the reason it
claims to cover. Replaced with a two-schema recipe whose second `extends` its
first, against a squatter that forces a re-key. Reverting the fix now fails
with `left: "widget"` / `right: "widget_2"` — the derived schema extending the
stranger, which is the corruption this guards.

I2 skipped and filed as #2843: `today()` uses `Local::now()` while
`days_since`/`days_until` use `Utc::now()`, so two conditions that read as
equivalent disagree by up to a day. Real, but pre-existing, and no shipped Play
mixes them. Unifying them needs a deliberate local-vs-UTC decision with
multi-device implications — not something to settle inside a methodology PR.

Nits skipped: all in 87afc00 (`AlreadyExists.id` unused, the
INVALID_ARGUMENT→ALREADY_EXISTS wire change, unreachable `CreationFailed`),
all assessed safe by the reviewer, none mine to churn.

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

* Fix a regression my own re-key fix introduced: rewrite ids, not vocabulary

Round 6 found that the previous commit broke installs that worked before it.
Applying `rewrite_schema_ids` — a blanket value walk — to a `create_schema`
payload was unsound. Its own doc says it rewrites every exact string match,
which is correct for the Play, vocabulary and skill payloads, whose ids all
sit in value position. A schema payload is a different shape: `fields[].name`,
`friendlyName`, a relationship's `name` and `reverseName`, enum values and
`title_template` tokens are user-authored vocabulary, and they share one
namespace of bare lowercase identifiers with schema ids. `cycle`, `issue` and
`status` are each plausible as a schema id AND as a field name.

So a recipe whose second schema has a field named `cycle`, installed where an
earlier step re-keyed to `cycle_2`, had its FIELD renamed behind the author's
back. Reproduced: the install now fails with "title_template references
undefined field 'cycle'" where it previously succeeded. That is the loud case
— a recipe without a template gets the silent one, storing a field under a
name it never wrote, which is precisely the corruption re-keying exists to
prevent. My fix for silent corruption introduced silent corruption.

Replaced with `rewrite_schema_step_ids`, which touches only `extends` and each
relationship's `targetType`. The keys were enumerated from CreateSchemaParams'
six fields rather than guessed, and the reasoning for each is recorded, since
guessing is how the first version went wrong. `EdgeField.target_type` is
called out as deliberately unhandled: it has no consumer anywhere in core, so
it cannot hold a live reference today.

`base_name` reads `step.params["name"]` again. Taking it from the rewritten
payload meant a schema whose display name happened to equal a rename key built
its suffix ladder on a substituted string.

Regression test written before the fix and confirmed failing without it.

Also removed `a_schema_steps_own_params_follow_an_earlier_re_key`: it tested
the helper rather than the call site (it passed with the fix reverted, which
the last commit message admitted while shipping it anyway), and under this
change it would pin the blanket-walk behavior being removed.

And corrected the I1 test's docstring. It claimed to pin the `extends` walk in
`resolve_reverse_segment`; I disabled that walk and all 84 tests stayed green,
because `get_inbound_relationships` already expands ancestors internally. The
test pins the reverse branch existing, which is real and was uncovered — just
not what the docstring said. The duplicated ancestor expansion between the two
is noted as worth collapsing.

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

* Sweep every re-key call site instead of fixing one more instance

Rounds 5, 6 and 7 each found the same defect at a different caller of
`rewrite_schema_ids`. Round 7's note is the right diagnosis: the productive
move is not another targeted fix but a sweep of all three callers, deciding
per payload whether a blanket value walk is sound.

It is sound for none of them, so there are now three key-targeted helpers and
the blanket walk is deleted. It became dead code once the last caller moved,
which is the structural confirmation the sweep was complete rather than my
assertion that it was.

The reported instance: `field_value_extensions` passes an UpdateSchemaParams
payload, which mixes references and vocabulary exactly as CreateSchemaParams
does. `schema_id`, `extends` and `add_relationships[].targetType` are ids;
`add_field_values[].field`, its `values[].value`, `add_fields[].name`,
`remove_fields`, `rename_fields` and both templates are user vocabulary.
Rewriting the field name retargets the extension at a field that does not
exist — reproduced as "Field 'cycle_2' not found in schema 'report'" — and
rewriting an enum value writes vocabulary the recipe never authored, silently.

The third caller, Play properties, round 7 assessed as safe. I changed it
anyway. The shipped rule names (`estimate`, `tasks`,
`create-successor-and-roll-over`) happen not to collide, but a rule `name` is
free-form and a CEL condition is a string; either could spell a schema id.
Judging a payload safe by reading the current recipe rather than the payload's
shape is what made me wrong in rounds 6 and 7, so none of the three now
depends on what the content happens to contain.

`rewrite_play_step_ids` covers `_seed.default_rules` as well as the live
rules. A mirror left pointing at the stranger's schema would silently undo the
re-key the moment someone reset the Play.

Unit tests retargeted at the three helpers and assert both directions: ids
followed, vocabulary untouched — including the `relationship_type` action
param, which is a relationship name rather than a schema id. Each new
integration test verified to fail when its own fix is reverted.

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

* Rewrite a trigger's property_key namespace with its node_type

Round 8 found the failure I had asked it to look for: having swung from a
blanket walk to key-targeted helpers, the new risk was a MISSED id-bearing
key, and `trigger.property_key` was one. It is namespaced as
`<node_type>.<field>`, so its leading segment is a schema id. Rewriting
`node_type` beside it and not it left the pair jointly incoherent.

One correction to the review's severity. It predicted both invariant gates
would silently fail open, since the trigger index would register
`{issue_2, "issue.status"}` while real events carry `"issue_2.status"`.
Reproducing it showed better: upstream's #2762 rejects a mis-namespaced
property_key at SAVE time, with a diagnostic naming the exact correction. So
the install fails loudly rather than the gates failing open. Still a blocker —
the recipe cannot install into a workspace where `issue` is taken — but the
graph is never left holding two dead guards.

Read the authored node_type before mutating it: the namespace is compared
against the type the rule was written with, so rewriting node_type first
leaves nothing to match. Guarded on the namespace equalling that type,
mirroring `lifecycle::renamespace_property_key` — a key namespaced to some
other type is not this rename's business.

`rewrite_rule_ids`' doc now enumerates TriggerDefinition's five fields and
ActionDefinition's three, classifying each, the way the create/update helpers'
docs already do. Round 8's point stands: that doc's value is being an
auditable enumeration, and this one had argued its case instead of listing the
fields — which is how `property_key` passed unmentioned.

Rebased onto main first, as round 8 recommended, since upstream had moved
through four playbook commits. Three conflicted, and the resolutions were
genuinely three-way rather than mechanical:

- engine.rs: #2817 now ACTIVATES a play whose validation was inconclusive
  rather than disabling it. My side disabled and returned. Took upstream's —
  undoing a deliberate behavior change would have been the wrong call.
- validation.rs: #2826 added `resolve_relationships`, an effective-set
  resolver spanning the extends chain, which supersedes my
  `resolve_forward_segment` wholesale. Deleted mine; the dead-code warning
  confirmed nothing else used it.
- Mayank's #2796 fixed the forward-before-reverse precedence I had skipped as
  I6. My first resolution put reverse first, reintroducing it. Caught and
  reordered: forward from the effective set, reverse as fallback.

Final shape is upstream's effective forward set, Mayank's precedence, my
reverse branch. 94 validation tests pass across all three.

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

* Address round 8's nits: correct a stale claim, share the targetType loop

The `create_schema` helper's doc still said a blanket value walk "is safe for
the Play, vocabulary and skill payloads". That was true when written and is
false now — this PR's own conclusion is that no recipe payload tolerates one,
which is why all three helpers are key-targeted. A leftover like that is what
invites the next maintainer to re-widen a helper.

The `targetType` loop was byte-identical between the create and update
helpers, differing only in whether the array is spelled `relationships` or
`add_relationships`. Extracted. Two near-identical copies is precisely how a
fix reaches one and not the other, which is the defect shape rounds 5, 6, 7
and 8 each found at a different call site.

Skipped, having checked rather than assumed: round 8's request to enumerate
TriggerDefinition/ActionDefinition in the play helper's doc, and to assert
trigger-key consistency, were both already done in the previous commit. The
`cycle_2` vs `cycle__2` nit is left alone deliberately — the rename map is
opaque to these helpers, so matching the production suffix format would imply
they know it, and they should not.

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

* Address round 9's nits: fix a dangling doc link, record a reachability check

`resolve_reverse_segment`'s doc still linked `resolve_forward_segment`, which
this branch's rebase deleted once upstream's `resolve_relationships` superseded
it. A dangling intra-doc link that `cargo doc` warns on; verified gone, with
only two pre-existing warnings left in files this PR does not touch.

`rewrite_rule_ids` early-returns when a trigger's `node_type` is absent from
the rename map, so a trigger carrying a `property_key` but no `node_type`
never reaches the rewrite. Round 9 checked and found it not a live defect. Now
says so in one comment, because "unreachable by construction" and "overlooked"
look identical to the next reader, and this PR has spent eight rounds on the
difference.

Not addressed: round 9's note that `e9eb3c3d`'s message understates its own
engine.rs resolution. It is accurate — I wrote "discarded my side entirely and
took upstream's", but `log_validation_errors` survives at all three sites,
retargeted from graph log nodes to tracing. The code is right and the message
describes it wrongly, which is the same class of error as the "memoized" claim
in round 3. Correcting it means rewriting a message on a 20-commit branch that
was just force-pushed, and a second force-push is more risk than the
inaccuracy carries. Corrected in the PR thread instead, where a reader of this
PR will actually look.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Mayank <[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.

validate_play rejects a legitimate Play condition referencing an inherited (extends-chain) field as BrokenPath

1 participant