khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! ADR-099 (cross-op atomicity for bulk apply) — prepared write-plan types.
//!
//! Async prepare materializes a synchronous write plan outside any
//! transaction; commit later applies DML or a typed GTD no-op read assertion under a per-op
//! SAVEPOINT. This module defines the plan *shapes* only, one family per
//! admissible verb group (`update`, `delete`, `link`, `merge`,
//! `gtd.transition`, `gtd.complete`, the governance verbs) — not yet wired
//! into a live handler or the dispatch path. Every plan is deliberately
//! inert (plain data, no async, no embedding reference).
//!
//! Two validation-staleness invariants every plan must satisfy:
//! 1. **Predicate-based plans** carry an "all rows matching a condition"
//!    effect as a statement evaluated inside the transaction
//!    (`PlanPredicate`), never as a prepare-time-enumerated row list.
//! 2. **Affected-row guards** (`PlanStatement::guard`) are attached to the
//!    exact statement they validate, checked in-transaction; a mismatch
//!    fails the op and rolls back the whole unit.
//!
//! See `docs/atomic-plan.md` for why guards are per-statement rather than
//! per-plan.

use uuid::Uuid;

use khive_storage::SqlStatement;

/// One statement in a plan, paired with the guard (if any) that validates
/// it. **Runner contract:** a present `guard` is checked against the
/// affected-row count of applying `statement` alone (`SqlWriter::execute`'s
/// return value), or the result-row count for a GTD no-op read assertion,
/// not a batch total and not another statement's count.
/// `guard: None` means prepare made no row-existence
/// assumption about this particular statement (e.g. a cascade delete that
/// may legitimately touch zero rows).
#[derive(Debug, Clone)]
pub struct PlanStatement {
    /// The DML, or GTD no-op SELECT assertion, to apply inside the atomic unit.
    pub statement: SqlStatement,
    /// The expected-effect guard for `statement`, if prepare's validation
    /// assumed a target row exists for it.
    pub guard: Option<AffectedRowGuard>,
}

/// The predicate a prepare pass validated a plan's target against, replayed
/// as a statement evaluated **inside** the transaction (ADR-099 D1, rule 1:
/// "predicate-based plans wherever a write's scope depends on current
/// state"). Carrying the predicate rather than a prepare-time-enumerated row
/// list is what lets a later op in the same file (e.g. an intervening
/// `link`) be visible to this plan's apply.
#[derive(Debug, Clone)]
pub struct PlanPredicate {
    /// Human-readable description of the condition, for diagnostics (e.g.
    /// `"source_id = :from"`).
    pub description: String,
    /// The in-transaction statement whose scope is evaluated against
    /// current (committed-so-far) state, not prepare-time state.
    pub statement: SqlStatement,
}

/// An affected-row guard (ADR-099 D1, rule 2): the row-count prepare assumed
/// its target write would affect, re-verified in-transaction. A prepare-time
/// validation is a plan *hypothesis*, never a commitment — if the guard does
/// not hold at apply time, the op fails inside the atomic unit and the whole
/// unit rolls back (ADR-099 acceptance criteria: "zero-row apply fails the
/// unit").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AffectedRowGuard {
    /// Minimum affected-row count for the guard to hold (inclusive).
    pub expected_min: u64,
    /// Maximum affected-row count for the guard to hold (inclusive), or
    /// `None` for "no upper bound" (e.g. a predicate-based rewire that may
    /// touch any number of rows).
    pub expected_max: Option<u64>,
}

impl AffectedRowGuard {
    /// A guard requiring exactly `n` affected rows (the common case for a
    /// single-target `update`/`delete`/`link` statement).
    pub fn exactly(n: u64) -> Self {
        Self {
            expected_min: n,
            expected_max: Some(n),
        }
    }

    /// A guard requiring at least one affected row and no upper bound (the
    /// shape for a predicate-based rewire that may touch any number of rows,
    /// e.g. `merge`'s edge rewire).
    pub fn at_least_one() -> Self {
        Self {
            expected_min: 1,
            expected_max: None,
        }
    }

