Skip to main content

khive_runtime/
atomic_prepare.rs

1//! ADR-099: the per-verb async prepare pass for the KG-substrate v1
2//! admissible verbs (`update`, `delete`, `link`, `merge`), plus
3//! [`prepare_add_entity`]/[`prepare_add_note`] for the ADR-046 proposal
4//! changeset `AddEntity`/`AddNote` arms. Each `prepare_*` function reads
5//! current state (async, outside any transaction) and returns a plain-data
6//! [`crate::atomic_runner::AtomicOpPlan`] ([`crate::atomic_plan`]) for the
7//! synchronous commit pass ([`crate::atomic_runner::run_atomic_unit`]) to
8//! apply.
9//!
10//! `gtd.transition`/`gtd.complete` prepare is deliberately not here (lives in
11//! `kkernel` instead), and `propose`/`review`/`withdraw`/`merge` are on the
12//! v1 admissible list but have no working prepare implementation in this
13//! module (`prepare_governance_unimplemented` fails loudly rather than
14//! silently no-opping; `prepare_merge` is unreachable through `--atomic` and
15//! kept only for its own tests and as defense in depth). See
16//! `docs/api/atomic_prepare.md#scope-what-is-excluded-and-why` for why each of these is excluded
17//! and what would be required to admit them.
18
19use serde_json::Value;
20use uuid::Uuid;
21
22use khive_storage::types::SqlValue;
23use khive_storage::{EdgeRelation, SqlStatement};
24use khive_types::{EventKind, SubstrateKind};
25
26use crate::atomic_plan::{
27    AddEntityPlan, AddNotePlan, AffectedRowGuard, DeletePlan, EdgeNaturalKey, LinkPlan, MergePlan,
28    PlanStatement, PostCommitEffect, UpdatePlan,
29};
30use crate::atomic_runner::AtomicOpPlan;
31use crate::atomic_runner::CommittedPostCommitEffects;
32use crate::curation::{entity_fts_document, note_fts_document};
33use crate::error::{RuntimeError, RuntimeResult};
34use crate::operations::{
35    canonical_edge_endpoints, merge_dependency_kind, validate_edge_metadata, validate_edge_weight,
36    Resolved,
37};
38use crate::runtime::{KhiveRuntime, NamespaceToken};
39
40use khive_db::stores::entity::{
41    entity_hard_delete_statement, entity_soft_delete_statement, entity_upsert_statement,
42};
43use khive_db::stores::event::event_insert_statements;
44use khive_db::stores::event::hard_delete_lineage_warning_statements;
45use khive_db::stores::graph::{
46    edge_hard_delete_statement, edge_insert_guarded_by_endpoints_statement,
47    edge_soft_delete_statement, edge_symmetric_absorb_or_update_inplace_statement,
48    edge_symmetric_delete_if_conflict_statement, edge_upsert_statement,
49    purge_incident_edges_statement,
50};
51use khive_db::stores::note::{
52    note_hard_delete_statement, note_soft_delete_statement, note_upsert_statement,
53};
54use khive_db::stores::text::insert_document_statement;
55
56// ---------------------------------------------------------------------------
57// arg extraction helpers
58// ---------------------------------------------------------------------------
59
60fn obj(args: &Value) -> RuntimeResult<&serde_json::Map<String, Value>> {
61    args.as_object()
62        .ok_or_else(|| RuntimeError::InvalidInput("op args must be a JSON object".into()))
63}
64
65fn require_str<'a>(args: &'a Value, key: &str) -> RuntimeResult<&'a str> {
66    obj(args)?
67        .get(key)
68        .and_then(|v| v.as_str())
69        .ok_or_else(|| RuntimeError::InvalidInput(format!("missing required field {key:?}")))
70}
71
72fn require_uuid(args: &Value, key: &str) -> RuntimeResult<Uuid> {
73    let raw = require_str(args, key)?;
74    Uuid::parse_str(raw)
75        .map_err(|_| RuntimeError::InvalidInput(format!("{key} must be a full UUID; got {raw:?}")))
76}
77
78fn optional_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
79    obj(args).ok()?.get(key).and_then(|v| v.as_str())
80}
81
82fn optional_create_string(args: &Value, key: &str) -> RuntimeResult<Option<String>> {
83    match obj(args)?.get(key) {
84        None | Some(Value::Null) => Ok(None),
85        Some(Value::String(value)) => Ok(Some(value.clone())),
86        Some(other) => Err(RuntimeError::InvalidInput(format!(
87            "{key} must be a string or null, got: {other}"
88        ))),
89    }
90}
91
92/// Nullable-string patch semantics mirroring the actually-reachable behavior
93/// of `khive-pack-kg::handlers::common::optional_string_patch`/
94/// `description_patch`, reimplemented here rather than imported (that
95/// module has no dependency edge back to `khive-runtime`). Canonical's field
96/// type is `Option<Value>` (`UpdateParams.name`/`.description`); serde_json's
97/// derived `Deserialize` for `Option<T>` intercepts a literal JSON `null` at
98/// the outer `Option` boundary and maps it straight to Rust `None`
99/// regardless of the inner type, so canonical's own "clear" arm is
100/// unreachable through normal struct deserialization: `update(name=null)` /
101/// `update(description=null)` are no-ops, not clears. This module reads raw,
102/// un-deserialized JSON, so it must replicate that collapse explicitly: key
103/// absent OR JSON `null` -> `None` (leave unchanged, no-op); key present as a
104/// string -> `Some(Some(s))` (set); any other JSON type -> a hard error.
105fn optional_string_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<String>>> {
106    match obj(args)?.get(key) {
107        None | Some(Value::Null) => Ok(None),
108        Some(Value::String(s)) => Ok(Some(Some(s.clone()))),
109        Some(other) => Err(RuntimeError::InvalidInput(format!(
110            "{key} must be a string or null, got: {other}"
111        ))),
112    }
113}
114
115/// Strict string-or-absent-or-null patch for entity `name`. Unlike
116/// `optional_str`'s `.as_str()`, this does not silently drop a non-string,
117/// non-null value like `name: 123` as absent: it rejects it instead of
118/// reporting success for an invalid update. Canonical validates entity
119/// `name` via `string_value` on `UpdateParams.name: Option<Value>`: null
120/// collapses to absent at the struct-deserialize boundary (see
121/// `optional_string_patch` doc above), so the reachable behavior is:
122/// absent/null -> unchanged; non-null string -> set; any other JSON type ->
123/// hard error. This mirrors that exactly, reading raw JSON instead of a
124/// deserialized struct.
125fn entity_name_patch(args: &Value) -> RuntimeResult<Option<String>> {
126    match obj(args)?.get("name") {
127        None | Some(Value::Null) => Ok(None),
128        Some(Value::String(s)) => Ok(Some(s.clone())),
129        Some(other) => Err(RuntimeError::InvalidInput(format!(
130            "name must be a string, got: {other}"
131        ))),
132    }
133}
134
135/// Nullable-JSON-value patch for `properties`: canonical
136/// `properties: Option<Value>` on `UpdateParams` collapses a literal JSON
137/// `null` to Rust `None` at the struct-deserialize boundary (same collapse
138/// as `optional_string_patch` above), so `properties=null` is canonically a
139/// no-op (leave existing properties unchanged): not a stored JSON `null`.
140/// This module reads raw JSON, so it must replicate that collapse: key
141/// absent OR JSON `null` -> `None` (no merge); any other JSON value ->
142/// `Some(value)` (merge), with no further shape validation at this layer.
143fn optional_properties(args: &Value, key: &str) -> RuntimeResult<Option<Value>> {
144    match obj(args)?.get(key) {
145        None | Some(Value::Null) => Ok(None),
146        Some(v) => Ok(Some(v.clone())),
147    }
148}
149
150/// `tags` patch: canonical `tags: Option<Vec<String>>` on `UpdateParams`
151/// collapses a literal JSON `null` to Rust `None` at the struct-deserialize
152/// boundary (same collapse as above), so `tags=null` is canonically a no-op
153/// (leave existing tags unchanged). A non-array, non-null value is still a
154/// hard error (mirrors the type failure `UpdateParams` deserialization would
155/// itself produce for a malformed `tags`).
156fn optional_tags(args: &Value) -> RuntimeResult<Option<Vec<String>>> {
157    match obj(args)?.get("tags") {
158        None | Some(Value::Null) => Ok(None),
159        Some(Value::Array(items)) => {
160            let mut tags = Vec::with_capacity(items.len());
161            for item in items {
162                let s = item.as_str().ok_or_else(|| {
163                    RuntimeError::InvalidInput("tags must be an array of strings".into())
164                })?;
165                tags.push(s.to_string());
166            }
167            Ok(Some(tags))
168        }
169        Some(_) => Err(RuntimeError::InvalidInput(
170            "tags must be an array of strings".into(),
171        )),
172    }
173}
174
175fn optional_f64(args: &Value, key: &str) -> RuntimeResult<Option<f64>> {
176    match obj(args)?.get(key) {
177        None => Ok(None),
178        Some(Value::Null) => Ok(None),
179        Some(v) => v
180            .as_f64()
181            .map(Some)
182            .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
183    }
184}
185
186/// Tri-state patch extraction for `Option<Option<f64>>`-shaped fields
187/// (`NotePatch::salience` / `NotePatch::decay_factor`): key absent -> `None`
188/// (untouched), key present as JSON `null` -> `Some(None)` (clear), key
189/// present as a number -> `Some(Some(v))` (set). Range validation lives in
190/// curation.rs's `prepare_update_note`, not here.
191fn optional_f64_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<f64>>> {
192    match obj(args)?.get(key) {
193        None => Ok(None),
194        Some(Value::Null) => Ok(Some(None)),
195        Some(v) => v
196            .as_f64()
197            .map(|f| Some(Some(f)))
198            .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
199    }
200}
201
202/// Every registered embedding model's vector table name, in the exact format
203/// `curation::merge_entity_sql` uses (`"vec_{sanitize_key(model_name)}"`) —
204/// reused here so atomic delete/merge purge the same tables the non-atomic
205/// paths do.
206fn vector_table_names(runtime: &KhiveRuntime) -> Vec<String> {
207    runtime
208        .registered_embedding_model_names()
209        .iter()
210        .map(|name| format!("vec_{}", crate::config::sanitize_key(name)))
211        .collect()
212}
213
214/// A guarded (`guard: None` — best-effort mirror, matching the non-atomic
215/// index-cleanup calls which don't assert a row existed) `DELETE` statement
216/// against one FTS or vector table for a single subject, scoped by namespace.
217fn purge_index_row_statement(
218    table: &str,
219    namespace: &str,
220    subject_id: Uuid,
221    label: &str,
222) -> PlanStatement {
223    PlanStatement {
224        statement: SqlStatement {
225            sql: format!("DELETE FROM {table} WHERE namespace = ?1 AND subject_id = ?2"),
226            params: vec![
227                SqlValue::Text(namespace.to_string()),
228                SqlValue::Text(subject_id.to_string()),
229            ],
230            label: Some(label.to_string()),
231        },
232        guard: None,
233    }
234}
235
236fn log_vector_row_delete_statement(
237    table: &str,
238    namespace: &str,
239    subject_id: Uuid,
240    label: &str,
241) -> PlanStatement {
242    PlanStatement {
243        statement: SqlStatement {
244            sql: format!(
245                "INSERT INTO ann_write_log \
246                 (namespace, embedding_model, kind, field, subject_id, op) \
247                 SELECT namespace, embedding_model, kind, field, subject_id, 'delete' \
248                 FROM {table} WHERE namespace = ?1 AND subject_id = ?2"
249            ),
250            params: vec![
251                SqlValue::Text(namespace.to_string()),
252                SqlValue::Text(subject_id.to_string()),
253            ],
254            label: Some(label.to_string()),
255        },
256        guard: None,
257    }
258}
259
260/// `true` iff a table named `table` currently exists in the backing SQLite
261/// database (`sqlite_master` probe, read-only — safe in async prepare, does
262/// NOT open/create the vector store, so it cannot lazily create the table
263/// itself).
264async fn vector_table_exists(runtime: &KhiveRuntime, table: &str) -> RuntimeResult<bool> {
265    let mut reader = runtime
266        .sql()
267        .reader()
268        .await
269        .map_err(RuntimeError::Storage)?;
270    let row = reader
271        .query_scalar(SqlStatement {
272            sql: "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1".to_string(),
273            params: vec![SqlValue::Text(table.to_string())],
274            label: Some("atomic-delete-vec-table-exists".to_string()),
275        })
276        .await
277        .map_err(RuntimeError::Storage)?;
278    Ok(row.is_some())
279}
280
281/// Append the FTS + every registered model's vector-row purge for `subject_id`
282/// (scoped to the RECORD's own namespace, matching `delete_entity`/
283/// `delete_note`'s `record_tok`/`record_ns` convention: not the caller
284/// token's namespace, per by-ID namespace-agnosticism) onto `statements`.
285///
286/// FTS tables (`fts_entities`/`fts_notes`) always exist (created at schema
287/// migration time) so their purge is unconditional. `vec_*` tables are
288/// created lazily on first vector-store open, so a default runtime can
289/// register embedding models before any vector table necessarily exists:
290/// a raw unconditional `DELETE FROM vec_*` can hit `no such table` on a
291/// fresh DB. Only push the vec purge for tables that actually exist:
292/// absence means the record definitionally has no vector row for that
293/// model, so skipping is data-parity-correct (the non-atomic path would
294/// lazily create the table then delete zero rows: same data outcome,
295/// without this read-only prepare pass performing an init side effect).
296async fn push_index_purge_statements(
297    runtime: &KhiveRuntime,
298    statements: &mut Vec<PlanStatement>,
299    fts_table: &str,
300    namespace: &str,
301    subject_id: Uuid,
302    label_prefix: &str,
303) -> RuntimeResult<()> {
304    statements.push(purge_index_row_statement(
305        fts_table,
306        namespace,
307        subject_id,
308        &format!("{label_prefix}-purge-fts"),
309    ));
310    for vec_table in vector_table_names(runtime) {
311        if vector_table_exists(runtime, &vec_table).await? {
312            statements.push(log_vector_row_delete_statement(
313                &vec_table,
314                namespace,
315                subject_id,
316                &format!("{label_prefix}-log-delete-vec-{vec_table}"),
317            ));
318            statements.push(purge_index_row_statement(
319                &vec_table,
320                namespace,
321                subject_id,
322                &format!("{label_prefix}-purge-vec-{vec_table}"),
323            ));
324        }
325    }
326    Ok(())
327}
328
329/// Event-store append parity for the canonical handlers that emit a
330/// lifecycle event after their row mutation: `update_entity` ->
331/// `EntityUpdated`, `delete_entity` -> `EntityDeleted`, `delete_note` ->
332/// `NoteDeleted`, `update_edge` -> `EdgeUpdated`, `delete_edge` ->
333/// `EdgeDeleted`. `update_note` and `link` append no event and must never
334/// call this. See `docs/api/atomic_prepare.md#event_append_statements` for why
335/// this is a `PlanStatement` rather than a `PostCommitEffect`.
336///
337/// Invariant: returned statements are unguarded — appended after the plan's
338/// own guarded row statement, so [`apply_plan`]'s stop-on-first-failure
339/// contract means they are only reached once that row mutation's guard has
340/// already held. Committing the event row atomically with the mutation it
341/// describes strengthens canonical's guarantee: the non-atomic handlers write
342/// the event in a separate transaction, ordered but not atomic with the row
343/// mutation.
344fn event_append_statements(
345    namespace: &str,
346    verb: &str,
347    kind: EventKind,
348    substrate: SubstrateKind,
349    target_id: Uuid,
350    payload: Value,
351) -> RuntimeResult<Vec<PlanStatement>> {
352    let event = khive_storage::event::Event::new(namespace.to_string(), verb, kind, substrate, "")
353        .with_target(target_id)
354        .with_payload(payload);
355    let statements = event_insert_statements(&event)
356        .map_err(|e| RuntimeError::Internal(format!("event_insert_statements: {e}")))?;
357    Ok(statements
358        .into_iter()
359        .map(|statement| PlanStatement {
360            statement,
361            guard: None,
362        })
363        .collect())
364}
365
366// ---------------------------------------------------------------------------
367// dispatch
368// ---------------------------------------------------------------------------
369
370/// Build the prepared [`AtomicOpPlan`] for one KG-substrate admissible op
371/// (`update`, `delete`, `link`, `merge`). Returns a loud [`RuntimeError`] for
372/// `propose`/`review`/`withdraw` (known scope gap, see module doc) and any
373/// other verb (the CLI boundary must reject those before calling this — a
374/// verb reaching here is either KG-substrate-admissible or a bug upstream).
375pub async fn prepare_op(
376    runtime: &KhiveRuntime,
377    token: &NamespaceToken,
378    tool: &str,
379    args: &Value,
380) -> RuntimeResult<AtomicOpPlan> {
381    match tool {
382        // `expected_kind: None` here — same reasoning as the `"delete"` arm
383        // below: callers that need `update(kind=...)` parity must resolve
384        // the kind spec themselves (it needs a `VerbRegistry`, unreachable
385        // from this crate: see `AtomicUpdateKind`'s doc comment) and call
386        // `prepare_update` directly with the resolved value; `kkernel`'s
387        // `--atomic` seam does exactly this and bypasses this dispatch arm.
388        // A caller reaching `prepare_op("update", ...)` without going
389        // through that seam gets kind-unchecked behavior.
390        "update" => prepare_update(runtime, token, args, None).await,
391        // `expected_kind: None` here — callers that need `delete(kind=...)`
392        // parity must resolve the kind spec themselves (it needs a
393        // `VerbRegistry`, unreachable from this crate: see
394        // `AtomicDeleteKind`'s doc comment) and call `prepare_delete`
395        // directly with the resolved value; `kkernel`'s `--atomic` seam does
396        // exactly this and bypasses this dispatch arm. A caller reaching
397        // `prepare_op("delete", ...)` without going through that seam gets
398        // kind-unchecked behavior.
399        "delete" => prepare_delete(runtime, token, args, None).await,
400        "link" => prepare_link(runtime, token, args).await,
401        "merge" => prepare_merge(runtime, token, args).await,
402        "propose" | "review" | "withdraw" => prepare_governance_unimplemented(tool),
403        other => Err(RuntimeError::InvalidInput(format!(
404            "{other:?} has no atomic_prepare::prepare_op implementation; the CLI \
405             admissibility check should have rejected this before prepare"
406        ))),
407    }
408}
409
410fn prepare_governance_unimplemented(tool: &str) -> RuntimeResult<AtomicOpPlan> {
411    Err(RuntimeError::InvalidInput(format!(
412        "{tool:?} is on the ADR-099 v1 admissible verb list but has no --atomic \
413         prepare/apply implementation yet: its lifecycle (ADR-046) is an \
414         event-sourced changeset-interpreter over a dedicated `proposals_open` \
415         table, not a small guarded-DML plan — a faithful non-stub atomic \
416         prepare for it is tracked as ADR-099 follow-up work, not implemented \
417         in slice B3. No write was attempted."
418    )))
419}
420
421// ---------------------------------------------------------------------------
422// create (AddEntity / AddNote)
423// ---------------------------------------------------------------------------
424
425/// Build the prepared plan for an `AddEntity` proposal change. The entity
426/// row and FTS document are committed together; vector indexing is deferred
427/// until after commit because embedding may suspend. `kind` must already be
428/// canonicalized by the caller because pack-aware resolution requires a
429/// `VerbRegistry`.
430pub async fn prepare_add_entity(
431    runtime: &KhiveRuntime,
432    token: &NamespaceToken,
433    args: &Value,
434) -> RuntimeResult<AtomicOpPlan> {
435    let kind = require_str(args, "kind")?;
436    let name = require_str(args, "name")?;
437    runtime.validate_entity_kind(kind)?;
438    if name.trim().is_empty() {
439        return Err(RuntimeError::InvalidInput(
440            "name must not be empty".to_string(),
441        ));
442    }
443
444    let description = optional_create_string(args, "description")?;
445    let properties = optional_properties(args, "properties")?;
446    let tags = optional_tags(args)?.unwrap_or_default();
447
448    crate::secret_gate::check(name)?;
449    if let Some(ref d) = description {
450        crate::secret_gate::check(d)?;
451    }
452    if let Some(ref p) = properties {
453        crate::secret_gate::check_json(p)?;
454    }
455    crate::secret_gate::check_tags(&tags)?;
456
457    let ns = token.namespace().as_str();
458    let mut entity = khive_storage::Entity::new(ns, kind, name);
459    if let Some(d) = description {
460        entity = entity.with_description(d);
461    }
462    if let Some(p) = properties {
463        entity = entity.with_properties(p);
464    }
465    if !tags.is_empty() {
466        entity = entity.with_tags(tags);
467    }
468
469    let statements = vec![
470        PlanStatement {
471            statement: entity_upsert_statement(&entity),
472            guard: Some(AffectedRowGuard::exactly(1)),
473        },
474        PlanStatement {
475            statement: insert_document_statement("fts_entities", &entity_fts_document(&entity)),
476            guard: None,
477        },
478    ];
479
480    Ok(AtomicOpPlan::AddEntity(AddEntityPlan {
481        entity_id: entity.id,
482        statements,
483        post_commit: PostCommitEffect::ReindexEntity {
484            entity_id: entity.id,
485        },
486    }))
487}
488
489/// Build the prepared plan for an `AddNote` proposal change. Mirrors
490/// [`prepare_add_entity`]'s shape and the same
491/// `kind`-already-canonicalized split. `annotates` is out of scope: the
492/// proposal `NoteDraft` this backs carries no annotates targets, unlike
493/// `KhiveRuntime::create_note`'s general-purpose signature.
494pub async fn prepare_add_note(
495    runtime: &KhiveRuntime,
496    token: &NamespaceToken,
497    args: &Value,
498) -> RuntimeResult<AtomicOpPlan> {
499    let kind = require_str(args, "kind")?;
500    let content = require_str(args, "content")?;
501    runtime.validate_note_kind(kind)?;
502
503    let name = optional_create_string(args, "name")?;
504    let properties = optional_properties(args, "properties")?;
505
506    crate::secret_gate::check(content)?;
507    if let Some(ref n) = name {
508        crate::secret_gate::check(n)?;
509    }
510    if let Some(ref p) = properties {
511        crate::secret_gate::check_json(p)?;
512    }
513
514    let ns = token.namespace().as_str();
515    let mut note = khive_storage::note::Note::new(ns, kind, content);
516    if let Some(n) = name {
517        note = note.with_name(n);
518    }
519    if let Some(p) = properties {
520        note = note.with_properties(p);
521    }
522
523    let statements = vec![
524        PlanStatement {
525            statement: note_upsert_statement(&note),
526            guard: Some(AffectedRowGuard::exactly(1)),
527        },
528        PlanStatement {
529            statement: insert_document_statement("fts_notes", &note_fts_document(&note)),
530            guard: None,
531        },
532    ];
533
534    Ok(AtomicOpPlan::AddNote(AddNotePlan {
535        note_id: note.id,
536        statements,
537        post_commit: PostCommitEffect::ReindexNote { note_id: note.id },
538    }))
539}
540
541// ---------------------------------------------------------------------------
542// update
543// ---------------------------------------------------------------------------
544
545/// Mirrors `khive-pack-kg::handlers::update::reject_inapplicable_fields`: a
546/// hard `InvalidInput` when a caller passes a field that does not apply to
547/// the resolved substrate (e.g. `salience` on an entity, or
548/// `description`/`tags` on a note). That function has no dependency edge
549/// back to `khive-runtime`, so its exact field-applicability check list and
550/// error message shape are reimplemented here rather than imported: same
551/// pattern as `optional_string_patch` above. Presence is checked directly on
552/// the raw args object (this module has no `UpdateParams` struct); a JSON
553/// `null` value is treated as absent, matching `Option<T>` deserialization
554/// semantics.
555fn reject_inapplicable_update_fields(args: &Value, substrate: &str) -> RuntimeResult<()> {
556    let o = obj(args)?;
557    let present = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
558    let (bad_field, valid): (Option<&str>, &str) = match substrate {
559        "entity" => {
560            let bad = if present("content") {
561                Some("content")
562            } else if present("salience") {
563                Some("salience")
564            } else if present("decay_factor") {
565                Some("decay_factor")
566            } else if present("relation") {
567                Some("relation")
568            } else if present("weight") {
569                Some("weight")
570            } else {
571                None
572            };
573            (bad, "name, description, tags, properties")
574        }
575        "note" => {
576            let bad = if present("description") {
577                Some("description")
578            } else if present("tags") {
579                Some("tags")
580            } else if present("relation") {
581                Some("relation")
582            } else if present("weight") {
583                Some("weight")
584            } else {
585                None
586            };
587            (bad, "name, content, salience, decay_factor, properties")
588        }
589        // `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, so
590        // this arm must reject entity/note-only fields (e.g. `name`) on an
591        // edge update rather than silently skip the guard, mirroring
592        // `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
593        // `KindSpec::Edge` arm.
594        "edge" => {
595            let bad = if present("name") {
596                Some("name")
597            } else if present("description") {
598                Some("description")
599            } else if present("content") {
600                Some("content")
601            } else if present("tags") {
602                Some("tags")
603            } else if present("salience") {
604                Some("salience")
605            } else if present("decay_factor") {
606                Some("decay_factor")
607            } else {
608                None
609            };
610            (bad, "relation, weight, properties")
611        }
612        _ => (None, ""),
613    };
614    if let Some(field) = bad_field {
615        let substrate_label = match substrate {
616            "entity" => "an entity",
617            "note" => "a note",
618            "edge" => "an edge",
619            other => other,
620        };
621        return Err(RuntimeError::InvalidInput(format!(
622            "field '{field}' is not valid for {substrate_label}; valid fields: {valid}"
623        )));
624    }
625    Ok(())
626}
627
628/// Caller-supplied update-kind expectation, resolved via the canonical
629/// `resolve_kind_spec` at the kkernel `--atomic` seam: the same pattern
630/// [`AtomicDeleteKind`] uses. Without this check, `update(kind="document",
631/// id=<concept>)` would be canonically `NotFound` but the atomic path would
632/// ignore the explicit kind and mutate the resolved entity anyway.
633/// `khive-runtime` must not depend on `khive-pack-kg`, so this is a plain
634/// substrate-level shape rather than `khive_pack_kg::handlers::KindSpec`
635/// itself: the kkernel seam does the pack-aware resolution and passes down
636/// only what `prepare_update` needs to enforce the mismatch check.
637pub enum AtomicUpdateKind {
638    Entity { specific: Option<String> },
639    Note { specific: Option<String> },
640    Edge,
641}
642
643/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
644/// with canonical's own optional discriminator); `Some(_)` enforces an
645/// exact-parity mismatch check against the resolved record's actual
646/// substrate/specific kind, mirroring `handle_update`'s
647/// `entity.kind != *k` / note kind checks (update.rs:200-201, :229-234).
648pub async fn prepare_update(
649    runtime: &KhiveRuntime,
650    token: &NamespaceToken,
651    args: &Value,
652    expected_kind: Option<AtomicUpdateKind>,
653) -> RuntimeResult<AtomicOpPlan> {
654    let id = require_uuid(args, "id")?;
655
656    // Mirrors update.rs's entity_kind immutability guard: entity_kind is a
657    // legacy top-level field, independent of the `kind` substrate
658    // discriminator handled elsewhere.
659    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
660        return Err(RuntimeError::InvalidInput(
661            "entity_kind is immutable; to change kind, delete then re-create the entity, \
662             or use merge() if this is a deduplication correction"
663                .into(),
664        ));
665    }
666
667    match runtime.resolve_by_id(token, id).await? {
668        Some(Resolved::Entity(entity)) => {
669            match &expected_kind {
670                None => {}
671                Some(AtomicUpdateKind::Entity {
672                    specific: Some(expected),
673                }) if &entity.kind != expected => {
674                    return Err(RuntimeError::NotFound(format!("entity {id}")));
675                }
676                Some(AtomicUpdateKind::Entity { .. }) => {}
677                Some(AtomicUpdateKind::Note { .. }) => {
678                    return Err(RuntimeError::NotFound(format!("note {id}")));
679                }
680                Some(AtomicUpdateKind::Edge) => {
681                    return Err(RuntimeError::NotFound(format!("edge {id}")));
682                }
683            }
684            // Decide step lives in curation.rs's `prepare_update_entity` —
685            // the SAME function canonical `update_entity` calls. Only the
686            // arg-extraction (raw JSON -> `EntityPatch`) and the plan-shape
687            // wiring (domain object -> `PlanStatement` via the shared
688            // `entity_upsert_statement` builder) are atomic-path-specific.
689            reject_inapplicable_update_fields(args, "entity")?;
690            let name = entity_name_patch(args)?;
691            let description = optional_string_patch(args, "description")?;
692            let properties = optional_properties(args, "properties")?;
693            let tags = optional_tags(args)?;
694
695            prepare_update_entity_plan(
696                runtime,
697                token,
698                id,
699                crate::curation::EntityPatch {
700                    name,
701                    description,
702                    properties,
703                    tags,
704                },
705            )
706            .await
707        }
708        Some(Resolved::Note(note)) => {
709            match &expected_kind {
710                None => {}
711                Some(AtomicUpdateKind::Note {
712                    specific: Some(expected),
713                }) if &note.kind != expected => {
714                    return Err(RuntimeError::NotFound(format!("note {id}")));
715                }
716                Some(AtomicUpdateKind::Note { .. }) => {}
717                Some(AtomicUpdateKind::Entity { .. }) => {
718                    return Err(RuntimeError::NotFound(format!("entity {id}")));
719                }
720                Some(AtomicUpdateKind::Edge) => {
721                    return Err(RuntimeError::NotFound(format!("edge {id}")));
722                }
723            }
724            // Decide step lives in curation.rs's `prepare_update_note` — the
725            // same function canonical `update_note` calls, including the
726            // salience/decay_factor range validation. `optional_f64_patch`
727            // below preserves tri-state patch semantics (key absent =
728            // untouched, key null = clear, key present = set) when
729            // constructing the `NotePatch`.
730            reject_inapplicable_update_fields(args, "note")?;
731            let name = optional_string_patch(args, "name")?;
732            let content = optional_str(args, "content").map(|s| s.to_string());
733            let properties = optional_properties(args, "properties")?;
734            let salience = optional_f64_patch(args, "salience")?;
735            let decay_factor = optional_f64_patch(args, "decay_factor")?;
736
737            let (note, text_changed) = runtime
738                .prepare_update_note(
739                    token,
740                    id,
741                    crate::curation::NotePatch::new(
742                        name,
743                        content,
744                        salience,
745                        decay_factor,
746                        properties,
747                    ),
748                )
749                .await?;
750
751            let post_commit = if text_changed {
752                PostCommitEffect::ReindexNote { note_id: id }
753            } else {
754                PostCommitEffect::None
755            };
756            Ok(AtomicOpPlan::Update(UpdatePlan {
757                target_id: id,
758                statements: vec![PlanStatement {
759                    statement: note_upsert_statement(&note),
760                    guard: Some(AffectedRowGuard::exactly(1)),
761                }],
762                post_commit,
763                edge_natural_key: None,
764            }))
765        }
766        Some(_) => Err(RuntimeError::InvalidInput(format!(
767            "update target {id} must be an entity, note, or edge"
768        ))),
769        // `Resolved` (khive-runtime::operations) has no `Edge` variant — an
770        // id that isn't an entity/note/pack-private/event record is checked
771        // against the graph store directly, mirroring
772        // `khive-pack-kg::handlers::KgPack::infer_kind_from_uuid`'s own
773        // entity/note-then-edge fallback order. `update` admits
774        // `kind="edge"`, so this arm must be able to build a plan for one.
775        None => match &expected_kind {
776            Some(AtomicUpdateKind::Entity { .. }) => {
777                Err(RuntimeError::NotFound(format!("entity/note {id}")))
778            }
779            Some(AtomicUpdateKind::Note { .. }) => {
780                Err(RuntimeError::NotFound(format!("entity/note {id}")))
781            }
782            Some(AtomicUpdateKind::Edge) | None => match runtime.get_edge(token, id).await? {
783                Some(edge) => prepare_update_edge(runtime, id, edge, args).await,
784                None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
785            },
786        },
787    }
788}
789
790/// Build an entity update plan from a typed patch. Proposal changesets use
791/// this entry point so their explicit `description: null` clear operation is
792/// preserved instead of being collapsed by raw verb deserialization.
793pub async fn prepare_update_entity_plan(
794    runtime: &KhiveRuntime,
795    token: &NamespaceToken,
796    id: Uuid,
797    patch: crate::curation::EntityPatch,
798) -> RuntimeResult<AtomicOpPlan> {
799    let (entity, text_changed, changed_fields) =
800        runtime.prepare_update_entity(token, id, patch).await?;
801    let mut statements = vec![PlanStatement {
802        statement: entity_upsert_statement(&entity),
803        guard: Some(AffectedRowGuard::exactly(1)),
804    }];
805    statements.extend(event_append_statements(
806        &entity.namespace,
807        "update",
808        EventKind::EntityUpdated,
809        SubstrateKind::Entity,
810        id,
811        serde_json::json!({
812            "id": id,
813            "namespace": entity.namespace,
814            "changed_fields": changed_fields,
815        }),
816    )?);
817    let post_commit = if text_changed {
818        PostCommitEffect::ReindexEntity { entity_id: id }
819    } else {
820        PostCommitEffect::None
821    };
822    Ok(AtomicOpPlan::Update(UpdatePlan {
823        target_id: id,
824        statements,
825        post_commit,
826        edge_natural_key: None,
827    }))
828}
829
830/// Edge branch of `prepare_update`. Mirrors `KhiveRuntime::update_edge`'s
831/// patch semantics: `relation`/`weight`/`properties` are the only applicable
832/// fields, a changed `relation` is endpoint-validated first, `weight` is
833/// range-checked, and `properties` REPLACES `metadata` wholesale (no merge).
834/// See `docs/api/atomic_prepare.md#prepare_update_edge` for the DML-shape parity
835/// detail with `update_edge`.
836///
837/// Invariant (symmetric relations `competes_with`/`composed_with`): this
838/// function must never branch on a prepare-time conflict probe — a different
839/// op in the same atomic unit could change the conflict landscape between
840/// probe and commit, making any such branch stale by construction. It always
841/// emits BOTH statements from [`edge_symmetric_delete_if_conflict_statement`]
842/// and [`edge_symmetric_absorb_or_update_inplace_statement`], each carrying
843/// its own commit-time `WHERE`/`CASE WHEN` predicate that re-evaluates the
844/// conflict condition fresh inside the transaction. This function reads no
845/// state to guess a surviving id; the plan instead carries `edge_natural_key`
846/// so a post-commit caller derives the actual surviving id from the
847/// committed row, never from a value computed before the rest of this atomic
848/// unit has even run.
849async fn prepare_update_edge(
850    runtime: &KhiveRuntime,
851    id: Uuid,
852    mut edge: khive_storage::types::Edge,
853    args: &Value,
854) -> RuntimeResult<AtomicOpPlan> {
855    reject_inapplicable_update_fields(args, "edge")?;
856
857    let relation_raw = optional_str(args, "relation");
858    let weight = optional_f64(args, "weight")?;
859    let properties = optional_properties(args, "properties")?;
860
861    if let Some(ref p) = properties {
862        crate::secret_gate::check_json(p)?;
863    }
864
865    let namespace = edge.namespace.clone();
866    let record_tok = NamespaceToken::for_namespace(
867        khive_types::Namespace::parse(&namespace)
868            .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
869    );
870
871    let mut changed_fields: Vec<&'static str> = Vec::new();
872    if let Some(raw) = relation_raw {
873        let relation = parse_edge_relation(raw)?;
874        runtime
875            .validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, relation)
876            .await?;
877        edge.relation = relation;
878        changed_fields.push("relation");
879    }
880    if let Some(w) = weight {
881        if !w.is_finite() || !(0.0..=1.0).contains(&w) {
882            return Err(RuntimeError::InvalidInput(format!(
883                "edge weight must be a finite value in [0.0, 1.0]; got {w}"
884            )));
885        }
886        edge.weight = w;
887        changed_fields.push("weight");
888    }
889    if let Some(p) = properties {
890        edge.metadata = Some(p);
891        changed_fields.push("properties");
892    }
893
894    let (canon_src, canon_tgt) =
895        canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
896    let now = chrono::Utc::now();
897
898    let mut statements: Vec<PlanStatement> = Vec::new();
899    let mut edge_natural_key: Option<EdgeNaturalKey> = None;
900
901    if edge.relation.is_symmetric() {
902        // The write for a symmetric relation never branches on a
903        // prepare-time probe result: it always carries both self-guarding,
904        // commit-time-predicate statements (see their doc comment in
905        // khive-db's graph.rs for the full rationale). This avoids the
906        // staleness window a prepare-time probe would expose: an earlier op
907        // in the same atomic unit could change the conflict landscape before
908        // commit. Canonical's own probe-then-branch
909        // `update_edge_symmetric_dml` has no such exposure (single
910        // transaction, no interleaving) and is unaffected.
911        let metadata_str = edge
912            .metadata
913            .as_ref()
914            .map(|v| serde_json::to_string(v).unwrap_or_default());
915
916        statements.push(PlanStatement {
917            statement: edge_symmetric_delete_if_conflict_statement(
918                &namespace,
919                id,
920                canon_src,
921                canon_tgt,
922                edge.relation,
923            ),
924            guard: Some(AffectedRowGuard {
925                expected_min: 0,
926                expected_max: Some(1),
927            }),
928        });
929        statements.push(PlanStatement {
930            statement: edge_symmetric_absorb_or_update_inplace_statement(
931                &namespace,
932                id,
933                canon_src,
934                canon_tgt,
935                edge.relation,
936                edge.weight,
937                now.timestamp_micros(),
938                metadata_str.as_deref(),
939                edge.target_backend.as_deref(),
940            ),
941            guard: Some(AffectedRowGuard::exactly(1)),
942        });
943
944        // No prepare-time read needed: the two statements above are
945        // self-guarding at commit time (see their doc comment). Post-commit
946        // result rendering derives the actual surviving id from THIS
947        // natural key, never from a value computed here.
948        edge_natural_key = Some(EdgeNaturalKey {
949            namespace: namespace.clone(),
950            canon_source_id: canon_src,
951            canon_target_id: canon_tgt,
952            relation: edge.relation,
953        });
954    } else {
955        // Non-symmetric: bit-for-bit the same builder `graph.upsert_edge`
956        // calls — see doc comment above.
957        edge.updated_at = now;
958        statements.push(PlanStatement {
959            statement: edge_upsert_statement(&edge),
960            guard: Some(AffectedRowGuard::exactly(1)),
961        });
962    }
963
964    // Mirrors `update_edge`'s unconditional post-mutation `EdgeUpdated`
965    // event append, keyed on the original `edge_id` the caller supplied:
966    // canonical does the same (the event target is `edge_id`, not the
967    // post-absorption surviving id).
968    statements.extend(event_append_statements(
969        &namespace,
970        "update",
971        EventKind::EdgeUpdated,
972        SubstrateKind::Entity,
973        id,
974        serde_json::json!({"id": id, "namespace": namespace, "changed_fields": changed_fields}),
975    )?);
976
977    Ok(AtomicOpPlan::Update(UpdatePlan {
978        target_id: id,
979        statements,
980        post_commit: PostCommitEffect::None,
981        edge_natural_key,
982    }))
983}
984
985// ---------------------------------------------------------------------------
986// delete
987// ---------------------------------------------------------------------------
988
989/// Caller-supplied delete-kind expectation, resolved via the canonical
990/// `resolve_kind_spec` at the kkernel `--atomic` seam. `khive-runtime` must
991/// not depend on `khive-pack-kg` (packs depend on the runtime, not the other
992/// way around), so this is a plain substrate-level shape rather than
993/// `khive_pack_kg::handlers::KindSpec` itself: the kkernel seam does the
994/// pack-aware `resolve_kind_spec` resolution (which needs a `VerbRegistry`,
995/// unreachable from this crate) and passes down only what `prepare_delete`
996/// needs to enforce the mismatch check.
997///
998/// `delete` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, hence the
999/// `Edge` variant. `Event`/`Proposal` remain rejected at the kkernel seam
1000/// (not v1-admissible for atomic delete at all).
1001pub enum AtomicDeleteKind {
1002    Entity { specific: Option<String> },
1003    Note { specific: Option<String> },
1004    Edge,
1005}
1006
1007/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
1008/// with canonical's own optional discriminator); `Some(_)` enforces an
1009/// exact-parity mismatch check against the resolved record's actual
1010/// substrate/specific kind, mirroring `handle_delete`'s
1011/// `entity.kind != *expected` / `note.kind != *expected` checks.
1012pub async fn prepare_delete(
1013    runtime: &KhiveRuntime,
1014    token: &NamespaceToken,
1015    args: &Value,
1016    expected_kind: Option<AtomicDeleteKind>,
1017) -> RuntimeResult<AtomicOpPlan> {
1018    let id = require_uuid(args, "id")?;
1019    let actor = format!("{}:{}", token.actor().kind, token.actor().id);
1020    let hard = obj(args)?
1021        .get("hard")
1022        .and_then(|v| v.as_bool())
1023        .unwrap_or(false);
1024
1025    // `delete(id, hard=true)` is the public purge route after a prior soft
1026    // delete, so it must resolve including already-tombstoned rows (a
1027    // live-only resolve would never find one). Soft delete keeps the
1028    // live-only resolve: a soft delete of an already-tombstoned row is a
1029    // no-op, matching non-atomic behavior.
1030    let resolved = if hard {
1031        runtime.resolve_by_id_including_deleted(token, id).await?
1032    } else {
1033        runtime.resolve_by_id(token, id).await?
1034    };
1035
1036    match resolved {
1037        Some(Resolved::Entity(entity)) => {
1038            match &expected_kind {
1039                None => {}
1040                Some(AtomicDeleteKind::Entity {
1041                    specific: Some(expected),
1042                }) if &entity.kind != expected => {
1043                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1044                }
1045                Some(AtomicDeleteKind::Entity { .. }) => {}
1046                Some(AtomicDeleteKind::Note { .. }) => {
1047                    return Err(RuntimeError::NotFound(format!("note {id}")));
1048                }
1049                Some(AtomicDeleteKind::Edge) => {
1050                    return Err(RuntimeError::NotFound(format!("edge {id}")));
1051                }
1052            }
1053            let namespace = entity.namespace.clone();
1054            // Storage parity: `entity_soft_delete_statement`/
1055            // `entity_hard_delete_statement` are the SAME khive-db builders
1056            // khive-db's own `SqlEntityStore::delete_entity` calls — no DML
1057            // text is hand-duplicated here.
1058            let mut statements = if hard {
1059                vec![PlanStatement {
1060                    statement: entity_hard_delete_statement(id),
1061                    guard: Some(AffectedRowGuard::exactly(1)),
1062                }]
1063            } else {
1064                let deleted_at = chrono::Utc::now().timestamp_micros();
1065                vec![PlanStatement {
1066                    statement: entity_soft_delete_statement(id, deleted_at),
1067                    guard: Some(AffectedRowGuard::exactly(1)),
1068                }]
1069            };
1070            if hard {
1071                statements.extend(
1072                    hard_delete_lineage_warning_statements(
1073                        &namespace,
1074                        &actor,
1075                        id,
1076                        SubstrateKind::Entity,
1077                    )
1078                    .into_iter()
1079                    .map(|statement| PlanStatement {
1080                        statement,
1081                        guard: None,
1082                    }),
1083                );
1084                // Same builder canonical `delete_entity`'s hard-delete
1085                // cascade calls (`graph.purge_incident_edges`).
1086                statements.push(PlanStatement {
1087                    statement: purge_incident_edges_statement(id),
1088                    guard: None,
1089                });
1090            }
1091            // FTS + vector index purge, matching operations.rs
1092            // `delete_entity`: both soft and hard delete clean indexes (a
1093            // hard delete of an already-tombstoned record must still purge
1094            // them); only hard additionally cascades edges above.
1095            push_index_purge_statements(
1096                runtime,
1097                &mut statements,
1098                "fts_entities",
1099                &namespace,
1100                id,
1101                "atomic-delete-entity",
1102            )
1103            .await?;
1104            // operations.rs's `delete_entity` appends an `EntityDeleted`
1105            // event after a successful row delete, on both soft and hard
1106            // delete. `apply_plan` never reaches this statement unless the
1107            // guarded row statement above affected a row, so no extra `if`
1108            // is needed here.
1109            statements.extend(event_append_statements(
1110                &namespace,
1111                "delete",
1112                EventKind::EntityDeleted,
1113                SubstrateKind::Entity,
1114                id,
1115                serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1116            )?);
1117            Ok(AtomicOpPlan::Delete(DeletePlan {
1118                target_id: id,
1119                statements,
1120                post_commit: PostCommitEffect::None,
1121            }))
1122        }
1123        Some(Resolved::Note(note)) => {
1124            match &expected_kind {
1125                None => {}
1126                Some(AtomicDeleteKind::Note {
1127                    specific: Some(expected),
1128                }) if &note.kind != expected => {
1129                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1130                }
1131                Some(AtomicDeleteKind::Note { .. }) => {}
1132                Some(AtomicDeleteKind::Entity { .. }) => {
1133                    return Err(RuntimeError::NotFound(format!("entity {id}")));
1134                }
1135                Some(AtomicDeleteKind::Edge) => {
1136                    return Err(RuntimeError::NotFound(format!("edge {id}")));
1137                }
1138            }
1139            let namespace = note.namespace.clone();
1140            // Storage parity: `note_soft_delete_statement`/
1141            // `note_hard_delete_statement` are the SAME khive-db builders
1142            // khive-db's own `SqlNoteStore::delete_note` calls.
1143            let mut statements = if hard {
1144                vec![PlanStatement {
1145                    statement: note_hard_delete_statement(id),
1146                    guard: Some(AffectedRowGuard::exactly(1)),
1147                }]
1148            } else {
1149                let deleted_at = chrono::Utc::now().timestamp_micros();
1150                vec![PlanStatement {
1151                    statement: note_soft_delete_statement(id, deleted_at),
1152                    guard: Some(AffectedRowGuard::exactly(1)),
1153                }]
1154            };
1155            if hard {
1156                statements.extend(
1157                    hard_delete_lineage_warning_statements(
1158                        &namespace,
1159                        &actor,
1160                        id,
1161                        SubstrateKind::Note,
1162                    )
1163                    .into_iter()
1164                    .map(|statement| PlanStatement {
1165                        statement,
1166                        guard: None,
1167                    }),
1168                );
1169                statements.push(PlanStatement {
1170                    statement: purge_incident_edges_statement(id),
1171                    guard: None,
1172                });
1173            }
1174            // FTS + vector index purge, matching operations.rs
1175            // `delete_note`: both soft and hard delete clean indexes (a hard
1176            // delete of an already-tombstoned record must still purge
1177            // them); only hard additionally cascades edges above.
1178            push_index_purge_statements(
1179                runtime,
1180                &mut statements,
1181                "fts_notes",
1182                &namespace,
1183                id,
1184                "atomic-delete-note",
1185            )
1186            .await?;
1187            // operations.rs's `delete_note` appends a `NoteDeleted` event
1188            // after a successful row delete, on both soft and hard delete:
1189            // same reasoning as the entity branch above.
1190            statements.extend(event_append_statements(
1191                &namespace,
1192                "delete",
1193                EventKind::NoteDeleted,
1194                SubstrateKind::Note,
1195                id,
1196                serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1197            )?);
1198            Ok(AtomicOpPlan::Delete(DeletePlan {
1199                target_id: id,
1200                statements,
1201                // A committed atomic note delete must fire the same
1202                // pack-installed note-mutation hook `operations.rs::
1203                // delete_note` fires, so a warm ANN cache sees the deletion
1204                // even when the mutation went through the atomic-plan path.
1205                post_commit: PostCommitEffect::NoteDeleted {
1206                    note_id: id,
1207                    kind: note.kind.clone(),
1208                },
1209            }))
1210        }
1211        Some(_) => Err(RuntimeError::InvalidInput(format!(
1212            "delete target {id} must be an entity, note, or edge"
1213        ))),
1214        // `Resolved` has no `Edge` variant (same reasoning as
1215        // `prepare_update`'s fallback above) — probe the graph store
1216        // directly.
1217        None => match &expected_kind {
1218            Some(AtomicDeleteKind::Entity { .. }) => {
1219                Err(RuntimeError::NotFound(format!("entity/note {id}")))
1220            }
1221            Some(AtomicDeleteKind::Note { .. }) => {
1222                Err(RuntimeError::NotFound(format!("entity/note {id}")))
1223            }
1224            Some(AtomicDeleteKind::Edge) | None => {
1225                let edge = if hard {
1226                    runtime.get_edge_including_deleted(token, id).await?
1227                } else {
1228                    runtime.get_edge(token, id).await?
1229                };
1230                match edge {
1231                    Some(edge) => prepare_delete_edge(id, edge, hard, &actor).await,
1232                    None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
1233                }
1234            }
1235        },
1236    }
1237}
1238
1239/// Edge branch of `prepare_delete`. Mirrors
1240/// `khive-runtime::operations::KhiveRuntime::delete_edge` exactly: hard
1241/// delete cascades `purge_incident_edges` (any `annotates` edge — or any
1242/// other edge — pointing AT this edge as a node) BEFORE deleting the edge
1243/// row itself, then a soft or hard delete statement, then an unconditional
1244/// `EdgeDeleted` event (edges are never FTS/vector-indexed, so unlike the
1245/// entity/note branches there is no index purge here — `delete_edge` has
1246/// none either).
1247async fn prepare_delete_edge(
1248    id: Uuid,
1249    edge: khive_storage::types::Edge,
1250    hard: bool,
1251    actor: &str,
1252) -> RuntimeResult<AtomicOpPlan> {
1253    let namespace = edge.namespace.clone();
1254    let mut statements: Vec<PlanStatement> = Vec::new();
1255
1256    if hard {
1257        statements.extend(
1258            hard_delete_lineage_warning_statements(&namespace, actor, id, SubstrateKind::Entity)
1259                .into_iter()
1260                .map(|statement| PlanStatement {
1261                    statement,
1262                    guard: None,
1263                }),
1264        );
1265        // Mirrors `delete_edge`'s `graph.purge_incident_edges(edge_id)` —
1266        // unguarded: zero incident edges is a legitimate outcome, not a
1267        // failure (same reasoning as the entity/note cascade-edges
1268        // statements above).
1269        statements.push(PlanStatement {
1270            statement: purge_incident_edges_statement(id),
1271            guard: None,
1272        });
1273        statements.push(PlanStatement {
1274            statement: edge_hard_delete_statement(id),
1275            guard: Some(AffectedRowGuard::exactly(1)),
1276        });
1277    } else {
1278        let now = chrono::Utc::now().timestamp_micros();
1279        statements.push(PlanStatement {
1280            statement: edge_soft_delete_statement(id, now),
1281            guard: Some(AffectedRowGuard::exactly(1)),
1282        });
1283    }
1284
1285    statements.extend(event_append_statements(
1286        &namespace,
1287        "delete",
1288        EventKind::EdgeDeleted,
1289        SubstrateKind::Entity,
1290        id,
1291        serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1292    )?);
1293
1294    Ok(AtomicOpPlan::Delete(DeletePlan {
1295        target_id: id,
1296        statements,
1297        post_commit: PostCommitEffect::None,
1298    }))
1299}
1300
1301// ---------------------------------------------------------------------------
1302// link
1303// ---------------------------------------------------------------------------
1304
1305fn parse_edge_relation(raw: &str) -> RuntimeResult<EdgeRelation> {
1306    raw.parse::<EdgeRelation>()
1307        .map_err(|e| RuntimeError::InvalidInput(format!("unknown edge relation {raw:?}: {e}")))
1308}
1309
1310async fn prepare_link(
1311    runtime: &KhiveRuntime,
1312    token: &NamespaceToken,
1313    args: &Value,
1314) -> RuntimeResult<AtomicOpPlan> {
1315    let source_id = require_uuid(args, "source_id")?;
1316    let target_id = require_uuid(args, "target_id")?;
1317    let relation = parse_edge_relation(require_str(args, "relation")?)?;
1318    let weight = optional_f64(args, "weight")?.unwrap_or(1.0);
1319    let metadata = obj(args)?.get("metadata").cloned();
1320
1321    // Top-level `dependency_kind` param merges into `metadata`: only fills
1322    // the key when metadata doesn't already carry one. Calls the same
1323    // `khive_runtime::merge_entry_metadata` `khive-pack-kg`'s canonical
1324    // `handle_link` calls, so both sides depend on one function instead of
1325    // each maintaining their own copy.
1326    let mut metadata = crate::merge_entry_metadata(
1327        metadata,
1328        optional_str(args, "dependency_kind").map(String::from),
1329    )?;
1330
1331    validate_edge_weight(weight)?;
1332    runtime
1333        .validate_edge_relation_endpoints(token, source_id, target_id, relation)
1334        .await?;
1335
1336    let (canon_source, canon_target) = canonical_edge_endpoints(relation, source_id, target_id);
1337
1338    // Endpoint-kind `dependency_kind` inference for `depends_on` edges,
1339    // matching operations.rs `link()`: only applies when both endpoints
1340    // resolve as entities and the key is still absent after the
1341    // top-level-param merge above. Runs against the canonical endpoints,
1342    // mirroring `KhiveRuntime::link`'s own ordering (canonicalize, then
1343    // infer).
1344    if relation == EdgeRelation::DependsOn {
1345        metadata = match (
1346            runtime.resolve_edge_endpoint(token, canon_source).await?,
1347            runtime.resolve_edge_endpoint(token, canon_target).await?,
1348        ) {
1349            (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
1350                merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
1351            }
1352            _ => metadata,
1353        };
1354    }
1355
1356    validate_edge_metadata(relation, metadata.as_ref())?;
1357    let edge_id = Uuid::new_v4();
1358    let namespace = token.namespace().as_str().to_string();
1359    let now = chrono::Utc::now().timestamp_micros();
1360    let metadata_str = metadata.map(|m| serde_json::to_string(&m).unwrap_or_default());
1361
1362    // The guarded `INSERT ... SELECT ... WHERE EXISTS(...)` shape is
1363    // load-bearing (see `LinkPlan`'s own doc comment): it re-probes both
1364    // endpoints inside the transaction, closing the intra-batch hazard
1365    // where an earlier op in the same atomic unit, e.g. `delete(X, hard)`,
1366    // could invalidate this op's prepare-time endpoint validation before
1367    // commit. The conflict-arm SET list shares the same
1368    // `EDGE_NATURAL_KEY_CONFLICT_SET` text `edge_upsert_statement`
1369    // (canonical `link`'s builder) uses, so the two cannot silently diverge
1370    // (a prior bug: this atomic literal never set
1371    // `target_backend = excluded.target_backend`, so a re-link of an edge
1372    // carrying a cross-backend `target_backend` stamp behaved differently
1373    // under `--atomic`).
1374    let statement = edge_insert_guarded_by_endpoints_statement(
1375        &namespace,
1376        edge_id,
1377        canon_source,
1378        canon_target,
1379        relation,
1380        weight,
1381        now,
1382        metadata_str.as_deref(),
1383    );
1384
1385    Ok(AtomicOpPlan::Link(LinkPlan {
1386        source_id: canon_source,
1387        target_id: canon_target,
1388        statement: PlanStatement {
1389            statement,
1390            guard: Some(AffectedRowGuard::exactly(1)),
1391        },
1392    }))
1393}
1394
1395// ---------------------------------------------------------------------------
1396// merge (entity-only)
1397// ---------------------------------------------------------------------------
1398
1399// Full atomic-merge parity (field folding, survivor FTS/vector reindex,
1400// loser index purge, merge provenance, same-kind rejection) is deferred:
1401// atomic `merge` is rejected entirely at the pre-runtime admissibility
1402// guard (`khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS`, alongside
1403// `propose`/`review`/`withdraw`). This function still produces a plan
1404// (kept for the existing direct-prepare test coverage below and as
1405// defense in depth), but the CLI's `--atomic` surface never reaches it,
1406// since `check_atomic_admissible` rejects `merge` before any runtime is
1407// built.
1408async fn prepare_merge(
1409    runtime: &KhiveRuntime,
1410    token: &NamespaceToken,
1411    args: &Value,
1412) -> RuntimeResult<AtomicOpPlan> {
1413    let into_id = require_uuid(args, "into_id")?;
1414    let from_id = require_uuid(args, "from_id")?;
1415    if into_id == from_id {
1416        return Err(RuntimeError::InvalidInput(
1417            "cannot merge an entity into itself".into(),
1418        ));
1419    }
1420
1421    let entities = runtime.entities(token)?;
1422    entities
1423        .get_entity(into_id)
1424        .await?
1425        .ok_or_else(|| RuntimeError::NotFound(format!("entity {into_id}")))?;
1426    entities
1427        .get_entity(from_id)
1428        .await?
1429        .ok_or_else(|| RuntimeError::NotFound(format!("entity {from_id}")))?;
1430
1431    let now = chrono::Utc::now().timestamp_micros();
1432    let rewires = vec![
1433        crate::atomic_plan::PlanPredicate {
1434            description: "source_id = :from".to_string(),
1435            statement: SqlStatement {
1436                sql: "UPDATE graph_edges SET source_id = ?1, updated_at = ?2 WHERE source_id = ?3"
1437                    .to_string(),
1438                params: vec![
1439                    SqlValue::Text(into_id.to_string()),
1440                    SqlValue::Integer(now),
1441                    SqlValue::Text(from_id.to_string()),
1442                ],
1443                label: Some("atomic-merge-rewire-source".to_string()),
1444            },
1445        },
1446        crate::atomic_plan::PlanPredicate {
1447            description: "target_id = :from".to_string(),
1448            statement: SqlStatement {
1449                sql: "UPDATE graph_edges SET target_id = ?1, updated_at = ?2 WHERE target_id = ?3"
1450                    .to_string(),
1451                params: vec![
1452                    SqlValue::Text(into_id.to_string()),
1453                    SqlValue::Integer(now),
1454                    SqlValue::Text(from_id.to_string()),
1455                ],
1456                label: Some("atomic-merge-rewire-target".to_string()),
1457            },
1458        },
1459    ];
1460    let lifecycle = vec![PlanStatement {
1461        statement: SqlStatement {
1462            sql: "UPDATE entities SET deleted_at = ?1, merged_into = ?2 \
1463                  WHERE id = ?3 AND deleted_at IS NULL"
1464                .to_string(),
1465            params: vec![
1466                SqlValue::Integer(now),
1467                SqlValue::Text(into_id.to_string()),
1468                SqlValue::Text(from_id.to_string()),
1469            ],
1470            label: Some("atomic-merge-tombstone-from-entity".to_string()),
1471        },
1472        guard: Some(AffectedRowGuard::exactly(1)),
1473    }];
1474
1475    Ok(AtomicOpPlan::Merge(MergePlan {
1476        into_id,
1477        from_id,
1478        rewires,
1479        lifecycle,
1480    }))
1481}
1482
1483// ---------------------------------------------------------------------------
1484// post-commit effects
1485// ---------------------------------------------------------------------------
1486
1487/// Embedding metadata produced by one successfully applied reindex effect.
1488///
1489/// The effect identity is retained so response builders can attach an advisory
1490/// to the exact atomic op that scheduled the reindex. Effects whose target is
1491/// no longer present are omitted from the returned outcome list.
1492#[derive(Clone, Debug, PartialEq, Eq)]
1493pub struct PostCommitEmbeddingOutcome {
1494    /// The committed reindex effect that produced this outcome.
1495    pub effect: PostCommitEffect,
1496    /// Actual input bounding observed while executing the effect.
1497    pub truncation: crate::retrieval::EmbeddingTruncationReport,
1498}
1499
1500/// Run every deferred [`PostCommitEffect`] after a committed atomic unit.
1501pub async fn apply_post_commit_effects(
1502    runtime: &KhiveRuntime,
1503    token: &NamespaceToken,
1504    effects: CommittedPostCommitEffects,
1505) -> RuntimeResult<()> {
1506    apply_post_commit_effects_with_report(runtime, token, effects)
1507        .await
1508        .map(|_| ())
1509}
1510
1511/// Truncation-reporting form of [`apply_post_commit_effects`]. Re-fetches each
1512/// target's now-committed row outside any transaction and reuses the existing
1513/// `reindex_entity`/`reindex_note` (FTS + embedding, same as the non-atomic
1514/// path) for exact parity. Returns the typed embedding outcome for each reindex
1515/// effect so callers can preserve write-response advisories instead of
1516/// discarding them after commit.
1517pub async fn apply_post_commit_effects_with_report(
1518    runtime: &KhiveRuntime,
1519    token: &NamespaceToken,
1520    effects: CommittedPostCommitEffects,
1521) -> RuntimeResult<Vec<PostCommitEmbeddingOutcome>> {
1522    let mut embedding_outcomes = Vec::new();
1523    for effect in effects.into_effects() {
1524        match effect {
1525            PostCommitEffect::None => {}
1526            PostCommitEffect::ReindexEntity { entity_id } => {
1527                if let Some(entity) = runtime.entities(token)?.get_entity(entity_id).await? {
1528                    let truncation = runtime.reindex_entity(token, &entity).await?;
1529                    embedding_outcomes.push(PostCommitEmbeddingOutcome {
1530                        effect: PostCommitEffect::ReindexEntity { entity_id },
1531                        truncation,
1532                    });
1533                }
1534            }
1535            PostCommitEffect::ReindexNote { note_id } => {
1536                if let Some(note) = runtime.notes(token)?.get_note(note_id).await? {
1537                    let truncation = runtime.reindex_note(token, &note).await?;
1538                    embedding_outcomes.push(PostCommitEmbeddingOutcome {
1539                        effect: PostCommitEffect::ReindexNote { note_id },
1540                        truncation,
1541                    });
1542                    // This handler calls `reindex_note` directly, bypassing
1543                    // `update_note()` and the note-mutation hook it fires
1544                    // after its own reindex (see `curation.rs`). Fire it
1545                    // here so any in-process consumer (e.g.
1546                    // khive-pack-memory's warm ANN cache) sees a bumped
1547                    // generation after a committed atomic note update,
1548                    // matching the non-atomic path.
1549                    runtime.fire_note_mutation_hook(&note.kind, note.id).await;
1550                }
1551            }
1552            PostCommitEffect::NoteDeleted { note_id, kind } => {
1553                // Unlike `operations.rs`'s `delete_note`, which fires
1554                // `fire_note_mutation_hook` directly (with the already-known
1555                // kind, no refetch) after a successful row delete, an atomic
1556                // note delete needs this post-commit pass to reach it. The
1557                // note row is gone (hard delete) or tombstoned (soft
1558                // delete) by the time this runs, so it mirrors
1559                // `delete_note`'s direct-fire shape rather than
1560                // `ReindexNote`'s refetch-then-fire shape.
1561                runtime.fire_note_mutation_hook(&kind, note_id).await;
1562            }
1563            PostCommitEffect::GtdAudit { .. } => {
1564                // Applied by the `kkernel` caller's own post-commit pass,
1565                // not here: `khive-pack-gtd` (owner of
1566                // `ensure_audit_schema`/`write_audit_record`) depends on
1567                // `khive-runtime`, not the other way around, so this crate
1568                // cannot act on the effect itself. See
1569                // `PostCommitEffect::GtdAudit`'s doc comment.
1570            }
1571        }
1572    }
1573    Ok(embedding_outcomes)
1574}
1575
1576#[cfg(test)]
1577mod tests {
1578    use super::*;
1579
1580    use async_trait::async_trait;
1581    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_CHARS};
1582    use serde_json::json;
1583
1584    use khive_types::Namespace;
1585
1586    use crate::embedder_registry::EmbedderProvider;
1587    use crate::runtime::RuntimeConfig;
1588
1589    const STUB_MODEL: &str = "stub-adr099-b3";
1590    const STUB_DIMS: usize = 4;
1591
1592    struct StubService;
1593
1594    #[async_trait]
1595    impl EmbeddingService for StubService {
1596        async fn embed(
1597            &self,
1598            texts: &[String],
1599            _model: EmbeddingModel,
1600        ) -> Result<Vec<Vec<f32>>, EmbedError> {
1601            Ok(texts.iter().map(|_| vec![0.5_f32; STUB_DIMS]).collect())
1602        }
1603
1604        fn supports_model(&self, _model: EmbeddingModel) -> bool {
1605            true
1606        }
1607
1608        fn name(&self) -> &'static str {
1609            STUB_MODEL
1610        }
1611    }
1612
1613    struct StubProvider;
1614
1615    #[async_trait]
1616    impl EmbedderProvider for StubProvider {
1617        fn name(&self) -> &str {
1618            STUB_MODEL
1619        }
1620
1621        fn dimensions(&self) -> usize {
1622            STUB_DIMS
1623        }
1624
1625        async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
1626            Ok(std::sync::Arc::new(StubService))
1627        }
1628    }
1629
1630    fn scratch_runtime() -> KhiveRuntime {
1631        let dir = tempfile::tempdir().expect("tempdir");
1632        let path = dir.path().join("atomic_prepare_reindex.db");
1633        let rt = KhiveRuntime::new(RuntimeConfig {
1634            db_path: Some(path),
1635            embedding_model: None,
1636            additional_embedding_models: vec![],
1637            ..RuntimeConfig::default()
1638        })
1639        .expect("runtime");
1640        std::mem::forget(dir);
1641        rt
1642    }
1643
1644    /// Atomic `update` must reject a field that does not apply to the
1645    /// resolved substrate: parity with
1646    /// `khive-pack-kg::handlers::update::reject_inapplicable_fields`.
1647    /// Without this check, atomic prepare would silently ignore `salience`
1648    /// on an entity: it would set every entity field to its current value,
1649    /// bump `updated_at`, satisfy the `exactly(1)` guard, and commit: a
1650    /// spurious no-op reported as success.
1651    #[tokio::test]
1652    async fn atomic_update_entity_rejects_note_only_field_salience() {
1653        let runtime = scratch_runtime();
1654        let token = runtime
1655            .authorize(Namespace::parse("local").expect("ns"))
1656            .expect("authorize");
1657        let entity = khive_storage::Entity::new("local", "concept", "GapFourEntity");
1658        let entity_id = entity.id;
1659        runtime
1660            .entities(&token)
1661            .expect("entities store")
1662            .upsert_entity(entity)
1663            .await
1664            .expect("seed entity");
1665
1666        let err = prepare_update(
1667            &runtime,
1668            &token,
1669            &json!({"id": entity_id.to_string(), "salience": 0.9}),
1670            None,
1671        )
1672        .await
1673        .expect_err("salience on an entity must be rejected, not silently accepted");
1674        assert!(
1675            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("salience") && msg.contains("not valid for an entity")),
1676            "expected an InvalidInput naming the offending field, got: {err:?}"
1677        );
1678
1679        // A valid entity update (name/description/tags) must still work.
1680        let plan = prepare_update(
1681            &runtime,
1682            &token,
1683            &json!({
1684                "id": entity_id.to_string(),
1685                "name": "GapFourEntity-renamed",
1686                "description": "updated description",
1687                "tags": ["a", "b"],
1688            }),
1689            None,
1690        )
1691        .await
1692        .expect("a valid entity field set must still be accepted");
1693        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1694            .await
1695            .expect("seam call ok");
1696        assert!(matches!(
1697            outcome,
1698            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1699        ));
1700        let entity = runtime
1701            .get_entity(&token, entity_id)
1702            .await
1703            .expect("get_entity");
1704        assert_eq!(entity.name, "GapFourEntity-renamed");
1705    }
1706
1707    /// Symmetric note-substrate case: `description` and `tags` are
1708    /// entity-only fields; passing either for a note must be rejected the
1709    /// same way update.rs rejects them.
1710    #[tokio::test]
1711    async fn atomic_update_note_rejects_entity_only_field_description() {
1712        let runtime = scratch_runtime();
1713        let token = runtime
1714            .authorize(Namespace::parse("local").expect("ns"))
1715            .expect("authorize");
1716        let mut note = khive_storage::note::Note::new("local", "observation", "gap-4 note content");
1717        note.name = Some("gap-four-note".to_string());
1718        let note_id = note.id;
1719        runtime
1720            .notes(&token)
1721            .expect("notes store")
1722            .upsert_note(note)
1723            .await
1724            .expect("seed note");
1725
1726        let err = prepare_update(
1727            &runtime,
1728            &token,
1729            &json!({"id": note_id.to_string(), "description": "entities have descriptions, notes don't"}),
1730                None,
1731            )
1732        .await
1733        .expect_err("description on a note must be rejected, not silently accepted");
1734        assert!(
1735            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("description") && msg.contains("not valid for a note")),
1736            "expected an InvalidInput naming the offending field, got: {err:?}"
1737        );
1738
1739        // A valid note update (content) must still work.
1740        let plan = prepare_update(
1741            &runtime,
1742            &token,
1743            &json!({"id": note_id.to_string(), "content": "gap-4 note content, revised"}),
1744            None,
1745        )
1746        .await
1747        .expect("a valid note field must still be accepted");
1748        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1749            .await
1750            .expect("seam call ok");
1751        assert!(matches!(
1752            outcome,
1753            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1754        ));
1755    }
1756
1757    /// Updating a note's content inside an atomic unit must, after commit,
1758    /// leave the note recallable via FTS under its new content and its
1759    /// vector row refreshed: parity with the non-atomic
1760    /// `update_note` -> `reindex_note` path.
1761    #[tokio::test]
1762    async fn atomic_update_note_content_is_fts_and_vector_reindexed_post_commit() {
1763        let runtime = scratch_runtime();
1764        runtime.register_embedder(StubProvider);
1765        let token = runtime
1766            .authorize(Namespace::parse("local").expect("ns"))
1767            .expect("authorize");
1768
1769        let mut note = khive_storage::note::Note::new("local", "observation", "original content");
1770        note.name = Some("reindex-target".to_string());
1771        let note_id = note.id;
1772        runtime
1773            .notes(&token)
1774            .expect("notes store")
1775            .upsert_note(note)
1776            .await
1777            .expect("seed note");
1778
1779        // Sanity: no vector row yet for the stub model.
1780        let vec_store = runtime
1781            .vectors_for_model(&token, STUB_MODEL)
1782            .expect("vec store");
1783        assert_eq!(vec_store.count().await.expect("count before"), 0);
1784
1785        let updated_content = format!("freshly-updated-content-xyz{}", "x".repeat(MAX_TEXT_CHARS));
1786        let plan = prepare_update(
1787            &runtime,
1788            &token,
1789            &json!({"id": note_id.to_string(), "content": updated_content}),
1790            None,
1791        )
1792        .await
1793        .expect("prepare update");
1794
1795        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1796            .await
1797            .expect("seam call ok");
1798        let post_commit = match outcome {
1799            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
1800            other => panic!("expected Committed, got {other:?}"),
1801        };
1802        assert_eq!(
1803            post_commit.as_slice(),
1804            &[PostCommitEffect::ReindexNote { note_id }],
1805            "content change must schedule exactly one ReindexNote post-commit effect"
1806        );
1807
1808        let embedding_outcomes =
1809            apply_post_commit_effects_with_report(&runtime, &token, post_commit)
1810                .await
1811                .expect("apply post-commit effects");
1812        assert_eq!(embedding_outcomes.len(), 1);
1813        assert_eq!(
1814            embedding_outcomes[0].effect,
1815            PostCommitEffect::ReindexNote { note_id }
1816        );
1817        assert_eq!(embedding_outcomes[0].truncation.truncated, 1);
1818        assert!(embedding_outcomes[0].truncation.discarded_bytes > 0);
1819
1820        // FTS: the note must be recallable under its NEW content.
1821        let doc = runtime
1822            .text_for_notes(&token)
1823            .expect("text store")
1824            .get_document("local", note_id)
1825            .await
1826            .expect("get_document")
1827            .expect("document must be indexed after post-commit reindex");
1828        assert!(
1829            doc.body.contains("freshly-updated-content-xyz"),
1830            "FTS body must reflect the committed content: {:?}",
1831            doc.body
1832        );
1833
1834        // Vector: a row must now exist for the registered stub model.
1835        assert_eq!(
1836            vec_store.count().await.expect("count after"),
1837            1,
1838            "post-commit reindex must have inserted a vector row for the stub model"
1839        );
1840    }
1841
1842    /// The atomic-plan path must fire the pack-installed note-mutation hook
1843    /// for both an atomic note UPDATE (`PostCommitEffect::ReindexNote`'s
1844    /// handler fires it after its own reindex, mirroring `update_note()`
1845    /// on the non-atomic path) and an atomic note DELETE (`DeletePlan`
1846    /// carries a `PostCommitEffect::NoteDeleted` that
1847    /// `apply_post_commit_effects` dispatches directly, mirroring
1848    /// `operations.rs::delete_note`'s direct-fire, no-refetch shape: the
1849    /// row may already be gone by the time this runs, for a hard delete).
1850    /// A minimal counting hook proves both fire; no `khive-pack-memory`
1851    /// dependency is needed at this layer, since the hook itself is
1852    /// generic.
1853    #[tokio::test]
1854    async fn atomic_note_update_and_delete_post_commit_effects_execute_exactly_once() {
1855        let runtime = scratch_runtime();
1856        let token = runtime
1857            .authorize(Namespace::parse("local").expect("ns"))
1858            .expect("authorize");
1859
1860        let fired: std::sync::Arc<std::sync::Mutex<Vec<(String, uuid::Uuid)>>> =
1861            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1862        let fired_for_hook = fired.clone();
1863        runtime.install_note_mutation_hook(std::sync::Arc::new(
1864            move |kind: String, id: uuid::Uuid| {
1865                let fired = fired_for_hook.clone();
1866                Box::pin(async move {
1867                    fired.lock().expect("lock").push((kind, id));
1868                })
1869            },
1870        ));
1871
1872        // Update path.
1873        let mut note = khive_storage::note::Note::new("local", "observation", "hook-update-target");
1874        note.name = Some("hook-update-target".to_string());
1875        let update_note_id = note.id;
1876        runtime
1877            .notes(&token)
1878            .expect("notes store")
1879            .upsert_note(note)
1880            .await
1881            .expect("seed update-target note");
1882
1883        let plan = prepare_update(
1884            &runtime,
1885            &token,
1886            &json!({"id": update_note_id.to_string(), "content": "hook-update-target, revised"}),
1887            None,
1888        )
1889        .await
1890        .expect("prepare update");
1891        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1892            .await
1893            .expect("seam call ok");
1894        let post_commit = match outcome {
1895            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
1896            other => panic!("expected Committed, got {other:?}"),
1897        };
1898        apply_post_commit_effects(&runtime, &token, post_commit)
1899            .await
1900            .expect("apply post-commit effects (update)");
1901
1902        // Delete path (soft delete: the row still exists, but the hook
1903        // fires directly from the captured kind rather than refetching).
1904        let mut del_note =
1905            khive_storage::note::Note::new("local", "observation", "hook-delete-target");
1906        del_note.name = Some("hook-delete-target".to_string());
1907        let delete_note_id = del_note.id;
1908        runtime
1909            .notes(&token)
1910            .expect("notes store")
1911            .upsert_note(del_note)
1912            .await
1913            .expect("seed delete-target note");
1914
1915        let plan = prepare_delete(
1916            &runtime,
1917            &token,
1918            &json!({"id": delete_note_id.to_string(), "hard": false}),
1919            None,
1920        )
1921        .await
1922        .expect("prepare delete");
1923        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1924            .await
1925            .expect("seam call ok");
1926        let post_commit = match outcome {
1927            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
1928            other => panic!("expected Committed, got {other:?}"),
1929        };
1930        assert_eq!(
1931            post_commit.as_slice(),
1932            &[PostCommitEffect::NoteDeleted {
1933                note_id: delete_note_id,
1934                kind: "observation".to_string(),
1935            }],
1936            "a committed note delete must schedule exactly one NoteDeleted post-commit effect"
1937        );
1938        apply_post_commit_effects(&runtime, &token, post_commit)
1939            .await
1940            .expect("apply post-commit effects (delete)");
1941
1942        assert_eq!(
1943            *fired.lock().expect("lock"),
1944            vec![
1945                ("observation".to_string(), update_note_id),
1946                ("observation".to_string(), delete_note_id),
1947            ],
1948            "each committed token must execute its note-mutation effect exactly once"
1949        );
1950    }
1951
1952    /// Atomic delete must purge the note's FTS row and vector row for both
1953    /// soft and hard delete: parity with `KhiveRuntime::delete_note`'s
1954    /// index-cleanup contract.
1955    #[tokio::test]
1956    async fn atomic_delete_note_purges_fts_and_vector_indexes_soft_and_hard() {
1957        let runtime = scratch_runtime();
1958        runtime.register_embedder(StubProvider);
1959        let token = runtime
1960            .authorize(Namespace::parse("local").expect("ns"))
1961            .expect("authorize");
1962
1963        for hard in [false, true] {
1964            let mut note =
1965                khive_storage::note::Note::new("local", "observation", "purge-target content");
1966            note.name = Some(format!("purge-target-hard-{hard}"));
1967            let note_id = note.id;
1968            runtime
1969                .notes(&token)
1970                .expect("notes store")
1971                .upsert_note(note.clone())
1972                .await
1973                .expect("seed note");
1974            runtime
1975                .reindex_note(&token, &note)
1976                .await
1977                .expect("seed index rows");
1978
1979            let vec_store = runtime
1980                .vectors_for_model(&token, STUB_MODEL)
1981                .expect("vec store");
1982            assert_eq!(
1983                vec_store.count().await.expect("count before"),
1984                1,
1985                "seeded note must have a vector row before delete (hard={hard})"
1986            );
1987            assert!(
1988                runtime
1989                    .text_for_notes(&token)
1990                    .expect("text store")
1991                    .get_document("local", note_id)
1992                    .await
1993                    .expect("get_document")
1994                    .is_some(),
1995                "seeded note must have an FTS row before delete (hard={hard})"
1996            );
1997
1998            let plan = prepare_delete(
1999                &runtime,
2000                &token,
2001                &json!({"id": note_id.to_string(), "hard": hard}),
2002                None,
2003            )
2004            .await
2005            .expect("prepare delete");
2006            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2007                .await
2008                .expect("seam call ok");
2009            assert!(
2010                matches!(
2011                    outcome,
2012                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2013                ),
2014                "expected commit (hard={hard}): {outcome:?}"
2015            );
2016
2017            assert!(
2018                runtime
2019                    .text_for_notes(&token)
2020                    .expect("text store")
2021                    .get_document("local", note_id)
2022                    .await
2023                    .expect("get_document")
2024                    .is_none(),
2025                "FTS row must be purged after atomic delete (hard={hard})"
2026            );
2027            assert_eq!(
2028                vec_store.count().await.expect("count after"),
2029                0,
2030                "vector row must be purged after atomic delete (hard={hard})"
2031            );
2032        }
2033    }
2034
2035    /// Atomic delete must purge the entity's FTS row and vector row for
2036    /// both soft and hard delete: parity with
2037    /// `KhiveRuntime::delete_entity`'s index-cleanup contract.
2038    #[tokio::test]
2039    async fn atomic_delete_entity_purges_fts_and_vector_indexes_soft_and_hard() {
2040        let runtime = scratch_runtime();
2041        runtime.register_embedder(StubProvider);
2042        let token = runtime
2043            .authorize(Namespace::parse("local").expect("ns"))
2044            .expect("authorize");
2045
2046        for hard in [false, true] {
2047            let entity =
2048                khive_storage::Entity::new("local", "concept", format!("purge-target-hard-{hard}"));
2049            let entity_id = entity.id;
2050            runtime
2051                .entities(&token)
2052                .expect("entities store")
2053                .upsert_entity(entity.clone())
2054                .await
2055                .expect("seed entity");
2056            runtime
2057                .reindex_entity(&token, &entity)
2058                .await
2059                .expect("seed index rows");
2060
2061            let vec_store = runtime
2062                .vectors_for_model(&token, STUB_MODEL)
2063                .expect("vec store");
2064            assert_eq!(
2065                vec_store.count().await.expect("count before"),
2066                1,
2067                "seeded entity must have a vector row before delete (hard={hard})"
2068            );
2069            assert!(
2070                runtime
2071                    .text(&token)
2072                    .expect("text store")
2073                    .get_document("local", entity_id)
2074                    .await
2075                    .expect("get_document")
2076                    .is_some(),
2077                "seeded entity must have an FTS row before delete (hard={hard})"
2078            );
2079
2080            let plan = prepare_delete(
2081                &runtime,
2082                &token,
2083                &json!({"id": entity_id.to_string(), "hard": hard}),
2084                None,
2085            )
2086            .await
2087            .expect("prepare delete");
2088            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2089                .await
2090                .expect("seam call ok");
2091            assert!(
2092                matches!(
2093                    outcome,
2094                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2095                ),
2096                "expected commit (hard={hard}): {outcome:?}"
2097            );
2098
2099            assert!(
2100                runtime
2101                    .text(&token)
2102                    .expect("text store")
2103                    .get_document("local", entity_id)
2104                    .await
2105                    .expect("get_document")
2106                    .is_none(),
2107                "FTS row must be purged after atomic delete (hard={hard})"
2108            );
2109            assert_eq!(
2110                vec_store.count().await.expect("count after"),
2111                0,
2112                "vector row must be purged after atomic delete (hard={hard})"
2113            );
2114        }
2115    }
2116
2117    #[tokio::test]
2118    async fn atomic_delete_entity_and_note_logs_vector_delete_rows() {
2119        let runtime = scratch_runtime();
2120        runtime.register_embedder(StubProvider);
2121        let token = runtime
2122            .authorize(Namespace::parse("local").expect("ns"))
2123            .expect("authorize");
2124
2125        let entity = khive_storage::Entity::new("local", "concept", "ann-delete-entity");
2126        let entity_id = entity.id;
2127        runtime
2128            .entities(&token)
2129            .expect("entities store")
2130            .upsert_entity(entity.clone())
2131            .await
2132            .expect("seed entity");
2133        runtime
2134            .reindex_entity(&token, &entity)
2135            .await
2136            .expect("seed entity vector row");
2137        let note = khive_storage::note::Note::new("local", "observation", "ann-delete-note");
2138        let note_id = note.id;
2139        runtime
2140            .notes(&token)
2141            .expect("notes store")
2142            .upsert_note(note.clone())
2143            .await
2144            .expect("seed note");
2145        runtime
2146            .reindex_note(&token, &note)
2147            .await
2148            .expect("seed note vector row");
2149
2150        for id in [entity_id, note_id] {
2151            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2152                .await
2153                .expect("prepare delete");
2154            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2155                .await
2156                .expect("seam call ok");
2157            assert!(matches!(
2158                outcome,
2159                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2160            ));
2161        }
2162
2163        let mut reader = runtime.sql().reader().await.expect("sql reader");
2164        let count = reader
2165            .query_scalar(SqlStatement {
2166                sql: "SELECT COUNT(*) FROM ann_write_log \
2167                      WHERE namespace = 'local' AND embedding_model = ?1 AND op = 'delete' \
2168                      AND ((kind = 'entity' AND field = 'entity.body' AND subject_id = ?2) \
2169                        OR (kind = 'note' AND field = 'note.content' AND subject_id = ?3))"
2170                    .to_string(),
2171                params: vec![
2172                    SqlValue::Text(STUB_MODEL.to_string()),
2173                    SqlValue::Text(entity_id.to_string()),
2174                    SqlValue::Text(note_id.to_string()),
2175                ],
2176                label: Some("test-atomic-delete-ann-write-log".to_string()),
2177            })
2178            .await
2179            .expect("query ANN write log");
2180        assert!(matches!(count, Some(SqlValue::Integer(2))));
2181    }
2182
2183    /// Atomic prepare validates the requested orientation before canonicalizing
2184    /// a symmetric edge for persistence. Fixed UUIDs force target < source so a
2185    /// regression would report the reverse ordered pair.
2186    #[tokio::test]
2187    async fn atomic_link_symmetric_rejection_preserves_requested_pair() {
2188        let runtime = scratch_runtime();
2189        let token = runtime
2190            .authorize(Namespace::parse("local").expect("ns"))
2191            .expect("authorize");
2192        let entities = runtime.entities(&token).expect("entities store");
2193        let concept_id =
2194            Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").expect("high UUID");
2195        let project_id = Uuid::nil();
2196        assert!(project_id < concept_id, "test must exercise UUID reversal");
2197
2198        let mut concept = khive_storage::Entity::new("local", "concept", "Concept source");
2199        concept.id = concept_id;
2200        let mut project = khive_storage::Entity::new("local", "project", "Project target");
2201        project.id = project_id;
2202        entities.upsert_entity(concept).await.expect("seed concept");
2203        entities.upsert_entity(project).await.expect("seed project");
2204
2205        let error = prepare_link(
2206            &runtime,
2207            &token,
2208            &json!({
2209                "source_id": concept_id.to_string(),
2210                "target_id": project_id.to_string(),
2211                "relation": "competes_with",
2212            }),
2213        )
2214        .await
2215        .expect_err("atomic link must reject concept competes_with project");
2216        let message = error.to_string();
2217        assert!(
2218            message.contains(
2219                "currently legal relations for concept -> project under the loaded endpoint rules: none"
2220            ),
2221            "atomic validation must diagnose caller order before persistence canonicalization; got: {message}"
2222        );
2223        assert!(
2224            !message.contains("currently legal relations for project -> concept"),
2225            "atomic validation must not diagnose the UUID-canonical reverse pair; got: {message}"
2226        );
2227    }
2228
2229    /// Atomic link must persist an explicit top-level `dependency_kind`
2230    /// param into edge metadata, and must infer one for `depends_on` edges
2231    /// when absent: parity with
2232    /// `link.rs`'s `merge_entry_metadata` and `operations.rs`'s
2233    /// `infer_dependency_kind` table.
2234    #[tokio::test]
2235    async fn atomic_link_persists_explicit_dependency_kind_and_infers_when_absent() {
2236        let runtime = scratch_runtime();
2237        let token = runtime
2238            .authorize(Namespace::parse("local").expect("ns"))
2239            .expect("authorize");
2240        let entities = runtime.entities(&token).expect("entities store");
2241
2242        fn metadata_json(plan: &AtomicOpPlan) -> String {
2243            let link_plan = match plan {
2244                AtomicOpPlan::Link(p) => p,
2245                other => panic!("expected an AtomicOpPlan::Link, got {other:?}"),
2246            };
2247            match link_plan.statement.statement.params.last() {
2248                Some(SqlValue::Text(s)) => s.clone(),
2249                other => panic!("expected the metadata param to be SqlValue::Text, got {other:?}"),
2250            }
2251        }
2252
2253        // (a) explicit top-level `dependency_kind` param persists in metadata.
2254        {
2255            let svc = khive_storage::Entity::new("local", "service", "SvcA");
2256            let proj = khive_storage::Entity::new("local", "project", "ProjB");
2257            let (svc_id, proj_id) = (svc.id, proj.id);
2258            entities.upsert_entity(svc).await.expect("seed svc");
2259            entities.upsert_entity(proj).await.expect("seed proj");
2260
2261            let plan = prepare_link(
2262                &runtime,
2263                &token,
2264                &json!({
2265                    "source_id": svc_id.to_string(),
2266                    "target_id": proj_id.to_string(),
2267                    "relation": "depends_on",
2268                    "dependency_kind": "artifact",
2269                }),
2270            )
2271            .await
2272            .expect("prepare link");
2273            let json_str = metadata_json(&plan);
2274            assert!(
2275                json_str.contains(r#""dependency_kind":"artifact""#),
2276                "explicit dependency_kind param must persist: {json_str}"
2277            );
2278        }
2279
2280        // (b) `depends_on` with no explicit dependency_kind infers from
2281        // endpoint kinds: (service, service) -> "runtime".
2282        {
2283            let svc_a = khive_storage::Entity::new("local", "service", "SvcC");
2284            let svc_b = khive_storage::Entity::new("local", "service", "SvcD");
2285            let (a_id, b_id) = (svc_a.id, svc_b.id);
2286            entities.upsert_entity(svc_a).await.expect("seed svc a");
2287            entities.upsert_entity(svc_b).await.expect("seed svc b");
2288
2289            let plan = prepare_link(
2290                &runtime,
2291                &token,
2292                &json!({
2293                    "source_id": a_id.to_string(),
2294                    "target_id": b_id.to_string(),
2295                    "relation": "depends_on",
2296                }),
2297            )
2298            .await
2299            .expect("prepare link");
2300            let json_str = metadata_json(&plan);
2301            assert!(
2302                json_str.contains(r#""dependency_kind":"runtime""#),
2303                "inferred dependency_kind for (service, service) must persist: {json_str}"
2304            );
2305        }
2306    }
2307
2308    /// Raw natural-key probe of `graph_edges` (namespace, source_id,
2309    /// target_id, relation) — returns `(weight, metadata_json, deleted_at)`
2310    /// for exactly the ONE row a UNIQUE(namespace, source_id, target_id,
2311    /// relation) constraint permits. `None` means no row at all.
2312    async fn probe_edge_natural_key(
2313        runtime: &KhiveRuntime,
2314        namespace: &str,
2315        source_id: Uuid,
2316        target_id: Uuid,
2317        relation: &str,
2318    ) -> (usize, Option<f64>, Option<String>, Option<i64>) {
2319        let mut reader = runtime.sql().reader().await.expect("reader");
2320        let rows = reader
2321            .query_all(SqlStatement {
2322                sql: "SELECT weight, metadata, deleted_at FROM graph_edges \
2323                      WHERE namespace = ?1 AND source_id = ?2 AND target_id = ?3 AND relation = ?4"
2324                    .to_string(),
2325                params: vec![
2326                    SqlValue::Text(namespace.to_string()),
2327                    SqlValue::Text(source_id.to_string()),
2328                    SqlValue::Text(target_id.to_string()),
2329                    SqlValue::Text(relation.to_string()),
2330                ],
2331                label: Some("test-probe-edge-natural-key".to_string()),
2332            })
2333            .await
2334            .expect("probe edge natural key");
2335        let count = rows.len();
2336        let Some(row) = rows.into_iter().next() else {
2337            return (count, None, None, None);
2338        };
2339        let weight = match row.get("weight") {
2340            Some(SqlValue::Float(f)) => Some(*f),
2341            Some(SqlValue::Integer(i)) => Some(*i as f64),
2342            _ => None,
2343        };
2344        let metadata = match row.get("metadata") {
2345            Some(SqlValue::Text(s)) => Some(s.clone()),
2346            _ => None,
2347        };
2348        let deleted_at = match row.get("deleted_at") {
2349            Some(SqlValue::Integer(i)) => Some(*i),
2350            _ => None,
2351        };
2352        (count, weight, metadata, deleted_at)
2353    }
2354
2355    /// Atomic `link` must be an upsert, exactly like canonical `link` ->
2356    /// `upsert_edge`'s natural-key `ON CONFLICT` arm: re-linking an
2357    /// already-linked triple must succeed and update weight/metadata, not
2358    /// hit the `UNIQUE(namespace, source_id, target_id, relation)`
2359    /// constraint and roll back the whole atomic unit.
2360    #[tokio::test]
2361    async fn atomic_link_of_already_linked_triple_upserts_weight_and_metadata() {
2362        let runtime = scratch_runtime();
2363        let token = runtime
2364            .authorize(Namespace::parse("local").expect("ns"))
2365            .expect("authorize");
2366        let entities = runtime.entities(&token).expect("entities store");
2367
2368        let a = khive_storage::Entity::new("local", "concept", "GapTwoA");
2369        let b = khive_storage::Entity::new("local", "concept", "GapTwoB");
2370        let (a_id, b_id) = (a.id, b.id);
2371        entities.upsert_entity(a).await.expect("seed a");
2372        entities.upsert_entity(b).await.expect("seed b");
2373
2374        // (a) a fresh link still works.
2375        let plan1 = prepare_link(
2376            &runtime,
2377            &token,
2378            &json!({
2379                "source_id": a_id.to_string(),
2380                "target_id": b_id.to_string(),
2381                "relation": "extends",
2382                "weight": 0.5,
2383            }),
2384        )
2385        .await
2386        .expect("prepare first link");
2387        let outcome1 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan1])
2388            .await
2389            .expect("seam call ok");
2390        assert!(
2391            matches!(
2392                outcome1,
2393                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2394            ),
2395            "fresh link must commit: {outcome1:?}"
2396        );
2397        let (count, weight, _metadata, deleted_at) =
2398            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2399        assert_eq!(count, 1, "exactly one edge row after the fresh link");
2400        assert_eq!(weight, Some(0.5));
2401        assert!(deleted_at.is_none());
2402
2403        // (b) re-linking the SAME triple with a different weight/metadata
2404        // must SUCCEED (not a constraint-violation rollback) and UPDATE the
2405        // existing row in place — natural key stays unique.
2406        let plan2 = prepare_link(
2407            &runtime,
2408            &token,
2409            &json!({
2410                "source_id": a_id.to_string(),
2411                "target_id": b_id.to_string(),
2412                "relation": "extends",
2413                "weight": 0.9,
2414                "metadata": {"note": "relinked"},
2415            }),
2416        )
2417        .await
2418        .expect("prepare second link");
2419        let outcome2 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan2])
2420            .await
2421            .expect("seam call ok");
2422        assert!(
2423            matches!(
2424                outcome2,
2425                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2426            ),
2427            "re-link of an already-linked triple must upsert, not roll back: {outcome2:?}"
2428        );
2429        let (count, weight, metadata, deleted_at) =
2430            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2431        assert_eq!(
2432            count, 1,
2433            "the natural-key UNIQUE constraint must still hold exactly one row (upsert, not a second insert)"
2434        );
2435        assert_eq!(weight, Some(0.9), "weight must be updated to the new value");
2436        assert!(
2437            metadata
2438                .as_deref()
2439                .is_some_and(|m| m.contains(r#""note":"relinked""#)),
2440            "metadata must be updated to the new value: {metadata:?}"
2441        );
2442        assert!(deleted_at.is_none());
2443    }
2444
2445    /// Atomic `link` of a soft-deleted triple must resurrect it
2446    /// (`deleted_at = NULL`), matching `upsert_edge`'s natural-key
2447    /// `ON CONFLICT ... DO UPDATE SET deleted_at = NULL`.
2448    #[tokio::test]
2449    async fn atomic_link_of_soft_deleted_triple_resurrects_it() {
2450        let runtime = scratch_runtime();
2451        let token = runtime
2452            .authorize(Namespace::parse("local").expect("ns"))
2453            .expect("authorize");
2454        let entities = runtime.entities(&token).expect("entities store");
2455
2456        let a = khive_storage::Entity::new("local", "concept", "GapTwoResurrectA");
2457        let b = khive_storage::Entity::new("local", "concept", "GapTwoResurrectB");
2458        let (a_id, b_id) = (a.id, b.id);
2459        entities.upsert_entity(a).await.expect("seed a");
2460        entities.upsert_entity(b).await.expect("seed b");
2461
2462        let plan = prepare_link(
2463            &runtime,
2464            &token,
2465            &json!({
2466                "source_id": a_id.to_string(),
2467                "target_id": b_id.to_string(),
2468                "relation": "extends",
2469            }),
2470        )
2471        .await
2472        .expect("prepare link");
2473        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2474            .await
2475            .expect("seam call ok");
2476        assert!(matches!(
2477            outcome,
2478            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2479        ));
2480
2481        // Soft-delete the edge row directly (natural-key UPDATE — mirrors
2482        // what `delete_edge(hard=false)` does to this same row).
2483        {
2484            let mut writer = runtime.sql().writer().await.expect("writer");
2485            let affected = writer
2486                .execute(SqlStatement {
2487                    sql: "UPDATE graph_edges SET deleted_at = ?1 \
2488                          WHERE namespace = ?2 AND source_id = ?3 AND target_id = ?4 AND relation = ?5"
2489                        .to_string(),
2490                    params: vec![
2491                        SqlValue::Integer(chrono::Utc::now().timestamp_micros()),
2492                        SqlValue::Text("local".to_string()),
2493                        SqlValue::Text(a_id.to_string()),
2494                        SqlValue::Text(b_id.to_string()),
2495                        SqlValue::Text("extends".to_string()),
2496                    ],
2497                    label: Some("test-soft-delete-edge".to_string()),
2498                })
2499                .await
2500                .expect("soft delete edge");
2501            assert_eq!(affected, 1, "soft-delete must touch exactly the seeded row");
2502        }
2503        let (_, _, _, deleted_at) =
2504            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2505        assert!(
2506            deleted_at.is_some(),
2507            "row must be soft-deleted before the resurrect attempt"
2508        );
2509
2510        // Re-link the same triple: must resurrect (deleted_at -> NULL), not
2511        // fail on the UNIQUE constraint of the still-present soft-deleted row.
2512        let plan_relink = prepare_link(
2513            &runtime,
2514            &token,
2515            &json!({
2516                "source_id": a_id.to_string(),
2517                "target_id": b_id.to_string(),
2518                "relation": "extends",
2519                "weight": 0.75,
2520            }),
2521        )
2522        .await
2523        .expect("prepare resurrecting link");
2524        let outcome_relink =
2525            crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan_relink])
2526                .await
2527                .expect("seam call ok");
2528        assert!(
2529            matches!(
2530                outcome_relink,
2531                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2532            ),
2533            "re-linking a soft-deleted triple must resurrect it, not roll back: {outcome_relink:?}"
2534        );
2535        let (count, weight, _, deleted_at) =
2536            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2537        assert_eq!(count, 1);
2538        assert_eq!(weight, Some(0.75));
2539        assert!(
2540            deleted_at.is_none(),
2541            "re-link must resurrect the soft-deleted row (deleted_at -> NULL)"
2542        );
2543    }
2544
2545    /// Atomic delete of an entity and a note must succeed even when the
2546    /// registered embedding model's `vec_*` table has never been lazily
2547    /// created (a fresh DB registers models before any vector store is
2548    /// opened): the raw purge DML must skip tables that don't exist
2549    /// rather than hit `no such table` and roll back the whole atomic
2550    /// unit. FTS purge still fires (those tables always exist) and the
2551    /// delete itself is a clean commit.
2552    #[tokio::test]
2553    async fn atomic_delete_succeeds_when_vec_table_never_created() {
2554        let runtime = scratch_runtime();
2555        runtime.register_embedder(StubProvider);
2556        let token = runtime
2557            .authorize(Namespace::parse("local").expect("ns"))
2558            .expect("authorize");
2559
2560        // Seed via raw upsert ONLY — never call reindex_entity/reindex_note
2561        // or vectors_for_model, so the stub model's `vec_*` table is never
2562        // lazily created (opening the vector store is what creates it).
2563        let entity = khive_storage::Entity::new("local", "concept", "no-vec-table-entity");
2564        let entity_id = entity.id;
2565        runtime
2566            .entities(&token)
2567            .expect("entities store")
2568            .upsert_entity(entity)
2569            .await
2570            .expect("seed entity");
2571
2572        let mut note = khive_storage::note::Note::new("local", "observation", "no-vec-table-note");
2573        note.name = Some("no-vec-table-note".to_string());
2574        let note_id = note.id;
2575        runtime
2576            .notes(&token)
2577            .expect("notes store")
2578            .upsert_note(note)
2579            .await
2580            .expect("seed note");
2581
2582        for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2583            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2584                .await
2585                .unwrap_or_else(|e| panic!("prepare delete ({kind}) must not fail: {e}"));
2586            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2587                .await
2588                .unwrap_or_else(|e| {
2589                    panic!("atomic delete ({kind}) must not hit `no such table`: {e}")
2590                });
2591            assert!(
2592                matches!(
2593                    outcome,
2594                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2595                ),
2596                "expected a clean commit ({kind}): {outcome:?}"
2597            );
2598        }
2599
2600        assert!(
2601            runtime
2602                .get_entity_including_deleted(&token, entity_id)
2603                .await
2604                .expect("get entity")
2605                .expect("entity row still present (soft delete)")
2606                .deleted_at
2607                .is_some(),
2608            "entity must be soft-deleted"
2609        );
2610        assert!(
2611            runtime
2612                .get_note_including_deleted(&token, note_id)
2613                .await
2614                .expect("get note")
2615                .expect("note row still present (soft delete)")
2616                .deleted_at
2617                .is_some(),
2618            "note must be soft-deleted"
2619        );
2620    }
2621
2622    /// Atomic hard delete must be able to purge a record that was already
2623    /// soft-deleted: parity with `delete(id, hard=true)` being the public
2624    /// purge route after a prior soft delete (the non-atomic hard path
2625    /// resolves including deleted rows and its DML carries no `deleted_at`
2626    /// predicate).
2627    #[tokio::test]
2628    async fn atomic_hard_delete_purges_already_soft_deleted_entity_and_note() {
2629        let runtime = scratch_runtime();
2630        runtime.register_embedder(StubProvider);
2631        let token = runtime
2632            .authorize(Namespace::parse("local").expect("ns"))
2633            .expect("authorize");
2634
2635        let entity =
2636            khive_storage::Entity::new("local", "concept", "tombstoned-entity-hard-delete");
2637        let entity_id = entity.id;
2638        runtime
2639            .entities(&token)
2640            .expect("entities store")
2641            .upsert_entity(entity.clone())
2642            .await
2643            .expect("seed entity");
2644        runtime
2645            .reindex_entity(&token, &entity)
2646            .await
2647            .expect("seed index rows");
2648
2649        let mut note =
2650            khive_storage::note::Note::new("local", "observation", "tombstoned-note-hard-delete");
2651        note.name = Some("tombstoned-note-hard-delete".to_string());
2652        let note_id = note.id;
2653        runtime
2654            .notes(&token)
2655            .expect("notes store")
2656            .upsert_note(note.clone())
2657            .await
2658            .expect("seed note");
2659        runtime
2660            .reindex_note(&token, &note)
2661            .await
2662            .expect("seed index rows");
2663
2664        // First: SOFT delete both (via atomic prepare) so they're tombstoned
2665        // going into the hard-delete attempt below.
2666        for id in [entity_id, note_id] {
2667            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2668                .await
2669                .expect("prepare soft delete");
2670            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2671                .await
2672                .expect("soft delete commit");
2673            assert!(matches!(
2674                outcome,
2675                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2676            ));
2677        }
2678        assert!(
2679            runtime
2680                .get_entity_including_deleted(&token, entity_id)
2681                .await
2682                .expect("get entity")
2683                .expect("entity present")
2684                .deleted_at
2685                .is_some(),
2686            "entity must be soft-deleted before the hard-delete attempt"
2687        );
2688        assert!(
2689            runtime
2690                .get_note_including_deleted(&token, note_id)
2691                .await
2692                .expect("get note")
2693                .expect("note present")
2694                .deleted_at
2695                .is_some(),
2696            "note must be soft-deleted before the hard-delete attempt"
2697        );
2698
2699        // Now: HARD delete the already-tombstoned records.
2700        for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2701            let plan = prepare_delete(
2702                &runtime,
2703                &token,
2704                &json!({"id": id.to_string(), "hard": true}),
2705                None,
2706            )
2707            .await
2708            .unwrap_or_else(|e| {
2709                panic!(
2710                    "prepare hard delete ({kind}) of an already-soft-deleted record \
2711                         must resolve it: {e}"
2712                )
2713            });
2714            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2715                .await
2716                .unwrap_or_else(|e| panic!("hard delete ({kind}) commit failed: {e}"));
2717            assert!(
2718                matches!(
2719                    outcome,
2720                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2721                ),
2722                "expected a clean hard-delete commit ({kind}): {outcome:?}"
2723            );
2724        }
2725
2726        assert!(
2727            runtime
2728                .get_entity_including_deleted(&token, entity_id)
2729                .await
2730                .expect("get entity")
2731                .is_none(),
2732            "entity row must be fully purged after hard delete"
2733        );
2734        assert!(
2735            runtime
2736                .get_note_including_deleted(&token, note_id)
2737                .await
2738                .expect("get note")
2739                .is_none(),
2740            "note row must be fully purged after hard delete"
2741        );
2742        assert!(
2743            runtime
2744                .text(&token)
2745                .expect("text store")
2746                .get_document("local", entity_id)
2747                .await
2748                .expect("get_document")
2749                .is_none(),
2750            "entity FTS row must be purged after hard delete"
2751        );
2752        assert!(
2753            runtime
2754                .text_for_notes(&token)
2755                .expect("text store")
2756                .get_document("local", note_id)
2757                .await
2758                .expect("get_document")
2759                .is_none(),
2760            "note FTS row must be purged after hard delete"
2761        );
2762        let vec_store = runtime
2763            .vectors_for_model(&token, STUB_MODEL)
2764            .expect("vec store");
2765        assert_eq!(
2766            vec_store.count().await.expect("count after"),
2767            0,
2768            "vector rows for both records must be purged after hard delete"
2769        );
2770    }
2771
2772    // ------------------------------------------------------------------
2773    // event-store append parity
2774    // ------------------------------------------------------------------
2775
2776    /// Fetch every event of `kind` targeting `target_id`, via the same
2777    /// `EventStore::query_events` surface `--atomic` callers would use to
2778    /// verify parity — not a raw SQL probe.
2779    async fn events_for_target(
2780        runtime: &KhiveRuntime,
2781        token: &NamespaceToken,
2782        target_id: Uuid,
2783        kind: EventKind,
2784    ) -> Vec<khive_storage::Event> {
2785        let event_store = runtime.events(token).expect("event store");
2786        let filter = khive_storage::EventFilter {
2787            kinds: vec![kind],
2788            ..Default::default()
2789        };
2790        let page = event_store
2791            .query_events(filter, khive_storage::types::PageRequest::default())
2792            .await
2793            .expect("query_events");
2794        page.items
2795            .into_iter()
2796            .filter(|e| e.target_id == Some(target_id))
2797            .collect()
2798    }
2799
2800    /// Atomic `update(id=<entity>, name=...)` must append an
2801    /// `EntityUpdated` event, matching `curation::update_entity`: the
2802    /// event is appended unconditionally after a successful row update,
2803    /// not only on the reindex-triggering subset.
2804    #[tokio::test]
2805    async fn atomic_update_entity_appends_entity_updated_event() {
2806        let runtime = scratch_runtime();
2807        let token = runtime
2808            .authorize(Namespace::parse("local").expect("ns"))
2809            .expect("authorize");
2810        let entity = khive_storage::Entity::new("local", "concept", "gap1-entity");
2811        let entity_id = entity.id;
2812        runtime
2813            .entities(&token)
2814            .expect("entities store")
2815            .upsert_entity(entity)
2816            .await
2817            .expect("seed entity");
2818
2819        let plan = prepare_update(
2820            &runtime,
2821            &token,
2822            &json!({"id": entity_id.to_string(), "name": "gap1-entity-renamed"}),
2823            None,
2824        )
2825        .await
2826        .expect("prepare update");
2827        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2828            .await
2829            .expect("seam call ok");
2830        assert!(matches!(
2831            outcome,
2832            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2833        ));
2834
2835        let events = events_for_target(&runtime, &token, entity_id, EventKind::EntityUpdated).await;
2836        assert_eq!(
2837            events.len(),
2838            1,
2839            "expected exactly one EntityUpdated event for {entity_id}"
2840        );
2841        assert_eq!(events[0].namespace, "local");
2842        assert_eq!(events[0].payload["id"], json!(entity_id.to_string()));
2843        assert_eq!(
2844            events[0].payload["changed_fields"],
2845            json!(["name"]),
2846            "changed_fields must name exactly the patched fields"
2847        );
2848    }
2849
2850    /// Atomic soft and hard delete of an entity must each append an
2851    /// `EntityDeleted` event, matching `operations::delete_entity`, which
2852    /// fires on both delete modes.
2853    #[tokio::test]
2854    async fn atomic_delete_entity_appends_entity_deleted_event_soft_and_hard() {
2855        let runtime = scratch_runtime();
2856        let token = runtime
2857            .authorize(Namespace::parse("local").expect("ns"))
2858            .expect("authorize");
2859
2860        for hard in [false, true] {
2861            let entity =
2862                khive_storage::Entity::new("local", "concept", format!("gap1-entity-hard-{hard}"));
2863            let entity_id = entity.id;
2864            runtime
2865                .entities(&token)
2866                .expect("entities store")
2867                .upsert_entity(entity)
2868                .await
2869                .expect("seed entity");
2870
2871            let args = if hard {
2872                json!({"id": entity_id.to_string(), "hard": true})
2873            } else {
2874                json!({"id": entity_id.to_string()})
2875            };
2876            let plan = prepare_delete(&runtime, &token, &args, None)
2877                .await
2878                .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
2879            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2880                .await
2881                .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
2882            assert!(
2883                matches!(
2884                    outcome,
2885                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2886                ),
2887                "expected a clean delete commit (hard={hard}): {outcome:?}"
2888            );
2889
2890            let events =
2891                events_for_target(&runtime, &token, entity_id, EventKind::EntityDeleted).await;
2892            assert_eq!(
2893                events.len(),
2894                1,
2895                "expected exactly one EntityDeleted event for {entity_id} (hard={hard})"
2896            );
2897            assert_eq!(events[0].payload["hard"], json!(hard));
2898        }
2899    }
2900
2901    #[tokio::test]
2902    async fn atomic_hard_delete_emits_lineage_warning_in_commit_unit() {
2903        let runtime = scratch_runtime();
2904        let token = NamespaceToken::mint_authorized(
2905            Namespace::local(),
2906            crate::ActorRef::new("agent", "atomic-lineage-deleter"),
2907        );
2908        let doomed = khive_storage::Entity::new("local", "document", "atomic-doomed");
2909        let source = khive_storage::Entity::new("local", "artifact", "atomic-source");
2910        let doomed_id = doomed.id;
2911        runtime
2912            .entities(&token)
2913            .expect("entities store")
2914            .upsert_entity(doomed)
2915            .await
2916            .expect("seed doomed entity");
2917        runtime
2918            .entities(&token)
2919            .expect("entities store")
2920            .upsert_entity(source.clone())
2921            .await
2922            .expect("seed source entity");
2923        runtime
2924            .link(
2925                &token,
2926                source.id,
2927                doomed_id,
2928                EdgeRelation::DerivedFrom,
2929                1.0,
2930                None,
2931            )
2932            .await
2933            .expect("seed protected edge");
2934
2935        let plan = prepare_delete(
2936            &runtime,
2937            &token,
2938            &json!({"id": doomed_id.to_string(), "hard": true}),
2939            None,
2940        )
2941        .await
2942        .expect("prepare hard delete");
2943        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2944            .await
2945            .expect("delete commit");
2946        assert!(matches!(
2947            outcome,
2948            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2949        ));
2950
2951        let warnings = events_for_target(&runtime, &token, doomed_id, EventKind::Audit).await;
2952        assert_eq!(warnings.len(), 1);
2953        assert_eq!(warnings[0].actor, "agent:atomic-lineage-deleter");
2954        assert_eq!(warnings[0].payload["relation"], "derived_from");
2955        assert_eq!(warnings[0].payload["warning"], "provenance_loss");
2956    }
2957
2958    /// Atomic soft and hard delete of a note must each append a
2959    /// `NoteDeleted` event, matching `operations::delete_note`, which
2960    /// fires on both delete modes.
2961    #[tokio::test]
2962    async fn atomic_delete_note_appends_note_deleted_event_soft_and_hard() {
2963        let runtime = scratch_runtime();
2964        let token = runtime
2965            .authorize(Namespace::parse("local").expect("ns"))
2966            .expect("authorize");
2967
2968        for hard in [false, true] {
2969            let mut note = khive_storage::note::Note::new(
2970                "local",
2971                "observation",
2972                format!("gap1-note-content-hard-{hard}"),
2973            );
2974            note.name = Some(format!("gap1-note-hard-{hard}"));
2975            let note_id = note.id;
2976            runtime
2977                .notes(&token)
2978                .expect("notes store")
2979                .upsert_note(note)
2980                .await
2981                .expect("seed note");
2982
2983            let args = if hard {
2984                json!({"id": note_id.to_string(), "hard": true})
2985            } else {
2986                json!({"id": note_id.to_string()})
2987            };
2988            let plan = prepare_delete(&runtime, &token, &args, None)
2989                .await
2990                .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
2991            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2992                .await
2993                .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
2994            assert!(
2995                matches!(
2996                    outcome,
2997                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2998                ),
2999                "expected a clean delete commit (hard={hard}): {outcome:?}"
3000            );
3001
3002            let events = events_for_target(&runtime, &token, note_id, EventKind::NoteDeleted).await;
3003            assert_eq!(
3004                events.len(),
3005                1,
3006                "expected exactly one NoteDeleted event for {note_id} (hard={hard})"
3007            );
3008            assert_eq!(events[0].payload["hard"], json!(hard));
3009        }
3010    }
3011
3012    /// `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`; this
3013    /// asserts `prepare_update` actually builds a plan for one, a
3014    /// non-symmetric relation (`extends`) exercises the
3015    /// `edge_upsert_statement` reuse branch, and that the committed row +
3016    /// `EdgeUpdated` event match canonical `update_edge`'s shape (weight
3017    /// persisted, relation unchanged, exactly one event).
3018    #[tokio::test]
3019    async fn atomic_update_edge_patches_weight_and_appends_edge_updated_event() {
3020        let runtime = scratch_runtime();
3021        let token = runtime
3022            .authorize(Namespace::parse("local").expect("ns"))
3023            .expect("authorize");
3024        let entities = runtime.entities(&token).expect("entities store");
3025        let a = khive_storage::Entity::new("local", "concept", "GapEdgeA");
3026        let b = khive_storage::Entity::new("local", "concept", "GapEdgeB");
3027        let (a_id, b_id) = (a.id, b.id);
3028        entities.upsert_entity(a).await.expect("seed a");
3029        entities.upsert_entity(b).await.expect("seed b");
3030
3031        let edge = runtime
3032            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.4, None)
3033            .await
3034            .expect("seed edge");
3035        let edge_id = Uuid::from(edge.id);
3036
3037        let plan = prepare_update(
3038            &runtime,
3039            &token,
3040            &json!({"id": edge_id.to_string(), "weight": 0.75}),
3041            None,
3042        )
3043        .await
3044        .expect("prepare update edge");
3045        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3046            .await
3047            .expect("seam call ok");
3048        assert!(
3049            matches!(
3050                outcome,
3051                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3052            ),
3053            "expected a clean edge update commit: {outcome:?}"
3054        );
3055
3056        let updated = runtime
3057            .get_edge(&token, edge_id)
3058            .await
3059            .expect("get_edge")
3060            .expect("edge still present");
3061        assert_eq!(updated.weight, 0.75, "weight patch must persist");
3062        assert_eq!(updated.relation, EdgeRelation::Extends);
3063
3064        let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeUpdated).await;
3065        assert_eq!(
3066            events.len(),
3067            1,
3068            "expected exactly one EdgeUpdated event for {edge_id}"
3069        );
3070        assert_eq!(
3071            events[0].payload["changed_fields"],
3072            json!(["weight"]),
3073            "changed_fields must name exactly the patched field"
3074        );
3075    }
3076
3077    /// The symmetric-relation conflict-absorption branch of
3078    /// `prepare_update_edge` — mirrors `update_edge_symmetric_dml`'s case
3079    /// (b): changing a non-symmetric edge's `relation` to a symmetric one
3080    /// whose canonical natural key collides with an ALREADY-EXISTING
3081    /// symmetric edge between the same two entities must delete the
3082    /// requested (non-canonical) row and leave the surviving canonical row
3083    /// untouched (ADR-039 ON CONFLICT DO NOTHING), rather than raising a
3084    /// uniqueness error OR overwriting the survivor with the discarded
3085    /// edge's attributes (khive#1213).
3086    #[tokio::test]
3087    async fn atomic_update_edge_symmetric_conflict_absorbs_into_surviving_row() {
3088        let runtime = scratch_runtime();
3089        let token = runtime
3090            .authorize(Namespace::parse("local").expect("ns"))
3091            .expect("authorize");
3092        let entities = runtime.entities(&token).expect("entities store");
3093        let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymA");
3094        let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymB");
3095        let (a_id, b_id) = (a.id, b.id);
3096        entities.upsert_entity(a).await.expect("seed a");
3097        entities.upsert_entity(b).await.expect("seed b");
3098
3099        // The non-canonical edge under test: A -> B, non-symmetric relation.
3100        let requested_edge = runtime
3101            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3102            .await
3103            .expect("seed requested edge");
3104        let requested_id = Uuid::from(requested_edge.id);
3105
3106        // The pre-existing canonical row this update will collide with once
3107        // `relation` becomes `competes_with` (symmetric).
3108        let canonical_edge = runtime
3109            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3110            .await
3111            .expect("seed canonical edge");
3112        let canonical_id = Uuid::from(canonical_edge.id);
3113        assert_ne!(requested_id, canonical_id);
3114
3115        let plan = prepare_update(
3116            &runtime,
3117            &token,
3118            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3119            None,
3120        )
3121        .await
3122        .expect("prepare update edge (symmetric conflict)");
3123        // The plan does not compute a prepare-time advisory surviving id
3124        // (`target_id` is just the requested id): it carries
3125        // `edge_natural_key` so a post-commit caller can derive the real
3126        // surviving id itself. Assert the plan carries the right natural
3127        // key to look up; the actual surviving row's identity is verified
3128        // against the DB after commit, below.
3129        let (canon_src, canon_tgt) =
3130            canonical_edge_endpoints(EdgeRelation::CompetesWith, a_id, b_id);
3131        match &plan {
3132            AtomicOpPlan::Update(p) => {
3133                assert_eq!(p.target_id, requested_id);
3134                let key = p
3135                    .edge_natural_key
3136                    .as_ref()
3137                    .expect("symmetric edge update must carry edge_natural_key");
3138                assert_eq!(key.canon_source_id, canon_src);
3139                assert_eq!(key.canon_target_id, canon_tgt);
3140                assert_eq!(key.relation, EdgeRelation::CompetesWith);
3141            }
3142            other => panic!("expected an Update plan, got {other:?}"),
3143        }
3144
3145        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3146            .await
3147            .expect("seam call ok");
3148        assert!(
3149            matches!(
3150                outcome,
3151                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3152            ),
3153            "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3154        );
3155
3156        // The requested (non-canonical) row must be gone.
3157        let requested_after = runtime
3158            .get_edge_including_deleted(&token, requested_id)
3159            .await
3160            .expect("get_edge_including_deleted");
3161        assert!(
3162            requested_after.is_none(),
3163            "the non-canonical requested row must be deleted, not just tombstoned"
3164        );
3165
3166        // ADR-039 DO NOTHING: the surviving canonical row keeps its OWN
3167        // pre-existing attributes — the discarded edge's patched weight
3168        // (0.9) must never overwrite it.
3169        let surviving = runtime
3170            .get_edge(&token, canonical_id)
3171            .await
3172            .expect("get_edge")
3173            .expect("surviving canonical row must remain");
3174        assert_eq!(
3175            surviving.weight, 0.6,
3176            "survivor weight must not be overwritten by the discarded edge's patch"
3177        );
3178        assert_eq!(surviving.relation, EdgeRelation::CompetesWith);
3179
3180        // Event target is the CALLER-supplied id, not the surviving id —
3181        // mirrors `update_edge`'s event using `edge_id` (the caller's
3182        // original argument), not the post-absorption id.
3183        let events =
3184            events_for_target(&runtime, &token, requested_id, EventKind::EdgeUpdated).await;
3185        assert_eq!(events.len(), 1);
3186    }
3187
3188    /// A soft-deleted surviving canonical row must not be resurrected by a
3189    /// conflicting symmetric-relation update (ADR-039 DO NOTHING; khive#1213):
3190    /// the requested edge is still deleted (conflict absorbed), but the
3191    /// tombstoned survivor must stay tombstoned.
3192    #[tokio::test]
3193    async fn atomic_update_edge_symmetric_conflict_does_not_resurrect_tombstoned_survivor() {
3194        let runtime = scratch_runtime();
3195        let token = runtime
3196            .authorize(Namespace::parse("local").expect("ns"))
3197            .expect("authorize");
3198        let entities = runtime.entities(&token).expect("entities store");
3199        let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombA");
3200        let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombB");
3201        let (a_id, b_id) = (a.id, b.id);
3202        entities.upsert_entity(a).await.expect("seed a");
3203        entities.upsert_entity(b).await.expect("seed b");
3204
3205        let requested_edge = runtime
3206            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3207            .await
3208            .expect("seed requested edge");
3209        let requested_id = Uuid::from(requested_edge.id);
3210
3211        let canonical_edge = runtime
3212            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3213            .await
3214            .expect("seed canonical edge");
3215        let canonical_id = Uuid::from(canonical_edge.id);
3216        runtime
3217            .delete_edge(&token, canonical_id, false)
3218            .await
3219            .expect("soft-delete canonical edge");
3220
3221        let plan = prepare_update(
3222            &runtime,
3223            &token,
3224            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3225            None,
3226        )
3227        .await
3228        .expect("prepare update edge (symmetric conflict over tombstone)");
3229
3230        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3231            .await
3232            .expect("seam call ok");
3233        assert!(
3234            matches!(
3235                outcome,
3236                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3237            ),
3238            "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3239        );
3240
3241        let requested_after = runtime
3242            .get_edge_including_deleted(&token, requested_id)
3243            .await
3244            .expect("get_edge_including_deleted");
3245        assert!(
3246            requested_after.is_none(),
3247            "the non-canonical requested row must be deleted, not just tombstoned"
3248        );
3249
3250        let canonical_after = runtime
3251            .get_edge(&token, canonical_id)
3252            .await
3253            .expect("get_edge");
3254        assert!(
3255            canonical_after.is_none(),
3256            "a tombstoned survivor must not be resurrected by a conflicting update"
3257        );
3258    }
3259
3260    /// The same-unit race: `[delete(X), update(X -> competes_with)]` where
3261    /// an already-existing canonical row sits at the post-update natural
3262    /// key. Both ops' async prepare passes run before either commits, so at
3263    /// prepare time `X` still exists and both plans build. At commit time
3264    /// `delete(X)` removes it first; `update(X -> competes_with)`'s own
3265    /// commit-time statements must then fail loud (its target no longer
3266    /// exists) rather than silently absorbing into the pre-existing
3267    /// canonical row it never causally touched. The whole atomic unit must
3268    /// roll back — parity with canonical `update_edge`'s `NotFound` for a
3269    /// missing edge, expressed here as the unit-level abort for any op
3270    /// whose commit-time guard fails.
3271    #[tokio::test]
3272    async fn atomic_update_edge_symmetric_same_unit_delete_race_aborts_the_unit() {
3273        let runtime = scratch_runtime();
3274        let token = runtime
3275            .authorize(Namespace::parse("local").expect("ns"))
3276            .expect("authorize");
3277        let entities = runtime.entities(&token).expect("entities store");
3278        let a = khive_storage::Entity::new("local", "concept", "GapEdgeRaceA");
3279        let b = khive_storage::Entity::new("local", "concept", "GapEdgeRaceB");
3280        let (a_id, b_id) = (a.id, b.id);
3281        entities.upsert_entity(a).await.expect("seed a");
3282        entities.upsert_entity(b).await.expect("seed b");
3283
3284        // The row op 1 will try to update — deleted by op 0 in the SAME unit.
3285        let requested_edge = runtime
3286            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3287            .await
3288            .expect("seed requested edge");
3289        let requested_id = Uuid::from(requested_edge.id);
3290
3291        // The pre-existing canonical row the buggy `id = ?2 OR natural-key`
3292        // predicate used to silently absorb into.
3293        let canonical_edge = runtime
3294            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3295            .await
3296            .expect("seed canonical edge");
3297        let canonical_id = Uuid::from(canonical_edge.id);
3298
3299        let delete_plan = prepare_delete(
3300            &runtime,
3301            &token,
3302            &json!({"id": requested_id.to_string(), "hard": true}),
3303            None,
3304        )
3305        .await
3306        .expect("prepare delete edge");
3307        let update_plan = prepare_update(
3308            &runtime,
3309            &token,
3310            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3311            None,
3312        )
3313        .await
3314        .expect("prepare update edge (both prepares run before either commits)");
3315
3316        let outcome = crate::atomic_runner::run_atomic_unit(
3317            runtime.sql().as_ref(),
3318            vec![delete_plan, update_plan],
3319        )
3320        .await
3321        .expect("the seam call itself must not error — the unit rolls back cleanly");
3322        match outcome {
3323            crate::atomic_runner::AtomicRunOutcome::RolledBack {
3324                failed_op_index, ..
3325            } => {
3326                assert_eq!(
3327                    failed_op_index, 1,
3328                    "op 1 (the update) must be the one whose guard fails"
3329                );
3330            }
3331            other => panic!("expected the whole unit to roll back, got {other:?}"),
3332        }
3333
3334        // Whole-unit rollback: op 0's delete must be undone too.
3335        let requested_after = runtime
3336            .get_edge(&token, requested_id)
3337            .await
3338            .expect("get_edge");
3339        assert!(
3340            requested_after.is_some(),
3341            "delete(X) must have rolled back along with the failed update"
3342        );
3343        // The pre-existing canonical row must be completely untouched.
3344        let canonical_after = runtime
3345            .get_edge(&token, canonical_id)
3346            .await
3347            .expect("get_edge")
3348            .expect("canonical row must still be present");
3349        assert_eq!(
3350            canonical_after.weight, 0.6,
3351            "the pre-existing canonical row must never have been touched by the aborted update"
3352        );
3353    }
3354
3355    /// `update` rejects an entity/note-only field (`name`) on an edge
3356    /// target, mirroring
3357    /// `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
3358    /// `KindSpec::Edge` arm.
3359    #[tokio::test]
3360    async fn atomic_update_edge_rejects_entity_only_field_name() {
3361        let runtime = scratch_runtime();
3362        let token = runtime
3363            .authorize(Namespace::parse("local").expect("ns"))
3364            .expect("authorize");
3365        let entities = runtime.entities(&token).expect("entities store");
3366        let a = khive_storage::Entity::new("local", "concept", "GapEdgeRejectA");
3367        let b = khive_storage::Entity::new("local", "concept", "GapEdgeRejectB");
3368        let (a_id, b_id) = (a.id, b.id);
3369        entities.upsert_entity(a).await.expect("seed a");
3370        entities.upsert_entity(b).await.expect("seed b");
3371        let edge = runtime
3372            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
3373            .await
3374            .expect("seed edge");
3375        let edge_id = Uuid::from(edge.id);
3376
3377        let err = prepare_update(
3378            &runtime,
3379            &token,
3380            &json!({"id": edge_id.to_string(), "name": "not-a-valid-edge-field"}),
3381            None,
3382        )
3383        .await
3384        .expect_err("edge update with an entity-only field must be rejected");
3385        let message = err.to_string();
3386        assert!(
3387            message.contains("name") && message.contains("edge"),
3388            "error must name the offending field and the substrate: {message}"
3389        );
3390    }
3391
3392    /// `delete` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`; this
3393    /// asserts `prepare_delete` actually builds a plan for one on both soft
3394    /// and hard delete, matching `operations::delete_edge`'s row-mode DML
3395    /// and unconditional `EdgeDeleted` event.
3396    #[tokio::test]
3397    async fn atomic_delete_edge_soft_and_hard_appends_edge_deleted_event() {
3398        let runtime = scratch_runtime();
3399        let token = runtime
3400            .authorize(Namespace::parse("local").expect("ns"))
3401            .expect("authorize");
3402
3403        for hard in [false, true] {
3404            let entities = runtime.entities(&token).expect("entities store");
3405            let a = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelA{hard}"));
3406            let b = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelB{hard}"));
3407            let (a_id, b_id) = (a.id, b.id);
3408            entities.upsert_entity(a).await.expect("seed a");
3409            entities.upsert_entity(b).await.expect("seed b");
3410            let edge = runtime
3411                .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
3412                .await
3413                .expect("seed edge");
3414            let edge_id = Uuid::from(edge.id);
3415
3416            let args = if hard {
3417                json!({"id": edge_id.to_string(), "hard": true})
3418            } else {
3419                json!({"id": edge_id.to_string()})
3420            };
3421            let plan = prepare_delete(&runtime, &token, &args, None)
3422                .await
3423                .unwrap_or_else(|e| panic!("prepare delete edge (hard={hard}): {e}"));
3424            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3425                .await
3426                .unwrap_or_else(|e| panic!("edge delete commit (hard={hard}): {e}"));
3427            assert!(
3428                matches!(
3429                    outcome,
3430                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3431                ),
3432                "expected a clean edge delete commit (hard={hard}): {outcome:?}"
3433            );
3434
3435            let after = runtime
3436                .get_edge_including_deleted(&token, edge_id)
3437                .await
3438                .expect("get_edge_including_deleted");
3439            if hard {
3440                assert!(after.is_none(), "hard delete must purge the row entirely");
3441            } else {
3442                assert!(
3443                    after.as_ref().is_some_and(|e| e.deleted_at.is_some()),
3444                    "soft delete must tombstone, not purge"
3445                );
3446            }
3447
3448            let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeDeleted).await;
3449            assert_eq!(
3450                events.len(),
3451                1,
3452                "expected exactly one EdgeDeleted event for {edge_id} (hard={hard})"
3453            );
3454            assert_eq!(events[0].payload["hard"], json!(hard));
3455        }
3456    }
3457
3458    /// Parity boundary: atomic `update` of a note must append no event:
3459    /// canonical `update_note` never calls `append_event` (unlike
3460    /// `update_entity`, which always does).
3461    #[tokio::test]
3462    async fn atomic_update_note_appends_no_event() {
3463        let runtime = scratch_runtime();
3464        let token = runtime
3465            .authorize(Namespace::parse("local").expect("ns"))
3466            .expect("authorize");
3467        let mut note = khive_storage::note::Note::new("local", "observation", "gap1-note-noevent");
3468        note.name = Some("gap1-note-noevent".to_string());
3469        let note_id = note.id;
3470        runtime
3471            .notes(&token)
3472            .expect("notes store")
3473            .upsert_note(note)
3474            .await
3475            .expect("seed note");
3476
3477        let plan = prepare_update(
3478            &runtime,
3479            &token,
3480            &json!({"id": note_id.to_string(), "content": "gap1-note-noevent, revised"}),
3481            None,
3482        )
3483        .await
3484        .expect("prepare update");
3485        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3486            .await
3487            .expect("seam call ok");
3488        assert!(matches!(
3489            outcome,
3490            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3491        ));
3492
3493        let event_store = runtime.events(&token).expect("event store");
3494        let page = event_store
3495            .query_events(
3496                khive_storage::EventFilter::default(),
3497                khive_storage::types::PageRequest::default(),
3498            )
3499            .await
3500            .expect("query_events");
3501        assert!(
3502            page.items.iter().all(|e| e.target_id != Some(note_id)),
3503            "update_note must append no event; found: {:?}",
3504            page.items
3505                .iter()
3506                .filter(|e| e.target_id == Some(note_id))
3507                .collect::<Vec<_>>()
3508        );
3509    }
3510
3511    /// Parity boundary: atomic `link` must append no event: canonical
3512    /// `link` never calls `append_event`.
3513    #[tokio::test]
3514    async fn atomic_link_appends_no_event() {
3515        let runtime = scratch_runtime();
3516        let token = runtime
3517            .authorize(Namespace::parse("local").expect("ns"))
3518            .expect("authorize");
3519        let source = khive_storage::Entity::new("local", "concept", "gap1-link-source");
3520        let target = khive_storage::Entity::new("local", "concept", "gap1-link-target");
3521        let (source_id, target_id) = (source.id, target.id);
3522        runtime
3523            .entities(&token)
3524            .expect("entities store")
3525            .upsert_entity(source)
3526            .await
3527            .expect("seed source");
3528        runtime
3529            .entities(&token)
3530            .expect("entities store")
3531            .upsert_entity(target)
3532            .await
3533            .expect("seed target");
3534
3535        let plan = prepare_link(
3536            &runtime,
3537            &token,
3538            &json!({
3539                "source_id": source_id.to_string(),
3540                "target_id": target_id.to_string(),
3541                "relation": "extends",
3542            }),
3543        )
3544        .await
3545        .expect("prepare link");
3546        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3547            .await
3548            .expect("seam call ok");
3549        assert!(matches!(
3550            outcome,
3551            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3552        ));
3553
3554        let event_store = runtime.events(&token).expect("event store");
3555        let page = event_store
3556            .query_events(
3557                khive_storage::EventFilter::default(),
3558                khive_storage::types::PageRequest::default(),
3559            )
3560            .await
3561            .expect("query_events");
3562        assert!(
3563            page.items.is_empty(),
3564            "link must append no event; found: {:?}",
3565            page.items
3566        );
3567    }
3568
3569    // ------------------------------------------------------------------
3570    // AddEntity and AddNote plans alongside link
3571    // ------------------------------------------------------------------
3572
3573    #[tokio::test]
3574    async fn prepare_add_entity_rejects_whitespace_only_name() {
3575        let runtime = scratch_runtime();
3576        let token = runtime
3577            .authorize(Namespace::parse("local").expect("ns"))
3578            .expect("authorize");
3579
3580        let err = prepare_add_entity(&runtime, &token, &json!({"kind": "concept", "name": "   "}))
3581            .await
3582            .expect_err("whitespace-only entity name must fail prepare");
3583
3584        assert!(matches!(
3585            err,
3586            RuntimeError::InvalidInput(message) if message.contains("name must not be empty")
3587        ));
3588    }
3589
3590    #[tokio::test]
3591    async fn prepare_add_entity_rejects_non_string_description() {
3592        let runtime = scratch_runtime();
3593        let token = runtime
3594            .authorize(Namespace::parse("local").expect("ns"))
3595            .expect("authorize");
3596
3597        let err = prepare_add_entity(
3598            &runtime,
3599            &token,
3600            &json!({"kind": "concept", "name": "Valid", "description": 42}),
3601        )
3602        .await
3603        .expect_err("non-string entity description must fail prepare");
3604
3605        assert!(matches!(
3606            err,
3607            RuntimeError::InvalidInput(message)
3608                if message.contains("description must be a string or null")
3609        ));
3610    }
3611
3612    #[tokio::test]
3613    async fn prepare_add_note_rejects_non_string_name() {
3614        let runtime = scratch_runtime();
3615        let token = runtime
3616            .authorize(Namespace::parse("local").expect("ns"))
3617            .expect("authorize");
3618
3619        let err = prepare_add_note(
3620            &runtime,
3621            &token,
3622            &json!({"kind": "observation", "content": "Valid", "name": 42}),
3623        )
3624        .await
3625        .expect_err("non-string note name must fail prepare");
3626
3627        assert!(matches!(
3628            err,
3629            RuntimeError::InvalidInput(message) if message.contains("name must be a string or null")
3630        ));
3631    }
3632
3633    #[tokio::test]
3634    async fn atomic_proposal_vectors_materialize_only_after_successful_commit() {
3635        let runtime = scratch_runtime();
3636        runtime.register_embedder(StubProvider);
3637        let token = runtime
3638            .authorize(Namespace::parse("local").expect("ns"))
3639            .expect("authorize");
3640        let vec_store = runtime
3641            .vectors_for_model(&token, STUB_MODEL)
3642            .expect("vec store");
3643        let entities = runtime.entities(&token).expect("entities store");
3644        let a = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkA");
3645        let b = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkB");
3646        let (a_id, b_id) = (a.id, b.id);
3647        entities.upsert_entity(a).await.expect("seed a");
3648        entities.upsert_entity(b).await.expect("seed b");
3649
3650        let add_entity_plan = prepare_add_entity(
3651            &runtime,
3652            &token,
3653            &json!({"kind": "concept", "name": "ProposalPlanNewEntity", "description": "created atomically"}),
3654        )
3655        .await
3656        .expect("prepare add_entity");
3657        let link_plan = prepare_link(
3658            &runtime,
3659            &token,
3660            &json!({"source_id": a_id.to_string(), "target_id": b_id.to_string(), "relation": "extends"}),
3661        )
3662        .await
3663        .expect("prepare link");
3664        let add_note_plan = prepare_add_note(
3665            &runtime,
3666            &token,
3667            &json!({"kind": "observation", "content": "created atomically alongside the entity"}),
3668        )
3669        .await
3670        .expect("prepare add_note");
3671
3672        let entity_id = match &add_entity_plan {
3673            AtomicOpPlan::AddEntity(p) => p.entity_id,
3674            other => panic!("expected an AddEntity plan, got {other:?}"),
3675        };
3676        let note_id = match &add_note_plan {
3677            AtomicOpPlan::AddNote(p) => p.note_id,
3678            other => panic!("expected an AddNote plan, got {other:?}"),
3679        };
3680
3681        let outcome = crate::atomic_runner::run_atomic_unit(
3682            runtime.sql().as_ref(),
3683            vec![add_entity_plan, link_plan, add_note_plan],
3684        )
3685        .await
3686        .expect("seam call ok");
3687        let post_commit = match outcome {
3688            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
3689            other => panic!("expected the whole unit to commit: {other:?}"),
3690        };
3691        assert_eq!(
3692            post_commit.as_slice(),
3693            &[
3694                PostCommitEffect::ReindexEntity { entity_id },
3695                PostCommitEffect::ReindexNote { note_id },
3696            ],
3697            "prepare-derived effects must reach the committed token unchanged"
3698        );
3699        assert_eq!(
3700            vec_store.count().await.expect("count before effects"),
3701            0,
3702            "commit returns deferred effects without materializing vectors"
3703        );
3704        let entity = runtime
3705            .entities(&token)
3706            .expect("entities store")
3707            .get_entity(entity_id)
3708            .await
3709            .expect("get_entity")
3710            .expect("entity must exist after commit");
3711        assert_eq!(entity.name, "ProposalPlanNewEntity");
3712        assert!(
3713            runtime
3714                .text(&token)
3715                .expect("text store")
3716                .get_document("local", entity_id)
3717                .await
3718                .expect("get_document")
3719                .is_some(),
3720            "entity's FTS document must exist after commit"
3721        );
3722
3723        let (edge_count, _, _, edge_deleted_at) =
3724            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
3725        assert_eq!(
3726            edge_count, 1,
3727            "the edge must be committed alongside the entity/note"
3728        );
3729        assert!(edge_deleted_at.is_none());
3730
3731        let note = runtime
3732            .notes(&token)
3733            .expect("notes store")
3734            .get_note(note_id)
3735            .await
3736            .expect("get_note")
3737            .expect("note must exist after commit");
3738        assert_eq!(note.content, "created atomically alongside the entity");
3739        assert!(
3740            runtime
3741                .text_for_notes(&token)
3742                .expect("text store")
3743                .get_document("local", note_id)
3744                .await
3745                .expect("get_document")
3746                .is_some(),
3747            "note's FTS document must exist after commit"
3748        );
3749
3750        apply_post_commit_effects(&runtime, &token, post_commit)
3751            .await
3752            .expect("apply post-commit effects");
3753
3754        assert_eq!(
3755            vec_store.count().await.expect("count after"),
3756            2,
3757            "post-commit reindex must have embedded both the new entity and the new note"
3758        );
3759    }
3760
3761    #[tokio::test]
3762    async fn atomic_proposal_abort_leaves_zero_vector_rows() {
3763        let runtime = scratch_runtime();
3764        runtime.register_embedder(StubProvider);
3765        let token = runtime
3766            .authorize(Namespace::parse("local").expect("ns"))
3767            .expect("authorize");
3768        let vec_store = runtime
3769            .vectors_for_model(&token, STUB_MODEL)
3770            .expect("vec store");
3771        let entities = runtime.entities(&token).expect("entities store");
3772        let a = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackA");
3773        let x = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackX");
3774        let (a_id, x_id) = (a.id, x.id);
3775        entities.upsert_entity(a).await.expect("seed a");
3776        entities.upsert_entity(x.clone()).await.expect("seed x");
3777
3778        let add_entity_plan = prepare_add_entity(
3779            &runtime,
3780            &token,
3781            &json!({"kind": "concept", "name": "ProposalPlanRollbackNewEntity"}),
3782        )
3783        .await
3784        .expect("prepare add_entity");
3785        let add_note_plan = prepare_add_note(
3786            &runtime,
3787            &token,
3788            &json!({"kind": "observation", "content": "must not survive the rollback"}),
3789        )
3790        .await
3791        .expect("prepare add_note");
3792        let delete_plan = prepare_delete(
3793            &runtime,
3794            &token,
3795            &json!({"id": x_id.to_string(), "hard": true}),
3796            None,
3797        )
3798        .await
3799        .expect("prepare delete x");
3800        // Prepare sees x before the transaction; the guarded link must detect
3801        // that the preceding hard delete removed it inside the transaction.
3802        let link_plan = prepare_link(
3803            &runtime,
3804            &token,
3805            &json!({"source_id": a_id.to_string(), "target_id": x_id.to_string(), "relation": "extends"}),
3806        )
3807        .await
3808        .expect("prepare link (endpoint still exists at prepare time)");
3809
3810        let entity_id = match &add_entity_plan {
3811            AtomicOpPlan::AddEntity(p) => p.entity_id,
3812            other => panic!("expected an AddEntity plan, got {other:?}"),
3813        };
3814        let note_id = match &add_note_plan {
3815            AtomicOpPlan::AddNote(p) => p.note_id,
3816            other => panic!("expected an AddNote plan, got {other:?}"),
3817        };
3818
3819        let outcome = crate::atomic_runner::run_atomic_unit(
3820            runtime.sql().as_ref(),
3821            vec![add_entity_plan, add_note_plan, delete_plan, link_plan],
3822        )
3823        .await
3824        .expect("the seam call itself must not error; the unit rolls back cleanly");
3825        match outcome {
3826            crate::atomic_runner::AtomicRunOutcome::RolledBack {
3827                failed_op_index, ..
3828            } => {
3829                assert_eq!(
3830                    failed_op_index, 3,
3831                    "the trailing link (index 3) must be the op whose guard fails"
3832                );
3833            }
3834            other => panic!("expected the whole unit to roll back, got {other:?}"),
3835        }
3836
3837        assert_eq!(
3838            vec_store
3839                .count()
3840                .await
3841                .expect("vector count after rollback"),
3842            0,
3843            "a rolled-back atomic apply must not materialize vectors"
3844        );
3845
3846        assert!(
3847            runtime
3848                .get_entity_including_deleted(&token, entity_id)
3849                .await
3850                .expect("get_entity_including_deleted")
3851                .is_none(),
3852            "the new entity must leave zero trace after rollback"
3853        );
3854        assert!(
3855            runtime
3856                .text(&token)
3857                .expect("text store")
3858                .get_document("local", entity_id)
3859                .await
3860                .expect("get_document")
3861                .is_none(),
3862            "the new entity's FTS document must leave zero trace after rollback"
3863        );
3864        assert!(
3865            runtime
3866                .get_note_including_deleted(&token, note_id)
3867                .await
3868                .expect("get_note_including_deleted")
3869                .is_none(),
3870            "the new note must leave zero trace after rollback"
3871        );
3872        assert!(
3873            runtime
3874                .text_for_notes(&token)
3875                .expect("text store")
3876                .get_document("local", note_id)
3877                .await
3878                .expect("get_document")
3879                .is_none(),
3880            "the new note's FTS document must leave zero trace after rollback"
3881        );
3882
3883        let x_after = runtime
3884            .get_entity_including_deleted(&token, x_id)
3885            .await
3886            .expect("get_entity_including_deleted")
3887            .expect("x must still be present because its delete rolled back too");
3888        assert!(
3889            x_after.deleted_at.is_none(),
3890            "x's delete must have rolled back along with the failed link"
3891        );
3892
3893        let (edge_count, _, _, _) =
3894            probe_edge_natural_key(&runtime, "local", a_id, x_id, "extends").await;
3895        assert_eq!(edge_count, 0, "no edge may have been committed");
3896    }
3897}