Skip to content

Fix four latent defects in methodology install and Play path validation - #2796

Merged
mstomar125 merged 2 commits into
issue-2596-methodology-recipesfrom
issue-2792-methodology-play-latent-defects
Sep 22, 2026
Merged

mstomar125 merged 2 commits into
issue-2596-methodology-recipesfrom
issue-2792-methodology-play-latent-defects

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Fixes four latent defects filed as #2792, found during code review of #2777 and deliberately skipped there as unreachable today. Stacked on #2777 (issue-2596-methodology-recipes) since that PR is what introduces the affected files — this PR targets that branch, not main.

  • is_already_exists matched on error-message text. packages/core/src/methodology/install.rs's collision detection decided "this id is taken" by substring-matching "already exists" in the error's Display output — fragile if any other schema error ever grows that phrase (e.g. a reworded add_field_values duplicate-value rejection). Added MarkdownError::AlreadyExists { id, message }, a structured variant the installer matches on instead. handle_create_schema's existing schema-collision rejection now constructs it directly.
  • create_node_resolving_collisions had a TOCTOU and swallowed read errors. It checked get_node for existence, then created — racy, and a transient read error was silently treated as "does not exist." Rewritten to mirror create_schema_resolving_collisions directly above it: the create is attempted first, and a rejection is interpreted by reading back the id afterward (occupied → real collision, retry the next suffix; free → a genuine failure, report it immediately rather than burning through every suffix attempt on the same underlying error). A failure of that follow-up read is itself reported, never treated as "no collision."
  • validate_schema_path checked reverse-relationship-name before forward. This inverted rel_ops::resolve_relationship_name's documented forward-first precedence, so validation could accept (or route) a path differently than the runtime resolver that actually walks it. Swapped the order so validation agrees with runtime resolution. Added test_forward_relationship_wins_over_colliding_reverse_name, which pins the precedence with a deliberately colliding forward/reverse name pair — verified it fails against the old reverse-first order and passes against the fix.
  • resolve_reverse_segment/resolve_forward_segment had no shared cache. resolve_reverse_segment didn't even take the schema_cache parameter resolve_forward_segment already does. Threaded it through, so a schema either check touches during a path walk is fetched once instead of twice.

Test plan

  • cargo test -p nodespace-core --lib — 1602 passed
  • cargo test -p nodespace-core --test methodology_linear_install_test — 13 passed, including installing_twice_re_keys_rather_than_failing_or_overwriting, which exercises the rewritten node-collision path end to end (every schema and play re-keyed on a second install)
  • cargo test -p nodespace-core --lib playbook::validation — 83 passed, including the new precedence test
  • cargo clippy -p nodespace-core -p nodespace-daemon --tests -- -D warnings — clean
  • Manually verified the new precedence test fails under the pre-fix (reverse-first) ordering and passes under the fix, confirming it actually pins the behavior
  • Pre-push gate (bun run test:all + cargo build --bin nodespaced + e2e) — green