    /// Whether an observed affected-row count satisfies this guard.
    pub fn holds_for(&self, affected: u64) -> bool {
        affected >= self.expected_min
            && self.expected_max.map(|max| affected <= max).unwrap_or(true)
    }
}

/// A deferred side effect recorded during prepare and run once, after the
/// atomic unit commits (ADR-099 D1, "post-commit pass"). v1's admissible set
/// computes no embeddings during prepare (D3's `update`/`merge` caveat), so
/// the only post-commit effects are reindex kicks computed from the
/// **committed** row content, plus the GAP-5 addition under B3: the
/// best-effort GTD lifecycle audit row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PostCommitEffect {
    /// No deferred side effect for this op.
    None,
    /// Re-embed and re-warm the given entity's vector row from its committed
    /// content (ADR-099 D3 `update` caveat: entity name/description change).
    ReindexEntity { entity_id: Uuid },
    /// Re-embed and re-warm the given note's vector row from its committed
    /// content (ADR-099 D3 `update` caveat: note name/content change).
    ReindexNote { note_id: Uuid, version: i64 },
    /// Invalidate consumers without recreating explicitly removed vectors.
    NoteChanged { note_id: Uuid, kind: String },
    /// Append one `gtd_lifecycle_audit` row for a committed `gtd.transition`
    /// or `gtd.complete` (ADR-099 B3, GAP-5): canonical `handle_transition`/
    /// `handle_complete` call `ensure_audit_schema` +
    /// `write_audit_record_with_status`
    /// (`khive-pack-gtd::handlers`) as a best-effort side write — a failed
    /// audit insert must never roll back an already-committed transition.
    /// Carries exactly the fields the lifecycle-audit helper needs. Applied
    /// outside `khive-runtime` (crate-direction: `khive-pack-gtd` depends on
    /// `khive-runtime`, not the other way around) — this crate's own
    /// `apply_post_commit_effects` treats this variant as a no-op; the
    /// `kkernel` caller that owns both crates applies it by calling the
    /// canonical `ensure_audit_schema`/`write_audit_record_with_status`
    /// functions
    /// directly.
    GtdAudit {
        task_id: Uuid,
        from_status: String,
        to_status: String,
        note: Option<String>,
        namespace: String,
    },
    /// A committed note delete (soft or hard) — fire the pack-installed
    /// note-mutation hook with the deleted note's kind (#750:
    /// `DeletePlan` previously carried no `post_commit`
    /// slot at all, so an atomic note delete never reached
    /// `KhiveRuntime::fire_note_mutation_hook`, unlike `operations.rs`'s
    /// `delete_note`, which fires it directly after a successful row
    /// delete). Entity deletes have no equivalent — the hook system is
    /// note-only (`khive-pack-memory`'s warm ANN cache is the only
    /// installed consumer today).
    NoteDeleted { note_id: Uuid, kind: String },
}

/// The natural key a committed symmetric edge update's surviving row must
/// be looked up by (ADR-099 B3, second
/// half). `khive-db`'s `edge_symmetric_absorb_or_update_inplace_statement`
/// pair never trusts a prepare-time-computed target id (see that builder's
/// doc comment); a caller rendering this op's result derives the actual
/// surviving id by querying `graph_edges`'s own
/// `UNIQUE(namespace, source_id, target_id, relation)` constraint via
/// `KhiveRuntime::get_edge_by_natural_key_including_deleted`, which — unlike
/// `list_edges` — includes soft-deleted rows: the ADR-039 DO NOTHING absorption
/// arm can commit leaving the surviving canonical row tombstoned
/// (khive#1213/#1214), and `list_edges` would report "not found" for exactly
/// that row. Looked up strictly after commit.
#[derive(Debug, Clone)]
pub struct EdgeNaturalKey {
    pub(crate) namespace: String,
    pub(crate) canon_source_id: Uuid,
    pub(crate) canon_target_id: Uuid,
    pub(crate) relation: khive_storage::EdgeRelation,
}

impl EdgeNaturalKey {
    /// The namespace containing the surviving edge.
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// The canonical source endpoint of the surviving edge.
    pub fn canon_source_id(&self) -> Uuid {
        self.canon_source_id
    }

    /// The canonical target endpoint of the surviving edge.
    pub fn canon_target_id(&self) -> Uuid {
        self.canon_target_id
    }

