Skip to content

Seed a core Play that completes a parent task when all its children are done (closes #2636) - #2752

Merged
malibio merged 4 commits into
mainfrom
issue-2636-parent-task-completion-play
Sep 18, 2026
Merged

malibio merged 4 commits into
mainfrom
issue-2636-parent-task-completion-play

Conversation

@malibio

@malibio malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

Implements the parent-task completion rollup from ADR-079: when every has_child child of a task reaches a terminal status, the parent is set to done.

The Play

Seeded unconditionally as a user-modifiable play node carrying _seed.default_rules (ADR-060 §8), so it can be inspected, edited, disabled or reset. Reconciled per id, so a user's edits survive startup and a Play added in a later release still reaches an existing database. Its node id is stable and hardcoded — ADR-060 §5 keys cross-Play rule ordering on it.

Semantics, each recorded in ADR-079 and covered by a test:

  • cancelled counts as terminal alongside done. The rollup asks whether work remains under the parent, not whether everything succeeded; excluding it would strand a parent whose last remaining child was abandoned. The parent is always set to done, never cancelled — propagating cancellation upward would assert an intent the Play has no basis to claim.
  • A childless task never auto-completes, guaranteed by the engine's empty-collection-is-false rule (a deliberate departure from vacuous truth) rather than by a count guard.
  • Completion cascades up the ancestor spine. The Play's own write is itself a task status change, re-firing the rule with the parent now in the child position. Accepted limitation: a rollup climbing more than ~10 ancestors hits the chain-depth cap, which disables the Play until reset. Documented in ADR-079 §4 as a deliberate trade against abandoning the idiomatic chaining model.
  • Reactive, not invariant — ADR-060 §2 restricts invariants to "non-chaining, depth 1", which this violates by construction.

Four bugs found while building it

Each has a regression test that I verified fails when its fix is reverted.

  1. maps_to was never applied to nodes reached by traversal. enrich_context built related nodes with node_to_cel_value, so a base-scoped Play comparing a subtype child's extended enum value never matched — a silent false, no error. This is item 4 of Cleanup deferred from ADR-078 extends implementation (#2598) #2747, triaged there as "not a known-live correctness bug"; it was live. scoped_node_value is now shared rather than reimplemented, per ADR-078's one-shared-resolution-function rule. Items 1, 2, 3 and 5 of Cleanup deferred from ADR-078 extends implementation (#2598) #2747 remain open.
  2. Play path validation rejected built-in relationships. has_child/child_of have no SchemaRelationship behind them, so validation refused paths the resolver walks perfectly well. This blocked seeding outright.
  3. A related node's core fields did not resolve. id/node_type/content are struct fields in no bucket, so node.child_of.id returned Missing and failed the action — which disables the whole Play — though node.child_of alone resolved fine.
  4. check_schema_change_impact was over-broad. It flagged any Play whose trigger named the schema, regardless of what changed. With a core Play on task, every task schema edit — including adding a status value — demanded force=true from every user for a change that provably cannot break it. Now classified additive vs destructive; the function's own TODO had called this out as "acceptable for v1".

Also

Adds the play core schema, which playbook-system.md specifies as isCore but was never present. No log/playbook_log schema alongside it: that surface writes nine properties today, and declaring them would switch on enforcement over drifted data — the ADR-076 ai-chat.status hazard that broke 16 tests. Worth its own issue.

Behavior change worth reviewer attention

Two existing tests now pass force: true. That is the real consequence of shipping a task-triggered core Play: destructive task schema edits (removes, renames) now require confirmation for every user. Additive ones do not, after fix 4.

Testing

  • 7 new integration tests drive the actually-seeded Play, not a hand-installed rule: last-child completion, cancelled sibling, childless no-op, grandparent cascade, one-open-child, seeded/active/resettable, and no duplication on reopen.
  • 4 new unit tests for the resolver/scope fixes.
  • Full pre-push gate passed (test:all + cargo build + e2e).

Closes #2636

🤖 Generated with Claude Code

…re done (closes #2636)

Adds the rollup Play from ADR-079: when every has_child child of a task
reaches a terminal status, the parent is set to done. Seeded
unconditionally as a user-modifiable play node carrying
_seed.default_rules (ADR-060 section 8), reconciled per id so a user's
edits survive startup and a later release still reaches an existing
database.

Semantics, per ADR-079:

- cancelled counts as terminal alongside done. The rollup asks whether
  work remains under the parent, not whether everything succeeded;
  excluding it strands a parent whose last child was abandoned. The
  parent is always set to done, never cancelled.
- A childless task never auto-completes, guaranteed by the engine's
  empty-collection-is-false rule rather than a count guard.
- Completion cascades up the ancestor spine: the Play's own write is
  itself a task status change, re-firing the rule with the parent in the
  child position. Reactive, not invariant - ADR-060 section 2 restricts
  invariants to non-chaining depth 1.

Four bugs surfaced while building this, each fixed with a regression
test that fails without its fix:

- maps_to was never applied to nodes reached by traversal. enrich_context
  built related nodes with node_to_cel_value, so a base-scoped Play
  comparing a subtype child's extended enum value never matched - a
  silent false, no error. scoped_node_value is now shared rather than
  reimplemented, per ADR-078's one-shared-resolution-function rule. This
  is item 4 of #2747, triaged there as non-breaking; it was live.
- Play path validation rejected built-in relationships. has_child and
  child_of have no SchemaRelationship behind them, so validation refused
  paths the resolver walks perfectly well.
- A related node's core fields did not resolve. id/node_type/content are
  struct fields in no bucket, so node.child_of.id returned Missing and
  failed the action - which disables the whole Play - though
  node.child_of alone resolved fine.
- check_schema_change_impact flagged any Play whose trigger named the
  schema, regardless of what changed. With a core Play on task, every
  task schema edit - including adding a status value - demanded
  force=true from every user for a change that provably cannot break it.
  Now classified additive vs destructive; its TODO called this out.

Also adds the play core schema, which playbook-system.md specifies as
isCore but was never present. No log/playbook_log schema alongside it:
that surface writes nine properties today and declaring them would
switch on enforcement over drifted data, the ADR-076 ai-chat.status
hazard. Tracked separately.

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

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2752 (Initial Review)

Verdict: REQUEST CHANGES — one correctness gap that silently defeats the feature (multi-parent), and one that disables the shipped Play on an ordinary, explicitly-blessed schema edit. Both are narrow, local fixes. Everything else here is genuinely strong work: the diff is tightly scoped to ADR-079, the four incidental bug fixes are each real and each carry a regression test that fails without the fix, and the doc comments explain why at a standard well above the bar.

I verified the load-bearing claims empirically rather than by reading, including two throwaway probe tests (since deleted; working tree is clean).


What is right, and worth saying so

  • The seeded-Play design tracks ADR-079 exactly. Stable hardcoded id (ADR-060 §5 ordering), _seed.default_rules for reset (§8), skip-if-exists reconciliation per id (ADR-072 durability), reactive not invariant (§5, and the_rollup_rule_is_reactive pins it). Seeding is placed after core schemas in NodeService::new with the ordering dependency stated at the call site — packages/core/src/services/node_service/mod.rs:1235.
  • The childless-task guarantee is real, and it is the mechanism the ADR claims. graph_resolver.rs:480 guards collection insertion with if !nodes.is_empty(), so an empty collection leaves the variable absent from the CEL context rather than present-and-empty; the condition then fails via NoSuchKey. ADR-079 §3's "no count guard needed" is accurate. Worth noting it is emergent from the absent-variable path rather than an explicit .all() special case — see the Nit below.
  • maps_to-on-traversal (bug fix 1) is a genuine live bug, correctly fixed. Sharing scoped_node_value rather than reimplementing is exactly ADR-078's "one shared resolution function". The two scope_tests are well-chosen: the first fails on bucket projection alone with a plain inherited done, the second isolates maps_to on top. That separation mirrors ADR-079 §2's own distinction and is the right way to pin it.
  • Replacing the bare assert_eq!(schemas.len(), 18) with a sorted id set (core_schemas.rs:1624) is a real improvement — the old assertion passed unchanged if one schema were swapped for another.
  • check_schema_change_impact short-circuits before the play-node query rather than collecting and discarding, so the common additive path costs no DB round trip. Good instinct.
  • The play schema's drift-risk reasoning is sound. Declaring rules/description only, and explicitly not adding a log/playbook_log schema because create_or_update_log_node writes nine undeclared properties, is the correct read of the ADR-076 ai-chat.status precedent. rules is required: false with rule-shape enforcement left to validate_play_rules — right call, since the schema layer cannot validate rule semantics. I checked the other play-node producers (cron_runner.rs:386, workflow_state.rs:404, seeded.rs) and none writes a property this schema would now reject.

Findings

🔴 [Critical/Blocker] 1. A node with two parents rolls up to neither — silently

packages/core/src/playbook/core_plays.rs:52 — condition node.child_of.has_child.all(...)

child_of is a built-in with no SchemaRelationship, so is_declared_many_relationship (graph_resolver.rs:410) returns false for it. Resolution therefore falls through to the count-based arm of resolve_path:

  • 1 parent → ResolvedValue::Node → .has_child walks on → works.
  • 2+ parents → ResolvedValue::Collection → graph_resolver.rs:283-289 returns Missing, because "Can't walk further into a collection with simple dot-path".

So the Play's shape is load-bearing on a node having exactly one parent, and the failure is the silent-false mode ADR-079 §2 explicitly calls a correctness bug rather than a cosmetic one.

I confirmed this with a probe: parent A and parent B both has_child → child; set child to done; after 900ms both parents remained open. No log node, no error — the path simply resolves Missing and the condition is false.

Whether has_child multi-parent is reachable in the product today is a fair question, but three things make this worth fixing rather than accepting:

  1. has_child is documented (issue Seed a core Play that completes a parent task when all its children are done #2636, and CLAUDE.md's component architecture) as the universal hierarchy edge — "any node can nest under any other via the same mechanism". Nothing in the relationship layer enforces single-parent.
  2. The {trigger.node.child_of.id} action binding has the same dependency, and actions.rs:553 would serialize a Collection into the node_id param — an action failure, which per engine.rs:1141 disables the whole play. So the two-parent case is not merely inert; the condition failing first is the only thing preventing a worse outcome.
  3. It is untested. None of the 7 integration tests has a node with two parents.

Recommendation: at minimum, add a test pinning the current behavior and record the single-parent assumption in ADR-079 and in parent_task_completion_rules's doc comment — an undocumented shape dependency is the thing that bites later. If multi-parent is genuinely reachable, the fix belongs in the resolver (treat built-in reverse segments as Node when exactly one row matches, Collection otherwise is already what happens — the gap is walking through a collection, which is a resolver capability question worth its own issue).

Principle: a correctness property that holds only for a data shape nobody has written down is an accident waiting to be promoted to a bug.


🔴 [Critical/Blocker] 2. The additive/destructive split fixes the prompt but not the runtime disable

packages/core/src/schema/mod.rs:1585-1600, packages/core/src/playbook/lifecycle.rs:235

The PR's stated motivation is that with a core Play on task, every task schema edit would demand force=true. That is fixed for check_schema_change_impact. But there is a second, independent path that disables plays on schema change, and it was not touched:

handle_schema_updated (engine.rs:894) → lifecycle.handle_schema_update (lifecycle.rs:235), which disables every active play referencing the changed node_type, with no additive/destructive distinction:

.filter(|(_, pb)| {
    play_references_node_type(pb, schema_node_type)
        || play_has_paths_through_schema(pb, schema_node_type)
})

So the exact scenario the PR describes — a user calls add_field_values to add a task status value — now sails past the force prompt and then disables the seeded rollup Play at runtime anyway, via schema drift. The user gets a worse experience than before: previously the prompt at least told them something would break.

Mitigating: disable_play (lifecycle.rs:204) mutates only in-memory PlayStatus; it is not persisted, so a restart re-activates. That makes this a degraded-until-restart bug rather than a permanent one — but it is still a silent, unexplained stop to a core behavior, and ADR-076's add_field_values is precisely the blessed way to extend task.

Recommendation: thread the same SchemaChangeKind into handle_schema_update, or have handle_schema_updated skip the drift sweep for additive changes. The classification already exists; it just needs to reach the second consumer. Alternatively, if that is too large for this PR, it deserves a follow-up issue referenced from ADR-079 — but shipping the Play with a known runtime-disable on an ordinary schema edit should be a conscious, recorded decision, not an omission.

Principle: when you introduce a classification to stop an over-broad guard, apply it at every consumer of that guard — a half-applied invariant reads as fixed while still failing.


🟡 [Improvement] 3. extends re-targeting is classified Additive, and it is not

packages/core/src/schema/mod.rs:1585

The destructive test covers remove_fields, rename_fields, remove_relationships. But UpdateSchemaParams also carries extends (schema/mod.rs:1379), documented there as re-targetable: "Re-targeting is validated exactly as creation is."

Re-pointing a schema's extends from task to something else removes every inherited field from its effective field set. A Play path referencing one of those inherited fields on that subtype goes stale — which is the definition of destructive in this enum's own doc comment ("Removes or renames something a Play may reference by name"). Classifying it Additive means no confirmation prompt for a change that genuinely can break a Play.

The add_fields-collides-with-existing-name case you flagged in the brief I think is genuinely fine: a colliding add is rejected by field-collision validation before it lands, so it never produces a schema where an existing name resolves differently.

Recommendation: add || params.extends.is_some() to the destructive predicate. One line, and it closes the only genuine hole I found in the classification.


🟡 [Improvement] 4. core_field_value shadowing is broader than the comment claims, and is a live behavior change

packages/core/src/playbook/graph_resolver.rs:495-506

The comment says these are checked before properties "so these names mean the node's identity consistently, rather than being shadowed by a same-named user property on some types but not others." The intent is right. Two problems with the execution:

(a) It is not related-node-only. The block sits inside the per-segment walk at graph_resolver.rs:153, which runs for i == start_idx == 0 too. So it also intercepts the root node's first segment. I verified: a task node with a stored property task.content = "USER PROPERTY VALUE" and struct content = "the real content" resolves node.content to "the real content". Before this PR that path returned the user property. That is a behavior change on the trigger node, not just on traversed nodes, and the doc comment (which frames the whole change around node.child_of.id) does not say so.

Note this is not hypothetical: content is a plausible user property name, and create_node accepted it into the task bucket without complaint in my probe.

(b) It does match is_core_key exactly — both are id | node_type | content | version | lifecycle_status (cel.rs:205, graph_resolver.rs:499-505). Good. But that agreement is asserted only by a comment ("the two must agree, or a name resolves in a condition but not in the action binding that acts on it"). Nothing enforces it. Since the comment itself names the exact failure mode of drift, this is the textbook case for a test.

Recommendation: (1) Extend the doc comment to state that the trigger node's own core fields shadow same-named properties too, and that this is intentional precedence. (2) Add a small test asserting the two key sets are identical — iterate the five names through both is_core_key and core_field_value and assert agreement, so a name added to one and not the other fails. Cheap, and it pins a stated invariant that currently rests on two humans reading two files.

Direction-wise I think core-wins is the right call (consistency beats per-type surprise, and .id must be dependable for action bindings) — it just needs to be documented as the broader change it is.


🟡 [Improvement] 5. Scope threading is condition-path-only; the action path silently reads at the node's own scope

packages/core/src/playbook/actions.rs:1144 and :1681, packages/core/src/playbook/workflow_state.rs:187

Your claim in the brief — that the segment cache holds unprojected ResolvedValues so reuse across set_scope is safe — is correct. I verified: the cache stores ResolvedValue::Node(n) / Collection(nodes) (raw Nodes), and projection happens only in enrich_context at graph_resolver.rs:455/466/483, after the cache is consulted. set_scope deliberately not clearing the cache is sound, and the doc comment at graph_resolver.rs:81-87 explains exactly why. No finding there.

The gap is elsewhere: all three production resolvers outside the condition path are built with bare GraphResolver::new(...) and so carry scope: None. scope: None means scoped_node_value falls back to node_to_cel_value — the node's-own-type view. So {trigger.node.child_of.id} resolves at the parent's own scope, not at task scope.

For this Play it is harmless: id is a core field, identical under any scope. But ADR-078's rule is "every read surface is affected; none can be left alone", and this PR is the one that made the condition path scope-aware — leaving the action path behind creates precisely the asymmetry that ADR-078 warns produces drift. A future Play doing {trigger.node.child_of.status} would read an untranslated subtype value into an action param.

Recommendation: either thread the scope into the action-path resolvers, or add a short comment at actions.rs:1144 recording that the action path reads at the node's own scope and why that is acceptable for now. I would not block on the code change, but the silent asymmetry should not go unrecorded.


🟡 [Improvement] 6. Test coverage is good but has two real holes

The 7 integration tests genuinely drive the seeded Play end-to-end through a real engine — they are not rule-shape unit tests wearing a costume, and the_rollup_play_is_seeded_and_active correctly asserts the shipped artifact rather than a fixture. reopening_a_database_does_not_duplicate_the_play actually reopens the same file, which is the right way to test reconciliation. All 7 pass (0.57s).

Two would pass even if parts of the Play were broken:

  • a_childless_task_never_auto_completes is a weak negative. It asserts a task stays in_progress after 400ms. That passes if the Play works as designed — and equally if the Play were disabled, misseeded, or its trigger never matched task at all. It is not wrong, but it pins less than its name claims. Since the other tests would catch a globally-dead Play, this is acceptable; a stronger version would assert in the same test that a sibling parent-with-children case does complete, proving the engine was live.
  • No test covers the ADR-079 §2 promise against a real subtype. The scope_tests in engine.rs cover projection and maps_to on a synthetic ticket/bug chain, and that is good coverage of the mechanism — but nothing exercises the actual shipped Play against a type that extends task, which is acceptance criterion Create design system foundation #2 on the issue and the headline claim of ADR-079 §2 ("a concrete proof that ADR-078's promise holds"). The mechanism is tested; the integration of mechanism-with-shipped-Play is not.
  • No multi-parent test (see Finding 1).

Recommendation: add one integration test creating an issue extends task schema with an extended status value carrying maps_to: done, then assert the seeded Play completes a task parent when its issue child reaches that value. That is the test ADR-079 is actually claiming, and it is the difference between "we built the mechanism" and "the shipped Play uses it".


🟢 [Nit] 7. validation.rs open-codes an existing helper

packages/core/src/playbook/validation.rs:651-654:

let is_builtin = crate::models::schema::BUILTIN_RELATIONSHIP_NAMES
    .contains(&segment.as_str())
    || crate::models::schema::builtin_forward_name(segment).is_some();

models::schema.rs:104 already provides exactly this, under a name that says what it means:

pub fn is_reserved_relationship_name(name: &str) -> bool {
    BUILTIN_RELATIONSHIPS.iter().any(|(f, r)| *f == name || *r == name)
}

Same semantics (both spellings, both directions), one call, and it stays correct if BUILTIN_RELATIONSHIPS grows. DRY.

🟢 [Nit] 8. Empty-collection-is-false deserves a pointer at the condition

ADR-079 §3 rests the childless guarantee on documented CEL semantics, but the actual mechanism is if !nodes.is_empty() at graph_resolver.rs:480 — absence, not an .all() special case. Someone "tidying" that guard to always insert the list would turn .all() back into vacuous truth and silently start auto-completing every childless task. Worth one line at graph_resolver.rs:480 noting that the emptiness guard is load-bearing for ADR-079 §3.

🟢 [Nit] 9. ADR-079 §4 overstates the depth-cap consequence

§4 says exceeding the cap "disables this Play workspace-wide until it is reset." engine.rs:979 does call disable_play, so the first half is right — but lifecycle.rs:204 only flips in-memory PlayStatus; nothing persists it. A restart re-seeds/re-activates. The real blast radius is "until the next restart", which is materially less alarming than the ADR's framing. Since you asked whether a cheaper mitigation was missed: this is the cheaper mitigation, it just isn't written down. Worth correcting in the ADR — an ADR that overstates a risk invites someone to engineer around a problem that is smaller than advertised.

🟢 [Nit] 10. Seeding failure aborts NodeService::new

node_service/mod.rs:1235 uses ?, so a transient DB error while seeding the Play fails the entire service construction — the app does not start. The three sibling seeds above it behave the same way, so this is consistent rather than novel, and arguably correct (a half-initialized store is worse). Flagging only because a Play is more optional than a schema or the local person node; a failed Play seed degrades one behavior, while aborting startup degrades everything. Consistency is a defensible reason to leave it.


Summary

Severity Count Items
🔴 Critical 2 Multi-parent silent no-op; additive/destructive not applied to the runtime drift path
🟡 Improvement 4 extends misclassified additive; core-field shadowing scope + unpinned key-set agreement; action-path scope asymmetry; two test holes
🟢 Nit 4 Duplicated builtin helper; empty-guard comment; ADR §4 overstatement; seed failure mode

The architecture is sound and the ADR alignment is unusually careful — this is a net improvement to code health and the four incidental bug fixes are each worth having on their own. The blockers are narrow: Finding 3 is one line, Finding 2 is threading an enum that already exists into a second call site, and Finding 1 may be resolvable by documenting-and-testing rather than by code. My scope-cache concern from the brief checked out clean, and so did the is_core_key agreement.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Two blockers, both narrow: (1) a node with two has_child parents rolls up to neither, verified empirically — silent false, no log; (2) the new additive/destructive split fixes the force=true prompt but not lifecycle.rs's schema-drift path, which still disables the seeded Play on an ordinary add_field_values edit. Plus one line missing from the destructive predicate (params.extends).

The scope-cache safety claim and the is_core_key/core_field_value agreement both checked out clean.

@malibio

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Review addendum — correcting my own Nit 8 upward to an Improvement

A follow-up verification pass (probing cel-interpreter 0.10.0 directly, the version pinned at packages/core/Cargo.toml:54) turned up a correction to my review above. Nit 8 was materially understated and should be read as 🟡 Improvement.

The empty-collection rationale in ADR-079 §3 is wrong about its own mechanism

ADR-079 §3 and the doc comment at core_plays.rs:39-42 both assert that an empty collection "evaluates to false here — including under .all()", citing it as a deliberate departure from vacuous truth. Probed against the actual interpreter with the literal shipped condition:

empty-list bound under .all()   => Ok(Bool(true))     <-- standard CEL vacuous truth
key absent entirely             => Err(NoSuchKey("child_of"))

CEL .all() on an empty list returns true. There is no departure from vacuous truth anywhere in the engine. The childless guarantee is produced entirely by a different mechanism: graph_resolver.rs:482's if !nodes.is_empty() omits the key, so the variable is absent, and cel.rs:758-765 maps NoSuchKey to ConditionResult::Fail.

Why this matters more than a comment nit: that guard is the only thing preventing mass auto-completion. Binding an empty list instead of omitting the key reads like a harmless normalization — and would flip .all() to true for every childless task, marking them all done. Nothing at line 482 flags it as load-bearing.

Recommendation: correct ADR-079 §3 and the core_plays.rs doc comment to name the real mechanism (absent key → NoSuchKey → Fail), and add a comment at graph_resolver.rs:482 marking the emptiness guard as load-bearing for it.

a_childless_task_never_auto_completes tests a different path than its name

I flagged this as a weak negative; it is more specific than that. The test creates let lonely = task_node(...) with no parent edge at all, so resolution fails at the child_of hop:

orphan node.child_of.has_child => Missing

It never reaches an empty has_child collection, which is the case its doc comment describes. It passes, but it does not pin the .all()-on-empty behavior the ADR rests on. A test binding the collection path to a genuinely empty list would be the one that catches the regression above.

Independently confirmed

The same pass separately reproduced both blockers from my review — two-parent child_of resolving Collection → child_of.has_child and child_of.id both Missing, and the action-path resolvers at actions.rs:1144/:1681 constructed with scope: None while the condition path threads scope at engine.rs:1042. It also found that node.child_of is never extracted as a standalone path at all (the whole chain is swallowed into the CollectionPath by handle_comprehension), which is why the single-parent shape dependency is invisible from the condition text.

Verdict is unchanged: REQUEST CHANGES.

…isabling

Review findings from PR #2752.

Critical 2 (runtime disable): check_schema_change_impact's additive/
destructive split fixed the force=true prompt but left a second path.
handle_schema_updated disabled every play referencing the changed type,
so an ADR-076-blessed add_field_values passed the prompt and disabled the
seeded Play anyway. Candidates are now re-validated against the new
schema and only genuinely-broken plays are disabled. Validation needs
store access, so it runs outside the lifecycle lock.

A FIFTH bug surfaced while writing the subtype test the review asked
for, and it is the one that made acceptance criterion 2 quietly false:
ancestor_keys rewrote a trigger key's node_type but carried its
property_key through verbatim. A real PropertyChanged event is
type-namespaced, so a bug.status change fanned out to
(task, "bug.status") - a key nothing is registered under. No
property-scoped Play has ever fired on a subtype. The existing fan-out
test used a bare "status", the one spelling where this cannot fail.

Critical 1 (multi-parent): not a defect. The outline is single-parent by
construction - get_parent and get_parent_id both resolve with LIMIT 1 -
so a two-parent node is already malformed and nothing in the product
creates one. The Play declines to act rather than completing whichever
parent sorts first. Documented in ADR-079 section 3 and pinned by a test.

Also: extends re-targeting reclassified as destructive (it removes the
previous parent's fields from the effective set); core-field shadowing
documented as applying to the trigger node too; the load-bearing
empty-collection guard commented; is_reserved_relationship_name reused
instead of open-coded.

Tests: the childless-task negative gained a positive control (it would
have passed with the Play disabled entirely), plus multi-parent and
subtype-integration cases. Each new fix has a regression test verified
to fail without it.

Skipped: threading scope through the three resolvers outside the
condition path (actions.rs, workflow_state.rs). Real per ADR-078, but no
current caller needs it and it widens an already-large PR - belongs with
the remaining #2747 items.

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

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 8 of 10 findings, plus a fifth bug the review's test request uncovered

Commit 8e3bd88f. All 34 core test binaries pass; gate green.

🔴 Critical 2 — runtime disable path — fixed

Correct and important. The additive/destructive split fixed the force=true prompt but left handle_schema_updated → handle_schema_update disabling every play referencing the changed type. So an ADR-076-blessed add_field_values passed the prompt and disabled the seeded Play anyway.

Candidates are now re-validated against the new schema via validate_play, and only genuinely-broken plays are disabled. Validation needs store access, so it runs outside the lifecycle lock: gather candidates under a read lock, validate, then take the write lock.

🆕 A fifth bug, found writing the subtype test this review asked for

The most consequential finding of the round, and it made acceptance criterion #2 quietly false:

ancestor_keys (lifecycle.rs) rewrote a trigger key's node_type but carried property_key through verbatim. A real PropertyChanged event is type-namespaced (PropertyChange::key — "namespaced, e.g. task.status"), so a bug.status change fanned out to (task, "bug.status") — a key nothing is registered under, since a Play on task indexes itself as (task, "task.status").

No property-scoped Play has ever fired on a subtype. The existing fan-out test used a bare "status", the one spelling where the bug cannot appear — which is exactly why it survived.

Fixed with renamespace_property_key; covered by a unit test using the realistic namespaced key, a helper edge-case test, and the end-to-end subtype test. All verified to fail without the fix.

This is the honest correction to my earlier claim that criterion #2 was satisfied: the maps_to unit tests passed, but the Play was never triggered at all.

🔴 Critical 1 — multi-parent — not a defect; documented and tested instead

Respectfully pushing back. The outline is single-parent by construction: SqliteStore::get_parent and get_parent_id both resolve with LIMIT 1, so no read path has ever contemplated a second one. A node with two has_child parents is already malformed, and nothing in the product creates one — the probe constructed a state the product cannot otherwise reach.

The Play no-ops there rather than completing whichever parent sorts first, which is the safer failure. Now documented in ADR-079 §3 (including that it is an assumption, not an enforced invariant — nothing rejects a second edge at write time) and pinned by a_malformed_multi_parent_child_completes_neither_parent.

🟡 Addressed

  • 3 — extends misclassified as Additive: correct, re-pointing removes the previous parent's fields from the effective set. Now destructive.
  • 4 — core-field shadowing broader than documented: correct, the walk starts at i == 0 so it affects the trigger node's own first segment. Documented; core-wins reaffirmed as deliberate (matches is_core_key).
  • 6 — test holes: a_childless_task_never_auto_completes gained a positive control in the same test (it would have passed with the Play disabled entirely — a fair hit). Added multi-parent and subtype-integration cases.

🟢 Nits

  • is_reserved_relationship_name reused instead of open-coded ✅
  • Empty-collection guard commented as load-bearing for ADR-079 §3 ✅
  • ADR-079 §5 corrected: the depth-cap disable is in-memory only, so a restart restores it — "until it is reset" overstated it ✅
  • Seed failure aborting NodeService::new: left as-is, consistent with its siblings ⏭️

⏭️ Skipped — 5, scope threading beyond the condition path

Real per ADR-078, but no current caller needs it (id is scope-invariant, which is all this Play walks) and it widens an already-large PR touching shared engine paths. Belongs with the remaining #2747 items. Revisit if a Play needs a scoped read from an action binding or workflow state.

Docs

ADR-079 updated and pushed (60e3153..95539da): new §3 for the single-parent assumption, corrected depth-cap claim, and a "Discovered while implementing" section recording all five defects with the general lesson — subtype identity must be threaded through matching, resolution and action binding alike, and a gap in any one fails silently.

Re-review requested: two criticals with substantive changes to shared engine paths, plus a bug fix the first pass never saw.

@malibio

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2752 (Re-review of 8e3bd88f)

Verdict: REQUEST CHANGES — one blocker, and it is the one that was pushed back on rather than fixed. The pushback on Critical 1 rests on a factual claim about the product that I tested directly and found to be false: two supported product surfaces create a second has_child parent today, with no error. Everything else in this commit is genuinely fixed, and the new subtype fan-out bug is the most valuable thing in the PR.

I verified the load-bearing claims by running code, not by reading it: a probe exercising the real ops layer, and two fix-revert runs to confirm the new tests actually pin their behaviors. All probe files deleted; git status carries only the author's own in-flight edits.


Verified fixed

🔴 Critical 2 — runtime disable path. Genuinely fixed, and the lock dance is sound.

handle_schema_updated now gathers candidates under a read lock, re-validates outside it, and takes a write lock only when something actually broke. I specifically looked for the TOCTOU you flagged and it is benign:

  • A play uninstalled between the two locks → disable_play (lifecycle.rs:218) takes the else branch and logs a warning. No panic, no corruption.
  • A play disabled between the two locks → re-disabling is idempotent.
  • A play activated between the two locks → it is not in candidates, so it is not disabled. It was activated against the new schema anyway, so skipping it is correct, not a gap.

Dropping the lock for an async DB-backed validation is the right call — holding a std::sync::RwLock across an .await is the failure mode worth avoiding, and this avoids it. The non-atomicity is acceptable and I would not change it.

🆕 Subtype trigger fan-out — correct, and the highest-value change in the commit.

renamespace_property_key is right, and I checked each edge case you asked about:

  • split_once('.') splits on the first dot and the guard namespace == from_type is an exact equality, so a field name containing a dot keeps its tail (bug.a.b → task.a.b) — pinned by the helper test.
  • A custom:-prefixed field is safe: the prefix lives in the field segment, not the namespace, so bug.custom:effort → task.custom:effort. The colon never interacts with the dot split.
  • The wildcard (None) path is untouched — .as_deref().map(...) leaves None as None.
  • No case where the old behavior was load-bearing: the old output (task, "bug.status") is a key nothing can ever be registered under, since registration (trigger_keys_for_graph_event, lifecycle.rs:351) stores the author's literal spelling and no Play author writes another type's namespace.

I confirmed both new tests fail with the fix reverted (replaced the .map(renamespace…) with property_key.clone()):

  • namespaced_property_keys_are_renamespaced_when_fanning_out_to_an_ancestor → left: 0, right: 1
  • the_play_completes_a_parent_whose_children_are_an_extending_subtype → assertion failure

These are real regression tests, not tests that happen to pass. The diagnosis in the commit's doc comment — that the existing test used a bare status, the one spelling where the bug cannot appear — is accurate and well worth having written down.

Other findings, all properly addressed:

  • 3 — extends → Destructive (schema/mod.rs:1596). One line, correct, with the rationale at the site.
  • 4 — core-field shadowing. The comment now states plainly that the walk starts at i == 0 and the root node's own first segment is affected. That was the missing half.
  • 7 — is_reserved_relationship_name reused. Correct, same semantics, DRY.
  • 8 — empty-collection guard commented as load-bearing (see Nit 13 for a residual inaccuracy).
  • 6 — test holes. The positive control in a_childless_task_never_auto_completes is the right shape: it asserts a sibling hierarchy does complete in the same test, so a globally-dead Play now fails it. That was a fair hit and it is properly closed.

Regression check: cargo test -p nodespace-core --tests → 34/34 binaries pass, 0 failures (1575 in the lib binary). cargo build -p nodespace-core is warning-clean.


Findings

🔴 [Critical/Blocker] 11. The multi-parent pushback is factually wrong — two product surfaces create a second has_child parent today

The claim is that "nothing in the product creates one" and that a two-parent node "is unreachable through the product." I tested this against the real ops layer — the exact entry point both the CLI and the agent tool call — and it succeeds:

PROBE create has_child A -> C: Ok("OK")
PROBE create has_child B -> C: Ok("OK")     <-- second parent, no error
PROBE has_child(in) count = Ok(2)
PROBE get_parent = Ok(Some("A"))            <-- LIMIT 1 silently picks one

get_parent's LIMIT 1 is not evidence that a second parent cannot exist. It is the mechanism by which a second parent is silently hidden. Those are opposite things, and the pushback reads the first as proof of the second.

Two supported surfaces reach this, both passing an arbitrary relationship name straight through:

  1. CLI — nodespace relationship create --from <B> --type has_child --to <C> (packages/cli/src/commands/relationship.rs:75). relationship_name is a free-text --type arg with no allowlist.
  2. Agent tool — create_relationship (packages/agent/src/local_agent/tools.rs:3440), whitelisted in two skill seed sets (skill_pipeline.rs:539, :658) and reachable by an LLM choosing relationship_type: "has_child".

Neither is a debug hook. Both call rel_ops::create_relationship, where has_child resolves as ResolvedRelName::Builtin (rel_ops.rs:184) — "legal between any two nodes without being declared" — and so skips the cardinality check entirely. That check (relationship.rs:593) only runs in the else branch for schema-declared relationships. append_child_edge (relationships.rs:388) is then a bare INSERT OR IGNORE with no parent-existence check.

So the corrupted state is reachable by a user typing one CLI command, or by an agent picking a plausible relationship type. The "malformed and unreachable" framing does not survive contact with the code.

What I am not asking for. I am not asking you to make the resolver walk through a collection, and I am not asking you to fix multi-parent hierarchies. The ADR's own §3 already states the right position: single-parent is an assumption, not an enforced invariant. The problem is that the PR closes the gap in prose while leaving the write path that opens it wide.

Recommendation — one of these, and I do not have a strong preference:

  • (a) Enforce it at the one write site. In create_relationship, when relationship_name == "has_child", reject if the target already has a has_child parent. This makes the ADR's "single-parent by construction" claim actually true by construction, which is what the word means. It is a few lines next to the existing cardinality check and it closes CLI, agent, and daemon in one place.
  • (b) Correct ADR-079 §3 and the core_plays.rs comment to say what is true: the outline reads as single-parent, nothing enforces it at write time, and the CLI and agent tools can both produce a node the rollup then silently skips with no log and no error. Then file the enforcement as a follow-up.

What should not ship is the current state, where §3 says "nothing in the product creates one" and two shipped product surfaces do. The Consequences section already concedes "a hierarchy corrupted by a direct has_child write simply stops rolling up with no signal" — which contradicts §3's own premise in the same document.

Principle: "unreachable" is a claim about the write path, and it has to be verified there. Verifying it on the read path establishes only that you cannot see the problem.

The new test a_malformed_multi_parent_child_completes_neither_parent is good and should stay either way — it pins the safe no-op, which is genuinely the right failure behavior.


🟡 [Improvement] 12. handle_schema_update is now dead code, and pub hides it from the compiler

lifecycle.rs:270. After this commit, nothing calls it — not the engine, not tests.rs, not lifecycle.rs's own tests, which were all correctly migrated to plays_referencing_schema. I grepped the whole workspace at 8e3bd88f: the only hit is the definition itself.

Because it is pub on a pub type, dead_code does not fire, so cargo build is clean and nothing will ever remind anyone. It is also now actively misleading: it implements the exact over-broad disable-everything-that-references-the-type policy this commit exists to replace, so the next person to reach for a "handle schema update" helper finds the superseded one.

CLAUDE.md is unambiguous here — "Delete unused code, don't suppress warnings" and "Delete old patterns immediately when replaced."

Recommendation: delete it. Its doc comment's useful half already lives on plays_referencing_schema.

(I can see from the working tree that this is already in progress — lifecycle.rs and tests.rs carry uncommitted edits doing exactly this deletion. Flagging it so it lands in the commit rather than being lost.)


🟡 [Improvement] 13. The disable warning discards the reason, and now over-attributes the cause

engine.rs:913-940. Two related problems in the new block:

(a) The validation errors are collected and thrown away. broken.push((play_id, errors)) — then every read is (id, _). The tuple destructuring is why there is no unused warning. The log says a play "no longer validates against the new schema" without saying which path, field or type broke. This is the one code path whose entire purpose is to stop core automation at runtime, and the prior review's own framing of Critical 2 was that the user experience problem is a silent, unexplained stop. Keeping the errors and logging them is a few characters and it is the difference between a debuggable event and a mystery.

(b) validate_play validates the whole play, not the delta. It walks every node_type and every condition path the play references (validation.rs:367), against all schemas — not only the one that just changed. So a play already broken for an unrelated reason (some other schema missing a field) gets disabled the first time any referenced schema is touched, and the warning will name the innocent schema as the cause.

This is arguably more correct than the old behavior — a broken play should not stay active — but it makes the log message's causal claim wrong, and (a) removes the only evidence that would let someone notice. Fixing (a) largely defuses (b).

Recommendation: log the errors. warn!("... disabling play {} — {:?}", play_id, errors), or filter to those mentioning schema_node_type before attributing cause.


🟢 [Nit] 14. The new empty-collection comment repeats the mechanism error it was added to clarify

graph_resolver.rs:491-495 (and ADR-079 §4, unchanged). The comment says the guard is "what makes .all() over 'no children' evaluate false rather than vacuously true."

That is still not the mechanism. As the prior review's addendum established by probing cel-interpreter 0.10.0 directly, CEL .all() on an empty list returns true; the engine does not override it. The childless guarantee comes from the key being absent → ExecutionError::NoSuchKey → ConditionResult::Fail (cel.rs:758-765, which I re-read and confirmed).

The actionable half landed — the guard is now marked load-bearing, and that was the point. But the stated reason is still the one that was disproved. playbook-engine.md:223 asserts the same thing, so the docs are the root of it; ADR-079 §4 inherits it and the code comment now inherits it too, which is three places carrying a claim the interpreter contradicts.

Recommendation: name the real chain in the comment — absent key → NoSuchKey → Fail — and correct ADR-079 §4. Ideally playbook-engine.md:223 too, since it is the source. Low urgency, but it is cheap and the current text will send the next debugger to the wrong layer.


🟢 [Nit] 15. A bare property_key can never match a real event

Not introduced here, but this commit's analysis is what makes it visible, so it is worth recording. Registration (trigger_keys_for_graph_event) stores the author's literal property_key, and every real NodeUpdated event carries a namespaced prop.key (events.rs:109). Nothing normalizes either side. So a Play authored with "property_key": "status" is indexed under (task, "status") and never fires at all — not on task, not on a subtype.

The shipped Play correctly writes "task.status", so nothing is broken today. But property_changed_keys_fan_out_to_ancestors_too (lifecycle.rs:1186) asserts a bare-key match that cannot occur in production, which is exactly the trap that let the fan-out bug survive. Worth either a validation-time rejection of a bare property_key, or a comment on that test saying the spelling is synthetic. Its own sibling test already explains why — the note just belongs on the older test too.


Verdict

Severity Count Items
🔴 Critical 1 Multi-parent pushback contradicted by the write path (CLI + agent tool)
🟡 Improvement 2 Dead handle_schema_update; discarded validation errors / mis-attributed cause
🟢 Nit 2 Empty-collection mechanism still misstated; bare property_key never matches

Eight of ten prior findings are properly closed, and the lock restructuring, the extends classification and the shadowing documentation are all correct as written. The subtype fan-out bug is a genuinely valuable catch — a whole class of Play never fired on a subtype, and the honest correction of the earlier acceptance-criterion claim is the right way to have handled it.

Finding 11 is the only blocker. It is narrow and has a cheap resolution: either add the single-parent guard at the one write site, or make the ADR say what is actually true about the write path. What cannot ship is the current combination, where the documentation asserts unreachability that two supported product surfaces contradict.

Findings 12–15 are all small and none needs a re-review on its own.

Skipped item (scope threading to actions.rs / workflow_state.rs) — the deferral to #2747 is reasonable. id is scope-invariant, it is the only thing this Play binds from an action, and the asymmetry is now recorded rather than silent. I would not hold the PR for it.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review (re-review): REQUEST CHANGES — full findings in the comment above.

8 of 10 prior findings properly closed. The lock restructuring is sound (I checked the TOCTOU — benign in all three directions), and the new subtype fan-out fix is the most valuable change in the PR; I confirmed both its tests fail with the fix reverted. 34/34 core test binaries pass.

One blocker: the multi-parent pushback is contradicted by the write path. I reproduced a two-parent node through rel_ops::create_relationship — the exact entry point the CLI (relationship create --type has_child) and the agent create_relationship tool both call. has_child resolves as a builtin and skips the cardinality check entirely. get_parent's LIMIT 1 hides the second parent rather than preventing it. Either guard it at the write site or correct ADR-079 §3 to say what is true.

Re-review findings from PR #2752.

Finding 11 (blocker) - I was wrong, and the reviewer proved it by running
the write path rather than reading it. My claim that 'nothing in the
product creates' a two-parent node was false: a built-in relationship has
no SchemaRelationship, so it skips the declared-cardinality check, and
two shipped surfaces reach that gap - the CLI's 'relationship create
--type has_child' (free-text name, no allowlist) and the agent's
create_relationship tool. Both added a second parent with no error.

The reasoning error is worth naming: I read get_parent's LIMIT 1 as
evidence a second parent could not exist. It is the opposite - it is the
mechanism that silently hides one, making a node's parent depend on row
order. A LIMIT 1 in a read path is not an enforced invariant.

create_relationship now rejects a second has_child edge onto a node that
already has a parent, at the one point every surface converges.
Re-asserting the SAME edge stays legal, so callers re-attaching an
existing child are unaffected. Single-parent is now true by construction,
which get_parent and the whole outline UI already assumed.

Finding 12: handle_schema_update was dead after the previous commit -
pub on a pub type, so dead_code never fired. Deleted, and its six tests
converted to plays_referencing_schema with assertions matching the new
contract: identifying a candidate must NOT disable it. They had been
asserting the superseded behavior while calling orphaned code.

Finding 13: the disable warning discarded the validation errors. Now
logged - validate_play checks the whole play against every schema it
references, not just the changed one, so without them the warning
misattributes a pre-existing break to whichever schema was touched first.

Finding 14: my empty-collection comment repeated the mechanism error it
was meant to fix. CEL's .all() over an empty list returns true, per spec.
The false comes from the key being ABSENT, raising NoSuchKey, which the
evaluator maps to Fail. Corrected in the code and in ADR-079 section 4,
which now flags that playbook-engine.md's phrasing is inaccurate.

Finding 15 (bare property_key never matches a real event): pre-existing,
not introduced here, and the shipped Play correctly uses 'task.status'.
Left for a separate issue rather than widening this PR.

ADR-079 updated: section 3 rewritten from 'assumed' to 'enforced', the
now-impossible silent-skip consequence replaced with the real one (a
second edge is now rejected where it previously succeeded), and the
LIMIT-1 reasoning error recorded so the next reader does not repeat it.

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

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed — blocker fixed at the root, 4 of 5 findings closed

Commit 9a96a278. 34/34 core test binaries pass; gate green.

🔴 Finding 11 — multi-parent — you were right, I was wrong; fixed at the write path

The pushback was based on a bad inference and the probe disproved it. Verified independently before acting: has_child resolves as ResolvedRelName::Builtin (rel_ops.rs:183) and short-circuits before the cardinality check, which only runs in the else branch for schema-declared relationships. The CLI passes a free-text relationship_name straight through (cli/src/commands/relationship.rs:75), and append_child_edge is a bare INSERT OR IGNORE.

The reasoning error, stated plainly: I read get_parent's LIMIT 1 as evidence a second parent could not exist. It is the mechanism that hides one — making a node's parent depend on row order. A LIMIT 1 in a read path is not an enforced invariant, and is usually a sign someone assumed it was.

Fixed at the root rather than documented around it. create_relationship now rejects a second has_child edge onto a node that already has a parent, placed in the built-in branch beside the existing member_of cycle check — the one point CLI, agent tool and daemon all converge. Re-asserting the same edge stays legal, so callers re-attaching an existing child are unaffected (pinned by the test).

a_malformed_multi_parent_child_completes_neither_parent is replaced by a_second_parent_edge_is_rejected: the old test can no longer construct its premise, which is the point. It asserts the rejection, that the original edge survives, and that the idempotent re-assert still works.

⚠️ Behavior change on a shipped write path — a caller that was adding a second parent now gets an error instead of a silently-hidden edge. Nothing in the product does this intentionally and no test depended on it, but it is recorded as a negative consequence in ADR-079 §3.

🟡 Finding 12 — dead handle_schema_update — fixed (found independently, mid-review)

Caught this while your review was running, which is why the working tree had edits you didn't recognise — thanks for flagging rather than assuming. pub on a pub type meant dead_code never fired.

Worse than dead: its six tests asserted the superseded policy ("referencing a type disables the play") while calling the orphaned method, so they passed while testing nothing real. Deleted the method and stale doc comment; converted all six to plays_referencing_schema with assertions matching the actual new contract — identifying a candidate must not disable it. Renamed accordingly (schema_change_flags_directly_referencing_play_as_a_candidate).

🟡 Finding 13 — discarded validation errors — fixed

Now logged with the detail. Your point (b) is the sharp one: validate_play checks the whole play against every schema it references, not the delta, so without the errors the warning misattributes a pre-existing break to whichever schema happened to be touched first.

🟢 Finding 14 — empty-collection mechanism — fixed, and you were right twice

My comment repeated the very error it was added to clarify. CEL's .all() over an empty list returns true, per spec; the false comes from the key being absent → NoSuchKey → Fail (cel.rs:758). Corrected in the resolver comment and in ADR-079 §4, which now states the real mechanism and flags that playbook-engine.md:223 — the root of the error — is inaccurate. Left that doc for a separate change rather than editing a shared architecture doc from this PR.

⏭️ Finding 15 — bare property_key never matches — deferred

Confirmed real and confirmed pre-existing: registration stores the author's literal key, every real event carries a namespaced one, nothing normalises either side. The shipped Play correctly writes task.status, so nothing here depends on it.

Not fixed in this PR because normalising registration keys changes trigger matching for every existing Play — the same blast radius as the fan-out fix, and it deserves its own change and its own review rather than riding along. Worth filing; I'd rather you decide whether it's normalise-at-registration or reject-a-bare-key at save time.

The trap you identified is real and shared with the fan-out bug: property_changed_keys_fan_out_to_ancestors_too still asserts a match that cannot occur in production. It now sits directly beside namespaced_property_keys_are_renamespaced_when_fanning_out_to_an_ancestor, which uses the realistic spelling, so the contrast is at least visible at the call site.

Docs

ADR-079 pushed (95539da..9610885): §3 rewritten from "assumed" to "enforced", §4's mechanism corrected, the now-impossible silent-skip consequence replaced with the real one, and the LIMIT 1 reasoning error recorded in "Discovered while implementing" so the next reader doesn't repeat it.

@malibio

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2752 (Round 3 re-review of 9a96a278)

Verdict: APPROVE — the blocker is genuinely fixed at the right layer, and I could not break the reparent flows I most expected this change to break.

This commit is small (6 files, +110/−80) and every part of it is a direct response to a round-2 finding. I verified the load-bearing claims by running code rather than reading it: six probe tests across the reparent/attach surfaces, a fix-revert run on the new guard, and the full core suite. All probe files deleted; git status is clean.


The single-parent guard — scrutinised hardest, and it holds

packages/core/src/services/node_service/relationship.rs:526-550

1. Placement and coverage. I mapped every path that can write a has_child row and checked each against the guard:

Path Reaches the guard? Can it create a second parent?
create_relationship (CLI, agent tool, daemon gRPC) ✅ yes ❌ now rejected — this was the hole
NodeService::move_node (drag-drop, indent/outdent) ❌ bypasses ❌ store deletes old edge + inserts new in one tx
move_node_unchecked (upsert reparent) ❌ bypasses ❌ same store tx
create_node_with_parent → create_parent_edge_in_tx ❌ bypasses ❌ child is created in the same tx; cannot pre-hold a parent
bulk_create_has_child_edges (sync cold-sweep) ❌ bypasses ❌ store skips any already-parented child (relationships.rs:1074)
move_children_to_parent ❌ bypasses ❌ version-gated DELETE then INSERT in one tx

So the guard sits at the one converging surface that was actually reachable, and every bypassing path is already structurally single-parent — either delete-then-insert, or skip-if-parented, or a same-transaction fresh node. Placing it beside the member_of cycle check in the is_builtin branch is right: that is where built-ins get their type-specific validation, and it is the reason a built-in skipping the declared-cardinality check needed compensating there rather than in each caller. The doc comment states exactly this, correctly.

2. The reparent regression — checked directly, not by reading. This was the highest-risk outcome, since a "add new parent, then remove old" reparent would now hard-fail. It is not implemented that way. SqliteStore::move_node (nodes.rs:2556-2578) does DELETE-then-INSERT inside one transaction, with a comment explaining the atomicity requirement. Probes confirmed:

  • reparent A→B via move_node with OCC: ✅ lands on B; moving back to A: ✅
  • reparent via move_node_unchecked: ✅
  • create_node_with_parent: ✅
  • bulk_create_has_child_edges onto an already-parented child: returns 0 created, parent unchanged — correctly skipped, not an error

No legitimate flow breaks. Drag-and-drop, indent/outdent, and paste/duplicate-subtree all route through move_node/create_node_with_parent, never through create_relationship.

3. The idempotent re-assert is genuinely safe, and narrower than "allow re-asserts". The guard compares existing != source_id, so it permits only the same (parent, child) pair and rejects every different parent. It cannot mask a second-parent attempt — a different source_id is precisely what trips it. I also confirmed the allowed re-assert does not duplicate the edge: with no order, append_child_edge is INSERT OR IGNORE; with an explicit order, the earlier already_exists idempotency check short-circuits. Three re-asserts (bare, bare, explicit-order) left exactly one child.

I also confirmed the guard applies on the explicit-order path, not just the auto-order one — it runs before the edge_data.get("order") branch, so --edge-data '{"order":2}' is rejected too. That is easy to get wrong and is right here.

4. Error type and message. invalid_update → NodeServiceError::InvalidUpdate → Display as Invalid update: Node 'X' already has parent 'Y'; the outline is single-parent. Move the node instead of adding a second has_child edge. It reaches CLI and agent callers intact through service_error_to_status. The variant is a reasonable fit (a rejected write on validation grounds, same as the adjacent member_of target-type rejection) and the message names both ids and the remedy. This is the right shape for an agent caller, which needs to be told to use move_node rather than retry.

Revert check: removing the guard makes a_second_parent_edge_is_rejected fail with a second has_child parent must be rejected: (). It is a real regression test, not one that happens to pass. Guard restored; tree clean.


Other findings verified

Finding 12 — dead handle_schema_update: fixed. Deleted; workspace-wide grep for handle_schema_update\b returns zero hits. The six tests are converted to plays_referencing_schema and — importantly — their assertions now pin the new contract, not just the new method name. schema_change_flags_directly_referencing_play_as_a_candidate asserts PlayStatus::Active with the message "identifying a candidate must not itself disable it", which is exactly the behavior change that made the old tests vacuous. They pin something meaningful now: previously they asserted the superseded disable-everything policy against an orphaned method.

Finding 13 — discarded errors: fixed. engine.rs:924-944 joins the errors into the warning. The doc comment records point (b) — that validate_play checks the whole play against every referenced schema, so the triggering schema is not necessarily the culprit — which is the more valuable half and was the subtler part of the finding.

Finding 14 — empty-collection mechanism: now accurate. The resolver comment (graph_resolver.rs:491-500) and ADR-079 §4 both now state absent key → NoSuchKey → Fail, and explicitly concede that CEL's .all() over an empty list returns true per spec. I re-confirmed at cel.rs:758: Err(ExecutionError::NoSuchKey(_)) | Err(ExecutionError::UndeclaredReference(_)) => ConditionResult::Fail. The comment's named function evaluate_conditions_at_scope exists (cel.rs:703) and is the right referent. ADR-079 §4 additionally flags playbook-engine.md:223 as the inaccurate root without editing a shared architecture doc from this PR — the right call.

Finding 15 — deferred: reasonable. Normalising registration keys changes trigger matching for every existing Play; that is the same blast radius as the fan-out fix and deserves its own review. Nothing shipped depends on it (the Play writes task.status), and asking the reviewer to choose between normalise-at-registration and reject-at-save is the right way to hand off an open design question rather than guessing.

ADR-079 §3 and §4 now match the code. §3 is rewritten from "assumed" to "enforced", names both reachable surfaces, records the idempotent-re-assert carve-out, and keeps the collection-walk no-op as defence in depth. The negative consequence ("a second has_child edge is now rejected where it previously succeeded") is recorded. The "Discovered while implementing" section records the LIMIT 1 reasoning error as a general lesson — that is the sort of note that stops the mistake recurring, and it is unusual to see an author write it down.

Regression: cargo test -p nodespace-core --tests → 34/34 binaries pass, 0 failures (1575 in the lib binary).


Findings

🟢 [Nit] 16. create_relationship_in_tx does not carry the guard, so a Play add_relationship action can still add a second parent

packages/core/src/services/node_service/relationship.rs:786-816

The tx-scoped twin mirrors the member_of target-type and cycle checks but not the new has_child single-parent check. It is reachable: execute_add_relationship_in_tx (actions.rs:1973) calls it, so an invariant rule with action_type: add_relationship, relationship_type: "has_child" and an explicit order would insert a second parent edge, bypassing the guard.

Why this is a Nit and not a blocker:

  • It is not a new hole — it existed identically before this commit, so nothing regresses.
  • It is not reachable from the surfaces the finding was actually about (CLI, agent tool, daemon), which all route through the non-tx create_relationship.
  • It requires a user to hand-author an invariant Play that deliberately writes has_child with an explicit order — validation.rs:993 already rejects that action without an explicit order, so the shape is narrow and deliberate.
  • No shipped Play does this.

Still worth closing, because the stated justification for the placement is "enforce here, where every surface converges" — and this is the one surface that does not converge there. The two methods are already maintained as deliberate twins (the doc comment on create_relationship_in_tx enumerates exactly which behaviors are and are not reproduced, and why), so the honest options are to add the check or to add it to that enumeration.

Recommendation: either lift the check into the tx twin using get_parent_id_in_tx-style access, or add one line to create_relationship_in_tx's doc comment noting the single-parent guard is deliberately not reproduced and why. The second costs nothing and keeps the twins' divergence documented, which is the existing convention in that file. I would not hold the PR for the code change.

Principle: when a guard's rationale is "this is where everything converges," any path that does not converge there needs to be either covered or named.


Verdict

Severity Count
🔴 Critical 0
🟡 Improvement 0
🟢 Nit 1

Approve. The round-2 blocker is fixed at the write path rather than documented around, which is the stronger of the two options offered and makes ADR-079 §3's "true by construction" claim literally true. Findings 12–14 are properly closed with assertions that pin real contracts, and 15's deferral is well reasoned.

The thing I most expected to go wrong — a reparent implemented as add-then-remove, which this guard would have broken outright — does not exist in this codebase; reparenting is delete-then-insert in a single transaction at the store layer, and every non-converging write path is already structurally single-parent by its own mechanism. I checked that by running the flows, not by reading them.

Finding 16 is genuinely optional and needs no re-review.


Automated pragmatic-code-review, round 3. All probe files deleted; working tree clean.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review (round 3): APPROVE — full findings in the comment above.

Round-3 review nit 16, and a fair one: the guard's own comment claimed
'enforce here, where every surface converges', but the in-tx twin was
the one surface it did not cover. An invariant Play's add_relationship
action reaches create_relationship_in_tx, so the claim was false for
exactly the path that runs inside a transaction.

Added get_parent_id_in_tx as the proper _in_tx twin of get_parent_id
(ADR-069 section 1a). check_relationship_exists_in_tx could not serve:
it counts by in_node, the parent side, and this asks the child side.

Also corrected the non-tx comment to say what is actually true - enforce
at the service entry point every external caller reaches - and to record
why the reparenting paths need no guard: move_node is delete-then-insert
in one transaction, bulk_create_has_child skips already-parented
children, and create_parent_edge_in_tx creates the child in the same
transaction.

New test pins that reparenting still works. A guard rejecting a second
parent is precisely the shape that breaks a move implemented as 'attach
new, detach old', and nothing else in the file would have caught that
regression.

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

malibio commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator Author

Nit 16 closed — a6149c94

Fair catch, and worth fixing rather than documenting around: the guard's own comment claimed "enforce here, where every surface converges", and create_relationship_in_tx was the one surface it didn't. An invariant Play's add_relationship action reaches that path, so the stated rationale was false for exactly the case that runs in a transaction.

  • Added get_parent_id_in_tx as the proper _in_tx twin of get_parent_id (ADR-069 §1a). check_relationship_exists_in_tx couldn't serve — it counts by in_node (the parent side), and this question is about the child side.
  • Mirrored the guard into the tx twin.
  • Corrected the non-tx comment to say what is actually true ("enforce at the service entry point every external caller reaches") and to record why the reparenting paths need no guard — the mapping in your review, now in the code where the next reader will look.

New test: reparenting_still_works_with_the_single_parent_guard. Your verification that reparenting is delete-then-insert was the reassuring part of the round-3 report, but it lived only in the review. A guard that rejects a second parent is precisely the shape that breaks a move implemented as "attach new, detach old," and nothing in the test suite would have caught that regression on a future refactor. Now it would.

34/34 binaries pass; quality:fix clean; gate green.


Round summary

Three rounds, six real defects, five of which only surfaced by running the code rather than reading it:

# Defect Found by
1 maps_to not applied to traversed nodes implementation
2 Play validation rejected built-in relationships implementation
3 Related node's core fields didn't resolve implementation
4 Over-broad schema-change impact check implementation
5 Subtype fan-out dropped the property namespace round-2's test request
6 Nothing enforced single-parent on has_child round-2's probe

Defects 5 and 6 are the ones worth calling out. Both were invisible to reading: #5 made acceptance criterion #2 quietly false — the Play never fired on a subtype at all — and #6 disproved a pushback I'd argued confidently from LIMIT 1. Neither would have been caught without someone executing the path.

The recurring lesson, now recorded in ADR-079: a LIMIT 1 in a read path is not evidence the second row cannot exist — it is usually evidence someone assumed it couldn't, and the query is what hides the counterexample.

One item deferred to its own issue (Finding 15): a bare property_key can never match a real event. Pre-existing, nothing shipped depends on it, but it is the same trap that concealed #5 — a test asserting a match that cannot occur in production.

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.

Seed a core Play that completes a parent task when all its children are done

1 participant