🤖 Generated with Claude Code

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]>
…rror 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]>
}
Err(e) if !is_already_exists(&e.to_string()) => {
Err(MarkdownError::AlreadyExists { .. }) => {}
Err(e) => {

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.

Schema-side TOCTOU fix is incomplete: a genuine collision under this exact function's own concurrency scenario still hard-fails instead of retrying.

create_schema_resolving_collisions only treats the structured MarkdownError::AlreadyExists variant as "collision, retry next suffix" (here, and again at the Err(MarkdownError::AlreadyExists { .. }) => continue arm in the suffix loop below). But AlreadyExists is produced only by handle_create_schema's pre-write existence check (schema/mod.rs around line 1180, get_schema_node) — a check-then-create pattern that is not atomic with the actual transactional insert further down (schema/mod.rs ~1248-1293). Any error surfacing from that insert (e.g. a raced duplicate id) falls through schema/mod.rs's own catch-all at the transaction's map_err (other => MarkdownError::internal_error(...), ~line 1289) — never AlreadyExists, since NodeServiceError (the transaction's error type) has no structured "already exists" variant to preserve that signal through the transaction boundary.

So the exact race this function's own doc comment cites as its rationale ("two installs could both see an id as free and both proceed") still produces StepOutcome::Failed with a raw internal-error message here — instead of the graceful suffix-retry that create_node_resolving_collisions (this same PR, just below) was specifically hardened to provide for the identical scenario on the node side. The schema half of this PR's TOCTOU fix was never actually applied.

Root cause: NodeServiceError (packages/core/src/services/error.rs) has no AlreadyExists/DuplicateId variant analogous to the new MarkdownError::AlreadyExists — that gap is what forces create_node_resolving_collisions's diagnostic-read workaround too, and it's why this function can't apply the same instead of a follow-up read: there's no structured signal from the transaction layer to match on at all.

// Try the next suffix.
Ok(Some(_)) => continue,
// `id` is free; the create failed for a real reason.
Ok(None) => {

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.

Residual race: a genuine collision can still be misreported as a hard failure.

The diagnostic get_node(&id) read here is not atomic with the create_node call that just failed above. Under the exact concurrent-install scenario this function's doc comment cites as its rationale ("two installs could both see an id as free and both proceed"): writer A's create commits first; writer B's create fails on the same id, but if B's immediate get_node(&id) read doesn't yet observe A's just-committed write (ordinary read-after-write visibility timing), B concludes "id is free, so this was a real fault" and returns StepOutcome::Failed with B's raw (collision-shaped, but now misleading) create error — aborting the whole recipe install — instead of retrying at {preferred_id}__2 the way the function is designed to. The window between the failed create and the confirmatory read is narrower than the pre-PR TOCTOU, but it isn't closed.

Err(create_err) => match node_service.get_node(&id).await {
// `id` is now occupied — the create lost a real collision.
// Try the next suffix.
Ok(Some(_)) => continue,

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.

Any create failure gets treated as "collision, retry" whenever id happens to already be occupied — even when the failure is unrelated to the id.

create_node's error type (NodeServiceError) carries no structured "already exists" signal, so this code infers a collision purely from "something is now at id", not from why the create actually failed. Concrete repro: a methodology install is retried after a prior partial run already created the node at preferred_id (install is documented as non-atomic/retryable). On retry, create_node fails for a genuine, unrelated reason (a validation or hierarchy-violation error in content/properties that has nothing to do with the id). get_node(&id) sees the id occupied (from the earlier run) and this arm silently discards the real error, moving on to preferred_id__2 instead of surfacing the actionable failure. If the same content-based error recurs at every suffix id (or those ids are also already occupied from an earlier partial run), the function exhausts MAX_SUFFIX_ATTEMPTS and reports the generic "...and every suffixed variant are already taken" message instead of the real, actionable validation error — a materially worse diagnostic than what a direct failure report would have given.

MarkdownError::NotFound(m) => write!(f, "not found: {m}"),
MarkdownError::CreationFailed(m) => write!(f, "node creation failed: {m}"),
MarkdownError::Internal(m) => write!(f, "{m}"),
MarkdownError::AlreadyExists { message, .. } => write!(f, "{message}"),

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.

Text-contract change: the AlreadyExists message silently drops the "invalid params: " prefix the identical schema-already-exists message carried pre-PR.

Before this PR, handle_create_schema's existing-schema rejection went through MarkdownError::invalid_params(...), whose Display is write!(f, "invalid params: {m}"). The new AlreadyExists variant's Display (this line) is just write!(f, "{message}") — no prefix. Since this file's own doc comment says "The Display text reaches the model verbatim as a tool result" (line 14), this is a real, if narrow, behavior change to what the agent/gRPC client sees as the error text for this case. Worth an explicit call-out even though nothing in this PR's own tests depends on the exact prefix.

/// grows the same phrase. `message` carries the full, agent-facing
/// explanation (e.g. the existing schema's rendered definition); `id` is
/// the exact, structured signal.
AlreadyExists { id: String, message: String },

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.

The id field is constructed but never read by any consumer in this diff (or anywhere in the repo).

schema/mod.rs passes schema_id.clone() as id when constructing this error, but every match site discards it: both collision-retry arms in install.rs match Err(MarkdownError::AlreadyExists { .. }), and both Status-mapping sites in node_service.rs destructure { message, .. }. A repo-wide grep for AlreadyExists confirms no site anywhere reads this field (contrast with the pre-existing, unrelated OpsError::AlreadyExists { id } used for collections, whose id is threaded into its Status::already_exists(format!("Already exists: {}", id)) mapping at this file's node_service.rs:2634 — this new variant's id has no equivalent consumer). Either wire id into the Display/Status mapping the way the collection variant does, or drop it until a real consumer needs it — as written it's dead data that every match site has to explicitly discard.

/// inheritance (ADR-078). Matching only the concrete type would refuse
/// `node.blocked_by` on an issue while allowing it on a task.
///
/// Takes the same `schema_cache` as [`resolve_forward_segment`], but this

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.

Altitude: "forward wins over reverse" is enforced only by two hand-mirrored implementations agreeing in prose, not by shared code — which is literally how this PR's own precedence bug got introduced.

resolve_forward_segment/resolve_reverse_segment here are an explicitly-documented hand-mirror of crate::ops::rel_ops::resolve_relationship_name's forward-then-reverse precedence (this doc block: "Mirrors the reverse half of rel_ops::resolve_relationship_name"). The precedence itself — forward checked before reverse — is asserted independently in each implementation's call order/comments, with nothing structural preventing them from drifting apart again the way they did in PR #2777 (the bug this PR fixes). A shared precedence-decision helper (or a single resolver both the validator and the runtime engine call) would make "forward wins" a property of the code's structure instead of two comments agreeing with each other.

},
Err(e) => StepOutcome::Failed {
message: e.to_string(),
match node_service.create_node(node).await {

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.

Efficiency regression for collision-heavy retries: every colliding suffix now pays for a doomed write attempt (with lock contention) plus a follow-up read, instead of the old single cheap read.

Old flow per iteration: one get_node read, and create_node only if that read found the id free — a colliding iteration cost exactly one cheap SELECT. New flow: create_node is attempted unconditionally, and only on failure does a get_node follow-up run to disambiguate. create_node is not cheap to fail: it runs node-type validation/defaulting, acquires the store's single writer lock, and only then fails on the id PRIMARY KEY constraint — contending with concurrent writers even on a doomed attempt. So a colliding suffix now costs one expensive failed write (with lock contention) plus one read, versus the old code's single read — up to MAX_SUFFIX_ATTEMPTS times. This matters most for realistic idempotent-reinstall scenarios (re-running methodology install against an already-partially-installed set of nodes), where many suffixes are already taken. (The no-collision common case is cheaper than before, so this is a collision-heavy-path regression specifically, not a blanket one.)


/// Create a node under `preferred_id`, re-keying if that id is taken.
///
/// Mirrors `create_schema_resolving_collisions` above: the create is

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.

Reuse: two independently hand-rolled retry/suffix loops with the same shape could be one generic helper.

This doc comment itself states this function "Mirrors create_schema_resolving_collisions above" — confirming the duplication between the two is deliberate/known. Both functions: loop up to MAX_SUFFIX_ATTEMPTS, attempt a create, classify the failure as collision-vs-real-fault, continue or return StepOutcome::Failed, and emit an "all suffixes taken" StepOutcome::Failed after the loop. A shared resolve_collisions_with_retry<F>(max_attempts, make_id, attempt: F, is_collision: ...) -> StepOutcome generic over the create call and the id-generation/collision-check strategy would let both call sites shrink to a closure each — and would be the natural place to fix the schema-side gap noted on the create_schema_resolving_collisions match arms above, since a shared collision-check strategy could be corrected once instead of per-caller. (Non-trivial in Rust given the two loops' differing id-mutation and collision-detection strategies — flagging for the author's judgment, not a drop-in one-liner.)

@mstomar125
mstomar125 merged commit 87afc00 into issue-2596-methodology-recipes Sep 22, 2026
@mstomar125
mstomar125 deleted the issue-2792-methodology-play-latent-defects branch September 22, 2026 08:13
.unwrap_or_else(|_| vec![node_type.to_string()]);

for scope in chain {
ensure_schema_cached(&scope, node_service, schema_cache).await;

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.

This cache-priming call doesn't reduce this function's own bottleneck — and the updated doc comment above now says so directly. The doc block just above (lines 598-606) already concedes: "this function never reads it back: the inbound-relationship data below always comes from a fresh get_inbound_relationships call, which is not cache-backed... the per-scope get_inbound_relationships cost this function actually incurs is untouched by it." That's an accurate description of the code, but it's worth flagging that the code itself is unchanged — only the comment was corrected to stop overclaiming. The doc's remaining justification ("warming the cache here still isn't wasted... a cache hit for the other [check]") only pays off if resolve_reverse_segment ever runs before resolve_forward_segment for a given segment. Given validate_schema_path's forward-first ordering, forward always runs first and, when it returns None (the only way execution reaches this function), it has by construction already walked and cached every scope in the identical chain — so under the code's actual current call order, this ensure_schema_cached call is always a redundant cache hit, and the theoretical benefit the doc still cites doesn't materialize today. The real, uncached cost (get_inbound_relationships/resolve_type_chain, both refetched fresh on every call for every segment) remains the actual bottleneck.


for scope in chain {
ensure_schema_cached(&scope, node_service, schema_cache).await;
let Ok(inbound) = node_service.get_inbound_relationships(&scope).await else {

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.

Silent failure swallow with no logging, inconsistent with the log-on-failure call two lines above. ensure_schema_cached (line 619) logs at debug! when its own fetch fails before caching None. This get_inbound_relationships failure — arguably the more consequential one, since it's what actually drives whether a reverse-name match is found — is swallowed via else { continue; } with zero logging. A transient error here (lock contention, timeout) makes an otherwise-valid reverse path segment fall through to a generic BrokenPath validation error with no breadcrumb anywhere explaining why, making this specific failure mode harder to diagnose than the schema-fetch failure right next to it.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Additional findings (can't be anchored inline — outside this diff's changed files)

1. packages/core/src/services/node_service/hierarchy.rs:733-740 (unchanged by this PR) does the exact same fragile substring-parsing pattern this PR eliminated for AlreadyExists. move_children_to_parent's error mapping does msg.strip_prefix("VERSION_CONFLICT: node '") to recover a node id from a raw anyhow! string the store layer raises, and even then can't recover real version numbers (hardcodes NodeServiceError::version_conflict(node_id, 0, 0)). Same bug class this PR just fixed for schema-already-exists, left unaddressed for version conflicts — worth a follow-up issue applying the same "structured variant instead of string-matching" treatment here.

2. packages/desktop-app/src-tauri/src/commands/nodes.rs:160's status_to_command_error hardcodes tonic::Code::AlreadyExists => "COLLECTION_EXISTS". That mapping predates this PR and was built for OpsError::AlreadyExists (collection-name collisions). This PR adds a second, semantically unrelated producer of the same gRPC code — MarkdownError::AlreadyExists from schema creation (packages/daemon/src/services/node_service.rs, markdown_error_to_status). Currently dormant (no desktop-app Tauri command calls create_schema today), but if one ever is wired up, a "schema already exists" rejection would be mislabeled as a collection conflict and likely trigger the wrong UI (a collection-conflict modal instead of a schema one). Worth a code comment or a distinguishing metadata header now, before this becomes reachable and silently wrong.

3. packages/core/src/services/error.rs's NodeServiceError has no structured AlreadyExists/DuplicateId variant analogous to the new MarkdownError::AlreadyExists. This is the root cause behind the two create_node_resolving_collisions / create_schema_resolving_collisions findings on the install.rs lines above — see inline comments there. A NodeServiceError::AlreadyExists { id }, surfaced from a structured DatabaseError::UniqueViolation at the SQLite layer, would let both collision-retry paths match an exact variant instead of diagnostic reads or (for the schema side) having no fallback at all.


Note: this PR received a follow-up commit (6d2aa2af, "Address review: fix overclaiming doc comment and collapse duplicate error mapping") partway through this review. That commit already fixed the node_service.rs match-arm duplication and corrected the resolve_reverse_segment doc comment this review would otherwise have flagged — both are reflected (or omitted) accordingly in the comments above and this summary.

malibio pushed a commit that referenced this pull request Sep 22, 2026
…on (#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]>
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.

1 participant