    /// The surviving edge's relation.
    pub fn relation(&self) -> khive_storage::EdgeRelation {
        self.relation
    }
}

/// Write plan for an `update` op (entity or note shape — ADR-099 D3's
/// `update` caveat covers both substrates the same way: row/FTS DML in the
/// plan, any reindex deferred to `post_commit`).
///
/// Deferred effects are assigned by this crate's prepare pass and cannot be
/// supplied by callers constructing a plan directly:
///
/// ```compile_fail
/// use khive_runtime::{PostCommitEffect, UpdatePlan};
/// use uuid::Uuid;
///
/// let id = Uuid::nil();
/// let plan = UpdatePlan {
///     target_id: id,
///     statements: Vec::new(),
///     post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
///     edge_natural_key: None,
///     idempotent_noop: false,
/// };
/// ```
///
/// A plan returned by a prepare function cannot have its validated
/// statements cleared or replaced before it reaches the runner:
///
/// ```compile_fail
/// use khive_runtime::UpdatePlan;
///
/// fn clear_prepared_statements(mut prepared: UpdatePlan) {
///     prepared.statements.clear();
/// }
/// ```
#[derive(Debug, Clone)]
pub struct UpdatePlan {
    /// The id of the entity or note being updated. For a symmetric edge
    /// update this is the CALLER's requested id — advisory only, never the
    /// basis for post-commit result rendering (see [`EdgeNaturalKey`]).
    pub(crate) target_id: Uuid,
    /// Row + FTS DML statements to apply inside the atomic unit, in order.
    /// The row-update statement carries the existence guard; any FTS-mirror
    /// statement that follows it is unguarded (its target row's existence
    /// was already asserted by the row-update statement's own guard).
    pub(crate) statements: Vec<PlanStatement>,
    /// Deferred reindex assigned by the prepare pass when the update changed
    /// name, description, or content.
    pub(crate) post_commit: PostCommitEffect,
    /// `Some` only for a symmetric edge update — the natural key a caller
    /// must use to derive the committed surviving row post-commit, rather
    /// than trusting `target_id`. `None` for every other update shape
    /// (entity, note, non-symmetric edge), where `target_id` alone is
    /// already an exact, non-advisory identifier.
    pub(crate) edge_natural_key: Option<EdgeNaturalKey>,
    /// True for a note patch whose normalized values already equal the
    /// snapshot. Such plans carry a guarded SELECT assertion and must not
    /// execute DML that would advance the note revision.
    pub(crate) idempotent_noop: bool,
    pub(crate) entity_guard: Option<crate::entity_write::EntityWriteGuard>,
    pub(crate) note_guard: Option<crate::note_write::NoteWriteGuard>,
    pub(crate) note_vector_purge: Option<crate::note_write::NoteVectors>,
    pub(crate) note_embedding_inheritance: Option<crate::note_write::NoteEmbeddingInheritance>,
    /// Typed kind-owned graph operations, applied after the note statements in
    /// the same savepoint. Assertions never execute as writes.
    pub(crate) graph_effects: Vec<NoteUpdateStatement>,
}

/// Only runtime preparation can append these to an update. Packs return typed
/// graph requests, not SQL or execution flags.
#[derive(Debug, Clone)]
pub(crate) enum NoteUpdateStatement {
    Write(PlanStatement),
    Assert(PlanStatement),
}

impl UpdatePlan {
    /// The record id supplied to the prepare pass.
    pub fn target_id(&self) -> Uuid {
        self.target_id
    }

    /// The committed lookup key required for a symmetric edge update.
    pub fn edge_natural_key(&self) -> Option<&EdgeNaturalKey> {
        self.edge_natural_key.as_ref()
    }

    /// The potential deferred effect. The writer resolves inherited embedding
    /// membership before issuing the committed-effects token.
    pub fn post_commit(&self) -> &PostCommitEffect {
        &self.post_commit
    }

    /// Whether this plan is a mutation-free note update assertion.
    pub fn is_idempotent_noop(&self) -> bool {
        self.idempotent_noop
    }
}

