Skip to main content

khive_runtime/
atomic_plan.rs

1//! ADR-099 (cross-op atomicity for bulk apply) — prepared write-plan types.
2//!
3//! Async prepare materializes a synchronous write plan outside any
4//! transaction; commit later applies its statements as DML under a per-op
5//! SAVEPOINT. This module defines the plan *shapes* only, one family per
6//! admissible verb group (`update`, `delete`, `link`, `merge`,
7//! `gtd.transition`, `gtd.complete`, the governance verbs) — not yet wired
8//! into a live handler or the dispatch path. Every plan is deliberately
9//! inert (plain data, no async, no embedding reference).
10//!
11//! Two validation-staleness invariants every plan must satisfy:
12//! 1. **Predicate-based plans** carry an "all rows matching a condition"
13//!    effect as a statement evaluated inside the transaction
14//!    (`PlanPredicate`), never as a prepare-time-enumerated row list.
15//! 2. **Affected-row guards** (`PlanStatement::guard`) are attached to the
16//!    exact statement they validate, checked in-transaction; a mismatch
17//!    fails the op and rolls back the whole unit.
18//!
19//! See `docs/atomic-plan.md` for why guards are per-statement rather than
20//! per-plan.
21
22use uuid::Uuid;
23
24use khive_storage::SqlStatement;
25
26/// One statement in a plan, paired with the guard (if any) that validates
27/// it. **Runner contract:** a present `guard` is checked against the
28/// affected-row count of applying `statement` alone (`SqlWriter::execute`'s
29/// return value for this statement), not a batch total and not another
30/// statement's count. `guard: None` means prepare made no row-existence
31/// assumption about this particular statement (e.g. a cascade delete that
32/// may legitimately touch zero rows).
33#[derive(Debug, Clone)]
34pub struct PlanStatement {
35    /// The DML to apply inside the atomic unit.
36    pub statement: SqlStatement,
37    /// The expected-effect guard for `statement`, if prepare's validation
38    /// assumed a target row exists for it.
39    pub guard: Option<AffectedRowGuard>,
40}
41
42/// The predicate a prepare pass validated a plan's target against, replayed
43/// as a statement evaluated **inside** the transaction (ADR-099 D1, rule 1:
44/// "predicate-based plans wherever a write's scope depends on current
45/// state"). Carrying the predicate rather than a prepare-time-enumerated row
46/// list is what lets a later op in the same file (e.g. an intervening
47/// `link`) be visible to this plan's apply.
48#[derive(Debug, Clone)]
49pub struct PlanPredicate {
50    /// Human-readable description of the condition, for diagnostics (e.g.
51    /// `"source_id = :from"`).
52    pub description: String,
53    /// The in-transaction statement whose scope is evaluated against
54    /// current (committed-so-far) state, not prepare-time state.
55    pub statement: SqlStatement,
56}
57
58/// An affected-row guard (ADR-099 D1, rule 2): the row-count prepare assumed
59/// its target write would affect, re-verified in-transaction. A prepare-time
60/// validation is a plan *hypothesis*, never a commitment — if the guard does
61/// not hold at apply time, the op fails inside the atomic unit and the whole
62/// unit rolls back (ADR-099 acceptance criteria: "zero-row apply fails the
63/// unit").
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AffectedRowGuard {
66    /// Minimum affected-row count for the guard to hold (inclusive).
67    pub expected_min: u64,
68    /// Maximum affected-row count for the guard to hold (inclusive), or
69    /// `None` for "no upper bound" (e.g. a predicate-based rewire that may
70    /// touch any number of rows).
71    pub expected_max: Option<u64>,
72}
73
74impl AffectedRowGuard {
75    /// A guard requiring exactly `n` affected rows (the common case for a
76    /// single-target `update`/`delete`/`link` statement).
77    pub fn exactly(n: u64) -> Self {
78        Self {
79            expected_min: n,
80            expected_max: Some(n),
81        }
82    }
83
84    /// A guard requiring at least one affected row and no upper bound (the
85    /// shape for a predicate-based rewire that may touch any number of rows,
86    /// e.g. `merge`'s edge rewire).
87    pub fn at_least_one() -> Self {
88        Self {
89            expected_min: 1,
90            expected_max: None,
91        }
92    }
93
94    /// Whether an observed affected-row count satisfies this guard.
95    pub fn holds_for(&self, affected: u64) -> bool {
96        affected >= self.expected_min
97            && self.expected_max.map(|max| affected <= max).unwrap_or(true)
98    }
99}
100
101/// A deferred side effect recorded during prepare and run once, after the
102/// atomic unit commits (ADR-099 D1, "post-commit pass"). v1's admissible set
103/// computes no embeddings during prepare (D3's `update`/`merge` caveat), so
104/// the only post-commit effects are reindex kicks computed from the
105/// **committed** row content, plus the GAP-5 addition under B3: the
106/// best-effort GTD lifecycle audit row.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum PostCommitEffect {
109    /// No deferred side effect for this op.
110    None,
111    /// Re-embed and re-warm the given entity's vector row from its committed
112    /// content (ADR-099 D3 `update` caveat: entity name/description change).
113    ReindexEntity { entity_id: Uuid },
114    /// Re-embed and re-warm the given note's vector row from its committed
115    /// content (ADR-099 D3 `update` caveat: note name/content change).
116    ReindexNote { note_id: Uuid },
117    /// Append one `gtd_lifecycle_audit` row for a committed `gtd.transition`
118    /// or `gtd.complete` (ADR-099 B3, GAP-5): canonical `handle_transition`/
119    /// `handle_complete` call `ensure_audit_schema` + `write_audit_record`
120    /// (`khive-pack-gtd::handlers`) as a best-effort side write — a failed
121    /// audit insert must never roll back an already-committed transition.
122    /// Carries exactly the fields `write_audit_record` needs. Applied
123    /// outside `khive-runtime` (crate-direction: `khive-pack-gtd` depends on
124    /// `khive-runtime`, not the other way around) — this crate's own
125    /// `apply_post_commit_effects` treats this variant as a no-op; the
126    /// `kkernel` caller that owns both crates applies it by calling the
127    /// canonical `ensure_audit_schema`/`write_audit_record` functions
128    /// directly.
129    GtdAudit {
130        task_id: Uuid,
131        from_status: String,
132        to_status: String,
133        note: Option<String>,
134        namespace: String,
135    },
136    /// A committed note delete (soft or hard) — fire the pack-installed
137    /// note-mutation hook with the deleted note's kind (#750:
138    /// `DeletePlan` previously carried no `post_commit`
139    /// slot at all, so an atomic note delete never reached
140    /// `KhiveRuntime::fire_note_mutation_hook`, unlike `operations.rs`'s
141    /// `delete_note`, which fires it directly after a successful row
142    /// delete). Entity deletes have no equivalent — the hook system is
143    /// note-only (`khive-pack-memory`'s warm ANN cache is the only
144    /// installed consumer today).
145    NoteDeleted { note_id: Uuid, kind: String },
146}
147
148/// The natural key a committed symmetric edge update's surviving row must
149/// be looked up by (ADR-099 B3, second
150/// half). `khive-db`'s `edge_symmetric_absorb_or_update_inplace_statement`
151/// pair never trusts a prepare-time-computed target id (see that builder's
152/// doc comment); a caller rendering this op's result derives the actual
153/// surviving id by querying `graph_edges`'s own
154/// `UNIQUE(namespace, source_id, target_id, relation)` constraint via
155/// `KhiveRuntime::get_edge_by_natural_key_including_deleted`, which — unlike
156/// `list_edges` — includes soft-deleted rows: the ADR-039 DO NOTHING absorption
157/// arm can commit leaving the surviving canonical row tombstoned
158/// (khive#1213/#1214), and `list_edges` would report "not found" for exactly
159/// that row. Looked up strictly after commit.
160#[derive(Debug, Clone)]
161pub struct EdgeNaturalKey {
162    pub(crate) namespace: String,
163    pub(crate) canon_source_id: Uuid,
164    pub(crate) canon_target_id: Uuid,
165    pub(crate) relation: khive_storage::EdgeRelation,
166}
167
168impl EdgeNaturalKey {
169    /// The namespace containing the surviving edge.
170    pub fn namespace(&self) -> &str {
171        &self.namespace
172    }
173
174    /// The canonical source endpoint of the surviving edge.
175    pub fn canon_source_id(&self) -> Uuid {
176        self.canon_source_id
177    }
178
179    /// The canonical target endpoint of the surviving edge.
180    pub fn canon_target_id(&self) -> Uuid {
181        self.canon_target_id
182    }
183
184    /// The surviving edge's relation.
185    pub fn relation(&self) -> khive_storage::EdgeRelation {
186        self.relation
187    }
188}
189
190/// Write plan for an `update` op (entity or note shape — ADR-099 D3's
191/// `update` caveat covers both substrates the same way: row/FTS DML in the
192/// plan, any reindex deferred to `post_commit`).
193///
194/// Deferred effects are assigned by this crate's prepare pass and cannot be
195/// supplied by callers constructing a plan directly:
196///
197/// ```compile_fail
198/// use khive_runtime::{PostCommitEffect, UpdatePlan};
199/// use uuid::Uuid;
200///
201/// let id = Uuid::nil();
202/// let plan = UpdatePlan {
203///     target_id: id,
204///     statements: Vec::new(),
205///     post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
206///     edge_natural_key: None,
207/// };
208/// ```
209///
210/// A plan returned by a prepare function cannot have its validated
211/// statements cleared or replaced before it reaches the runner:
212///
213/// ```compile_fail
214/// use khive_runtime::UpdatePlan;
215///
216/// fn clear_prepared_statements(mut prepared: UpdatePlan) {
217///     prepared.statements.clear();
218/// }
219/// ```
220#[derive(Debug, Clone)]
221pub struct UpdatePlan {
222    /// The id of the entity or note being updated. For a symmetric edge
223    /// update this is the CALLER's requested id — advisory only, never the
224    /// basis for post-commit result rendering (see [`EdgeNaturalKey`]).
225    pub(crate) target_id: Uuid,
226    /// Row + FTS DML statements to apply inside the atomic unit, in order.
227    /// The row-update statement carries the existence guard; any FTS-mirror
228    /// statement that follows it is unguarded (its target row's existence
229    /// was already asserted by the row-update statement's own guard).
230    pub(crate) statements: Vec<PlanStatement>,
231    /// Deferred reindex assigned by the prepare pass when the update changed
232    /// name, description, or content.
233    pub(crate) post_commit: PostCommitEffect,
234    /// `Some` only for a symmetric edge update — the natural key a caller
235    /// must use to derive the committed surviving row post-commit, rather
236    /// than trusting `target_id`. `None` for every other update shape
237    /// (entity, note, non-symmetric edge), where `target_id` alone is
238    /// already an exact, non-advisory identifier.
239    pub(crate) edge_natural_key: Option<EdgeNaturalKey>,
240}
241
242impl UpdatePlan {
243    /// The record id supplied to the prepare pass.
244    pub fn target_id(&self) -> Uuid {
245        self.target_id
246    }
247
248    /// The committed lookup key required for a symmetric edge update.
249    pub fn edge_natural_key(&self) -> Option<&EdgeNaturalKey> {
250        self.edge_natural_key.as_ref()
251    }
252
253    /// The deferred post-commit effect assigned by the prepare pass.
254    pub fn post_commit(&self) -> &PostCommitEffect {
255        &self.post_commit
256    }
257}
258
259/// Write plan for an `AddEntity` proposal change: a fresh entity row plus its
260/// FTS document in the same atomic unit. Vector indexing remains a deferred
261/// effect because embedding may suspend.
262#[derive(Debug, Clone)]
263pub struct AddEntityPlan {
264    /// The freshly generated id of the entity being created.
265    pub(crate) entity_id: Uuid,
266    /// Row + FTS insert statements to apply inside the atomic unit, in
267    /// order. The row-insert statement carries the existence guard; the
268    /// FTS-insert statement that follows it is unguarded (an ordinary
269    /// `INSERT` into a virtual table with no conflicting row).
270    pub(crate) statements: Vec<PlanStatement>,
271    /// Reindex the committed entity after the transaction closes, as
272    /// assigned by the prepare pass.
273    pub(crate) post_commit: PostCommitEffect,
274}
275
276impl AddEntityPlan {
277    /// The id generated for the prepared entity.
278    pub fn entity_id(&self) -> Uuid {
279        self.entity_id
280    }
281}
282
283/// Write plan for an `AddNote` proposal change: a fresh note row plus its FTS
284/// document in the same atomic unit.
285#[derive(Debug, Clone)]
286pub struct AddNotePlan {
287    /// The freshly generated id of the note being created.
288    pub(crate) note_id: Uuid,
289    /// Row + FTS insert statements to apply inside the atomic unit, in
290    /// order, mirroring [`AddEntityPlan::statements`].
291    pub(crate) statements: Vec<PlanStatement>,
292    /// Reindex the committed note after the transaction closes, as assigned
293    /// by the prepare pass.
294    pub(crate) post_commit: PostCommitEffect,
295}
296
297impl AddNotePlan {
298    /// The id generated for the prepared note.
299    pub fn note_id(&self) -> Uuid {
300        self.note_id
301    }
302}
303
304/// Write plan for a `delete` op (soft or hard).
305///
306/// Deferred effects are assigned by this crate's prepare pass and cannot be
307/// attached to a statement-free plan by external callers:
308///
309/// ```compile_fail
310/// use khive_runtime::{DeletePlan, PostCommitEffect};
311/// use uuid::Uuid;
312///
313/// let id = Uuid::nil();
314/// let plan = DeletePlan {
315///     target_id: id,
316///     statements: Vec::new(),
317///     post_commit: PostCommitEffect::NoteDeleted {
318///         note_id: id,
319///         kind: "observation".to_owned(),
320///     },
321/// };
322/// ```
323#[derive(Debug, Clone)]
324pub struct DeletePlan {
325    /// The id of the entity or note being deleted.
326    pub(crate) target_id: Uuid,
327    /// Row DML (and, for a hard delete, incident-edge cascade DML) to apply
328    /// inside the atomic unit, in order. The target-row delete statement
329    /// carries the existence guard; a cascade edge-delete statement (hard
330    /// delete only) is unguarded — it may legitimately affect zero rows if
331    /// the target had no incident edges.
332    pub(crate) statements: Vec<PlanStatement>,
333    /// Deferred note-mutation-hook fire assigned by the prepare pass for a
334    /// note delete (#750 2). `PostCommitEffect::None` for entity and edge
335    /// deletes — the hook system is note-only.
336    pub(crate) post_commit: PostCommitEffect,
337}
338
339impl DeletePlan {
340    /// The record id supplied to the prepare pass.
341    pub fn target_id(&self) -> Uuid {
342        self.target_id
343    }
344}
345
346/// Write plan for a `link` op (create a typed directed edge). Endpoint
347/// existence is checked **structurally**, not via an unanchored plan-level
348/// guard: `statement` is a guarded `INSERT ... SELECT ... WHERE EXISTS`
349/// shape whose `SELECT` re-probes both endpoints inside the transaction, so
350/// the runner's affected-row check on this one statement *is* the
351/// in-transaction existence probe (ADR-099 acceptance criteria's
352/// dangling-edge case — `[delete(X, hard), link(A, X)]` — is closed by this
353/// guard failing once X is gone, regardless of statement ordering
354/// convention).
355#[derive(Debug, Clone)]
356pub struct LinkPlan {
357    pub(crate) source_id: Uuid,
358    pub(crate) target_id: Uuid,
359    /// The guarded `INSERT ... SELECT ... WHERE EXISTS(...)` statement:
360    /// its affected-row count is the endpoint-existence probe.
361    pub(crate) statement: PlanStatement,
362}
363
364impl LinkPlan {
365    /// The canonical source endpoint used by the prepared statement.
366    pub fn source_id(&self) -> Uuid {
367        self.source_id
368    }
369
370    /// The canonical target endpoint used by the prepared statement.
371    pub fn target_id(&self) -> Uuid {
372        self.target_id
373    }
374}
375
376/// Write plan for a `merge` op (deduplicate two entities). Rewires and
377/// lifecycle writes are split into separate fields precisely so a guard is
378/// never ambiguous between them: the edge rewire is **predicate-based**
379/// (ADR-099 D1 rule 1) and may touch zero or many rows depending on earlier
380/// in-file writes, so it is never guarded; the `from`/`into` entity
381/// lifecycle write assumes both rows exist, so it always is.
382#[derive(Debug, Clone)]
383pub struct MergePlan {
384    pub(crate) into_id: Uuid,
385    pub(crate) from_id: Uuid,
386    /// Predicate-based edge-rewire statement(s)
387    /// (`UPDATE graph_edges SET source_id = :into WHERE source_id = :from`-
388    /// shaped), evaluated inside the transaction so they structurally see
389    /// any earlier op's edge writes in the same file (ADR-099 acceptance
390    /// criteria: "merge rewires see earlier in-file writes"). Never
391    /// guarded — a rewire touching zero rows is a legitimate outcome.
392    pub(crate) rewires: Vec<PlanPredicate>,
393    /// The `from` entity's soft-delete/tombstone DML (and any other
394    /// lifecycle write prepare assumed a target row exists for). Always
395    /// guarded — prepare validated `into`/`from` both exist.
396    pub(crate) lifecycle: Vec<PlanStatement>,
397}
398
399impl MergePlan {
400    /// The entity retained by the prepared merge.
401    pub fn into_id(&self) -> Uuid {
402        self.into_id
403    }
404
405    /// The entity retired by the prepared merge.
406    pub fn from_id(&self) -> Uuid {
407        self.from_id
408    }
409}
410
411/// Write plan for a `gtd.transition` op (explicit task lifecycle change).
412#[derive(Debug, Clone)]
413pub struct GtdTransitionPlan {
414    pub(crate) task_id: Uuid,
415    /// Status-column DML to apply inside the atomic unit. Property-only
416    /// status mutation — triggers no reindex (ADR-099 D3). The transition
417    /// statement carries the guard (prepare validated the current status
418    /// and the requested transition were legal). Empty for an idempotent
419    /// no-op (`current == target` after `normalize_status`, GAP-5/GAP-6 fix
420    /// round) — canonical performs no write in that case either
421    /// (`handlers.rs:995-1005`).
422    pub(crate) statements: Vec<PlanStatement>,
423    /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
424    /// `PostCommitEffect::None` for the idempotent no-op case, matching
425    /// canonical's early return before its own
426    /// `ensure_audit_schema`/`write_audit_record` call.
427    pub(crate) post_commit: PostCommitEffect,
428}
429
430impl GtdTransitionPlan {
431    /// Build a plan from its already-decided statements and audit effect.
432    /// Callers outside this crate (e.g. the atomic-apply layer wiring
433    /// `gtd.transition` into a multi-op unit) cannot construct the struct
434    /// literal directly since its fields are crate-private.
435    pub fn new(
436        task_id: Uuid,
437        statements: Vec<PlanStatement>,
438        post_commit: PostCommitEffect,
439    ) -> Self {
440        Self {
441            task_id,
442            statements,
443            post_commit,
444        }
445    }
446
447    /// The task targeted by the prepared transition.
448    pub fn task_id(&self) -> Uuid {
449        self.task_id
450    }
451
452    /// Status-column DML for this transition; empty for the idempotent
453    /// no-op case.
454    pub fn statements(&self) -> &[PlanStatement] {
455        &self.statements
456    }
457
458    /// The deferred lifecycle audit effect assigned by the prepare pass.
459    pub fn post_commit(&self) -> &PostCommitEffect {
460        &self.post_commit
461    }
462}
463
464/// Write plan for a `gtd.complete` op (task lifecycle terminal transition).
465#[derive(Debug, Clone)]
466pub struct GtdCompletePlan {
467    pub(crate) task_id: Uuid,
468    /// Status + `completed_at` DML to apply inside the atomic unit, in
469    /// order. The status-update statement carries the guard (prepare
470    /// validated the task was in a completable state); the `completed_at`
471    /// write targets the same already-guarded row and is unguarded.
472    pub(crate) statements: Vec<PlanStatement>,
473    /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
474    /// mirrors `handle_complete`'s best-effort `write_audit_record` call.
475    pub(crate) post_commit: PostCommitEffect,
476}
477
478impl GtdCompletePlan {
479    /// Build a plan from its already-decided statements and audit effect.
480    /// Callers outside this crate (e.g. the atomic-apply layer wiring
481    /// `gtd.complete` into a multi-op unit) cannot construct the struct
482    /// literal directly since its fields are crate-private.
483    pub fn new(
484        task_id: Uuid,
485        statements: Vec<PlanStatement>,
486        post_commit: PostCommitEffect,
487    ) -> Self {
488        Self {
489            task_id,
490            statements,
491            post_commit,
492        }
493    }
494
495    /// The task targeted by the prepared completion.
496    pub fn task_id(&self) -> Uuid {
497        self.task_id
498    }
499
500    /// Status + `completed_at` DML for this completion.
501    pub fn statements(&self) -> &[PlanStatement] {
502        &self.statements
503    }
504
505    /// The deferred lifecycle audit effect assigned by the prepare pass.
506    pub fn post_commit(&self) -> &PostCommitEffect {
507        &self.post_commit
508    }
509}
510
511/// Which governance verb (`propose` / `review` / `withdraw`) a
512/// [`GovernancePlan`] applies.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum GovernanceOp {
515    Propose,
516    Review,
517    Withdraw,
518}
519
520/// Write plan for a governance op (`propose`, `review`, or `withdraw` — the
521/// event-sourced change-proposal lifecycle, ADR-046).
522#[derive(Debug, Clone)]
523pub struct GovernancePlan {
524    pub(crate) op: GovernanceOp,
525    pub(crate) proposal_id: Uuid,
526    /// Event-log + status DML to apply inside the atomic unit. The
527    /// lifecycle-state-check statement carries the guard (prepare validated
528    /// the proposal was in a state admitting this transition).
529    pub(crate) statements: Vec<PlanStatement>,
530}
531
532impl GovernancePlan {
533    /// The governance operation represented by this plan.
534    pub fn op(&self) -> GovernanceOp {
535        self.op
536    }
537
538    /// The proposal targeted by this plan.
539    pub fn proposal_id(&self) -> Uuid {
540        self.proposal_id
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547
548    fn stmt(label: &str) -> SqlStatement {
549        SqlStatement {
550            sql: "UPDATE t SET x = ? WHERE id = ?".to_string(),
551            params: vec![],
552            label: Some(label.to_string()),
553        }
554    }
555
556    fn guarded(label: &str, guard: AffectedRowGuard) -> PlanStatement {
557        PlanStatement {
558            statement: stmt(label),
559            guard: Some(guard),
560        }
561    }
562
563    fn unguarded(label: &str) -> PlanStatement {
564        PlanStatement {
565            statement: stmt(label),
566            guard: None,
567        }
568    }
569
570    #[test]
571    fn affected_row_guard_exactly_holds_only_for_n() {
572        let g = AffectedRowGuard::exactly(1);
573        assert!(!g.holds_for(0));
574        assert!(g.holds_for(1));
575        assert!(!g.holds_for(2));
576    }
577
578    #[test]
579    fn affected_row_guard_at_least_one_has_no_upper_bound() {
580        let g = AffectedRowGuard::at_least_one();
581        assert!(!g.holds_for(0));
582        assert!(g.holds_for(1));
583        assert!(g.holds_for(1_000));
584    }
585
586    #[test]
587    fn update_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
588        let id = Uuid::new_v4();
589        let plan = UpdatePlan {
590            target_id: id,
591            statements: vec![
592                guarded("update-row", AffectedRowGuard::exactly(1)),
593                unguarded("update-fts-mirror"),
594            ],
595            post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
596            edge_natural_key: None,
597        };
598        assert_eq!(plan.target_id, id);
599        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
600        assert_eq!(plan.statements[1].guard, None);
601        assert_eq!(
602            plan.post_commit,
603            PostCommitEffect::ReindexEntity { entity_id: id }
604        );
605    }
606
607    #[test]
608    fn delete_plan_guard_is_anchored_to_the_target_row_not_the_cascade() {
609        let plan = DeletePlan {
610            target_id: Uuid::new_v4(),
611            post_commit: PostCommitEffect::None,
612            statements: vec![
613                guarded("delete-row", AffectedRowGuard::exactly(1)),
614                unguarded("cascade-edges"),
615            ],
616        };
617        let row_guard = plan.statements[0].guard.expect("row delete is guarded");
618        assert!(row_guard.holds_for(1));
619        assert!(!row_guard.holds_for(0));
620        assert_eq!(plan.statements[1].guard, None);
621    }
622
623    #[test]
624    fn link_plan_guard_is_the_endpoint_existence_probe_itself() {
625        let source = Uuid::new_v4();
626        let target = Uuid::new_v4();
627        let plan = LinkPlan {
628            source_id: source,
629            target_id: target,
630            statement: guarded("insert-edge-where-exists", AffectedRowGuard::exactly(1)),
631        };
632        assert_eq!(plan.source_id, source);
633        assert_eq!(plan.target_id, target);
634        // Dangling-edge acceptance criterion: once an endpoint row is gone,
635        // the guarded INSERT...WHERE EXISTS affects 0 rows and the guard
636        // on *that exact statement* must fail, not silently pass.
637        let guard = plan.statement.guard.expect("link insert is guarded");
638        assert!(!guard.holds_for(0));
639    }
640
641    #[test]
642    fn merge_plan_rewires_are_never_guarded_lifecycle_writes_always_are() {
643        let into = Uuid::new_v4();
644        let from = Uuid::new_v4();
645        let rewire = PlanPredicate {
646            description: "source_id = :from".to_string(),
647            statement: SqlStatement {
648                sql: "UPDATE graph_edges SET source_id = ? WHERE source_id = ?".to_string(),
649                params: vec![],
650                label: Some("merge-rewire".to_string()),
651            },
652        };
653        let plan = MergePlan {
654            into_id: into,
655            from_id: from,
656            rewires: vec![rewire],
657            lifecycle: vec![guarded(
658                "tombstone-from-entity",
659                AffectedRowGuard::exactly(1),
660            )],
661        };
662        assert_eq!(plan.into_id, into);
663        assert_eq!(plan.from_id, from);
664        assert_eq!(plan.rewires[0].description, "source_id = :from");
665        // A predicate-based rewire may legitimately touch zero or many rows
666        // depending on how many edges an earlier in-file op inserted — the
667        // type carries no guard field for it at all.
668        let lifecycle_guard = plan.lifecycle[0].guard.expect("lifecycle write is guarded");
669        assert!(!lifecycle_guard.holds_for(0));
670    }
671
672    #[test]
673    fn gtd_transition_plan_triggers_no_reindex_by_construction() {
674        let plan = GtdTransitionPlan {
675            task_id: Uuid::new_v4(),
676            statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
677            post_commit: PostCommitEffect::None,
678        };
679        // A status-only transition never triggers a reindex: the type has no
680        // *reindex* post-commit variant to construct, only the best-effort
681        // `GtdAudit` lifecycle-audit effect, which itself does no embedding work.
682        assert_eq!(plan.statements.len(), 1);
683        assert!(plan.statements[0].guard.is_some());
684        assert_eq!(plan.post_commit, PostCommitEffect::None);
685    }
686
687    #[test]
688    fn gtd_transition_plan_idempotent_noop_carries_no_statements_and_no_audit() {
689        // current == target after normalization is an idempotent no-op:
690        // canonical performs no write and never reaches its audit-record call.
691        let plan = GtdTransitionPlan {
692            task_id: Uuid::new_v4(),
693            statements: vec![],
694            post_commit: PostCommitEffect::None,
695        };
696        assert!(plan.statements.is_empty());
697        assert_eq!(plan.post_commit, PostCommitEffect::None);
698    }
699
700    #[test]
701    fn gtd_transition_plan_carries_gtd_audit_post_commit_effect() {
702        let task_id = Uuid::new_v4();
703        let plan = GtdTransitionPlan {
704            task_id,
705            statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
706            post_commit: PostCommitEffect::GtdAudit {
707                task_id,
708                from_status: "inbox".to_string(),
709                to_status: "next".to_string(),
710                note: Some("handed off".to_string()),
711                namespace: "local".to_string(),
712            },
713        };
714        assert_eq!(
715            plan.post_commit,
716            PostCommitEffect::GtdAudit {
717                task_id,
718                from_status: "inbox".to_string(),
719                to_status: "next".to_string(),
720                note: Some("handed off".to_string()),
721                namespace: "local".to_string(),
722            }
723        );
724    }
725
726    #[test]
727    fn gtd_complete_plan_guard_is_anchored_to_the_status_write() {
728        let plan = GtdCompletePlan {
729            task_id: Uuid::new_v4(),
730            statements: vec![
731                guarded("update-status", AffectedRowGuard::exactly(1)),
732                unguarded("update-completed-at"),
733            ],
734            post_commit: PostCommitEffect::None,
735        };
736        assert_eq!(plan.statements.len(), 2);
737        let guard = plan.statements[0].guard.expect("status write is guarded");
738        assert!(guard.holds_for(1));
739        assert_eq!(plan.statements[1].guard, None);
740    }
741
742    #[test]
743    fn governance_plan_covers_all_three_lifecycle_ops() {
744        for op in [
745            GovernanceOp::Propose,
746            GovernanceOp::Review,
747            GovernanceOp::Withdraw,
748        ] {
749            let plan = GovernancePlan {
750                op,
751                proposal_id: Uuid::new_v4(),
752                statements: vec![guarded("governance-event", AffectedRowGuard::exactly(1))],
753            };
754            assert_eq!(plan.op, op);
755            assert!(plan.statements[0].guard.is_some());
756        }
757    }
758
759    #[test]
760    fn add_entity_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
761        let id = Uuid::new_v4();
762        let plan = AddEntityPlan {
763            entity_id: id,
764            statements: vec![
765                guarded("entity-insert", AffectedRowGuard::exactly(1)),
766                unguarded("entity-fts-insert"),
767            ],
768            post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
769        };
770        assert_eq!(plan.entity_id, id);
771        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
772        assert_eq!(plan.statements[1].guard, None);
773        assert_eq!(
774            plan.post_commit,
775            PostCommitEffect::ReindexEntity { entity_id: id }
776        );
777    }
778
779    #[test]
780    fn add_note_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
781        let id = Uuid::new_v4();
782        let plan = AddNotePlan {
783            note_id: id,
784            statements: vec![
785                guarded("note-insert", AffectedRowGuard::exactly(1)),
786                unguarded("note-fts-insert"),
787            ],
788            post_commit: PostCommitEffect::ReindexNote { note_id: id },
789        };
790        assert_eq!(plan.note_id, id);
791        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
792        assert_eq!(plan.statements[1].guard, None);
793        assert_eq!(
794            plan.post_commit,
795            PostCommitEffect::ReindexNote { note_id: id }
796        );
797    }
798
799    #[test]
800    fn plans_are_plain_data_no_async_no_embedding() {
801        // Documents a compile-time property: every plan type above derives
802        // only Debug/Clone/PartialEq, never Future or an embedding-provider
803        // trait. Plans must stay inert data: flag any edit that adds an
804        // async method or embedding-model field to one of these types.
805        let _ = PostCommitEffect::None;
806    }
807}