Repository navigation
Description
Overview
Every playbook rule today runs post-commit and fail-open: actions abort on failure with no rollback, leaving a log node and a node that never received the rule's effect. That is the right model for enrichment and notification. It is the wrong model for any rule that establishes a property the node must never be observable without — most obviously a rule that assigns access or membership, where a post-commit rule leaves a window in which the node exists unprotected, and a failed action leaves it permanently wrong.
This issue introduces a second rule class that runs synchronously inside the creating transaction, fail-closed, on the originating device only.
Problem Statement
Current execution semantics: actions run sequentially, abort on first failure, and are never rolled back. A rule that adds a required classification to a newly created node therefore has two failure modes that cannot be fixed within the model — a window between commit and effect, and a permanent divergence when an action fails.
The reason a second class is possible at all is an asymmetry worth stating plainly: synchronous pre-commit execution is only ever available on the originating device. A remote device receives an already-committed node; there is no open transaction to join. That asymmetry is the design, not an obstacle:
- Because an invariant rule's effect commits atomically with the node, remote devices must not re-run it — the effect arrives with the node as ordinary synced data.
- So the multi-device duplicate-execution problem does not apply to this class at all, and the class that does have that problem (reactive) is the one where duplicates are tolerable and convergent.
Proposed Solution
Two rule classes, declared in the playbook and validated at save time.
| Invariant rule | Reactive rule | |
|---|---|---|
| Executes | Synchronously, inside the creating transaction | Asynchronously, post-commit |
| Runs on | The originating device only | Every device that observes the event |
| On failure | The triggering write fails (fail-closed) | Actions abort, a log node records it; no rollback |
| Multi-device duplication | Does not apply | Applies; handled by derived identity |
Eligibility, validated at save time
A rule may be declared invariant only if it provably terminates inside a transaction. Saving a playbook whose invariant rule violates any condition is rejected, naming the offending action:
- Local writes only — no LLM inference, no network call, no PTY. A transaction cannot await an external service, and holding a write transaction across an unbounded wait is a correctness and liveness hazard.
- Non-chaining, depth 1 — the rule's actions must not themselves trigger rule evaluation. Unbounded recursion inside a transaction is unacceptable.
- Deterministic — no random values, no wall-clock reads. Two devices reasoning about the same node must agree on what the invariant requires.
- Same-graph scope — actions address the triggering node and what it already references; no queries whose results depend on sync state.
Invariant violations arriving from a remote device
A device can receive an already-committed node that violates an invariant it holds — the originating device ran an older playbook version, had the rule disabled, or predates the rule. The node cannot be un-committed. The resolution is repair and log: apply the effect to the received node and record a log node describing what was repaired and why.
Repair is preferred over quarantine (which hides real user data and creates a state no other device shares) and over silent acceptance (which lets a violation persist). It is only safe because invariant rules are deterministic and local-write-only by the eligibility rules — the repairing device computes the same effect the originating device should have.
Seeded playbooks carry protection semantics
Playbooks shipped as part of the product are seeded as ordinary playbook nodes, user-inspectable and user-modifiable. Seeded playbooks carrying an invariant additionally are resettable to their shipped default and warn explicitly on edit or disable, naming the consequence concretely — disabling a privacy invariant silently changes the default for everything created afterwards while leaving existing nodes correct, a divergence the user will not notice.
The engine is not an authorization boundary
Invariant rules give correctness for well-behaved clients only. A client that does not run the engine, holds a stale playbook, or has the rule disabled produces no effect. Any invariant with a privacy or access consequence must also be enforced server-side as a Pro tenant-schema constraint or trigger — mirroring how the last-admin invariant is enforced by a BEFORE DELETE OR UPDATE trigger on membership edges regardless of which client path attempts the write. That server-side enforcement is scoped to the consuming issue, not this one; this issue must not be understood as delivering a guarantee it cannot.
Architecture Impact
- ADR-060 (
../nodespace-docs/decisions/060-playbook-execution-under-multi-device-sync.md) is the governing decision. This issue implements §1 (rule classes), §2 (eligibility), §7 (repair-and-log), and §8 (seeded-playbook protection). architecture/playbook-system.mdpreviously specified one rule class with post-commit, abort-on-failure, no-rollback semantics as the only model. It has been amended with the two-class table and the eligibility rules.- ADR-030 (
../nodespace-docs/decisions/030-prompt-skill-node-architecture.md) is the precedent for DB-seeded, user-modifiable product content that the seeded-playbook mechanism follows. - The companion
nodespace-docschanges are already committed; no further docs work is required.
Acceptance Criteria
- A rule can be declared
invariantorreactive; absent a declaration, a rule isreactive(current behavior preserved) - An invariant rule's actions execute inside the same transaction as the triggering write
- An invariant rule action failure fails the triggering write — the node is not created
- An invariant rule does not re-execute on a device that received the node via sync
- Save-time validation rejects an invariant rule containing an LLM, network, or PTY action, naming the offending action
- Save-time validation rejects an invariant rule whose actions would trigger further rule evaluation
- Save-time validation rejects an invariant rule using random values or wall-clock reads
- A device receiving a node that violates an invariant it holds repairs the node and creates a log node recording the repair
- A seeded playbook can be reset to its shipped default
- Editing or disabling a seeded playbook carrying an invariant surfaces a warning naming the concrete consequence
- Reactive rules behave exactly as before (no regression in the existing playbook test suite)
- Tests pass (
bun run test:all) - Code passes
bun run quality:fix
Technical Specifications
Reference Files
- Rule types:
packages/core/src/playbook/types.rs— the rule struct the class declaration is added to - Save-time validation:
packages/core/src/playbook/validation.rs— where eligibility checks belong (schema/version validation already happens here) - Engine:
packages/core/src/playbook/engine.rs—handle_event, theRuleProcessorqueue (reactive path); the invariant path does not go through this queue - Actions:
packages/core/src/playbook/actions.rs—execute_actions; needs a transaction-scoped variant - Lifecycle:
packages/core/src/playbook/lifecycle.rs—activate_playbook,disable_playbook - Node creation:
packages/core/src/services/node_service/— the transaction the invariant path must join - Last-admin trigger precedent:
db/tenant-schema.sqlinnodespace-cloud—enforce_last_admin, the pattern for DB-level invariant enforcement
Implementation Details
- The invariant path is architecturally distinct from the reactive path: reactive rules are dispatched to a bounded
mpscqueue with a single consumer, which is exactly what an invariant rule must not do (the queue is post-commit and asynchronous by design). Invariant rules must be evaluated inline in the write path, before commit. - This means the write path gains a dependency on rule lookup. Keep the lookup read-only and lock-free relative to the transaction —
lifecyclealready holds rules behind astd::sync::RwLockfor in-memory HashMap reads with no.awaitacross the lock, which is the property needed here. - Save-time eligibility validation needs an action-classification table (which action kinds are local-write-only, which are non-deterministic). Define it once and share it with the non-idempotent-action classification the reactive path needs.
- Repair-and-log runs on the receiving device against an already-committed node, so it is an ordinary write, not a transaction join. It must be idempotent — several devices may repair the same node concurrently, and the repair must converge rather than produce N log nodes for one violation. The existing log-node fingerprinting and deduplication mechanism is the tool for this.
- "Reset to shipped default" implies the seeded playbook's default content is available at runtime, not only at seed time.
Dependencies
- Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738 (the reactive-side machinery and the originating-client signal; the two classes are defined against each other and the action-classification table is shared)
Related Issues
- Playbook execution under multi-device sync: derived identity, stable ordering, causal cycle depth, and catch-up suppression #1738 (multi-device reactive execution)
- AI chats private by default: seeded personal collection, transactional membership, and implement the non-embeddable revision #1740 (ai-chat private by default — the consuming use case for the invariant class)
Activity
mstomar125 commentedon Jul 28, 2026
Picking this up (mstomar125), implementing ADR-060 in reviewable slices. Slice A (this first PR): rule class + save-time eligibility validation — add the invariant/reactive rule class (default reactive, no execution change yet) and reject at save time any invariant rule that violates ADR-060 §2 (local-writes-only, non-chaining depth-1, deterministic, same-graph scope). Slice B adds the synchronous pre-commit invariant execution; C = repair-and-log for remote violations (§7); D = seeded-playbook protection (§8). §6 (DB-side enforcement) is a separate cloud task and will be flagged.
Add the invariant/reactive playbook rule class and its save-time elig…
mstomar125 commentedon Jul 28, 2026
Slice A merged in #1773 (issue stays open — 3 slices remain). Added the invariant/reactive rule class (default reactive, behavior-neutral — no execution change) and the save-time eligibility gate for invariant rules per ADR-060 §2: local-writes-only (exhaustive action classification), deterministic (rejects wall-clock CEL functions, the only non-deterministic surface), same-graph scope (rejects literal target ids), and the statically-decidable self-chaining case of non-chaining depth-1. The general cross-rule/multi-device chaining case is deferred to the runtime causal-depth guard (Slice B, ADR-060 §5). Next: Slice B — synchronous pre-commit invariant execution in the create transaction (I'll surface its design before it lands, as it modifies the write path); then C (repair-and-log, §7) and D (seeded-playbook protection, §8). §6 (DB-side enforcement) is a separate cloud task.
mstomar125 commentedon Jul 28, 2026
⏸️ PARKED for later pickup (Slice A landed; remaining slices blocked on a design decision).
Done: Slice A merged in #1773 — the invariant/reactive rule class + save-time eligibility gate (ADR-060 §2). Behavior-neutral (default reactive, no execution change, no invariant rules seeded yet).
Why parked — Slice B needs a transaction-model decision before any code: ADR-060 requires an invariant rule to run inside the creating transaction, fail-closed. But
NodeService::create_nodetoday does its pre-processing, a singlestore.create_nodewrite, and emitsNodeCreatedafterwards — there is no open, joinable transaction the engine can inject invariant-action writes into. So Slice B needs one of:create_nodeto open an explicit libsqlTransactionspanning the node insert + the invariant-rule action writes, commit atomically; any invariant-action failure rolls the whole thing back (the node never commits). This is what ADR-060's atomicity actually requires — but it's a significant core write-path change and needs the store/NodeService to expose transaction-scoped writes.Also for Slice B: dispatch must run invariant rules ONLY pre-commit on the originating device; the existing post-commit event handler AND the sync-apply path must NOT re-run them (reuse sync's reserved client-identity tag — the #1738 §5 signal; coordinate to avoid an
engine.rscollision).Still queued: Slice C = repair-and-log for remote invariant violations (§7). Slice D = seeded-playbook protection: resettable + warn on edit/disable (§8). §6 (DB-side enforcement of privacy invariants in the Pro tenant schema) is a separate cloud task (the engine is not an authorization boundary).
Resolve Option 1 vs 2 (likely a malibio/architecture call) to unpark.
mstomar125 commentedon Jul 29, 2026
@malibio — flagging this for your sign-off before Slice B lands, because the transaction-model decision here changes the core write path (
NodeService::create_node) and therefore affects the whole app's create flow. I want your confirmation on the approach before writing any of it.Where we are
Slice A is merged (rule model + save-time eligibility):
RuleClass { Invariant, Reactive }, defaulting toReactive, plus a validator that rejects an invariant rule doing network/LLM/random/wall-clock work (per ADR-060 §2). Nothing behavioral changed yet — no rule executes pre-commit.Slice B is the core of the ADR and it's blocked on one design question, which is why I'm parking it here rather than proceeding autonomously.
The blocker
ADR-060 §1 requires invariant rules to run "synchronously, inside the creating transaction," fail-closed. But today
create_nodedoes its pre-processing, callsstore.create_node, and emitsNodeCreatedafter the write returns — there is no open, joinable transaction the playbook engine can inject its action-writes into. The store hascreate_child_node_atomic(a single atomic child insert) but no general "run these N writes + the node insert as one transaction" primitive. So Slice B needs one of:Option A — Restructure to an explicit transaction (my recommendation).
Open a real libsql
Transactionincreate_node: insert the node, match + run the invariant rule's actions through that same tx, commit atomically. Any invariant-action failure rolls the whole thing back — the node never commits.NodeServicemust expose transaction-scoped writes, and the action executors must accept a tx handle. Needs a deadlock/re-entrancy review against the existingreorder_lockdiscipline.Option B — Logical pre-commit.
Run the invariant actions before finalizing the create and abort the create on failure, but without a single SQL transaction wrapping node-insert + actions.
Why I recommend Option A
The entire justification for having an invariant class (vs. just reactive rules) is the fail-closed, no-window guarantee for access/membership/classification properties. Option B reintroduces exactly the window we're trying to close, so it doesn't really deliver the class's reason for existing — it's a smaller change that buys a weaker version of the thing we need. Option A is more work but it's the correct shape, and I think it's worth doing once rather than shipping B and re-doing it.
I believe Option A is correct — but given this reshapes the create path app-wide, I'd like your explicit sign-off before I write it.
One coupling to note
Slice B also needs to distinguish a local write from a sync-apply so invariant rules run only pre-commit on the origin and are not re-run on the receiving device (the effect arrives as synced data). That signal is the same reserved client-identity tag #1738 §5 formalizes — so Slices B and the #1738 dispatch work should coordinate on
engine.rsto avoid colliding.What I'd like from you
NodeService/ the store growing a transaction-scoped write API.Parked until you weigh in. Slices C (repair-and-log, §7) and D (seeded-playbook protection, §8) follow B and are lower-risk.
mstomar125 commentedon Sep 12, 2026
Re-checked against current
main(0435c4d) — this issue's title ("...with synchronous pre-commit execution on the origin device") is still not satisfied. Summarizing so the board reflects the actual state rather than just staleness:What's actually merged: only Slice A, commit
4e368e78(PR #1773, "Add the invariant/reactive playbook rule class and its save-time eligibility gate"). This is explicitly behavior-neutral:RuleClass { Invariant, Reactive }on the rule model (packages/core/src/playbook/types.rs, defaults toReactive), plus save-time eligibility validation inpackages/core/src/playbook/validation.rsrejecting non-local-write/non-deterministic/out-of-scope/self-chaining invariant rules. No rule executes pre-commit anywhere in the codebase — confirmed bypackages/core/src/playbook/engine.rs's own comment: "This does not makeRuleClass::Invariantrules sync-safe: their fail-closed guarantee depends on ADR-060 §2/§7 mechanisms that are out of scope here."Still unimplemented (the actual headline of this issue): Slice B (synchronous pre-commit execution inside the creating transaction — the core mechanism the title names), Slice C (repair-and-log for remote invariant violations, §7), Slice D (seeded-playbook reset/warn protection, §8).
grep-ing the repo for invariant execution wiring,repair, orseeded/reset_to_defaultplaybook logic outsidevalidation.rs's eligibility checks andtests.rsturns up nothing.Why it's stuck: Slice B was explicitly parked on 2026-07-29 pending an architecture sign-off that never came. The blocker, per the parked comment:
NodeService::create_nodehas no open, joinable transaction to inject invariant-rule action writes into, and the fix is a real core write-path change (Option A: restructurecreate_nodearound an explicit libsql transaction spanning node-insert + invariant actions, vs. Option B: a weaker non-transactional pre-commit check). The playbook author (issue author, GitHub handle malibio) was asked to confirm Option A vs B on 2026-07-29; no response as of today (2026-09-12, 45 days later). No related commits since (git log --all --grepfor "1739"/"invariant"/"slice b/c/d" turns up nothing past #1773).Leaving open — genuinely not done, and still blocked on the same unresolved decision as when it was parked. Not re-pinging for sign-off here since that request already stands on the thread above.
mstomar125 commentedon Sep 15, 2026
Unblocked — the transaction-model decision Slice B was parked on has been resolved by ADR-069 (merged as PR#2513, commit
a555f9aa, "Add unit-of-work transaction seam; make multi-write operations atomic and emit events after commit").This is exactly Option 1 from the parking comment:
NodeServicenow has its ownwith_transaction/NodeServiceTxseam (packages/core/src/services/node_service/mod.rs), giving composed operations a real, joinable transaction to inject writes into —create_node's public entry point wraps acreate_node_in_txthat runs inside this seam, exactly what Slice B needs to inject invariant-rule action writes into the same transaction as the node insert, fail-closed on rollback.Moving to Todo — ready to pick up Slice B (synchronous pre-commit invariant execution, ADR-060 §5) against this now-real seam.
mstomar125 commentedon Sep 15, 2026
Baseline (frontend, bun run test): 242/243 files passed, 4966/4967 tests passed. 1 pre-existing failure unrelated to this issue: architecture-benchmarks.test.ts's combineNodes <40ms perf threshold (flaky timing assertion, no playbook/core-write-path code touched). Starting Slice B/C/D implementation (ADR-069 transaction seam is in place per prior comments; #1738's originating-client signal — SYNC_SERVICE_CLIENT_ID/self.client_id — and the action-classification table from Slice A are independently sufficient, confirmed by direct code read, so proceeding without further blocking on #1738).
mstomar125 commentedon Sep 15, 2026
Merged via PR #2632 (commit 8252a4d). Slices B (synchronous pre-commit invariant execution), C (repair-and-log), and D (seeded-playbook protection) all shipped, on top of Slice A (#1773). Not blocked on #1738 in the end — the originating-client signal (SYNC_SERVICE_CLIENT_ID/self.client_id) it depends on turned out to be a pre-existing ADR-027 convention, not something #1738's still-open reactive-engine work needed to supply first; confirmed by direct code read before starting.
Two independent adversarial review passes caught and fixed a real, serious bug before merge: PlaybookEngine::handle_event's local-event branch enqueued RuleClass::Invariant rules onto the reactive ExecutionQueue with no class filter, so every invariant rule ran TWICE — once correctly (synchronous, pre-commit, fail-closed) and once more asynchronously post-commit with no rollback protection. A failure of that spurious second run would have silently disabled the whole play via the existing fail-open path, for a rule that had already succeeded moments earlier. Fixed by filtering RuleClass::Invariant out of what gets enqueued (mirroring the filter repair-and-log already applied on the sync-apply side), with a regression test asserting a node's version doesn't advance after the synchronous stamp. Also fixed a transaction-consistency gap in the member_of cycle check for invariant add_relationship actions, caught by the same review.
Board still lists follow-ups from #1738's own thread (single-writer election NodeSpaceAI/nodespace-sync#521, relaxing the ADR-073 blanket sync gate) — unrelated to this issue, left untouched.