/// Write plan for an `AddEntity` proposal change: a fresh entity row plus its
/// FTS document in the same atomic unit. Vector indexing remains a deferred
/// effect because embedding may suspend.
#[derive(Debug, Clone)]
pub struct AddEntityPlan {
    /// The freshly generated id of the entity being created.
    pub(crate) entity_id: Uuid,
    /// Row + FTS insert statements to apply inside the atomic unit, in
    /// order. The row-insert statement carries the existence guard; the
    /// FTS-insert statement that follows it is unguarded (an ordinary
    /// `INSERT` into a virtual table with no conflicting row).
    pub(crate) statements: Vec<PlanStatement>,
    /// Reindex the committed entity after the transaction closes, as
    /// assigned by the prepare pass.
    pub(crate) post_commit: PostCommitEffect,
}

impl AddEntityPlan {
    /// The id generated for the prepared entity.
    pub fn entity_id(&self) -> Uuid {
        self.entity_id
    }
}

/// Write plan for an `AddNote` proposal change: a fresh note row plus its FTS
/// document in the same atomic unit.
#[derive(Debug, Clone)]
pub struct AddNotePlan {
    /// The freshly generated id of the note being created.
    pub(crate) note_id: Uuid,
    pub(crate) note_guard: Option<crate::note_write::NoteWriteGuard>,
    /// Row + FTS insert statements to apply inside the atomic unit, in
    /// order, mirroring [`AddEntityPlan::statements`].
    pub(crate) statements: Vec<PlanStatement>,
    /// Reindex the committed note after the transaction closes, as assigned
    /// by the prepare pass.
    pub(crate) post_commit: PostCommitEffect,
}

impl AddNotePlan {
    /// The id generated for the prepared note.
    pub fn note_id(&self) -> Uuid {
        self.note_id
    }
}

/// Write plan for a `delete` op (soft or hard).
///
/// Deferred effects are assigned by this crate's prepare pass and cannot be
/// attached to a statement-free plan by external callers:
///
/// ```compile_fail
/// use khive_runtime::{DeletePlan, PostCommitEffect};
/// use uuid::Uuid;
///
/// let id = Uuid::nil();
/// let plan = DeletePlan {
///     target_id: id,
///     statements: Vec::new(),
///     post_commit: PostCommitEffect::NoteDeleted {
///         note_id: id,
///         kind: "observation".to_owned(),
///     },
/// };
/// ```
#[derive(Debug, Clone)]
pub struct DeletePlan {
    /// The id of the entity or note being deleted.
    pub(crate) target_id: Uuid,
    /// Row DML (and, for a hard delete, incident-edge cascade DML) to apply
    /// inside the atomic unit, in order. The target-row delete statement
    /// carries the existence guard; a cascade edge-delete statement (hard
    /// delete only) is unguarded — it may legitimately affect zero rows if
    /// the target had no incident edges.
    pub(crate) statements: Vec<PlanStatement>,
    /// Deferred note-mutation-hook fire assigned by the prepare pass for a
    /// note delete (#750 2). `PostCommitEffect::None` for entity and edge
    /// deletes — the hook system is note-only.
    pub(crate) post_commit: PostCommitEffect,
}

impl DeletePlan {
    /// The record id supplied to the prepare pass.
    pub fn target_id(&self) -> Uuid {
        self.target_id
    }
}

/// Write plan for a `link` op (create a typed directed edge). Endpoint
/// existence is checked **structurally**, not via an unanchored plan-level
/// guard: `statement` is a guarded `INSERT ... SELECT ... WHERE EXISTS`
/// shape whose `SELECT` re-probes both endpoints inside the transaction, so
/// the runner's affected-row check on this one statement *is* the
/// in-transaction existence probe (ADR-099 acceptance criteria's
/// dangling-edge case — `[delete(X, hard), link(A, X)]` — is closed by this
/// guard failing once X is gone, regardless of statement ordering
/// convention).
#[derive(Debug, Clone)]
pub struct LinkPlan {
    pub(crate) source_id: Uuid,
    pub(crate) target_id: Uuid,
    /// Guarded edge mutation followed by its event-plane append statements.
    /// The first statement's affected-row count is also the endpoint and
    /// compare-and-swap probe; event statements are reached only after it
    /// succeeds.
    pub(crate) statements: Vec<PlanStatement>,
    /// Prepare-time disposition, protected by the first statement's guard.
    pub(crate) disposition: khive_storage::EdgeUpsertDisposition,
}

impl LinkPlan {
    /// The canonical source endpoint used by the prepared statement.
    pub fn source_id(&self) -> Uuid {
        self.source_id
    }

    /// The canonical target endpoint used by the prepared statement.
    pub fn target_id(&self) -> Uuid {
        self.target_id
    }

    /// Whether this atomic link created, replaced, or explicitly resurrected
    /// its natural-key row.
    pub fn disposition(&self) -> khive_storage::EdgeUpsertDisposition {
        self.disposition
    }
}

/// Write plan for a `merge` op (deduplicate two entities). Rewires and
/// lifecycle writes are split into separate fields precisely so a guard is
/// never ambiguous between them: the edge rewire is **predicate-based**
/// (ADR-099 D1 rule 1) and may touch zero or many rows depending on earlier
/// in-file writes, so it is never guarded; the `from`/`into` entity
/// lifecycle write assumes both rows exist, so it always is.
#[derive(Debug, Clone)]
pub struct MergePlan {
    pub(crate) into_id: Uuid,
    pub(crate) from_id: Uuid,
    /// Predicate-based edge-rewire statement(s)
    /// (`UPDATE graph_edges SET source_id = :into WHERE source_id = :from`-
    /// shaped), evaluated inside the transaction so they structurally see
    /// any earlier op's edge writes in the same file (ADR-099 acceptance
    /// criteria: "merge rewires see earlier in-file writes"). Never
    /// guarded — a rewire touching zero rows is a legitimate outcome.
    pub(crate) rewires: Vec<PlanPredicate>,
    /// The `from` entity's soft-delete/tombstone DML (and any other
    /// lifecycle write prepare assumed a target row exists for). Always
    /// guarded — prepare validated `into`/`from` both exist.
    pub(crate) lifecycle: Vec<PlanStatement>,
}

impl MergePlan {
    /// The entity retained by the prepared merge.
    pub fn into_id(&self) -> Uuid {
        self.into_id
    }

    /// The entity retired by the prepared merge.
    pub fn from_id(&self) -> Uuid {
        self.from_id
    }
}

/// Write plan for a `gtd.transition` op (explicit task lifecycle change).
#[derive(Debug, Clone)]
pub struct GtdTransitionPlan {
    pub(crate) task_id: Uuid,
    /// Task-property DML to apply inside the atomic unit. Property-only status
    /// mutation triggers no reindex (ADR-099 D3). The transition
    /// statement carries the guard over the exact decision snapshot's note
    /// revision, deletion marker, and semantic status (prepare validated the
    /// current status and requested transition were legal). For an idempotent
    /// no-op (`current == target` after `normalize_status`) this contains one
    /// guarded SELECT assertion that revalidates the prepare snapshot
    /// under the commit transaction. Atomic v1 and canonical dispatch both
    /// persist no caller note.
    pub(crate) statements: Vec<PlanStatement>,
    /// Explicit result-shape and execution discriminator: true executes the
    /// snapshot assertion through the writer's read API and guards its result
    /// count; false executes DML and guards affected rows.
    pub(crate) idempotent_noop: bool,
    /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
    /// `PostCommitEffect::None` for the idempotent no-op case. This matches
    /// canonical dispatch, which emits no audit row for a same-status request.
    pub(crate) post_commit: PostCommitEffect,
}

impl GtdTransitionPlan {
    /// Build a plan from its already-decided statements, no-op classification,
    /// and audit effect.
    /// Callers outside this crate (e.g. the atomic-apply layer wiring
    /// `gtd.transition` into a multi-op unit) cannot construct the struct
    /// literal directly since its fields are crate-private.
    pub fn new(
        task_id: Uuid,
        statements: Vec<PlanStatement>,
        idempotent_noop: bool,
        post_commit: PostCommitEffect,
    ) -> Self {
        Self {
            task_id,
            statements,
            idempotent_noop,
            post_commit,
        }
    }

    /// The task targeted by the prepared transition.
    pub fn task_id(&self) -> Uuid {
        self.task_id
    }

    /// Guarded task-property DML for this transition, or the guarded
    /// mutation-free snapshot assertion for an idempotent no-op.
    pub fn statements(&self) -> &[PlanStatement] {
        &self.statements
    }

    /// Whether prepare classified this transition as already at its target.
    pub fn is_idempotent_noop(&self) -> bool {
        self.idempotent_noop
    }

    /// The deferred lifecycle audit effect assigned by the prepare pass.
    pub fn post_commit(&self) -> &PostCommitEffect {
        &self.post_commit
    }
}

/// Write plan for a `gtd.complete` op (task lifecycle terminal transition).
#[derive(Debug, Clone)]
pub struct GtdCompletePlan {
    pub(crate) task_id: Uuid,
    /// Status + `completed_at` property DML to apply inside the atomic unit.
    /// The statement guards the exact decision snapshot's note revision,
    /// deletion marker, and semantic status after prepare validated that the
    /// task was in a completable state.
    pub(crate) statements: Vec<PlanStatement>,
    /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
    /// mirrors `handle_complete`'s best-effort
    /// `write_audit_record_with_status` call.
    pub(crate) post_commit: PostCommitEffect,
}

impl GtdCompletePlan {
    /// Build a plan from its already-decided statements and audit effect.
    /// Callers outside this crate (e.g. the atomic-apply layer wiring
    /// `gtd.complete` into a multi-op unit) cannot construct the struct
    /// literal directly since its fields are crate-private.
    pub fn new(
        task_id: Uuid,
        statements: Vec<PlanStatement>,
        post_commit: PostCommitEffect,
    ) -> Self {
        Self {
            task_id,
            statements,
            post_commit,
        }
    }

    /// The task targeted by the prepared completion.
    pub fn task_id(&self) -> Uuid {
        self.task_id
    }

    /// Guarded status + `completed_at` property DML for this completion.
    pub fn statements(&self) -> &[PlanStatement] {
        &self.statements
    }

    /// The deferred lifecycle audit effect assigned by the prepare pass.
    pub fn post_commit(&self) -> &PostCommitEffect {
        &self.post_commit
    }
}

/// Which governance verb (`propose` / `review` / `withdraw`) a
/// [`GovernancePlan`] applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GovernanceOp {
    Propose,
    Review,
    Withdraw,
}

/// Write plan for a governance op (`propose`, `review`, or `withdraw` — the
/// event-sourced change-proposal lifecycle, ADR-046).
#[derive(Debug, Clone)]
pub struct GovernancePlan {
    pub(crate) op: GovernanceOp,
    pub(crate) proposal_id: Uuid,
    /// Event-log + status DML to apply inside the atomic unit. The
    /// lifecycle-state-check statement carries the guard (prepare validated
    /// the proposal was in a state admitting this transition).
    pub(crate) statements: Vec<PlanStatement>,
}

impl GovernancePlan {
    /// The governance operation represented by this plan.
    pub fn op(&self) -> GovernanceOp {
        self.op
    }

    /// The proposal targeted by this plan.
    pub fn proposal_id(&self) -> Uuid {
        self.proposal_id
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn stmt(label: &str) -> SqlStatement {
        SqlStatement {
            sql: "UPDATE t SET x = ? WHERE id = ?".to_string(),
            params: vec![],
            label: Some(label.to_string()),
        }
    }

    fn guarded(label: &str, guard: AffectedRowGuard) -> PlanStatement {
        PlanStatement {
            statement: stmt(label),
            guard: Some(guard),
        }
    }

    fn unguarded(label: &str) -> PlanStatement {
        PlanStatement {
            statement: stmt(label),
            guard: None,
        }
    }

    #[test]
    fn affected_row_guard_exactly_holds_only_for_n() {
        let g = AffectedRowGuard::exactly(1);
        assert!(!g.holds_for(0));
        assert!(g.holds_for(1));
        assert!(!g.holds_for(2));
    }

    #[test]
    fn affected_row_guard_at_least_one_has_no_upper_bound() {
        let g = AffectedRowGuard::at_least_one();
        assert!(!g.holds_for(0));
        assert!(g.holds_for(1));
        assert!(g.holds_for(1_000));
    }

    #[test]
    fn update_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
        let id = Uuid::new_v4();
        let plan = UpdatePlan {
            graph_effects: Vec::new(),
            entity_guard: None,
            note_guard: None,
            note_vector_purge: None,
            note_embedding_inheritance: None,
            target_id: id,
            statements: vec![
                guarded("update-row", AffectedRowGuard::exactly(1)),
                unguarded("update-fts-mirror"),
            ],
            post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
            edge_natural_key: None,
            idempotent_noop: false,
        };
        assert_eq!(plan.target_id, id);
        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
        assert_eq!(plan.statements[1].guard, None);
        assert_eq!(
            plan.post_commit,
            PostCommitEffect::ReindexEntity { entity_id: id }
        );
    }

    #[test]
    fn delete_plan_guard_is_anchored_to_the_target_row_not_the_cascade() {
        let plan = DeletePlan {
            target_id: Uuid::new_v4(),
            post_commit: PostCommitEffect::None,
            statements: vec![
                guarded("delete-row", AffectedRowGuard::exactly(1)),
                unguarded("cascade-edges"),
            ],
        };
        let row_guard = plan.statements[0].guard.expect("row delete is guarded");
        assert!(row_guard.holds_for(1));
        assert!(!row_guard.holds_for(0));
        assert_eq!(plan.statements[1].guard, None);
    }

    #[test]
    fn link_plan_guard_is_the_endpoint_existence_probe_itself() {
        let source = Uuid::new_v4();
        let target = Uuid::new_v4();
        let plan = LinkPlan {
            source_id: source,
            target_id: target,
            statements: vec![guarded(
                "insert-edge-where-exists",
                AffectedRowGuard::exactly(1),
            )],
            disposition: khive_storage::EdgeUpsertDisposition::Created,
        };
        assert_eq!(plan.source_id, source);
        assert_eq!(plan.target_id, target);
        // Dangling-edge acceptance criterion: once an endpoint row is gone,
        // the guarded INSERT...WHERE EXISTS affects 0 rows and the guard
        // on *that exact statement* must fail, not silently pass.
        let guard = plan.statements[0].guard.expect("link insert is guarded");
        assert!(!guard.holds_for(0));
    }

    #[test]
    fn merge_plan_rewires_are_never_guarded_lifecycle_writes_always_are() {
        let into = Uuid::new_v4();
        let from = Uuid::new_v4();
        let rewire = PlanPredicate {
            description: "source_id = :from".to_string(),
            statement: SqlStatement {
                sql: "UPDATE graph_edges SET source_id = ? WHERE source_id = ?".to_string(),
                params: vec![],
                label: Some("merge-rewire".to_string()),
            },
        };
        let plan = MergePlan {
            into_id: into,
            from_id: from,
            rewires: vec![rewire],
            lifecycle: vec![guarded(
                "tombstone-from-entity",
                AffectedRowGuard::exactly(1),
            )],
        };
        assert_eq!(plan.into_id, into);
        assert_eq!(plan.from_id, from);
        assert_eq!(plan.rewires[0].description, "source_id = :from");
        // A predicate-based rewire may legitimately touch zero or many rows
        // depending on how many edges an earlier in-file op inserted — the
        // type carries no guard field for it at all.
        let lifecycle_guard = plan.lifecycle[0].guard.expect("lifecycle write is guarded");
        assert!(!lifecycle_guard.holds_for(0));
    }

    #[test]
    fn gtd_transition_plan_triggers_no_reindex_by_construction() {
        let plan = GtdTransitionPlan {
            task_id: Uuid::new_v4(),
            statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
            idempotent_noop: false,
            post_commit: PostCommitEffect::None,
        };
        // A status-only transition never triggers a reindex: the type has no
        // *reindex* post-commit variant to construct, only the best-effort
        // `GtdAudit` lifecycle-audit effect, which itself does no embedding work.
        assert_eq!(plan.statements.len(), 1);
        assert!(plan.statements[0].guard.is_some());
        assert_eq!(plan.post_commit, PostCommitEffect::None);
    }

    #[test]
    fn gtd_transition_plan_idempotent_noop_carries_guarded_assertion_and_no_audit() {
        // Atomic v1 keeps current == target mutation-free and audit-free, but
        // must revalidate the prepare snapshot in a multi-op unit. A canonical
        // no-op carrying a note has a separate note-event contract.
        let plan = GtdTransitionPlan {
            task_id: Uuid::new_v4(),
            statements: vec![guarded(
                "assert-noop-snapshot",
                AffectedRowGuard::exactly(1),
            )],
            idempotent_noop: true,
            post_commit: PostCommitEffect::None,
        };
        assert_eq!(plan.statements.len(), 1);
        assert!(plan.statements[0].guard.is_some());
        assert!(plan.is_idempotent_noop());
        assert_eq!(plan.post_commit, PostCommitEffect::None);
    }

    #[test]
    fn gtd_transition_plan_carries_gtd_audit_post_commit_effect() {
        let task_id = Uuid::new_v4();
        let plan = GtdTransitionPlan {
            task_id,
            statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
            idempotent_noop: false,
            post_commit: PostCommitEffect::GtdAudit {
                task_id,
                from_status: "inbox".to_string(),
                to_status: "next".to_string(),
                note: Some("handed off".to_string()),
                namespace: "local".to_string(),
            },
        };
        assert_eq!(
            plan.post_commit,
            PostCommitEffect::GtdAudit {
                task_id,
                from_status: "inbox".to_string(),
                to_status: "next".to_string(),
                note: Some("handed off".to_string()),
                namespace: "local".to_string(),
            }
        );
    }

    #[test]
    fn gtd_complete_plan_guards_the_single_snapshot_property_write() {
        let plan = GtdCompletePlan {
            task_id: Uuid::new_v4(),
            statements: vec![guarded(
                "update-status-and-completed-at",
                AffectedRowGuard::exactly(1),
            )],
            post_commit: PostCommitEffect::None,
        };
        assert_eq!(plan.statements.len(), 1);
        let guard = plan.statements[0]
            .guard
            .expect("snapshot property write is guarded");
        assert!(guard.holds_for(1));
    }

    #[test]
    fn governance_plan_covers_all_three_lifecycle_ops() {
        for op in [
            GovernanceOp::Propose,
            GovernanceOp::Review,
            GovernanceOp::Withdraw,
        ] {
            let plan = GovernancePlan {
                op,
                proposal_id: Uuid::new_v4(),
                statements: vec![guarded("governance-event", AffectedRowGuard::exactly(1))],
            };
            assert_eq!(plan.op, op);
            assert!(plan.statements[0].guard.is_some());
        }
    }

    #[test]
    fn add_entity_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
        let id = Uuid::new_v4();
        let plan = AddEntityPlan {
            entity_id: id,
            statements: vec![
                guarded("entity-insert", AffectedRowGuard::exactly(1)),
                unguarded("entity-fts-insert"),
            ],
            post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
        };
        assert_eq!(plan.entity_id, id);
        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
        assert_eq!(plan.statements[1].guard, None);
        assert_eq!(
            plan.post_commit,
            PostCommitEffect::ReindexEntity { entity_id: id }
        );
    }

    #[test]
    fn add_note_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
        let id = Uuid::new_v4();
        let plan = AddNotePlan {
            note_guard: None,
            note_id: id,
            statements: vec![
                guarded("note-insert", AffectedRowGuard::exactly(1)),
                unguarded("note-fts-insert"),
            ],
            post_commit: PostCommitEffect::ReindexNote {
                note_id: id,
                version: 1,
            },
        };
        assert_eq!(plan.note_id, id);
        assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
        assert_eq!(plan.statements[1].guard, None);
        assert_eq!(
            plan.post_commit,
            PostCommitEffect::ReindexNote {
                note_id: id,
                version: 1
            }
        );
    }

    #[test]
    fn plans_are_plain_data_no_async_no_embedding() {
        // Documents a compile-time property: every plan type above derives
        // only Debug/Clone/PartialEq, never Future or an embedding-provider
        // trait. Plans must stay inert data: flag any edit that adds an
        // async method or embedding-model field to one of these types.
        let _ = PostCommitEffect::None;
    }
}