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::{AttachmentSubstrate, 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::attachment::delete_record_attachments_statement;
41use khive_db::stores::entity::{
42    entity_hard_delete_statement, entity_replace_if_unchanged_statement,
43    entity_soft_delete_statement, entity_upsert_statement,
44};
45use khive_db::stores::event::event_insert_statements;
46use khive_db::stores::event::hard_delete_lineage_warning_statements;
47use khive_db::stores::graph::{
48    edge_hard_delete_statement, edge_insert_guarded_by_endpoints_statement,
49    edge_replace_if_unchanged_statement, edge_soft_delete_statement,
50    edge_symmetric_absorb_or_update_inplace_statement, edge_symmetric_delete_if_conflict_statement,
51    purge_incident_edges_statement,
52};
53use khive_db::stores::note::{
54    note_hard_delete_statement, note_replace_if_unchanged_statement, note_soft_delete_statement,
55    note_upsert_statement,
56};
57use khive_db::stores::text::insert_document_statement;
58
59// ---------------------------------------------------------------------------
60// arg extraction helpers
61// ---------------------------------------------------------------------------
62
63fn obj(args: &Value) -> RuntimeResult<&serde_json::Map<String, Value>> {
64    args.as_object()
65        .ok_or_else(|| RuntimeError::InvalidInput("op args must be a JSON object".into()))
66}
67
68fn require_str<'a>(args: &'a Value, key: &str) -> RuntimeResult<&'a str> {
69    obj(args)?
70        .get(key)
71        .and_then(|v| v.as_str())
72        .ok_or_else(|| RuntimeError::InvalidInput(format!("missing required field {key:?}")))
73}
74
75fn require_uuid(args: &Value, key: &str) -> RuntimeResult<Uuid> {
76    let raw = require_str(args, key)?;
77    Uuid::parse_str(raw)
78        .map_err(|_| RuntimeError::InvalidInput(format!("{key} must be a full UUID; got {raw:?}")))
79}
80
81fn optional_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
82    obj(args).ok()?.get(key).and_then(|v| v.as_str())
83}
84
85fn optional_create_string(args: &Value, key: &str) -> RuntimeResult<Option<String>> {
86    match obj(args)?.get(key) {
87        None | Some(Value::Null) => Ok(None),
88        Some(Value::String(value)) => Ok(Some(value.clone())),
89        Some(other) => Err(RuntimeError::InvalidInput(format!(
90            "{key} must be a string or null, got: {other}"
91        ))),
92    }
93}
94
95/// ADR-014 tri-state patch for entity `entity_type`, read from raw JSON to
96/// mirror `UpdateParams.entity_type`'s `tri_string` deserializer (the
97/// kkernel `--atomic` seam deserializes through that struct first, so the
98/// two surfaces cannot diverge): key absent -> `None` (unchanged), key
99/// present as `null` -> `Some(None)` (explicit clear), key present as a
100/// string -> `Some(Some(s))` (set); any other JSON type -> a hard error.
101fn optional_entity_type_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<String>>> {
102    match obj(args)?.get(key) {
103        None => Ok(None),
104        Some(Value::Null) => Ok(Some(None)),
105        Some(Value::String(value)) => Ok(Some(Some(value.clone()))),
106        Some(other) => Err(RuntimeError::InvalidInput(format!(
107            "{key} must be a string or null, got: {other}"
108        ))),
109    }
110}
111
112/// Nullable-string patch semantics mirroring the actually-reachable behavior
113/// of `khive-pack-kg::handlers::common::optional_string_patch`/
114/// `description_patch`, reimplemented here rather than imported (that
115/// module has no dependency edge back to `khive-runtime`). Canonical's field
116/// type is `Option<Value>` (`UpdateParams.name`/`.description`); serde_json's
117/// derived `Deserialize` for `Option<T>` intercepts a literal JSON `null` at
118/// the outer `Option` boundary and maps it straight to Rust `None`
119/// regardless of the inner type, so canonical's own "clear" arm is
120/// unreachable through normal struct deserialization: `update(name=null)` /
121/// `update(description=null)` are no-ops, not clears. This module reads raw,
122/// un-deserialized JSON, so it must replicate that collapse explicitly: key
123/// absent OR JSON `null` -> `None` (leave unchanged, no-op); key present as a
124/// string -> `Some(Some(s))` (set); any other JSON type -> a hard error.
125fn optional_string_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<String>>> {
126    match obj(args)?.get(key) {
127        None | Some(Value::Null) => Ok(None),
128        Some(Value::String(s)) => Ok(Some(Some(s.clone()))),
129        Some(other) => Err(RuntimeError::InvalidInput(format!(
130            "{key} must be a string or null, got: {other}"
131        ))),
132    }
133}
134
135/// Strict string-or-absent-or-null patch for entity `name`. Unlike
136/// `optional_str`'s `.as_str()`, this does not silently drop a non-string,
137/// non-null value like `name: 123` as absent: it rejects it instead of
138/// reporting success for an invalid update. Canonical validates entity
139/// `name` via `string_value` on `UpdateParams.name: Option<Value>`: null
140/// collapses to absent at the struct-deserialize boundary (see
141/// `optional_string_patch` doc above), so the reachable behavior is:
142/// absent/null -> unchanged; non-null string -> set; any other JSON type ->
143/// hard error. This mirrors that exactly, reading raw JSON instead of a
144/// deserialized struct.
145fn entity_name_patch(args: &Value) -> RuntimeResult<Option<String>> {
146    match obj(args)?.get("name") {
147        None | Some(Value::Null) => Ok(None),
148        Some(Value::String(s)) => Ok(Some(s.clone())),
149        Some(other) => Err(RuntimeError::InvalidInput(format!(
150            "name must be a string, got: {other}"
151        ))),
152    }
153}
154
155/// Nullable-JSON-value patch for `properties`: canonical
156/// `properties: Option<Value>` on `UpdateParams` collapses a literal JSON
157/// `null` to Rust `None` at the struct-deserialize boundary (same collapse
158/// as `optional_string_patch` above), so `properties=null` is canonically a
159/// no-op (leave existing properties unchanged): not a stored JSON `null`.
160/// This module reads raw JSON, so it must replicate that collapse: key
161/// absent OR JSON `null` -> `None` (no merge); any other JSON value ->
162/// `Some(value)` (merge), with no further shape validation at this layer.
163fn optional_properties(args: &Value, key: &str) -> RuntimeResult<Option<Value>> {
164    match obj(args)?.get(key) {
165        None | Some(Value::Null) => Ok(None),
166        Some(v) => Ok(Some(v.clone())),
167    }
168}
169
170/// `tags` patch: canonical `tags: Option<Vec<String>>` on `UpdateParams`
171/// collapses a literal JSON `null` to Rust `None` at the struct-deserialize
172/// boundary (same collapse as above), so `tags=null` is canonically a no-op
173/// (leave existing tags unchanged). A non-array, non-null value is still a
174/// hard error (mirrors the type failure `UpdateParams` deserialization would
175/// itself produce for a malformed `tags`).
176fn optional_tags(args: &Value) -> RuntimeResult<Option<Vec<String>>> {
177    match obj(args)?.get("tags") {
178        None | Some(Value::Null) => Ok(None),
179        Some(Value::Array(items)) => {
180            let mut tags = Vec::with_capacity(items.len());
181            for item in items {
182                let s = item.as_str().ok_or_else(|| {
183                    RuntimeError::InvalidInput("tags must be an array of strings".into())
184                })?;
185                tags.push(s.to_string());
186            }
187            Ok(Some(tags))
188        }
189        Some(_) => Err(RuntimeError::InvalidInput(
190            "tags must be an array of strings".into(),
191        )),
192    }
193}
194
195fn optional_f64(args: &Value, key: &str) -> RuntimeResult<Option<f64>> {
196    match obj(args)?.get(key) {
197        None => Ok(None),
198        Some(Value::Null) => Ok(None),
199        Some(v) => v
200            .as_f64()
201            .map(Some)
202            .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
203    }
204}
205
206/// Tri-state patch extraction for `Option<Option<f64>>`-shaped fields
207/// (`NotePatch::salience` / `NotePatch::decay_factor`): key absent -> `None`
208/// (untouched), key present as JSON `null` -> `Some(None)` (clear), key
209/// present as a number -> `Some(Some(v))` (set). Range validation lives in
210/// curation.rs's `prepare_update_note_from_snapshot`, not here.
211fn optional_f64_patch(args: &Value, key: &str) -> RuntimeResult<Option<Option<f64>>> {
212    match obj(args)?.get(key) {
213        None => Ok(None),
214        Some(Value::Null) => Ok(Some(None)),
215        Some(v) => v
216            .as_f64()
217            .map(|f| Some(Some(f)))
218            .ok_or_else(|| RuntimeError::InvalidInput(format!("{key} must be a number"))),
219    }
220}
221
222/// Every registered embedding model's vector table name, in the exact format
223/// `curation::merge_entity_sql` uses (`"vec_{sanitize_key(model_name)}"`) —
224/// reused here so atomic delete/merge purge the same tables the non-atomic
225/// paths do.
226fn vector_table_names(runtime: &KhiveRuntime) -> Vec<String> {
227    runtime
228        .registered_embedding_model_names()
229        .iter()
230        .map(|name| format!("vec_{}", crate::config::sanitize_key(name)))
231        .collect()
232}
233
234/// A guarded (`guard: None` — best-effort mirror, matching the non-atomic
235/// index-cleanup calls which don't assert a row existed) `DELETE` statement
236/// against one FTS or vector table for a single subject, scoped by namespace.
237fn purge_index_row_statement(
238    table: &str,
239    namespace: &str,
240    subject_id: Uuid,
241    label: &str,
242) -> PlanStatement {
243    PlanStatement {
244        statement: SqlStatement {
245            sql: format!("DELETE FROM {table} WHERE namespace = ?1 AND subject_id = ?2"),
246            params: vec![
247                SqlValue::Text(namespace.to_string()),
248                SqlValue::Text(subject_id.to_string()),
249            ],
250            label: Some(label.to_string()),
251        },
252        guard: None,
253    }
254}
255
256fn log_vector_row_delete_statement(
257    table: &str,
258    namespace: &str,
259    subject_id: Uuid,
260    label: &str,
261) -> PlanStatement {
262    PlanStatement {
263        statement: SqlStatement {
264            sql: format!(
265                "INSERT INTO ann_write_log \
266                 (namespace, embedding_model, kind, field, subject_id, op) \
267                 SELECT namespace, embedding_model, kind, field, subject_id, 'delete' \
268                 FROM {table} WHERE namespace = ?1 AND subject_id = ?2"
269            ),
270            params: vec![
271                SqlValue::Text(namespace.to_string()),
272                SqlValue::Text(subject_id.to_string()),
273            ],
274            label: Some(label.to_string()),
275        },
276        guard: None,
277    }
278}
279
280/// `true` iff a table named `table` currently exists in the backing SQLite
281/// database (`sqlite_master` probe, read-only — safe in async prepare, does
282/// NOT open/create the vector store, so it cannot lazily create the table
283/// itself).
284async fn vector_table_exists(runtime: &KhiveRuntime, table: &str) -> RuntimeResult<bool> {
285    let mut reader = runtime
286        .sql()
287        .reader()
288        .await
289        .map_err(RuntimeError::Storage)?;
290    let row = reader
291        .query_scalar(SqlStatement {
292            sql: "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1".to_string(),
293            params: vec![SqlValue::Text(table.to_string())],
294            label: Some("atomic-delete-vec-table-exists".to_string()),
295        })
296        .await
297        .map_err(RuntimeError::Storage)?;
298    Ok(row.is_some())
299}
300
301/// Append the FTS + every registered model's vector-row purge for `subject_id`
302/// (scoped to the RECORD's own namespace, matching `delete_entity`/
303/// `delete_note`'s `record_tok`/`record_ns` convention: not the caller
304/// token's namespace, per by-ID namespace-agnosticism) onto `statements`.
305///
306/// FTS tables (`fts_entities`/`fts_notes`) always exist (created at schema
307/// migration time) so their purge is unconditional. `vec_*` tables are
308/// created lazily on first vector-store open, so a default runtime can
309/// register embedding models before any vector table necessarily exists:
310/// a raw unconditional `DELETE FROM vec_*` can hit `no such table` on a
311/// fresh DB. Only push the vec purge for tables that actually exist:
312/// absence means the record definitionally has no vector row for that
313/// model, so skipping is data-parity-correct (the non-atomic path would
314/// lazily create the table then delete zero rows: same data outcome,
315/// without this read-only prepare pass performing an init side effect).
316async fn push_index_purge_statements(
317    runtime: &KhiveRuntime,
318    statements: &mut Vec<PlanStatement>,
319    fts_table: &str,
320    namespace: &str,
321    subject_id: Uuid,
322    label_prefix: &str,
323) -> RuntimeResult<()> {
324    statements.push(purge_index_row_statement(
325        fts_table,
326        namespace,
327        subject_id,
328        &format!("{label_prefix}-purge-fts"),
329    ));
330    for vec_table in vector_table_names(runtime) {
331        if vector_table_exists(runtime, &vec_table).await? {
332            statements.push(log_vector_row_delete_statement(
333                &vec_table,
334                namespace,
335                subject_id,
336                &format!("{label_prefix}-log-delete-vec-{vec_table}"),
337            ));
338            statements.push(purge_index_row_statement(
339                &vec_table,
340                namespace,
341                subject_id,
342                &format!("{label_prefix}-purge-vec-{vec_table}"),
343            ));
344        }
345    }
346    Ok(())
347}
348
349/// Event-store append parity for the canonical handlers that emit a
350/// lifecycle event after their row mutation: `update_entity` ->
351/// `EntityUpdated`, `delete_entity` -> `EntityDeleted`, `delete_note` ->
352/// `NoteDeleted`, `update_edge` -> `EdgeUpdated`, `delete_edge` ->
353/// `EdgeDeleted`. `update_note` and `link` append no event and must never
354/// call this. See `docs/api/atomic_prepare.md#event_append_statements` for why
355/// this is a `PlanStatement` rather than a `PostCommitEffect`.
356///
357/// Invariant: returned statements are unguarded — appended after the plan's
358/// own guarded row statement, so [`apply_plan`]'s stop-on-first-failure
359/// contract means they are only reached once that row mutation's guard has
360/// already held. Committing the event row atomically with the mutation it
361/// describes strengthens canonical's guarantee: the non-atomic handlers write
362/// the event in a separate transaction, ordered but not atomic with the row
363/// mutation.
364fn event_append_statements(
365    namespace: &str,
366    verb: &str,
367    kind: EventKind,
368    substrate: SubstrateKind,
369    target_id: Uuid,
370    payload: Value,
371) -> RuntimeResult<Vec<PlanStatement>> {
372    let event = khive_storage::event::Event::new(namespace.to_string(), verb, kind, substrate, "")
373        .with_target(target_id)
374        .with_payload(payload);
375    let statements = event_insert_statements(&event)
376        .map_err(|e| RuntimeError::Internal(format!("event_insert_statements: {e}")))?;
377    Ok(statements
378        .into_iter()
379        .map(|statement| PlanStatement {
380            statement,
381            guard: None,
382        })
383        .collect())
384}
385
386// ---------------------------------------------------------------------------
387// dispatch
388// ---------------------------------------------------------------------------
389
390/// Build the prepared [`AtomicOpPlan`] for one KG-substrate admissible op
391/// (`update`, `delete`, `link`, `merge`). Returns a loud [`RuntimeError`] for
392/// `propose`/`review`/`withdraw` (known scope gap, see module doc) and any
393/// other verb (the CLI boundary must reject those before calling this — a
394/// verb reaching here is either KG-substrate-admissible or a bug upstream).
395pub async fn prepare_op(
396    runtime: &KhiveRuntime,
397    token: &NamespaceToken,
398    tool: &str,
399    args: &Value,
400) -> RuntimeResult<AtomicOpPlan> {
401    match tool {
402        // `expected_kind: None` here — same reasoning as the `"delete"` arm
403        // below: callers that need `update(kind=...)` parity must resolve
404        // the kind spec themselves (it needs a `VerbRegistry`, unreachable
405        // from this crate: see `AtomicUpdateKind`'s doc comment) and call
406        // `prepare_update` directly with the resolved value; `kkernel`'s
407        // `--atomic` seam does exactly this and bypasses this dispatch arm.
408        // A caller reaching `prepare_op("update", ...)` without going
409        // through that seam gets kind-unchecked behavior.
410        "update" => prepare_update(runtime, token, args, None).await,
411        // `expected_kind: None` here — callers that need `delete(kind=...)`
412        // parity must resolve the kind spec themselves (it needs a
413        // `VerbRegistry`, unreachable from this crate: see
414        // `AtomicDeleteKind`'s doc comment) and call `prepare_delete`
415        // directly with the resolved value; `kkernel`'s `--atomic` seam does
416        // exactly this and bypasses this dispatch arm. A caller reaching
417        // `prepare_op("delete", ...)` without going through that seam gets
418        // kind-unchecked behavior.
419        "delete" => prepare_delete(runtime, token, args, None).await,
420        "link" => prepare_link(runtime, token, args).await,
421        "merge" => prepare_merge(runtime, token, args).await,
422        "propose" | "review" | "withdraw" => prepare_governance_unimplemented(tool),
423        other => Err(RuntimeError::InvalidInput(format!(
424            "{other:?} has no atomic_prepare::prepare_op implementation; the CLI \
425             admissibility check should have rejected this before prepare"
426        ))),
427    }
428}
429
430fn prepare_governance_unimplemented(tool: &str) -> RuntimeResult<AtomicOpPlan> {
431    Err(RuntimeError::InvalidInput(format!(
432        "{tool:?} is on the ADR-099 v1 admissible verb list but has no --atomic \
433         prepare/apply implementation yet: its lifecycle (ADR-046) is an \
434         event-sourced changeset-interpreter over a dedicated `proposals_open` \
435         table, not a small guarded-DML plan — a faithful non-stub atomic \
436         prepare for it is tracked as ADR-099 follow-up work, not implemented \
437         in slice B3. No write was attempted."
438    )))
439}
440
441// ---------------------------------------------------------------------------
442// create (AddEntity / AddNote)
443// ---------------------------------------------------------------------------
444
445/// Build the prepared plan for an `AddEntity` proposal change. The entity
446/// row and FTS document are committed together; vector indexing is deferred
447/// until after commit because embedding may suspend. `kind` must already be
448/// canonicalized by the caller because pack-aware resolution requires a
449/// `VerbRegistry`.
450pub async fn prepare_add_entity(
451    runtime: &KhiveRuntime,
452    token: &NamespaceToken,
453    args: &Value,
454) -> RuntimeResult<AtomicOpPlan> {
455    let kind = require_str(args, "kind")?;
456    let name = require_str(args, "name")?;
457    runtime.validate_entity_kind(kind)?;
458    if name.trim().is_empty() {
459        return Err(RuntimeError::InvalidInput(
460            "name must not be empty".to_string(),
461        ));
462    }
463
464    let description = optional_create_string(args, "description")?;
465    let properties = optional_properties(args, "properties")?;
466    let tags = optional_tags(args)?.unwrap_or_default();
467
468    crate::secret_gate::check(name)?;
469    if let Some(ref d) = description {
470        crate::secret_gate::check(d)?;
471    }
472    if let Some(ref p) = properties {
473        crate::secret_gate::check_json(p)?;
474    }
475    crate::secret_gate::check_tags(&tags)?;
476    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
477
478    let ns = token.namespace().as_str();
479    let mut entity = khive_storage::Entity::new(ns, kind, name);
480    if let Some(d) = description {
481        entity = entity.with_description(d);
482    }
483    if let Some(p) = properties {
484        entity = entity.with_properties(p);
485    }
486    if !tags.is_empty() {
487        entity = entity.with_tags(tags);
488    }
489
490    let statements = vec![
491        PlanStatement {
492            statement: entity_upsert_statement(&entity),
493            guard: Some(AffectedRowGuard::exactly(1)),
494        },
495        PlanStatement {
496            statement: insert_document_statement("fts_entities", &entity_fts_document(&entity)),
497            guard: None,
498        },
499    ];
500
501    Ok(AtomicOpPlan::AddEntity(AddEntityPlan {
502        entity_id: entity.id,
503        statements,
504        post_commit: PostCommitEffect::ReindexEntity {
505            entity_id: entity.id,
506        },
507    }))
508}
509
510/// Build the prepared plan for an `AddNote` proposal change. Mirrors
511/// [`prepare_add_entity`]'s shape and the same
512/// `kind`-already-canonicalized split. `annotates` is out of scope: the
513/// proposal `NoteDraft` this backs carries no annotates targets, unlike
514/// `KhiveRuntime::create_note`'s general-purpose signature.
515pub async fn prepare_add_note(
516    runtime: &KhiveRuntime,
517    token: &NamespaceToken,
518    args: &Value,
519) -> RuntimeResult<AtomicOpPlan> {
520    let kind = require_str(args, "kind")?;
521    let content = require_str(args, "content")?;
522    runtime.validate_note_kind(kind)?;
523
524    let name = optional_create_string(args, "name")?;
525    let properties = optional_properties(args, "properties")?;
526    // Same note-write validator `create_note_inner` runs: this path builds its
527    // args itself and dispatches no pack hook, so without this call a proposal
528    // changeset would be the one note-write that stores caller-supplied owned
529    // identity properties verbatim. The token here is the applying caller's
530    // (threaded in by the apply worker), not the proposer's.
531    let properties = runtime.derive_note_write_properties(kind, token, properties)?;
532
533    crate::secret_gate::check(content)?;
534    if let Some(ref n) = name {
535        crate::secret_gate::check(n)?;
536    }
537    if let Some(ref p) = properties {
538        crate::secret_gate::check_json(p)?;
539    }
540    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
541
542    let ns = token.namespace().as_str();
543    let mut note = khive_storage::note::Note::new(ns, kind, content);
544    if let Some(n) = name {
545        note = note.with_name(n);
546    }
547    if let Some(p) = properties {
548        note = note.with_properties(p);
549    }
550
551    let statements = vec![
552        PlanStatement {
553            statement: note_upsert_statement(&note),
554            guard: Some(AffectedRowGuard::exactly(1)),
555        },
556        PlanStatement {
557            statement: insert_document_statement("fts_notes", &note_fts_document(&note)),
558            guard: None,
559        },
560    ];
561
562    Ok(AtomicOpPlan::AddNote(AddNotePlan {
563        note_id: note.id,
564        statements,
565        post_commit: PostCommitEffect::ReindexNote { note_id: note.id },
566    }))
567}
568
569// ---------------------------------------------------------------------------
570// update
571// ---------------------------------------------------------------------------
572
573/// Mirrors `khive-pack-kg::handlers::update::reject_inapplicable_fields`: a
574/// hard `InvalidInput` when a caller passes a field that does not apply to
575/// the resolved substrate (e.g. `salience` on an entity, or
576/// `description`/`tags` on a note). That function has no dependency edge
577/// back to `khive-runtime`, so its exact field-applicability check list and
578/// error message shape are reimplemented here rather than imported: same
579/// pattern as `optional_string_patch` above. Presence is checked directly on
580/// the raw args object (this module has no `UpdateParams` struct); a JSON
581/// `null` value is treated as absent, matching `Option<T>` deserialization
582/// semantics.
583fn reject_inapplicable_update_fields(args: &Value, substrate: &str) -> RuntimeResult<()> {
584    let o = obj(args)?;
585    let present = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
586    let (bad_field, valid): (Option<&str>, &str) = match substrate {
587        "entity" => {
588            let bad = if present("content") {
589                Some("content")
590            } else if present("salience") {
591                Some("salience")
592            } else if present("decay_factor") {
593                Some("decay_factor")
594            } else if present("relation") {
595                Some("relation")
596            } else if present("weight") {
597                Some("weight")
598            } else {
599                None
600            };
601            (bad, "name, description, tags, properties, entity_type")
602        }
603        "note" => {
604            let bad = if present("description") {
605                Some("description")
606            } else if present("tags") {
607                Some("tags")
608            } else if present("relation") {
609                Some("relation")
610            } else if present("weight") {
611                Some("weight")
612            } else if o.contains_key("entity_type") {
613                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
614                // the explicit clear) is inapplicable to notes.
615                Some("entity_type")
616            } else {
617                None
618            };
619            (bad, "name, content, salience, decay_factor, properties")
620        }
621        // `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, so
622        // this arm must reject entity/note-only fields (e.g. `name`) on an
623        // edge update rather than silently skip the guard, mirroring
624        // `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
625        // `KindSpec::Edge` arm.
626        "edge" => {
627            let bad = if present("name") {
628                Some("name")
629            } else if present("description") {
630                Some("description")
631            } else if present("content") {
632                Some("content")
633            } else if present("tags") {
634                Some("tags")
635            } else if present("salience") {
636                Some("salience")
637            } else if present("decay_factor") {
638                Some("decay_factor")
639            } else if o.contains_key("entity_type") {
640                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
641                // the explicit clear) is inapplicable to edges.
642                Some("entity_type")
643            } else {
644                None
645            };
646            (bad, "relation, weight, properties")
647        }
648        _ => (None, ""),
649    };
650    if let Some(field) = bad_field {
651        let substrate_label = match substrate {
652            "entity" => "an entity",
653            "note" => "a note",
654            "edge" => "an edge",
655            other => other,
656        };
657        return Err(RuntimeError::InvalidInput(format!(
658            "field '{field}' is not valid for {substrate_label}; valid fields: {valid}"
659        )));
660    }
661    Ok(())
662}
663
664/// Caller-supplied update-kind expectation, resolved via the canonical
665/// `resolve_kind_spec` at the kkernel `--atomic` seam: the same pattern
666/// [`AtomicDeleteKind`] uses. Without this check, `update(kind="document",
667/// id=<concept>)` would be canonically `NotFound` but the atomic path would
668/// ignore the explicit kind and mutate the resolved entity anyway.
669/// `khive-runtime` must not depend on `khive-pack-kg`, so this is a plain
670/// substrate-level shape rather than `khive_pack_kg::handlers::KindSpec`
671/// itself: the kkernel seam does the pack-aware resolution and passes down
672/// only what `prepare_update` needs to enforce the mismatch check.
673pub enum AtomicUpdateKind {
674    Entity { specific: Option<String> },
675    Note { specific: Option<String> },
676    Edge,
677}
678
679/// Enforce a caller's explicit update-kind discriminator against a resolved
680/// note before any pack hook can inspect or normalize the request. Canonical
681/// KG dispatch performs this mismatch check before its hook; the atomic
682/// adapter calls this same helper to preserve that error ordering.
683pub fn validate_note_update_expected_kind(
684    note: &khive_storage::note::Note,
685    expected_kind: &Option<AtomicUpdateKind>,
686) -> RuntimeResult<()> {
687    let id = note.id;
688    match expected_kind {
689        None => Ok(()),
690        Some(AtomicUpdateKind::Note {
691            specific: Some(expected),
692        }) if &note.kind != expected => Err(RuntimeError::NotFound(format!("note {id}"))),
693        Some(AtomicUpdateKind::Note { .. }) => Ok(()),
694        Some(AtomicUpdateKind::Entity { .. }) => {
695            Err(RuntimeError::NotFound(format!("entity {id}")))
696        }
697        Some(AtomicUpdateKind::Edge) => Err(RuntimeError::NotFound(format!("edge {id}"))),
698    }
699}
700
701async fn prepare_note_update_plan_from_snapshot(
702    runtime: &KhiveRuntime,
703    token: &NamespaceToken,
704    args: &Value,
705    expected_kind: &Option<AtomicUpdateKind>,
706    note: khive_storage::note::Note,
707) -> RuntimeResult<AtomicOpPlan> {
708    let id = require_uuid(args, "id")?;
709    if note.id != id {
710        return Err(RuntimeError::NotFound(format!("note {id}")));
711    }
712    validate_note_update_expected_kind(&note, expected_kind)?;
713
714    reject_inapplicable_update_fields(args, "note")?;
715    let name = optional_string_patch(args, "name")?;
716    let content = optional_str(args, "content").map(str::to_string);
717    let properties = optional_properties(args, "properties")?;
718    let salience = optional_f64_patch(args, "salience")?;
719    let decay_factor = optional_f64_patch(args, "decay_factor")?;
720    let expected_updated_at = note.updated_at;
721    let expected_deleted_at = note.deleted_at;
722
723    let (note, text_changed) = runtime
724        .prepare_update_note_from_snapshot(
725            token,
726            note,
727            crate::curation::NotePatch::new(name, content, salience, decay_factor, properties),
728        )
729        .await?;
730
731    let post_commit = if text_changed {
732        PostCommitEffect::ReindexNote { note_id: id }
733    } else {
734        PostCommitEffect::None
735    };
736    Ok(AtomicOpPlan::Update(UpdatePlan {
737        target_id: id,
738        statements: vec![PlanStatement {
739            statement: note_replace_if_unchanged_statement(
740                &note,
741                expected_updated_at,
742                expected_deleted_at,
743            ),
744            guard: Some(AffectedRowGuard::exactly(1)),
745        }],
746        post_commit,
747        edge_natural_key: None,
748    }))
749}
750
751/// Build an atomic update plan from the exact note snapshot already supplied
752/// to a pack update hook. Persistence is guarded by that snapshot's revision
753/// and deletion marker, so hook normalization cannot race a second read.
754pub async fn prepare_update_from_note_snapshot(
755    runtime: &KhiveRuntime,
756    token: &NamespaceToken,
757    args: &Value,
758    expected_kind: Option<AtomicUpdateKind>,
759    note: khive_storage::note::Note,
760) -> RuntimeResult<AtomicOpPlan> {
761    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
762        return Err(RuntimeError::InvalidInput(
763            "entity_kind is immutable; to change kind, delete then re-create the entity, \
764             or use merge() if this is a deduplication correction"
765                .into(),
766        ));
767    }
768    let current = runtime
769        .notes(token)?
770        .get_note(note.id)
771        .await?
772        .ok_or_else(|| RuntimeError::NotFound(format!("note {}", note.id)))?;
773    if current != note {
774        return Err(crate::curation::stale_note_snapshot_error(note.id));
775    }
776    prepare_note_update_plan_from_snapshot(runtime, token, args, &expected_kind, note).await
777}
778
779/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
780/// with canonical's own optional discriminator); `Some(_)` enforces an
781/// exact-parity mismatch check against the resolved record's actual
782/// substrate/specific kind, mirroring `handle_update`'s
783/// `entity.kind != *k` / note kind checks (update.rs:200-201, :229-234).
784/// Task notes must pass the GTD pack hook before this or
785/// `prepare_op("update", ..)`; neither runs it.
786pub async fn prepare_update(
787    runtime: &KhiveRuntime,
788    token: &NamespaceToken,
789    args: &Value,
790    expected_kind: Option<AtomicUpdateKind>,
791) -> RuntimeResult<AtomicOpPlan> {
792    let id = require_uuid(args, "id")?;
793
794    // Mirrors update.rs's entity_kind immutability guard: entity_kind is a
795    // legacy top-level field, independent of the `kind` substrate
796    // discriminator handled elsewhere.
797    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
798        return Err(RuntimeError::InvalidInput(
799            "entity_kind is immutable; to change kind, delete then re-create the entity, \
800             or use merge() if this is a deduplication correction"
801                .into(),
802        ));
803    }
804
805    match runtime.resolve_by_id(token, id).await? {
806        Some(Resolved::Entity(entity)) => {
807            match &expected_kind {
808                None => {}
809                Some(AtomicUpdateKind::Entity {
810                    specific: Some(expected),
811                }) if &entity.kind != expected => {
812                    return Err(RuntimeError::NotFound(format!("entity {id}")));
813                }
814                Some(AtomicUpdateKind::Entity { .. }) => {}
815                Some(AtomicUpdateKind::Note { .. }) => {
816                    return Err(RuntimeError::NotFound(format!("note {id}")));
817                }
818                Some(AtomicUpdateKind::Edge) => {
819                    return Err(RuntimeError::NotFound(format!("edge {id}")));
820                }
821            }
822            // Decide step lives in curation.rs's `prepare_update_entity` —
823            // the SAME function canonical `update_entity` calls. Only the
824            // arg-extraction (raw JSON -> `EntityPatch`) and the plan-shape
825            // wiring are atomic-path-specific: the domain object becomes a
826            // `PlanStatement` via `entity_replace_if_unchanged_statement`,
827            // whose CAS predicate binds the snapshot's revision and deletion
828            // marker, under an exactly-one affected-row guard.
829            reject_inapplicable_update_fields(args, "entity")?;
830            let name = entity_name_patch(args)?;
831            let description = optional_string_patch(args, "description")?;
832            let properties = optional_properties(args, "properties")?;
833            let tags = optional_tags(args)?;
834            let entity_type = optional_entity_type_patch(args, "entity_type")?;
835
836            prepare_update_entity_plan(
837                runtime,
838                token,
839                id,
840                crate::curation::EntityPatch {
841                    name,
842                    description,
843                    properties,
844                    tags,
845                    entity_type,
846                },
847            )
848            .await
849        }
850        Some(Resolved::Note(note)) => {
851            // Patch application lives in curation.rs's
852            // `prepare_update_note_from_snapshot` — the same implementation
853            // canonical guarded update calls, including salience/decay range
854            // validation. The plan retains this exact snapshot's revision.
855            prepare_note_update_plan_from_snapshot(runtime, token, args, &expected_kind, note).await
856        }
857        Some(_) => Err(RuntimeError::InvalidInput(format!(
858            "update target {id} must be an entity, note, or edge"
859        ))),
860        // `Resolved` (khive-runtime::operations) has no `Edge` variant — an
861        // id that isn't an entity/note/pack-private/event record is checked
862        // against the graph store directly, mirroring
863        // `khive-pack-kg::handlers::KgPack::infer_kind_from_uuid`'s own
864        // entity/note-then-edge fallback order. `update` admits
865        // `kind="edge"`, so this arm must be able to build a plan for one.
866        None => match &expected_kind {
867            Some(AtomicUpdateKind::Entity { .. }) => {
868                Err(RuntimeError::NotFound(format!("entity/note {id}")))
869            }
870            Some(AtomicUpdateKind::Note { .. }) => {
871                Err(RuntimeError::NotFound(format!("entity/note {id}")))
872            }
873            Some(AtomicUpdateKind::Edge) | None => match runtime.get_edge(token, id).await? {
874                Some(edge) => prepare_update_edge(runtime, id, edge, args).await,
875                None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
876            },
877        },
878    }
879}
880
881/// Build an entity update plan from a typed patch. Proposal changesets use
882/// this entry point so their explicit `description: null` clear operation is
883/// preserved instead of being collapsed by raw verb deserialization.
884pub async fn prepare_update_entity_plan(
885    runtime: &KhiveRuntime,
886    token: &NamespaceToken,
887    id: Uuid,
888    patch: crate::curation::EntityPatch,
889) -> RuntimeResult<AtomicOpPlan> {
890    let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
891        runtime.prepare_update_entity(token, id, patch).await?;
892    let mut statements = vec![PlanStatement {
893        statement: entity_replace_if_unchanged_statement(
894            &entity,
895            expected_updated_at,
896            expected_deleted_at,
897        ),
898        guard: Some(AffectedRowGuard::exactly(1)),
899    }];
900    statements.extend(event_append_statements(
901        &entity.namespace,
902        "update",
903        EventKind::EntityUpdated,
904        SubstrateKind::Entity,
905        id,
906        serde_json::json!({
907            "id": id,
908            "namespace": entity.namespace,
909            "changed_fields": changed_fields,
910        }),
911    )?);
912    let post_commit = if reindex_required {
913        PostCommitEffect::ReindexEntity { entity_id: id }
914    } else {
915        PostCommitEffect::None
916    };
917    Ok(AtomicOpPlan::Update(UpdatePlan {
918        target_id: id,
919        statements,
920        post_commit,
921        edge_natural_key: None,
922    }))
923}
924
925/// Edge branch of `prepare_update`. Mirrors `KhiveRuntime::update_edge`'s
926/// patch semantics: `relation`/`weight`/`properties` are the only applicable
927/// fields, a changed `relation` is endpoint-validated first, `weight` is
928/// range-checked, and `properties` REPLACES `metadata` wholesale (no merge).
929/// See `docs/api/atomic_prepare.md#prepare_update_edge` for the DML-shape parity
930/// detail with `update_edge`.
931///
932/// Invariant (symmetric relations `competes_with`/`composed_with`): this
933/// function must never branch on a prepare-time conflict probe — a different
934/// op in the same atomic unit could change the conflict landscape between
935/// probe and commit, making any such branch stale by construction. It always
936/// emits BOTH statements from [`edge_symmetric_delete_if_conflict_statement`]
937/// and [`edge_symmetric_absorb_or_update_inplace_statement`], each carrying
938/// its own commit-time `WHERE`/`CASE WHEN` predicate that re-evaluates the
939/// conflict condition fresh inside the transaction. This function reads no
940/// state to guess a surviving id; the plan instead carries `edge_natural_key`
941/// so a post-commit caller derives the actual surviving id from the
942/// committed row, never from a value computed before the rest of this atomic
943/// unit has even run.
944async fn prepare_update_edge(
945    runtime: &KhiveRuntime,
946    id: Uuid,
947    mut edge: khive_storage::types::Edge,
948    args: &Value,
949) -> RuntimeResult<AtomicOpPlan> {
950    reject_inapplicable_update_fields(args, "edge")?;
951
952    let expected_updated_at = edge.updated_at;
953    let expected_deleted_at = edge.deleted_at;
954
955    let relation_raw = optional_str(args, "relation");
956    let weight = optional_f64(args, "weight")?;
957    let properties = optional_properties(args, "properties")?;
958
959    if let Some(ref p) = properties {
960        crate::secret_gate::check_json(p)?;
961    }
962    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
963
964    let namespace = edge.namespace.clone();
965    let record_tok = NamespaceToken::for_namespace(
966        khive_types::Namespace::parse(&namespace)
967            .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
968    );
969
970    let mut changed_fields: Vec<&'static str> = Vec::new();
971    if let Some(raw) = relation_raw {
972        let relation = parse_edge_relation(raw)?;
973        runtime
974            .validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, relation)
975            .await?;
976        edge.relation = relation;
977        changed_fields.push("relation");
978    }
979    if let Some(w) = weight {
980        if !w.is_finite() || !(0.0..=1.0).contains(&w) {
981            return Err(RuntimeError::InvalidInput(format!(
982                "edge weight must be a finite value in [0.0, 1.0]; got {w}"
983            )));
984        }
985        edge.weight = w;
986        changed_fields.push("weight");
987    }
988    if let Some(p) = properties {
989        edge.metadata = Some(p);
990        changed_fields.push("properties");
991    }
992
993    let (canon_src, canon_tgt) =
994        canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
995    let now = chrono::Utc::now();
996
997    let mut statements: Vec<PlanStatement> = Vec::new();
998    let mut edge_natural_key: Option<EdgeNaturalKey> = None;
999
1000    if edge.relation.is_symmetric() {
1001        // The write for a symmetric relation never branches on a
1002        // prepare-time probe result: it always carries both self-guarding,
1003        // commit-time-predicate statements (see their doc comment in
1004        // khive-db's graph.rs for the full rationale). This avoids the
1005        // staleness window a prepare-time probe would expose: an earlier op
1006        // in the same atomic unit could change the conflict landscape before
1007        // commit. Canonical's own probe-then-branch
1008        // `update_edge_symmetric_dml` has no such exposure (single
1009        // transaction, no interleaving) and is unaffected.
1010        let metadata_str = edge
1011            .metadata
1012            .as_ref()
1013            .map(|v| serde_json::to_string(v).unwrap_or_default());
1014
1015        // `updated_at` must strictly advance past the snapshot even when two
1016        // operations land inside one clock microsecond; saturating to
1017        // i64::MAX would let the CAS accept a write without advancing its
1018        // revision, so that is not a valid fallback (mirrors the note path).
1019        let minimum_updated_at_micros = expected_updated_at
1020            .timestamp_micros()
1021            .checked_add(1)
1022            .ok_or_else(|| {
1023                RuntimeError::Internal(format!(
1024                    "edge {id} updated_at is already at i64::MAX and cannot advance"
1025                ))
1026            })?;
1027        let symmetric_updated_at_micros = now.timestamp_micros().max(minimum_updated_at_micros);
1028        let expected_deleted_at_micros = expected_deleted_at.map(|v| v.timestamp_micros());
1029
1030        statements.push(PlanStatement {
1031            statement: edge_symmetric_delete_if_conflict_statement(
1032                &namespace,
1033                id,
1034                canon_src,
1035                canon_tgt,
1036                edge.relation,
1037                expected_updated_at.timestamp_micros(),
1038                expected_deleted_at_micros,
1039            ),
1040            guard: Some(AffectedRowGuard {
1041                expected_min: 0,
1042                expected_max: Some(1),
1043            }),
1044        });
1045        statements.push(PlanStatement {
1046            statement: edge_symmetric_absorb_or_update_inplace_statement(
1047                &namespace,
1048                id,
1049                canon_src,
1050                canon_tgt,
1051                edge.relation,
1052                edge.weight,
1053                symmetric_updated_at_micros,
1054                metadata_str.as_deref(),
1055                edge.target_backend.as_deref(),
1056                expected_updated_at.timestamp_micros(),
1057                expected_deleted_at_micros,
1058            ),
1059            guard: Some(AffectedRowGuard::exactly(1)),
1060        });
1061
1062        // No prepare-time read needed: the two statements above are
1063        // self-guarding at commit time (see their doc comment). Post-commit
1064        // result rendering derives the actual surviving id from THIS
1065        // natural key, never from a value computed here.
1066        edge_natural_key = Some(EdgeNaturalKey {
1067            namespace: namespace.clone(),
1068            canon_source_id: canon_src,
1069            canon_target_id: canon_tgt,
1070            relation: edge.relation,
1071        });
1072    } else {
1073        // Non-symmetric: guarded replace of the read snapshot rather than
1074        // `graph.upsert_edge`'s unconditional natural-key upsert — a zero
1075        // affected-row result now means a concurrent writer moved this edge
1076        // between PREPARE and commit, and the atomic unit must roll back
1077        // instead of silently overwriting it.
1078        //
1079        // `updated_at` must strictly advance past the snapshot even when two
1080        // operations land inside one clock microsecond; saturating to
1081        // i64::MAX would let the CAS accept a write without advancing its
1082        // revision, so that is not a valid fallback (mirrors the note path).
1083        let minimum_updated_at_micros = expected_updated_at
1084            .timestamp_micros()
1085            .checked_add(1)
1086            .ok_or_else(|| {
1087                RuntimeError::Internal(format!(
1088                    "edge {id} updated_at is already at i64::MAX and cannot advance"
1089                ))
1090            })?;
1091        let now_micros = now.timestamp_micros().max(minimum_updated_at_micros);
1092        edge.updated_at = chrono::DateTime::from_timestamp_micros(now_micros).ok_or_else(|| {
1093            RuntimeError::Internal(format!(
1094                "edge {id}: computed updated_at {now_micros} is not a valid timestamp"
1095            ))
1096        })?;
1097        statements.push(PlanStatement {
1098            statement: edge_replace_if_unchanged_statement(
1099                &edge,
1100                expected_updated_at,
1101                expected_deleted_at,
1102            ),
1103            guard: Some(AffectedRowGuard::exactly(1)),
1104        });
1105    }
1106
1107    // Mirrors `update_edge`'s unconditional post-mutation `EdgeUpdated`
1108    // event append, keyed on the original `edge_id` the caller supplied:
1109    // canonical does the same (the event target is `edge_id`, not the
1110    // post-absorption surviving id).
1111    statements.extend(event_append_statements(
1112        &namespace,
1113        "update",
1114        EventKind::EdgeUpdated,
1115        SubstrateKind::Entity,
1116        id,
1117        serde_json::json!({"id": id, "namespace": namespace, "changed_fields": changed_fields}),
1118    )?);
1119
1120    Ok(AtomicOpPlan::Update(UpdatePlan {
1121        target_id: id,
1122        statements,
1123        post_commit: PostCommitEffect::None,
1124        edge_natural_key,
1125    }))
1126}
1127
1128// ---------------------------------------------------------------------------
1129// delete
1130// ---------------------------------------------------------------------------
1131
1132/// Caller-supplied delete-kind expectation, resolved via the canonical
1133/// `resolve_kind_spec` at the kkernel `--atomic` seam. `khive-runtime` must
1134/// not depend on `khive-pack-kg` (packs depend on the runtime, not the other
1135/// way around), so this is a plain substrate-level shape rather than
1136/// `khive_pack_kg::handlers::KindSpec` itself: the kkernel seam does the
1137/// pack-aware `resolve_kind_spec` resolution (which needs a `VerbRegistry`,
1138/// unreachable from this crate) and passes down only what `prepare_delete`
1139/// needs to enforce the mismatch check.
1140///
1141/// `delete` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, hence the
1142/// `Edge` variant. `Event`/`Proposal` remain rejected at the kkernel seam
1143/// (not v1-admissible for atomic delete at all).
1144pub enum AtomicDeleteKind {
1145    Entity { specific: Option<String> },
1146    Note { specific: Option<String> },
1147    Edge,
1148}
1149
1150/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
1151/// with canonical's own optional discriminator); `Some(_)` enforces an
1152/// exact-parity mismatch check against the resolved record's actual
1153/// substrate/specific kind, mirroring `handle_delete`'s
1154/// `entity.kind != *expected` / `note.kind != *expected` checks.
1155pub async fn prepare_delete(
1156    runtime: &KhiveRuntime,
1157    token: &NamespaceToken,
1158    args: &Value,
1159    expected_kind: Option<AtomicDeleteKind>,
1160) -> RuntimeResult<AtomicOpPlan> {
1161    let id = require_uuid(args, "id")?;
1162    let actor = format!("{}:{}", token.actor().kind, token.actor().id);
1163    let hard = obj(args)?
1164        .get("hard")
1165        .and_then(|v| v.as_bool())
1166        .unwrap_or(false);
1167
1168    // `delete(id, hard=true)` is the public purge route after a prior soft
1169    // delete, so it must resolve including already-tombstoned rows (a
1170    // live-only resolve would never find one). Soft delete keeps the
1171    // live-only resolve: a soft delete of an already-tombstoned row is a
1172    // no-op, matching non-atomic behavior.
1173    let resolved = if hard {
1174        runtime.resolve_by_id_including_deleted(token, id).await?
1175    } else {
1176        runtime.resolve_by_id(token, id).await?
1177    };
1178
1179    match resolved {
1180        Some(Resolved::Entity(entity)) => {
1181            match &expected_kind {
1182                None => {}
1183                Some(AtomicDeleteKind::Entity {
1184                    specific: Some(expected),
1185                }) if &entity.kind != expected => {
1186                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1187                }
1188                Some(AtomicDeleteKind::Entity { .. }) => {}
1189                Some(AtomicDeleteKind::Note { .. }) => {
1190                    return Err(RuntimeError::NotFound(format!("note {id}")));
1191                }
1192                Some(AtomicDeleteKind::Edge) => {
1193                    return Err(RuntimeError::NotFound(format!("edge {id}")));
1194                }
1195            }
1196            let namespace = entity.namespace.clone();
1197            // Storage parity: `entity_soft_delete_statement`/
1198            // `entity_hard_delete_statement` are the SAME khive-db builders
1199            // khive-db's own `SqlEntityStore::delete_entity` calls — no DML
1200            // text is hand-duplicated here.
1201            let mut statements = if hard {
1202                vec![
1203                    PlanStatement {
1204                        statement: delete_record_attachments_statement(
1205                            id,
1206                            AttachmentSubstrate::Entity,
1207                        ),
1208                        guard: None,
1209                    },
1210                    PlanStatement {
1211                        statement: entity_hard_delete_statement(id),
1212                        guard: Some(AffectedRowGuard::exactly(1)),
1213                    },
1214                ]
1215            } else {
1216                let deleted_at = chrono::Utc::now().timestamp_micros();
1217                vec![PlanStatement {
1218                    statement: entity_soft_delete_statement(id, deleted_at),
1219                    guard: Some(AffectedRowGuard::exactly(1)),
1220                }]
1221            };
1222            if hard {
1223                statements.extend(
1224                    hard_delete_lineage_warning_statements(
1225                        &namespace,
1226                        &actor,
1227                        id,
1228                        SubstrateKind::Entity,
1229                    )
1230                    .into_iter()
1231                    .map(|statement| PlanStatement {
1232                        statement,
1233                        guard: None,
1234                    }),
1235                );
1236                // Same builder canonical `delete_entity`'s hard-delete
1237                // cascade calls (`graph.purge_incident_edges`).
1238                statements.push(PlanStatement {
1239                    statement: purge_incident_edges_statement(id),
1240                    guard: None,
1241                });
1242            }
1243            // FTS + vector index purge, matching operations.rs
1244            // `delete_entity`: both soft and hard delete clean indexes (a
1245            // hard delete of an already-tombstoned record must still purge
1246            // them); only hard additionally cascades edges above.
1247            push_index_purge_statements(
1248                runtime,
1249                &mut statements,
1250                "fts_entities",
1251                &namespace,
1252                id,
1253                "atomic-delete-entity",
1254            )
1255            .await?;
1256            // operations.rs's `delete_entity` appends an `EntityDeleted`
1257            // event after a successful row delete, on both soft and hard
1258            // delete. `apply_plan` never reaches this statement unless the
1259            // guarded row statement above affected a row, so no extra `if`
1260            // is needed here.
1261            statements.extend(event_append_statements(
1262                &namespace,
1263                "delete",
1264                EventKind::EntityDeleted,
1265                SubstrateKind::Entity,
1266                id,
1267                serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1268            )?);
1269            Ok(AtomicOpPlan::Delete(DeletePlan {
1270                target_id: id,
1271                statements,
1272                post_commit: PostCommitEffect::None,
1273            }))
1274        }
1275        Some(Resolved::Note(note)) => {
1276            match &expected_kind {
1277                None => {}
1278                Some(AtomicDeleteKind::Note {
1279                    specific: Some(expected),
1280                }) if &note.kind != expected => {
1281                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
1282                }
1283                Some(AtomicDeleteKind::Note { .. }) => {}
1284                Some(AtomicDeleteKind::Entity { .. }) => {
1285                    return Err(RuntimeError::NotFound(format!("entity {id}")));
1286                }
1287                Some(AtomicDeleteKind::Edge) => {
1288                    return Err(RuntimeError::NotFound(format!("edge {id}")));
1289                }
1290            }
1291            let namespace = note.namespace.clone();
1292            // Storage parity: `note_soft_delete_statement`/
1293            // `note_hard_delete_statement` are the SAME khive-db builders
1294            // khive-db's own `SqlNoteStore::delete_note` calls.
1295            let mut statements = if hard {
1296                vec![
1297                    PlanStatement {
1298                        statement: delete_record_attachments_statement(
1299                            id,
1300                            AttachmentSubstrate::Note,
1301                        ),
1302                        guard: None,
1303                    },
1304                    PlanStatement {
1305                        statement: note_hard_delete_statement(id),
1306                        guard: Some(AffectedRowGuard::exactly(1)),
1307                    },
1308                ]
1309            } else {
1310                let deleted_at = chrono::Utc::now().timestamp_micros();
1311                vec![PlanStatement {
1312                    statement: note_soft_delete_statement(id, deleted_at),
1313                    guard: Some(AffectedRowGuard::exactly(1)),
1314                }]
1315            };
1316            if hard {
1317                statements.extend(
1318                    hard_delete_lineage_warning_statements(
1319                        &namespace,
1320                        &actor,
1321                        id,
1322                        SubstrateKind::Note,
1323                    )
1324                    .into_iter()
1325                    .map(|statement| PlanStatement {
1326                        statement,
1327                        guard: None,
1328                    }),
1329                );
1330                statements.push(PlanStatement {
1331                    statement: purge_incident_edges_statement(id),
1332                    guard: None,
1333                });
1334            }
1335            // FTS + vector index purge, matching operations.rs
1336            // `delete_note`: both soft and hard delete clean indexes (a hard
1337            // delete of an already-tombstoned record must still purge
1338            // them); only hard additionally cascades edges above.
1339            push_index_purge_statements(
1340                runtime,
1341                &mut statements,
1342                "fts_notes",
1343                &namespace,
1344                id,
1345                "atomic-delete-note",
1346            )
1347            .await?;
1348            // operations.rs's `delete_note` appends a `NoteDeleted` event
1349            // after a successful row delete, on both soft and hard delete:
1350            // same reasoning as the entity branch above.
1351            statements.extend(event_append_statements(
1352                &namespace,
1353                "delete",
1354                EventKind::NoteDeleted,
1355                SubstrateKind::Note,
1356                id,
1357                serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1358            )?);
1359            Ok(AtomicOpPlan::Delete(DeletePlan {
1360                target_id: id,
1361                statements,
1362                // A committed atomic note delete must fire the same
1363                // pack-installed note-mutation hook `operations.rs::
1364                // delete_note` fires, so a warm ANN cache sees the deletion
1365                // even when the mutation went through the atomic-plan path.
1366                post_commit: PostCommitEffect::NoteDeleted {
1367                    note_id: id,
1368                    kind: note.kind.clone(),
1369                },
1370            }))
1371        }
1372        Some(_) => Err(RuntimeError::InvalidInput(format!(
1373            "delete target {id} must be an entity, note, or edge"
1374        ))),
1375        // `Resolved` has no `Edge` variant (same reasoning as
1376        // `prepare_update`'s fallback above) — probe the graph store
1377        // directly.
1378        None => match &expected_kind {
1379            Some(AtomicDeleteKind::Entity { .. }) => {
1380                Err(RuntimeError::NotFound(format!("entity/note {id}")))
1381            }
1382            Some(AtomicDeleteKind::Note { .. }) => {
1383                Err(RuntimeError::NotFound(format!("entity/note {id}")))
1384            }
1385            Some(AtomicDeleteKind::Edge) | None => {
1386                let edge = if hard {
1387                    runtime.get_edge_including_deleted(token, id).await?
1388                } else {
1389                    runtime.get_edge(token, id).await?
1390                };
1391                match edge {
1392                    Some(edge) => prepare_delete_edge(id, edge, hard, &actor).await,
1393                    None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
1394                }
1395            }
1396        },
1397    }
1398}
1399
1400/// Edge branch of `prepare_delete`. Mirrors
1401/// `khive-runtime::operations::KhiveRuntime::delete_edge` exactly: hard
1402/// delete cascades `purge_incident_edges` (any `annotates` edge — or any
1403/// other edge — pointing AT this edge as a node) BEFORE deleting the edge
1404/// row itself, then a soft or hard delete statement, then an unconditional
1405/// `EdgeDeleted` event (edges are never FTS/vector-indexed, so unlike the
1406/// entity/note branches there is no index purge here — `delete_edge` has
1407/// none either).
1408async fn prepare_delete_edge(
1409    id: Uuid,
1410    edge: khive_storage::types::Edge,
1411    hard: bool,
1412    actor: &str,
1413) -> RuntimeResult<AtomicOpPlan> {
1414    let namespace = edge.namespace.clone();
1415    let mut statements: Vec<PlanStatement> = Vec::new();
1416
1417    if hard {
1418        statements.extend(
1419            hard_delete_lineage_warning_statements(&namespace, actor, id, SubstrateKind::Entity)
1420                .into_iter()
1421                .map(|statement| PlanStatement {
1422                    statement,
1423                    guard: None,
1424                }),
1425        );
1426        // Mirrors `delete_edge`'s `graph.purge_incident_edges(edge_id)` —
1427        // unguarded: zero incident edges is a legitimate outcome, not a
1428        // failure (same reasoning as the entity/note cascade-edges
1429        // statements above).
1430        statements.push(PlanStatement {
1431            statement: purge_incident_edges_statement(id),
1432            guard: None,
1433        });
1434        statements.push(PlanStatement {
1435            statement: edge_hard_delete_statement(id),
1436            guard: Some(AffectedRowGuard::exactly(1)),
1437        });
1438    } else {
1439        let now = chrono::Utc::now().timestamp_micros();
1440        statements.push(PlanStatement {
1441            statement: edge_soft_delete_statement(id, now),
1442            guard: Some(AffectedRowGuard::exactly(1)),
1443        });
1444    }
1445
1446    statements.extend(event_append_statements(
1447        &namespace,
1448        "delete",
1449        EventKind::EdgeDeleted,
1450        SubstrateKind::Entity,
1451        id,
1452        serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
1453    )?);
1454
1455    Ok(AtomicOpPlan::Delete(DeletePlan {
1456        target_id: id,
1457        statements,
1458        post_commit: PostCommitEffect::None,
1459    }))
1460}
1461
1462// ---------------------------------------------------------------------------
1463// link
1464// ---------------------------------------------------------------------------
1465
1466fn parse_edge_relation(raw: &str) -> RuntimeResult<EdgeRelation> {
1467    raw.parse::<EdgeRelation>()
1468        .map_err(|e| RuntimeError::InvalidInput(format!("unknown edge relation {raw:?}: {e}")))
1469}
1470
1471async fn prepare_link(
1472    runtime: &KhiveRuntime,
1473    token: &NamespaceToken,
1474    args: &Value,
1475) -> RuntimeResult<AtomicOpPlan> {
1476    let source_id = require_uuid(args, "source_id")?;
1477    let target_id = require_uuid(args, "target_id")?;
1478    let relation = parse_edge_relation(require_str(args, "relation")?)?;
1479    let weight = optional_f64(args, "weight")?.unwrap_or(1.0);
1480    let metadata = obj(args)?.get("metadata").cloned();
1481
1482    // Top-level `dependency_kind` param merges into `metadata`: only fills
1483    // the key when metadata doesn't already carry one. Calls the same
1484    // `khive_runtime::merge_entry_metadata` `khive-pack-kg`'s canonical
1485    // `handle_link` calls, so both sides depend on one function instead of
1486    // each maintaining their own copy.
1487    let mut metadata = crate::merge_entry_metadata(
1488        metadata,
1489        optional_str(args, "dependency_kind").map(String::from),
1490    )?;
1491
1492    validate_edge_weight(weight)?;
1493    runtime
1494        .validate_edge_relation_endpoints(token, source_id, target_id, relation)
1495        .await?;
1496
1497    let (canon_source, canon_target) = canonical_edge_endpoints(relation, source_id, target_id);
1498
1499    // Endpoint-kind `dependency_kind` inference for `depends_on` edges,
1500    // matching operations.rs `link()`: only applies when both endpoints
1501    // resolve as entities and the key is still absent after the
1502    // top-level-param merge above. Runs against the canonical endpoints,
1503    // mirroring `KhiveRuntime::link`'s own ordering (canonicalize, then
1504    // infer).
1505    if relation == EdgeRelation::DependsOn {
1506        metadata = match (
1507            runtime.resolve_edge_endpoint(token, canon_source).await?,
1508            runtime.resolve_edge_endpoint(token, canon_target).await?,
1509        ) {
1510            (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
1511                merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
1512            }
1513            _ => metadata,
1514        };
1515    }
1516
1517    validate_edge_metadata(relation, metadata.as_ref())?;
1518    let edge_id = Uuid::new_v4();
1519    let namespace = token.namespace().as_str().to_string();
1520    let now = chrono::Utc::now().timestamp_micros();
1521    let metadata_str = metadata.map(|m| serde_json::to_string(&m).unwrap_or_default());
1522
1523    // The guarded `INSERT ... SELECT ... WHERE EXISTS(...)` shape is
1524    // load-bearing (see `LinkPlan`'s own doc comment): it re-probes both
1525    // endpoints inside the transaction, closing the intra-batch hazard
1526    // where an earlier op in the same atomic unit, e.g. `delete(X, hard)`,
1527    // could invalidate this op's prepare-time endpoint validation before
1528    // commit. The conflict-arm SET list shares the same
1529    // `EDGE_NATURAL_KEY_CONFLICT_SET` text `edge_upsert_statement`
1530    // (canonical `link`'s builder) uses, so the two cannot silently diverge
1531    // (a prior bug: this atomic literal never set
1532    // `target_backend = excluded.target_backend`, so a re-link of an edge
1533    // carrying a cross-backend `target_backend` stamp behaved differently
1534    // under `--atomic`).
1535    let statement = edge_insert_guarded_by_endpoints_statement(
1536        &namespace,
1537        edge_id,
1538        canon_source,
1539        canon_target,
1540        relation,
1541        weight,
1542        now,
1543        metadata_str.as_deref(),
1544    );
1545
1546    Ok(AtomicOpPlan::Link(LinkPlan {
1547        source_id: canon_source,
1548        target_id: canon_target,
1549        statement: PlanStatement {
1550            statement,
1551            guard: Some(AffectedRowGuard::exactly(1)),
1552        },
1553    }))
1554}
1555
1556// ---------------------------------------------------------------------------
1557// merge (entity-only)
1558// ---------------------------------------------------------------------------
1559
1560// Full atomic-merge parity (field folding, survivor FTS/vector reindex,
1561// loser index purge, merge provenance, same-kind rejection) is deferred:
1562// atomic `merge` is rejected entirely at the pre-runtime admissibility
1563// guard (`khive_types::pack::ATOMIC_KNOWN_UNIMPLEMENTED_VERBS`, alongside
1564// `propose`/`review`/`withdraw`). This function still produces a plan
1565// (kept for the existing direct-prepare test coverage below and as
1566// defense in depth), but the CLI's `--atomic` surface never reaches it,
1567// since `check_atomic_admissible` rejects `merge` before any runtime is
1568// built.
1569async fn prepare_merge(
1570    runtime: &KhiveRuntime,
1571    token: &NamespaceToken,
1572    args: &Value,
1573) -> RuntimeResult<AtomicOpPlan> {
1574    let into_id = require_uuid(args, "into_id")?;
1575    let from_id = require_uuid(args, "from_id")?;
1576    if into_id == from_id {
1577        return Err(RuntimeError::InvalidInput(
1578            "cannot merge an entity into itself".into(),
1579        ));
1580    }
1581
1582    let entities = runtime.entities(token)?;
1583    entities
1584        .get_entity(into_id)
1585        .await?
1586        .ok_or_else(|| RuntimeError::NotFound(format!("entity {into_id}")))?;
1587    entities
1588        .get_entity(from_id)
1589        .await?
1590        .ok_or_else(|| RuntimeError::NotFound(format!("entity {from_id}")))?;
1591
1592    let now = chrono::Utc::now().timestamp_micros();
1593    let rewires = vec![
1594        crate::atomic_plan::PlanPredicate {
1595            description: "source_id = :from".to_string(),
1596            statement: SqlStatement {
1597                sql: "UPDATE graph_edges SET source_id = ?1, updated_at = ?2 WHERE source_id = ?3"
1598                    .to_string(),
1599                params: vec![
1600                    SqlValue::Text(into_id.to_string()),
1601                    SqlValue::Integer(now),
1602                    SqlValue::Text(from_id.to_string()),
1603                ],
1604                label: Some("atomic-merge-rewire-source".to_string()),
1605            },
1606        },
1607        crate::atomic_plan::PlanPredicate {
1608            description: "target_id = :from".to_string(),
1609            statement: SqlStatement {
1610                sql: "UPDATE graph_edges SET target_id = ?1, updated_at = ?2 WHERE target_id = ?3"
1611                    .to_string(),
1612                params: vec![
1613                    SqlValue::Text(into_id.to_string()),
1614                    SqlValue::Integer(now),
1615                    SqlValue::Text(from_id.to_string()),
1616                ],
1617                label: Some("atomic-merge-rewire-target".to_string()),
1618            },
1619        },
1620    ];
1621    let lifecycle = vec![PlanStatement {
1622        statement: SqlStatement {
1623            sql: "UPDATE entities SET deleted_at = ?1, merged_into = ?2 \
1624                  WHERE id = ?3 AND deleted_at IS NULL"
1625                .to_string(),
1626            params: vec![
1627                SqlValue::Integer(now),
1628                SqlValue::Text(into_id.to_string()),
1629                SqlValue::Text(from_id.to_string()),
1630            ],
1631            label: Some("atomic-merge-tombstone-from-entity".to_string()),
1632        },
1633        guard: Some(AffectedRowGuard::exactly(1)),
1634    }];
1635
1636    Ok(AtomicOpPlan::Merge(MergePlan {
1637        into_id,
1638        from_id,
1639        rewires,
1640        lifecycle,
1641    }))
1642}
1643
1644// ---------------------------------------------------------------------------
1645// post-commit effects
1646// ---------------------------------------------------------------------------
1647
1648/// Embedding metadata produced by one successfully applied reindex effect.
1649///
1650/// The effect identity is retained so response builders can attach an advisory
1651/// to the exact atomic op that scheduled the reindex. Effects whose target is
1652/// no longer present are omitted from the returned outcome list.
1653#[derive(Clone, Debug, PartialEq, Eq)]
1654pub struct PostCommitEmbeddingOutcome {
1655    /// The committed reindex effect that produced this outcome.
1656    pub effect: PostCommitEffect,
1657    /// Actual input bounding observed while executing the effect.
1658    pub truncation: crate::retrieval::EmbeddingTruncationReport,
1659}
1660
1661/// Run every deferred [`PostCommitEffect`] after a committed atomic unit.
1662pub async fn apply_post_commit_effects(
1663    runtime: &KhiveRuntime,
1664    token: &NamespaceToken,
1665    effects: CommittedPostCommitEffects,
1666) -> RuntimeResult<()> {
1667    apply_post_commit_effects_with_report(runtime, token, effects)
1668        .await
1669        .map(|_| ())
1670}
1671
1672/// Truncation-reporting form of [`apply_post_commit_effects`]. Re-fetches each
1673/// target's now-committed row outside any transaction and reuses the existing
1674/// `reindex_entity`/`reindex_note` (FTS + embedding, same as the non-atomic
1675/// path) for exact parity. Returns the typed embedding outcome for each reindex
1676/// effect so callers can preserve write-response advisories instead of
1677/// discarding them after commit.
1678pub async fn apply_post_commit_effects_with_report(
1679    runtime: &KhiveRuntime,
1680    token: &NamespaceToken,
1681    effects: CommittedPostCommitEffects,
1682) -> RuntimeResult<Vec<PostCommitEmbeddingOutcome>> {
1683    let mut embedding_outcomes = Vec::new();
1684    for effect in effects.into_effects() {
1685        match effect {
1686            PostCommitEffect::None => {}
1687            PostCommitEffect::ReindexEntity { entity_id } => {
1688                if let Some(entity) = runtime.entities(token)?.get_entity(entity_id).await? {
1689                    let truncation = runtime.reindex_entity(token, &entity).await?;
1690                    embedding_outcomes.push(PostCommitEmbeddingOutcome {
1691                        effect: PostCommitEffect::ReindexEntity { entity_id },
1692                        truncation,
1693                    });
1694                }
1695            }
1696            PostCommitEffect::ReindexNote { note_id } => {
1697                if let Some(note) = runtime.notes(token)?.get_note(note_id).await? {
1698                    let truncation = runtime.reindex_note(token, &note).await?;
1699                    embedding_outcomes.push(PostCommitEmbeddingOutcome {
1700                        effect: PostCommitEffect::ReindexNote { note_id },
1701                        truncation,
1702                    });
1703                    // This handler calls `reindex_note` directly, bypassing
1704                    // `update_note()` and the note-mutation hook it fires
1705                    // after its own reindex (see `curation.rs`). Fire it
1706                    // here so any in-process consumer (e.g.
1707                    // khive-pack-memory's warm ANN cache) sees a bumped
1708                    // generation after a committed atomic note update,
1709                    // matching the non-atomic path.
1710                    runtime.fire_note_mutation_hook(&note.kind, note.id).await;
1711                }
1712            }
1713            PostCommitEffect::NoteDeleted { note_id, kind } => {
1714                // Unlike `operations.rs`'s `delete_note`, which fires
1715                // `fire_note_mutation_hook` directly (with the already-known
1716                // kind, no refetch) after a successful row delete, an atomic
1717                // note delete needs this post-commit pass to reach it. The
1718                // note row is gone (hard delete) or tombstoned (soft
1719                // delete) by the time this runs, so it mirrors
1720                // `delete_note`'s direct-fire shape rather than
1721                // `ReindexNote`'s refetch-then-fire shape.
1722                runtime.fire_note_mutation_hook(&kind, note_id).await;
1723            }
1724            PostCommitEffect::GtdAudit { .. } => {
1725                // Applied by the `kkernel` caller's own post-commit pass,
1726                // not here: `khive-pack-gtd` (owner of
1727                // `ensure_audit_schema`/`write_audit_record_with_status`)
1728                // depends on
1729                // `khive-runtime`, not the other way around, so this crate
1730                // cannot act on the effect itself. See
1731                // `PostCommitEffect::GtdAudit`'s doc comment.
1732            }
1733        }
1734    }
1735    Ok(embedding_outcomes)
1736}
1737
1738#[cfg(test)]
1739mod tests {
1740    use super::*;
1741
1742    use async_trait::async_trait;
1743    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};
1744    use serde_json::json;
1745
1746    use khive_types::Namespace;
1747
1748    use crate::embedder_registry::EmbedderProvider;
1749    use crate::runtime::RuntimeConfig;
1750
1751    const STUB_MODEL: &str = "stub-adr099-b3";
1752    const STUB_DIMS: usize = 4;
1753
1754    struct StubService;
1755
1756    #[async_trait]
1757    impl EmbeddingService for StubService {
1758        async fn embed(
1759            &self,
1760            texts: &[String],
1761            _model: EmbeddingModel,
1762        ) -> Result<Vec<Vec<f32>>, EmbedError> {
1763            Ok(texts.iter().map(|_| vec![0.5_f32; STUB_DIMS]).collect())
1764        }
1765
1766        fn supports_model(&self, _model: EmbeddingModel) -> bool {
1767            true
1768        }
1769
1770        fn name(&self) -> &'static str {
1771            STUB_MODEL
1772        }
1773    }
1774
1775    struct StubProvider;
1776
1777    #[async_trait]
1778    impl EmbedderProvider for StubProvider {
1779        fn name(&self) -> &str {
1780            STUB_MODEL
1781        }
1782
1783        fn dimensions(&self) -> usize {
1784            STUB_DIMS
1785        }
1786
1787        async fn build(&self) -> RuntimeResult<std::sync::Arc<dyn EmbeddingService>> {
1788            Ok(std::sync::Arc::new(StubService))
1789        }
1790    }
1791
1792    fn scratch_runtime() -> KhiveRuntime {
1793        let dir = tempfile::tempdir().expect("tempdir");
1794        let path = dir.path().join("atomic_prepare_reindex.db");
1795        let rt = KhiveRuntime::new(RuntimeConfig {
1796            db_path: Some(path),
1797            embedding_model: None,
1798            additional_embedding_models: vec![],
1799            ..RuntimeConfig::default()
1800        })
1801        .expect("runtime");
1802        std::mem::forget(dir);
1803        rt
1804    }
1805
1806    /// Atomic `update` must reject a field that does not apply to the
1807    /// resolved substrate: parity with
1808    /// `khive-pack-kg::handlers::update::reject_inapplicable_fields`.
1809    /// Without this check, atomic prepare would silently ignore `salience`
1810    /// on an entity: it would set every entity field to its current value,
1811    /// bump `updated_at`, satisfy the `exactly(1)` guard, and commit: a
1812    /// spurious no-op reported as success.
1813    #[tokio::test]
1814    async fn atomic_update_entity_rejects_note_only_field_salience() {
1815        let runtime = scratch_runtime();
1816        let token = runtime
1817            .authorize(Namespace::parse("local").expect("ns"))
1818            .expect("authorize");
1819        let entity = khive_storage::Entity::new("local", "concept", "GapFourEntity");
1820        let entity_id = entity.id;
1821        runtime
1822            .entities(&token)
1823            .expect("entities store")
1824            .upsert_entity(entity)
1825            .await
1826            .expect("seed entity");
1827
1828        let err = prepare_update(
1829            &runtime,
1830            &token,
1831            &json!({"id": entity_id.to_string(), "salience": 0.9}),
1832            None,
1833        )
1834        .await
1835        .expect_err("salience on an entity must be rejected, not silently accepted");
1836        assert!(
1837            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("salience") && msg.contains("not valid for an entity")),
1838            "expected an InvalidInput naming the offending field, got: {err:?}"
1839        );
1840
1841        // A valid entity update (name/description/tags) must still work.
1842        let plan = prepare_update(
1843            &runtime,
1844            &token,
1845            &json!({
1846                "id": entity_id.to_string(),
1847                "name": "GapFourEntity-renamed",
1848                "description": "updated description",
1849                "tags": ["a", "b"],
1850            }),
1851            None,
1852        )
1853        .await
1854        .expect("a valid entity field set must still be accepted");
1855        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1856            .await
1857            .expect("seam call ok");
1858        assert!(matches!(
1859            outcome,
1860            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1861        ));
1862        let entity = runtime
1863            .get_entity(&token, entity_id)
1864            .await
1865            .expect("get_entity");
1866        assert_eq!(entity.name, "GapFourEntity-renamed");
1867    }
1868
1869    #[tokio::test]
1870    async fn atomic_update_entity_type_persists_patch_and_schedules_reindex() {
1871        let runtime = scratch_runtime();
1872        runtime.install_entity_type_validator(std::sync::Arc::new(|kind, entity_type| {
1873            let Some(raw) = entity_type else {
1874                return Ok(None);
1875            };
1876            let normalized = raw.trim().to_ascii_lowercase();
1877            if kind == "concept" && normalized == "algorithm" {
1878                Ok(Some(normalized))
1879            } else {
1880                Err(RuntimeError::InvalidInput(format!(
1881                    "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
1882                )))
1883            }
1884        }));
1885        let token = runtime
1886            .authorize(Namespace::parse("local").expect("ns"))
1887            .expect("authorize");
1888        let mut entity = khive_storage::Entity::new("local", "concept", "AtomicHistorical");
1889        entity.description = Some("keep description".to_string());
1890        entity.properties = Some(json!({"type": "algorithm", "keep": true}));
1891        entity.tags = vec!["keep-tag".to_string()];
1892        let entity_id = entity.id;
1893        runtime
1894            .entities(&token)
1895            .expect("entities store")
1896            .upsert_entity(entity)
1897            .await
1898            .expect("seed entity");
1899
1900        let plan = prepare_update(
1901            &runtime,
1902            &token,
1903            &json!({"id": entity_id.to_string(), "entity_type": " Algorithm "}),
1904            None,
1905        )
1906        .await
1907        .expect("atomic prepare must accept a registered entity_type");
1908        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1909            .await
1910            .expect("atomic update must run");
1911        let post_commit = match outcome {
1912            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
1913            other => panic!("expected Committed, got {other:?}"),
1914        };
1915        assert_eq!(
1916            post_commit.as_slice(),
1917            &[PostCommitEffect::ReindexEntity { entity_id }],
1918            "entity_type patch must schedule the normal entity reindex path"
1919        );
1920
1921        let updated = runtime
1922            .get_entity(&token, entity_id)
1923            .await
1924            .expect("read updated entity");
1925        assert_eq!(updated.entity_type.as_deref(), Some("algorithm"));
1926        assert_eq!(updated.name, "AtomicHistorical");
1927        assert_eq!(updated.description.as_deref(), Some("keep description"));
1928        assert_eq!(
1929            updated.properties,
1930            Some(json!({"type": "algorithm", "keep": true}))
1931        );
1932        assert_eq!(updated.tags, vec!["keep-tag"]);
1933    }
1934
1935    /// Symmetric note-substrate case: `description` and `tags` are
1936    /// entity-only fields; passing either for a note must be rejected the
1937    /// same way update.rs rejects them.
1938    #[tokio::test]
1939    async fn atomic_update_note_rejects_entity_only_field_description() {
1940        let runtime = scratch_runtime();
1941        let token = runtime
1942            .authorize(Namespace::parse("local").expect("ns"))
1943            .expect("authorize");
1944        let mut note = khive_storage::note::Note::new("local", "observation", "gap-4 note content");
1945        note.name = Some("gap-four-note".to_string());
1946        let note_id = note.id;
1947        runtime
1948            .notes(&token)
1949            .expect("notes store")
1950            .upsert_note(note)
1951            .await
1952            .expect("seed note");
1953
1954        let err = prepare_update(
1955            &runtime,
1956            &token,
1957            &json!({"id": note_id.to_string(), "description": "entities have descriptions, notes don't"}),
1958                None,
1959            )
1960        .await
1961        .expect_err("description on a note must be rejected, not silently accepted");
1962        assert!(
1963            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("description") && msg.contains("not valid for a note")),
1964            "expected an InvalidInput naming the offending field, got: {err:?}"
1965        );
1966
1967        // A valid note update (content) must still work.
1968        let plan = prepare_update(
1969            &runtime,
1970            &token,
1971            &json!({"id": note_id.to_string(), "content": "gap-4 note content, revised"}),
1972            None,
1973        )
1974        .await
1975        .expect("a valid note field must still be accepted");
1976        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
1977            .await
1978            .expect("seam call ok");
1979        assert!(matches!(
1980            outcome,
1981            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
1982        ));
1983    }
1984
1985    /// Updating a note's content inside an atomic unit must, after commit,
1986    /// leave the note recallable via FTS under its new content and its
1987    /// vector row refreshed: parity with the non-atomic
1988    /// `update_note` -> `reindex_note` path.
1989    #[tokio::test]
1990    async fn atomic_update_note_content_is_fts_and_vector_reindexed_post_commit() {
1991        let runtime = scratch_runtime();
1992        runtime.register_embedder(StubProvider);
1993        let token = runtime
1994            .authorize(Namespace::parse("local").expect("ns"))
1995            .expect("authorize");
1996
1997        let mut note = khive_storage::note::Note::new("local", "observation", "original content");
1998        note.name = Some("reindex-target".to_string());
1999        let note_id = note.id;
2000        runtime
2001            .notes(&token)
2002            .expect("notes store")
2003            .upsert_note(note)
2004            .await
2005            .expect("seed note");
2006
2007        // Sanity: no vector row yet for the stub model.
2008        let vec_store = runtime
2009            .vectors_for_model(&token, STUB_MODEL)
2010            .expect("vec store");
2011        assert_eq!(vec_store.count().await.expect("count before"), 0);
2012
2013        let updated_content = format!("freshly-updated-content-xyz{}", "x".repeat(MAX_TEXT_BYTES));
2014        let plan = prepare_update(
2015            &runtime,
2016            &token,
2017            &json!({"id": note_id.to_string(), "content": updated_content}),
2018            None,
2019        )
2020        .await
2021        .expect("prepare update");
2022
2023        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2024            .await
2025            .expect("seam call ok");
2026        let post_commit = match outcome {
2027            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2028            other => panic!("expected Committed, got {other:?}"),
2029        };
2030        assert_eq!(
2031            post_commit.as_slice(),
2032            &[PostCommitEffect::ReindexNote { note_id }],
2033            "content change must schedule exactly one ReindexNote post-commit effect"
2034        );
2035
2036        let embedding_outcomes =
2037            apply_post_commit_effects_with_report(&runtime, &token, post_commit)
2038                .await
2039                .expect("apply post-commit effects");
2040        assert_eq!(embedding_outcomes.len(), 1);
2041        assert_eq!(
2042            embedding_outcomes[0].effect,
2043            PostCommitEffect::ReindexNote { note_id }
2044        );
2045        assert_eq!(embedding_outcomes[0].truncation.truncated, 1);
2046        assert!(embedding_outcomes[0].truncation.discarded_bytes > 0);
2047
2048        // FTS: the note must be recallable under its NEW content.
2049        let doc = runtime
2050            .text_for_notes(&token)
2051            .expect("text store")
2052            .get_document("local", note_id)
2053            .await
2054            .expect("get_document")
2055            .expect("document must be indexed after post-commit reindex");
2056        assert!(
2057            doc.body.contains("freshly-updated-content-xyz"),
2058            "FTS body must reflect the committed content: {:?}",
2059            doc.body
2060        );
2061
2062        // Vector: a row must now exist for the registered stub model.
2063        assert_eq!(
2064            vec_store.count().await.expect("count after"),
2065            1,
2066            "post-commit reindex must have inserted a vector row for the stub model"
2067        );
2068    }
2069
2070    /// The atomic-plan path must fire the pack-installed note-mutation hook
2071    /// for both an atomic note UPDATE (`PostCommitEffect::ReindexNote`'s
2072    /// handler fires it after its own reindex, mirroring `update_note()`
2073    /// on the non-atomic path) and an atomic note DELETE (`DeletePlan`
2074    /// carries a `PostCommitEffect::NoteDeleted` that
2075    /// `apply_post_commit_effects` dispatches directly, mirroring
2076    /// `operations.rs::delete_note`'s direct-fire, no-refetch shape: the
2077    /// row may already be gone by the time this runs, for a hard delete).
2078    /// A minimal counting hook proves both fire; no `khive-pack-memory`
2079    /// dependency is needed at this layer, since the hook itself is
2080    /// generic.
2081    #[tokio::test]
2082    async fn atomic_note_update_and_delete_post_commit_effects_execute_exactly_once() {
2083        let runtime = scratch_runtime();
2084        let token = runtime
2085            .authorize(Namespace::parse("local").expect("ns"))
2086            .expect("authorize");
2087
2088        let fired: std::sync::Arc<std::sync::Mutex<Vec<(String, uuid::Uuid)>>> =
2089            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2090        let fired_for_hook = fired.clone();
2091        runtime.install_note_mutation_hook(std::sync::Arc::new(
2092            move |kind: String, id: uuid::Uuid| {
2093                let fired = fired_for_hook.clone();
2094                Box::pin(async move {
2095                    fired.lock().expect("lock").push((kind, id));
2096                })
2097            },
2098        ));
2099
2100        // Update path.
2101        let mut note = khive_storage::note::Note::new("local", "observation", "hook-update-target");
2102        note.name = Some("hook-update-target".to_string());
2103        let update_note_id = note.id;
2104        runtime
2105            .notes(&token)
2106            .expect("notes store")
2107            .upsert_note(note)
2108            .await
2109            .expect("seed update-target note");
2110
2111        let plan = prepare_update(
2112            &runtime,
2113            &token,
2114            &json!({"id": update_note_id.to_string(), "content": "hook-update-target, revised"}),
2115            None,
2116        )
2117        .await
2118        .expect("prepare update");
2119        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2120            .await
2121            .expect("seam call ok");
2122        let post_commit = match outcome {
2123            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2124            other => panic!("expected Committed, got {other:?}"),
2125        };
2126        apply_post_commit_effects(&runtime, &token, post_commit)
2127            .await
2128            .expect("apply post-commit effects (update)");
2129
2130        // Delete path (soft delete: the row still exists, but the hook
2131        // fires directly from the captured kind rather than refetching).
2132        let mut del_note =
2133            khive_storage::note::Note::new("local", "observation", "hook-delete-target");
2134        del_note.name = Some("hook-delete-target".to_string());
2135        let delete_note_id = del_note.id;
2136        runtime
2137            .notes(&token)
2138            .expect("notes store")
2139            .upsert_note(del_note)
2140            .await
2141            .expect("seed delete-target note");
2142
2143        let plan = prepare_delete(
2144            &runtime,
2145            &token,
2146            &json!({"id": delete_note_id.to_string(), "hard": false}),
2147            None,
2148        )
2149        .await
2150        .expect("prepare delete");
2151        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2152            .await
2153            .expect("seam call ok");
2154        let post_commit = match outcome {
2155            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
2156            other => panic!("expected Committed, got {other:?}"),
2157        };
2158        assert_eq!(
2159            post_commit.as_slice(),
2160            &[PostCommitEffect::NoteDeleted {
2161                note_id: delete_note_id,
2162                kind: "observation".to_string(),
2163            }],
2164            "a committed note delete must schedule exactly one NoteDeleted post-commit effect"
2165        );
2166        apply_post_commit_effects(&runtime, &token, post_commit)
2167            .await
2168            .expect("apply post-commit effects (delete)");
2169
2170        assert_eq!(
2171            *fired.lock().expect("lock"),
2172            vec![
2173                ("observation".to_string(), update_note_id),
2174                ("observation".to_string(), delete_note_id),
2175            ],
2176            "each committed token must execute its note-mutation effect exactly once"
2177        );
2178    }
2179
2180    /// Atomic delete must purge the note's FTS row and vector row for both
2181    /// soft and hard delete: parity with `KhiveRuntime::delete_note`'s
2182    /// index-cleanup contract.
2183    #[tokio::test]
2184    async fn atomic_delete_note_purges_fts_and_vector_indexes_soft_and_hard() {
2185        let runtime = scratch_runtime();
2186        runtime.register_embedder(StubProvider);
2187        let token = runtime
2188            .authorize(Namespace::parse("local").expect("ns"))
2189            .expect("authorize");
2190
2191        for hard in [false, true] {
2192            let mut note =
2193                khive_storage::note::Note::new("local", "observation", "purge-target content");
2194            note.name = Some(format!("purge-target-hard-{hard}"));
2195            let note_id = note.id;
2196            runtime
2197                .notes(&token)
2198                .expect("notes store")
2199                .upsert_note(note.clone())
2200                .await
2201                .expect("seed note");
2202            runtime
2203                .reindex_note(&token, &note)
2204                .await
2205                .expect("seed index rows");
2206
2207            let vec_store = runtime
2208                .vectors_for_model(&token, STUB_MODEL)
2209                .expect("vec store");
2210            assert_eq!(
2211                vec_store.count().await.expect("count before"),
2212                1,
2213                "seeded note must have a vector row before delete (hard={hard})"
2214            );
2215            assert!(
2216                runtime
2217                    .text_for_notes(&token)
2218                    .expect("text store")
2219                    .get_document("local", note_id)
2220                    .await
2221                    .expect("get_document")
2222                    .is_some(),
2223                "seeded note must have an FTS row before delete (hard={hard})"
2224            );
2225
2226            let plan = prepare_delete(
2227                &runtime,
2228                &token,
2229                &json!({"id": note_id.to_string(), "hard": hard}),
2230                None,
2231            )
2232            .await
2233            .expect("prepare delete");
2234            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2235                .await
2236                .expect("seam call ok");
2237            assert!(
2238                matches!(
2239                    outcome,
2240                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2241                ),
2242                "expected commit (hard={hard}): {outcome:?}"
2243            );
2244
2245            assert!(
2246                runtime
2247                    .text_for_notes(&token)
2248                    .expect("text store")
2249                    .get_document("local", note_id)
2250                    .await
2251                    .expect("get_document")
2252                    .is_none(),
2253                "FTS row must be purged after atomic delete (hard={hard})"
2254            );
2255            assert_eq!(
2256                vec_store.count().await.expect("count after"),
2257                0,
2258                "vector row must be purged after atomic delete (hard={hard})"
2259            );
2260        }
2261    }
2262
2263    /// Atomic delete must purge the entity's FTS row and vector row for
2264    /// both soft and hard delete: parity with
2265    /// `KhiveRuntime::delete_entity`'s index-cleanup contract.
2266    #[tokio::test]
2267    async fn atomic_delete_entity_purges_fts_and_vector_indexes_soft_and_hard() {
2268        let runtime = scratch_runtime();
2269        runtime.register_embedder(StubProvider);
2270        let token = runtime
2271            .authorize(Namespace::parse("local").expect("ns"))
2272            .expect("authorize");
2273
2274        for hard in [false, true] {
2275            let entity =
2276                khive_storage::Entity::new("local", "concept", format!("purge-target-hard-{hard}"));
2277            let entity_id = entity.id;
2278            runtime
2279                .entities(&token)
2280                .expect("entities store")
2281                .upsert_entity(entity.clone())
2282                .await
2283                .expect("seed entity");
2284            runtime
2285                .reindex_entity(&token, &entity)
2286                .await
2287                .expect("seed index rows");
2288
2289            let vec_store = runtime
2290                .vectors_for_model(&token, STUB_MODEL)
2291                .expect("vec store");
2292            assert_eq!(
2293                vec_store.count().await.expect("count before"),
2294                1,
2295                "seeded entity must have a vector row before delete (hard={hard})"
2296            );
2297            assert!(
2298                runtime
2299                    .text(&token)
2300                    .expect("text store")
2301                    .get_document("local", entity_id)
2302                    .await
2303                    .expect("get_document")
2304                    .is_some(),
2305                "seeded entity must have an FTS row before delete (hard={hard})"
2306            );
2307
2308            let plan = prepare_delete(
2309                &runtime,
2310                &token,
2311                &json!({"id": entity_id.to_string(), "hard": hard}),
2312                None,
2313            )
2314            .await
2315            .expect("prepare delete");
2316            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2317                .await
2318                .expect("seam call ok");
2319            assert!(
2320                matches!(
2321                    outcome,
2322                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2323                ),
2324                "expected commit (hard={hard}): {outcome:?}"
2325            );
2326
2327            assert!(
2328                runtime
2329                    .text(&token)
2330                    .expect("text store")
2331                    .get_document("local", entity_id)
2332                    .await
2333                    .expect("get_document")
2334                    .is_none(),
2335                "FTS row must be purged after atomic delete (hard={hard})"
2336            );
2337            assert_eq!(
2338                vec_store.count().await.expect("count after"),
2339                0,
2340                "vector row must be purged after atomic delete (hard={hard})"
2341            );
2342        }
2343    }
2344
2345    #[tokio::test]
2346    async fn atomic_delete_entity_and_note_logs_vector_delete_rows() {
2347        let runtime = scratch_runtime();
2348        runtime.register_embedder(StubProvider);
2349        let token = runtime
2350            .authorize(Namespace::parse("local").expect("ns"))
2351            .expect("authorize");
2352
2353        let entity = khive_storage::Entity::new("local", "concept", "ann-delete-entity");
2354        let entity_id = entity.id;
2355        runtime
2356            .entities(&token)
2357            .expect("entities store")
2358            .upsert_entity(entity.clone())
2359            .await
2360            .expect("seed entity");
2361        runtime
2362            .reindex_entity(&token, &entity)
2363            .await
2364            .expect("seed entity vector row");
2365        let note = khive_storage::note::Note::new("local", "observation", "ann-delete-note");
2366        let note_id = note.id;
2367        runtime
2368            .notes(&token)
2369            .expect("notes store")
2370            .upsert_note(note.clone())
2371            .await
2372            .expect("seed note");
2373        runtime
2374            .reindex_note(&token, &note)
2375            .await
2376            .expect("seed note vector row");
2377
2378        for id in [entity_id, note_id] {
2379            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2380                .await
2381                .expect("prepare delete");
2382            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2383                .await
2384                .expect("seam call ok");
2385            assert!(matches!(
2386                outcome,
2387                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2388            ));
2389        }
2390
2391        let mut reader = runtime.sql().reader().await.expect("sql reader");
2392        let count = reader
2393            .query_scalar(SqlStatement {
2394                sql: "SELECT COUNT(*) FROM ann_write_log \
2395                      WHERE namespace = 'local' AND embedding_model = ?1 AND op = 'delete' \
2396                      AND ((kind = 'entity' AND field = 'entity.body' AND subject_id = ?2) \
2397                        OR (kind = 'note' AND field = 'note.content' AND subject_id = ?3))"
2398                    .to_string(),
2399                params: vec![
2400                    SqlValue::Text(STUB_MODEL.to_string()),
2401                    SqlValue::Text(entity_id.to_string()),
2402                    SqlValue::Text(note_id.to_string()),
2403                ],
2404                label: Some("test-atomic-delete-ann-write-log".to_string()),
2405            })
2406            .await
2407            .expect("query ANN write log");
2408        assert!(matches!(count, Some(SqlValue::Integer(2))));
2409    }
2410
2411    /// Atomic prepare validates the requested orientation before canonicalizing
2412    /// a symmetric edge for persistence. Fixed UUIDs force target < source so a
2413    /// regression would report the reverse ordered pair.
2414    #[tokio::test]
2415    async fn atomic_link_symmetric_rejection_preserves_requested_pair() {
2416        let runtime = scratch_runtime();
2417        let token = runtime
2418            .authorize(Namespace::parse("local").expect("ns"))
2419            .expect("authorize");
2420        let entities = runtime.entities(&token).expect("entities store");
2421        let concept_id =
2422            Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").expect("high UUID");
2423        let project_id = Uuid::nil();
2424        assert!(project_id < concept_id, "test must exercise UUID reversal");
2425
2426        let mut concept = khive_storage::Entity::new("local", "concept", "Concept source");
2427        concept.id = concept_id;
2428        let mut project = khive_storage::Entity::new("local", "project", "Project target");
2429        project.id = project_id;
2430        entities.upsert_entity(concept).await.expect("seed concept");
2431        entities.upsert_entity(project).await.expect("seed project");
2432
2433        let error = prepare_link(
2434            &runtime,
2435            &token,
2436            &json!({
2437                "source_id": concept_id.to_string(),
2438                "target_id": project_id.to_string(),
2439                "relation": "competes_with",
2440            }),
2441        )
2442        .await
2443        .expect_err("atomic link must reject concept competes_with project");
2444        let message = error.to_string();
2445        assert!(
2446            message.contains(
2447                "currently legal relations for concept -> project under the loaded endpoint rules: none"
2448            ),
2449            "atomic validation must diagnose caller order before persistence canonicalization; got: {message}"
2450        );
2451        assert!(
2452            !message.contains("currently legal relations for project -> concept"),
2453            "atomic validation must not diagnose the UUID-canonical reverse pair; got: {message}"
2454        );
2455    }
2456
2457    /// Atomic link must persist an explicit top-level `dependency_kind`
2458    /// param into edge metadata, and must infer one for `depends_on` edges
2459    /// when absent: parity with
2460    /// `link.rs`'s `merge_entry_metadata` and `operations.rs`'s
2461    /// `infer_dependency_kind` table.
2462    #[tokio::test]
2463    async fn atomic_link_persists_explicit_dependency_kind_and_infers_when_absent() {
2464        let runtime = scratch_runtime();
2465        let token = runtime
2466            .authorize(Namespace::parse("local").expect("ns"))
2467            .expect("authorize");
2468        let entities = runtime.entities(&token).expect("entities store");
2469
2470        fn metadata_json(plan: &AtomicOpPlan) -> String {
2471            let link_plan = match plan {
2472                AtomicOpPlan::Link(p) => p,
2473                other => panic!("expected an AtomicOpPlan::Link, got {other:?}"),
2474            };
2475            match link_plan.statement.statement.params.last() {
2476                Some(SqlValue::Text(s)) => s.clone(),
2477                other => panic!("expected the metadata param to be SqlValue::Text, got {other:?}"),
2478            }
2479        }
2480
2481        // (a) explicit top-level `dependency_kind` param persists in metadata.
2482        {
2483            let svc = khive_storage::Entity::new("local", "service", "SvcA");
2484            let proj = khive_storage::Entity::new("local", "project", "ProjB");
2485            let (svc_id, proj_id) = (svc.id, proj.id);
2486            entities.upsert_entity(svc).await.expect("seed svc");
2487            entities.upsert_entity(proj).await.expect("seed proj");
2488
2489            let plan = prepare_link(
2490                &runtime,
2491                &token,
2492                &json!({
2493                    "source_id": svc_id.to_string(),
2494                    "target_id": proj_id.to_string(),
2495                    "relation": "depends_on",
2496                    "dependency_kind": "artifact",
2497                }),
2498            )
2499            .await
2500            .expect("prepare link");
2501            let json_str = metadata_json(&plan);
2502            assert!(
2503                json_str.contains(r#""dependency_kind":"artifact""#),
2504                "explicit dependency_kind param must persist: {json_str}"
2505            );
2506        }
2507
2508        // (b) `depends_on` with no explicit dependency_kind infers from
2509        // endpoint kinds: (service, service) -> "runtime".
2510        {
2511            let svc_a = khive_storage::Entity::new("local", "service", "SvcC");
2512            let svc_b = khive_storage::Entity::new("local", "service", "SvcD");
2513            let (a_id, b_id) = (svc_a.id, svc_b.id);
2514            entities.upsert_entity(svc_a).await.expect("seed svc a");
2515            entities.upsert_entity(svc_b).await.expect("seed svc b");
2516
2517            let plan = prepare_link(
2518                &runtime,
2519                &token,
2520                &json!({
2521                    "source_id": a_id.to_string(),
2522                    "target_id": b_id.to_string(),
2523                    "relation": "depends_on",
2524                }),
2525            )
2526            .await
2527            .expect("prepare link");
2528            let json_str = metadata_json(&plan);
2529            assert!(
2530                json_str.contains(r#""dependency_kind":"runtime""#),
2531                "inferred dependency_kind for (service, service) must persist: {json_str}"
2532            );
2533        }
2534    }
2535
2536    /// Raw natural-key probe of `graph_edges` (namespace, source_id,
2537    /// target_id, relation) — returns `(weight, metadata_json, deleted_at)`
2538    /// for exactly the ONE row a UNIQUE(namespace, source_id, target_id,
2539    /// relation) constraint permits. `None` means no row at all.
2540    async fn probe_edge_natural_key(
2541        runtime: &KhiveRuntime,
2542        namespace: &str,
2543        source_id: Uuid,
2544        target_id: Uuid,
2545        relation: &str,
2546    ) -> (usize, Option<f64>, Option<String>, Option<i64>) {
2547        let mut reader = runtime.sql().reader().await.expect("reader");
2548        let rows = reader
2549            .query_all(SqlStatement {
2550                sql: "SELECT weight, metadata, deleted_at FROM graph_edges \
2551                      WHERE namespace = ?1 AND source_id = ?2 AND target_id = ?3 AND relation = ?4"
2552                    .to_string(),
2553                params: vec![
2554                    SqlValue::Text(namespace.to_string()),
2555                    SqlValue::Text(source_id.to_string()),
2556                    SqlValue::Text(target_id.to_string()),
2557                    SqlValue::Text(relation.to_string()),
2558                ],
2559                label: Some("test-probe-edge-natural-key".to_string()),
2560            })
2561            .await
2562            .expect("probe edge natural key");
2563        let count = rows.len();
2564        let Some(row) = rows.into_iter().next() else {
2565            return (count, None, None, None);
2566        };
2567        let weight = match row.get("weight") {
2568            Some(SqlValue::Float(f)) => Some(*f),
2569            Some(SqlValue::Integer(i)) => Some(*i as f64),
2570            _ => None,
2571        };
2572        let metadata = match row.get("metadata") {
2573            Some(SqlValue::Text(s)) => Some(s.clone()),
2574            _ => None,
2575        };
2576        let deleted_at = match row.get("deleted_at") {
2577            Some(SqlValue::Integer(i)) => Some(*i),
2578            _ => None,
2579        };
2580        (count, weight, metadata, deleted_at)
2581    }
2582
2583    /// Atomic `link` must be an upsert, exactly like canonical `link` ->
2584    /// `upsert_edge`'s natural-key `ON CONFLICT` arm: re-linking an
2585    /// already-linked triple must succeed and update weight/metadata, not
2586    /// hit the `UNIQUE(namespace, source_id, target_id, relation)`
2587    /// constraint and roll back the whole atomic unit.
2588    #[tokio::test]
2589    async fn atomic_link_of_already_linked_triple_upserts_weight_and_metadata() {
2590        let runtime = scratch_runtime();
2591        let token = runtime
2592            .authorize(Namespace::parse("local").expect("ns"))
2593            .expect("authorize");
2594        let entities = runtime.entities(&token).expect("entities store");
2595
2596        let a = khive_storage::Entity::new("local", "concept", "GapTwoA");
2597        let b = khive_storage::Entity::new("local", "concept", "GapTwoB");
2598        let (a_id, b_id) = (a.id, b.id);
2599        entities.upsert_entity(a).await.expect("seed a");
2600        entities.upsert_entity(b).await.expect("seed b");
2601
2602        // (a) a fresh link still works.
2603        let plan1 = prepare_link(
2604            &runtime,
2605            &token,
2606            &json!({
2607                "source_id": a_id.to_string(),
2608                "target_id": b_id.to_string(),
2609                "relation": "extends",
2610                "weight": 0.5,
2611            }),
2612        )
2613        .await
2614        .expect("prepare first link");
2615        let outcome1 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan1])
2616            .await
2617            .expect("seam call ok");
2618        assert!(
2619            matches!(
2620                outcome1,
2621                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2622            ),
2623            "fresh link must commit: {outcome1:?}"
2624        );
2625        let (count, weight, _metadata, deleted_at) =
2626            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2627        assert_eq!(count, 1, "exactly one edge row after the fresh link");
2628        assert_eq!(weight, Some(0.5));
2629        assert!(deleted_at.is_none());
2630
2631        // (b) re-linking the SAME triple with a different weight/metadata
2632        // must SUCCEED (not a constraint-violation rollback) and UPDATE the
2633        // existing row in place — natural key stays unique.
2634        let plan2 = prepare_link(
2635            &runtime,
2636            &token,
2637            &json!({
2638                "source_id": a_id.to_string(),
2639                "target_id": b_id.to_string(),
2640                "relation": "extends",
2641                "weight": 0.9,
2642                "metadata": {"note": "relinked"},
2643            }),
2644        )
2645        .await
2646        .expect("prepare second link");
2647        let outcome2 = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan2])
2648            .await
2649            .expect("seam call ok");
2650        assert!(
2651            matches!(
2652                outcome2,
2653                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2654            ),
2655            "re-link of an already-linked triple must upsert, not roll back: {outcome2:?}"
2656        );
2657        let (count, weight, metadata, deleted_at) =
2658            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2659        assert_eq!(
2660            count, 1,
2661            "the natural-key UNIQUE constraint must still hold exactly one row (upsert, not a second insert)"
2662        );
2663        assert_eq!(weight, Some(0.9), "weight must be updated to the new value");
2664        assert!(
2665            metadata
2666                .as_deref()
2667                .is_some_and(|m| m.contains(r#""note":"relinked""#)),
2668            "metadata must be updated to the new value: {metadata:?}"
2669        );
2670        assert!(deleted_at.is_none());
2671    }
2672
2673    /// Atomic `link` of a soft-deleted triple must resurrect it
2674    /// (`deleted_at = NULL`), matching `upsert_edge`'s natural-key
2675    /// `ON CONFLICT ... DO UPDATE SET deleted_at = NULL`.
2676    #[tokio::test]
2677    async fn atomic_link_of_soft_deleted_triple_resurrects_it() {
2678        let runtime = scratch_runtime();
2679        let token = runtime
2680            .authorize(Namespace::parse("local").expect("ns"))
2681            .expect("authorize");
2682        let entities = runtime.entities(&token).expect("entities store");
2683
2684        let a = khive_storage::Entity::new("local", "concept", "GapTwoResurrectA");
2685        let b = khive_storage::Entity::new("local", "concept", "GapTwoResurrectB");
2686        let (a_id, b_id) = (a.id, b.id);
2687        entities.upsert_entity(a).await.expect("seed a");
2688        entities.upsert_entity(b).await.expect("seed b");
2689
2690        let plan = prepare_link(
2691            &runtime,
2692            &token,
2693            &json!({
2694                "source_id": a_id.to_string(),
2695                "target_id": b_id.to_string(),
2696                "relation": "extends",
2697            }),
2698        )
2699        .await
2700        .expect("prepare link");
2701        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2702            .await
2703            .expect("seam call ok");
2704        assert!(matches!(
2705            outcome,
2706            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2707        ));
2708
2709        // Soft-delete the edge row directly (natural-key UPDATE — mirrors
2710        // what `delete_edge(hard=false)` does to this same row).
2711        {
2712            let mut writer = runtime.sql().writer().await.expect("writer");
2713            let affected = writer
2714                .execute(SqlStatement {
2715                    sql: "UPDATE graph_edges SET deleted_at = ?1 \
2716                          WHERE namespace = ?2 AND source_id = ?3 AND target_id = ?4 AND relation = ?5"
2717                        .to_string(),
2718                    params: vec![
2719                        SqlValue::Integer(chrono::Utc::now().timestamp_micros()),
2720                        SqlValue::Text("local".to_string()),
2721                        SqlValue::Text(a_id.to_string()),
2722                        SqlValue::Text(b_id.to_string()),
2723                        SqlValue::Text("extends".to_string()),
2724                    ],
2725                    label: Some("test-soft-delete-edge".to_string()),
2726                })
2727                .await
2728                .expect("soft delete edge");
2729            assert_eq!(affected, 1, "soft-delete must touch exactly the seeded row");
2730        }
2731        let (_, _, _, deleted_at) =
2732            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2733        assert!(
2734            deleted_at.is_some(),
2735            "row must be soft-deleted before the resurrect attempt"
2736        );
2737
2738        // Re-link the same triple: must resurrect (deleted_at -> NULL), not
2739        // fail on the UNIQUE constraint of the still-present soft-deleted row.
2740        let plan_relink = prepare_link(
2741            &runtime,
2742            &token,
2743            &json!({
2744                "source_id": a_id.to_string(),
2745                "target_id": b_id.to_string(),
2746                "relation": "extends",
2747                "weight": 0.75,
2748            }),
2749        )
2750        .await
2751        .expect("prepare resurrecting link");
2752        let outcome_relink =
2753            crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan_relink])
2754                .await
2755                .expect("seam call ok");
2756        assert!(
2757            matches!(
2758                outcome_relink,
2759                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2760            ),
2761            "re-linking a soft-deleted triple must resurrect it, not roll back: {outcome_relink:?}"
2762        );
2763        let (count, weight, _, deleted_at) =
2764            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
2765        assert_eq!(count, 1);
2766        assert_eq!(weight, Some(0.75));
2767        assert!(
2768            deleted_at.is_none(),
2769            "re-link must resurrect the soft-deleted row (deleted_at -> NULL)"
2770        );
2771    }
2772
2773    /// Atomic delete of an entity and a note must succeed even when the
2774    /// registered embedding model's `vec_*` table has never been lazily
2775    /// created (a fresh DB registers models before any vector store is
2776    /// opened): the raw purge DML must skip tables that don't exist
2777    /// rather than hit `no such table` and roll back the whole atomic
2778    /// unit. FTS purge still fires (those tables always exist) and the
2779    /// delete itself is a clean commit.
2780    #[tokio::test]
2781    async fn atomic_delete_succeeds_when_vec_table_never_created() {
2782        let runtime = scratch_runtime();
2783        runtime.register_embedder(StubProvider);
2784        let token = runtime
2785            .authorize(Namespace::parse("local").expect("ns"))
2786            .expect("authorize");
2787
2788        // Seed via raw upsert ONLY — never call reindex_entity/reindex_note
2789        // or vectors_for_model, so the stub model's `vec_*` table is never
2790        // lazily created (opening the vector store is what creates it).
2791        let entity = khive_storage::Entity::new("local", "concept", "no-vec-table-entity");
2792        let entity_id = entity.id;
2793        runtime
2794            .entities(&token)
2795            .expect("entities store")
2796            .upsert_entity(entity)
2797            .await
2798            .expect("seed entity");
2799
2800        let mut note = khive_storage::note::Note::new("local", "observation", "no-vec-table-note");
2801        note.name = Some("no-vec-table-note".to_string());
2802        let note_id = note.id;
2803        runtime
2804            .notes(&token)
2805            .expect("notes store")
2806            .upsert_note(note)
2807            .await
2808            .expect("seed note");
2809
2810        for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2811            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2812                .await
2813                .unwrap_or_else(|e| panic!("prepare delete ({kind}) must not fail: {e}"));
2814            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2815                .await
2816                .unwrap_or_else(|e| {
2817                    panic!("atomic delete ({kind}) must not hit `no such table`: {e}")
2818                });
2819            assert!(
2820                matches!(
2821                    outcome,
2822                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2823                ),
2824                "expected a clean commit ({kind}): {outcome:?}"
2825            );
2826        }
2827
2828        assert!(
2829            runtime
2830                .get_entity_including_deleted(&token, entity_id)
2831                .await
2832                .expect("get entity")
2833                .expect("entity row still present (soft delete)")
2834                .deleted_at
2835                .is_some(),
2836            "entity must be soft-deleted"
2837        );
2838        assert!(
2839            runtime
2840                .get_note_including_deleted(&token, note_id)
2841                .await
2842                .expect("get note")
2843                .expect("note row still present (soft delete)")
2844                .deleted_at
2845                .is_some(),
2846            "note must be soft-deleted"
2847        );
2848    }
2849
2850    /// Atomic hard delete must be able to purge a record that was already
2851    /// soft-deleted: parity with `delete(id, hard=true)` being the public
2852    /// purge route after a prior soft delete (the non-atomic hard path
2853    /// resolves including deleted rows and its DML carries no `deleted_at`
2854    /// predicate).
2855    #[tokio::test]
2856    async fn atomic_hard_delete_purges_already_soft_deleted_entity_and_note() {
2857        let runtime = scratch_runtime();
2858        runtime.register_embedder(StubProvider);
2859        let token = runtime
2860            .authorize(Namespace::parse("local").expect("ns"))
2861            .expect("authorize");
2862
2863        let entity =
2864            khive_storage::Entity::new("local", "concept", "tombstoned-entity-hard-delete");
2865        let entity_id = entity.id;
2866        runtime
2867            .entities(&token)
2868            .expect("entities store")
2869            .upsert_entity(entity.clone())
2870            .await
2871            .expect("seed entity");
2872        runtime
2873            .reindex_entity(&token, &entity)
2874            .await
2875            .expect("seed index rows");
2876
2877        let mut note =
2878            khive_storage::note::Note::new("local", "observation", "tombstoned-note-hard-delete");
2879        note.name = Some("tombstoned-note-hard-delete".to_string());
2880        let note_id = note.id;
2881        runtime
2882            .notes(&token)
2883            .expect("notes store")
2884            .upsert_note(note.clone())
2885            .await
2886            .expect("seed note");
2887        runtime
2888            .reindex_note(&token, &note)
2889            .await
2890            .expect("seed index rows");
2891
2892        // First: SOFT delete both (via atomic prepare) so they're tombstoned
2893        // going into the hard-delete attempt below.
2894        for id in [entity_id, note_id] {
2895            let plan = prepare_delete(&runtime, &token, &json!({"id": id.to_string()}), None)
2896                .await
2897                .expect("prepare soft delete");
2898            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2899                .await
2900                .expect("soft delete commit");
2901            assert!(matches!(
2902                outcome,
2903                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2904            ));
2905        }
2906        assert!(
2907            runtime
2908                .get_entity_including_deleted(&token, entity_id)
2909                .await
2910                .expect("get entity")
2911                .expect("entity present")
2912                .deleted_at
2913                .is_some(),
2914            "entity must be soft-deleted before the hard-delete attempt"
2915        );
2916        assert!(
2917            runtime
2918                .get_note_including_deleted(&token, note_id)
2919                .await
2920                .expect("get note")
2921                .expect("note present")
2922                .deleted_at
2923                .is_some(),
2924            "note must be soft-deleted before the hard-delete attempt"
2925        );
2926
2927        // Now: HARD delete the already-tombstoned records.
2928        for (id, kind) in [(entity_id, "entity"), (note_id, "note")] {
2929            let plan = prepare_delete(
2930                &runtime,
2931                &token,
2932                &json!({"id": id.to_string(), "hard": true}),
2933                None,
2934            )
2935            .await
2936            .unwrap_or_else(|e| {
2937                panic!(
2938                    "prepare hard delete ({kind}) of an already-soft-deleted record \
2939                         must resolve it: {e}"
2940                )
2941            });
2942            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
2943                .await
2944                .unwrap_or_else(|e| panic!("hard delete ({kind}) commit failed: {e}"));
2945            assert!(
2946                matches!(
2947                    outcome,
2948                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
2949                ),
2950                "expected a clean hard-delete commit ({kind}): {outcome:?}"
2951            );
2952        }
2953
2954        assert!(
2955            runtime
2956                .get_entity_including_deleted(&token, entity_id)
2957                .await
2958                .expect("get entity")
2959                .is_none(),
2960            "entity row must be fully purged after hard delete"
2961        );
2962        assert!(
2963            runtime
2964                .get_note_including_deleted(&token, note_id)
2965                .await
2966                .expect("get note")
2967                .is_none(),
2968            "note row must be fully purged after hard delete"
2969        );
2970        assert!(
2971            runtime
2972                .text(&token)
2973                .expect("text store")
2974                .get_document("local", entity_id)
2975                .await
2976                .expect("get_document")
2977                .is_none(),
2978            "entity FTS row must be purged after hard delete"
2979        );
2980        assert!(
2981            runtime
2982                .text_for_notes(&token)
2983                .expect("text store")
2984                .get_document("local", note_id)
2985                .await
2986                .expect("get_document")
2987                .is_none(),
2988            "note FTS row must be purged after hard delete"
2989        );
2990        let vec_store = runtime
2991            .vectors_for_model(&token, STUB_MODEL)
2992            .expect("vec store");
2993        assert_eq!(
2994            vec_store.count().await.expect("count after"),
2995            0,
2996            "vector rows for both records must be purged after hard delete"
2997        );
2998    }
2999
3000    // ------------------------------------------------------------------
3001    // event-store append parity
3002    // ------------------------------------------------------------------
3003
3004    /// Fetch every event of `kind` targeting `target_id`, via the same
3005    /// `EventStore::query_events` surface `--atomic` callers would use to
3006    /// verify parity — not a raw SQL probe.
3007    async fn events_for_target(
3008        runtime: &KhiveRuntime,
3009        token: &NamespaceToken,
3010        target_id: Uuid,
3011        kind: EventKind,
3012    ) -> Vec<khive_storage::Event> {
3013        let event_store = runtime.events(token).expect("event store");
3014        let filter = khive_storage::EventFilter {
3015            kinds: vec![kind],
3016            ..Default::default()
3017        };
3018        let page = event_store
3019            .query_events(filter, khive_storage::types::PageRequest::default())
3020            .await
3021            .expect("query_events");
3022        page.items
3023            .into_iter()
3024            .filter(|e| e.target_id == Some(target_id))
3025            .collect()
3026    }
3027
3028    /// Atomic `update(id=<entity>, name=...)` must append an
3029    /// `EntityUpdated` event, matching `curation::update_entity`: the
3030    /// event is appended unconditionally after a successful row update,
3031    /// not only on the reindex-triggering subset.
3032    #[tokio::test]
3033    async fn atomic_update_entity_appends_entity_updated_event() {
3034        let runtime = scratch_runtime();
3035        let token = runtime
3036            .authorize(Namespace::parse("local").expect("ns"))
3037            .expect("authorize");
3038        let entity = khive_storage::Entity::new("local", "concept", "gap1-entity");
3039        let entity_id = entity.id;
3040        runtime
3041            .entities(&token)
3042            .expect("entities store")
3043            .upsert_entity(entity)
3044            .await
3045            .expect("seed entity");
3046
3047        let plan = prepare_update(
3048            &runtime,
3049            &token,
3050            &json!({"id": entity_id.to_string(), "name": "gap1-entity-renamed"}),
3051            None,
3052        )
3053        .await
3054        .expect("prepare update");
3055        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3056            .await
3057            .expect("seam call ok");
3058        assert!(matches!(
3059            outcome,
3060            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3061        ));
3062
3063        let events = events_for_target(&runtime, &token, entity_id, EventKind::EntityUpdated).await;
3064        assert_eq!(
3065            events.len(),
3066            1,
3067            "expected exactly one EntityUpdated event for {entity_id}"
3068        );
3069        assert_eq!(events[0].namespace, "local");
3070        assert_eq!(events[0].payload["id"], json!(entity_id.to_string()));
3071        assert_eq!(
3072            events[0].payload["changed_fields"],
3073            json!(["name"]),
3074            "changed_fields must name exactly the patched fields"
3075        );
3076    }
3077
3078    /// Atomic soft and hard delete of an entity must each append an
3079    /// `EntityDeleted` event, matching `operations::delete_entity`, which
3080    /// fires on both delete modes.
3081    #[tokio::test]
3082    async fn atomic_delete_entity_appends_entity_deleted_event_soft_and_hard() {
3083        let runtime = scratch_runtime();
3084        let token = runtime
3085            .authorize(Namespace::parse("local").expect("ns"))
3086            .expect("authorize");
3087
3088        for hard in [false, true] {
3089            let entity =
3090                khive_storage::Entity::new("local", "concept", format!("gap1-entity-hard-{hard}"));
3091            let entity_id = entity.id;
3092            runtime
3093                .entities(&token)
3094                .expect("entities store")
3095                .upsert_entity(entity)
3096                .await
3097                .expect("seed entity");
3098
3099            let args = if hard {
3100                json!({"id": entity_id.to_string(), "hard": true})
3101            } else {
3102                json!({"id": entity_id.to_string()})
3103            };
3104            let plan = prepare_delete(&runtime, &token, &args, None)
3105                .await
3106                .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
3107            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3108                .await
3109                .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
3110            assert!(
3111                matches!(
3112                    outcome,
3113                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3114                ),
3115                "expected a clean delete commit (hard={hard}): {outcome:?}"
3116            );
3117
3118            let events =
3119                events_for_target(&runtime, &token, entity_id, EventKind::EntityDeleted).await;
3120            assert_eq!(
3121                events.len(),
3122                1,
3123                "expected exactly one EntityDeleted event for {entity_id} (hard={hard})"
3124            );
3125            assert_eq!(events[0].payload["hard"], json!(hard));
3126        }
3127    }
3128
3129    #[tokio::test]
3130    async fn atomic_hard_delete_emits_lineage_warning_in_commit_unit() {
3131        let runtime = scratch_runtime();
3132        let token = NamespaceToken::mint_authorized(
3133            Namespace::local(),
3134            crate::ActorRef::new("agent", "atomic-lineage-deleter"),
3135        );
3136        let doomed = khive_storage::Entity::new("local", "document", "atomic-doomed");
3137        let source = khive_storage::Entity::new("local", "artifact", "atomic-source");
3138        let doomed_id = doomed.id;
3139        runtime
3140            .entities(&token)
3141            .expect("entities store")
3142            .upsert_entity(doomed)
3143            .await
3144            .expect("seed doomed entity");
3145        runtime
3146            .entities(&token)
3147            .expect("entities store")
3148            .upsert_entity(source.clone())
3149            .await
3150            .expect("seed source entity");
3151        runtime
3152            .link(
3153                &token,
3154                source.id,
3155                doomed_id,
3156                EdgeRelation::DerivedFrom,
3157                1.0,
3158                None,
3159            )
3160            .await
3161            .expect("seed protected edge");
3162
3163        let plan = prepare_delete(
3164            &runtime,
3165            &token,
3166            &json!({"id": doomed_id.to_string(), "hard": true}),
3167            None,
3168        )
3169        .await
3170        .expect("prepare hard delete");
3171        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3172            .await
3173            .expect("delete commit");
3174        assert!(matches!(
3175            outcome,
3176            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3177        ));
3178
3179        let warnings = events_for_target(&runtime, &token, doomed_id, EventKind::Audit).await;
3180        assert_eq!(warnings.len(), 1);
3181        assert_eq!(warnings[0].actor, "agent:atomic-lineage-deleter");
3182        assert_eq!(warnings[0].payload["relation"], "derived_from");
3183        assert_eq!(warnings[0].payload["warning"], "provenance_loss");
3184    }
3185
3186    /// Atomic soft and hard delete of a note must each append a
3187    /// `NoteDeleted` event, matching `operations::delete_note`, which
3188    /// fires on both delete modes.
3189    #[tokio::test]
3190    async fn atomic_delete_note_appends_note_deleted_event_soft_and_hard() {
3191        let runtime = scratch_runtime();
3192        let token = runtime
3193            .authorize(Namespace::parse("local").expect("ns"))
3194            .expect("authorize");
3195
3196        for hard in [false, true] {
3197            let mut note = khive_storage::note::Note::new(
3198                "local",
3199                "observation",
3200                format!("gap1-note-content-hard-{hard}"),
3201            );
3202            note.name = Some(format!("gap1-note-hard-{hard}"));
3203            let note_id = note.id;
3204            runtime
3205                .notes(&token)
3206                .expect("notes store")
3207                .upsert_note(note)
3208                .await
3209                .expect("seed note");
3210
3211            let args = if hard {
3212                json!({"id": note_id.to_string(), "hard": true})
3213            } else {
3214                json!({"id": note_id.to_string()})
3215            };
3216            let plan = prepare_delete(&runtime, &token, &args, None)
3217                .await
3218                .unwrap_or_else(|e| panic!("prepare delete (hard={hard}): {e}"));
3219            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3220                .await
3221                .unwrap_or_else(|e| panic!("delete commit (hard={hard}): {e}"));
3222            assert!(
3223                matches!(
3224                    outcome,
3225                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3226                ),
3227                "expected a clean delete commit (hard={hard}): {outcome:?}"
3228            );
3229
3230            let events = events_for_target(&runtime, &token, note_id, EventKind::NoteDeleted).await;
3231            assert_eq!(
3232                events.len(),
3233                1,
3234                "expected exactly one NoteDeleted event for {note_id} (hard={hard})"
3235            );
3236            assert_eq!(events[0].payload["hard"], json!(hard));
3237        }
3238    }
3239
3240    /// `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`; this
3241    /// asserts `prepare_update` actually builds a plan for one, a
3242    /// non-symmetric relation (`extends`) exercises the
3243    /// `edge_upsert_statement` reuse branch, and that the committed row +
3244    /// `EdgeUpdated` event match canonical `update_edge`'s shape (weight
3245    /// persisted, relation unchanged, exactly one event).
3246    #[tokio::test]
3247    async fn atomic_update_edge_patches_weight_and_appends_edge_updated_event() {
3248        let runtime = scratch_runtime();
3249        let token = runtime
3250            .authorize(Namespace::parse("local").expect("ns"))
3251            .expect("authorize");
3252        let entities = runtime.entities(&token).expect("entities store");
3253        let a = khive_storage::Entity::new("local", "concept", "GapEdgeA");
3254        let b = khive_storage::Entity::new("local", "concept", "GapEdgeB");
3255        let (a_id, b_id) = (a.id, b.id);
3256        entities.upsert_entity(a).await.expect("seed a");
3257        entities.upsert_entity(b).await.expect("seed b");
3258
3259        let edge = runtime
3260            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.4, None)
3261            .await
3262            .expect("seed edge");
3263        let edge_id = Uuid::from(edge.id);
3264
3265        let plan = prepare_update(
3266            &runtime,
3267            &token,
3268            &json!({"id": edge_id.to_string(), "weight": 0.75}),
3269            None,
3270        )
3271        .await
3272        .expect("prepare update edge");
3273        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3274            .await
3275            .expect("seam call ok");
3276        assert!(
3277            matches!(
3278                outcome,
3279                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3280            ),
3281            "expected a clean edge update commit: {outcome:?}"
3282        );
3283
3284        let updated = runtime
3285            .get_edge(&token, edge_id)
3286            .await
3287            .expect("get_edge")
3288            .expect("edge still present");
3289        assert_eq!(updated.weight, 0.75, "weight patch must persist");
3290        assert_eq!(updated.relation, EdgeRelation::Extends);
3291
3292        let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeUpdated).await;
3293        assert_eq!(
3294            events.len(),
3295            1,
3296            "expected exactly one EdgeUpdated event for {edge_id}"
3297        );
3298        assert_eq!(
3299            events[0].payload["changed_fields"],
3300            json!(["weight"]),
3301            "changed_fields must name exactly the patched field"
3302        );
3303    }
3304
3305    /// ADR-115 Amendment 1 §3: the reserved `khive:secret_gate` property key
3306    /// must be rejected on atomic edge-metadata updates the same way it is
3307    /// on canonical `update_edge`.
3308    #[tokio::test]
3309    async fn atomic_update_edge_rejects_reserved_secret_gate_property() {
3310        let runtime = scratch_runtime();
3311        let token = runtime
3312            .authorize(Namespace::parse("local").expect("ns"))
3313            .expect("authorize");
3314        let entities = runtime.entities(&token).expect("entities store");
3315        let a = khive_storage::Entity::new("local", "concept", "ReservedEdgeA");
3316        let b = khive_storage::Entity::new("local", "concept", "ReservedEdgeB");
3317        let (a_id, b_id) = (a.id, b.id);
3318        entities.upsert_entity(a).await.expect("seed a");
3319        entities.upsert_entity(b).await.expect("seed b");
3320
3321        let edge = runtime
3322            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.4, None)
3323            .await
3324            .expect("seed edge");
3325        let edge_id = Uuid::from(edge.id);
3326
3327        let err = prepare_update(
3328            &runtime,
3329            &token,
3330            &json!({
3331                "id": edge_id.to_string(),
3332                "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
3333            }),
3334            None,
3335        )
3336        .await
3337        .expect_err("a caller-supplied reserved key on edge metadata must be rejected");
3338        assert!(
3339            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
3340            "expected a reservation rejection, got: {err:?}"
3341        );
3342
3343        let unchanged = runtime
3344            .get_edge(&token, edge_id)
3345            .await
3346            .expect("get_edge")
3347            .expect("edge still present");
3348        assert!(
3349            unchanged.metadata.is_none(),
3350            "rejected edge update must leave metadata untouched"
3351        );
3352    }
3353
3354    /// The symmetric-relation conflict-absorption branch of
3355    /// `prepare_update_edge` — mirrors `update_edge_symmetric_dml`'s case
3356    /// (b): changing a non-symmetric edge's `relation` to a symmetric one
3357    /// whose canonical natural key collides with an ALREADY-EXISTING
3358    /// symmetric edge between the same two entities must delete the
3359    /// requested (non-canonical) row and leave the surviving canonical row
3360    /// untouched (ADR-039 ON CONFLICT DO NOTHING), rather than raising a
3361    /// uniqueness error OR overwriting the survivor with the discarded
3362    /// edge's attributes (khive#1213).
3363    #[tokio::test]
3364    async fn atomic_update_edge_symmetric_conflict_absorbs_into_surviving_row() {
3365        let runtime = scratch_runtime();
3366        let token = runtime
3367            .authorize(Namespace::parse("local").expect("ns"))
3368            .expect("authorize");
3369        let entities = runtime.entities(&token).expect("entities store");
3370        let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymA");
3371        let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymB");
3372        let (a_id, b_id) = (a.id, b.id);
3373        entities.upsert_entity(a).await.expect("seed a");
3374        entities.upsert_entity(b).await.expect("seed b");
3375
3376        // The non-canonical edge under test: A -> B, non-symmetric relation.
3377        let requested_edge = runtime
3378            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3379            .await
3380            .expect("seed requested edge");
3381        let requested_id = Uuid::from(requested_edge.id);
3382
3383        // The pre-existing canonical row this update will collide with once
3384        // `relation` becomes `competes_with` (symmetric).
3385        let canonical_edge = runtime
3386            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3387            .await
3388            .expect("seed canonical edge");
3389        let canonical_id = Uuid::from(canonical_edge.id);
3390        assert_ne!(requested_id, canonical_id);
3391
3392        let plan = prepare_update(
3393            &runtime,
3394            &token,
3395            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3396            None,
3397        )
3398        .await
3399        .expect("prepare update edge (symmetric conflict)");
3400        // The plan does not compute a prepare-time advisory surviving id
3401        // (`target_id` is just the requested id): it carries
3402        // `edge_natural_key` so a post-commit caller can derive the real
3403        // surviving id itself. Assert the plan carries the right natural
3404        // key to look up; the actual surviving row's identity is verified
3405        // against the DB after commit, below.
3406        let (canon_src, canon_tgt) =
3407            canonical_edge_endpoints(EdgeRelation::CompetesWith, a_id, b_id);
3408        match &plan {
3409            AtomicOpPlan::Update(p) => {
3410                assert_eq!(p.target_id, requested_id);
3411                let key = p
3412                    .edge_natural_key
3413                    .as_ref()
3414                    .expect("symmetric edge update must carry edge_natural_key");
3415                assert_eq!(key.canon_source_id, canon_src);
3416                assert_eq!(key.canon_target_id, canon_tgt);
3417                assert_eq!(key.relation, EdgeRelation::CompetesWith);
3418            }
3419            other => panic!("expected an Update plan, got {other:?}"),
3420        }
3421
3422        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3423            .await
3424            .expect("seam call ok");
3425        assert!(
3426            matches!(
3427                outcome,
3428                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3429            ),
3430            "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3431        );
3432
3433        // The requested (non-canonical) row must be gone.
3434        let requested_after = runtime
3435            .get_edge_including_deleted(&token, requested_id)
3436            .await
3437            .expect("get_edge_including_deleted");
3438        assert!(
3439            requested_after.is_none(),
3440            "the non-canonical requested row must be deleted, not just tombstoned"
3441        );
3442
3443        // ADR-039 DO NOTHING: the surviving canonical row keeps its OWN
3444        // pre-existing attributes — the discarded edge's patched weight
3445        // (0.9) must never overwrite it.
3446        let surviving = runtime
3447            .get_edge(&token, canonical_id)
3448            .await
3449            .expect("get_edge")
3450            .expect("surviving canonical row must remain");
3451        assert_eq!(
3452            surviving.weight, 0.6,
3453            "survivor weight must not be overwritten by the discarded edge's patch"
3454        );
3455        assert_eq!(surviving.relation, EdgeRelation::CompetesWith);
3456
3457        // Event target is the CALLER-supplied id, not the surviving id —
3458        // mirrors `update_edge`'s event using `edge_id` (the caller's
3459        // original argument), not the post-absorption id.
3460        let events =
3461            events_for_target(&runtime, &token, requested_id, EventKind::EdgeUpdated).await;
3462        assert_eq!(events.len(), 1);
3463    }
3464
3465    /// Regression for khive #1753: an entity atomic update plan is prepared
3466    /// from one revision, a concurrent (out-of-plan) writer advances the row
3467    /// past that revision before the plan commits, and the plan's guarded
3468    /// `entity_replace_if_unchanged_statement` must then affect zero rows —
3469    /// which `AffectedRowGuard::exactly(1)` must turn into a whole-unit
3470    /// rollback, not a silent overwrite of the concurrent writer's change.
3471    /// Before threading the expected revision into the plan's `WHERE`
3472    /// predicate, this plan used the unconditional `entity_upsert_statement`,
3473    /// which always affects exactly 1 row regardless of staleness — the
3474    /// guard could never fire and this test would redden (the outcome would
3475    /// be `Committed`, and the concurrent writer's `name` change would be
3476    /// lost under the stale plan's `description`-only patch).
3477    #[tokio::test]
3478    async fn atomic_entity_update_plan_stale_revision_rolls_back_unit() {
3479        let runtime = scratch_runtime();
3480        let token = runtime
3481            .authorize(Namespace::parse("local").expect("ns"))
3482            .expect("authorize");
3483        let entity = runtime
3484            .create_entity(
3485                &token,
3486                "concept",
3487                None,
3488                "StaleEntityPlanTarget",
3489                None,
3490                Some(json!({"a": 0})),
3491                vec![],
3492            )
3493            .await
3494            .expect("seed entity");
3495        let id = entity.id;
3496
3497        // PREPARE time: build the plan from the current (soon-to-be-stale)
3498        // revision.
3499        let plan = prepare_update(
3500            &runtime,
3501            &token,
3502            &json!({"id": id.to_string(), "description": "from the stale plan"}),
3503            None,
3504        )
3505        .await
3506        .expect("prepare update entity plan");
3507
3508        // Read the plan's OWN bound values, so the isolation below is
3509        // derived from the plan rather than assumed about it. Per
3510        // `entity_replace_if_unchanged_statement`, `?8` (index 7) is the
3511        // replacement revision, `?12` (index 11) the target id, `?13`
3512        // (index 12) the expected revision, and `?14` (index 13) the
3513        // expected deletion marker.
3514        let (planned_replacement, plan_target_id, plan_expected, plan_expected_deleted) = {
3515            let statements = match &plan {
3516                AtomicOpPlan::Update(p) => p.statements.clone(),
3517                other => panic!("expected an Update plan, got {other:?}"),
3518            };
3519            // Locate by LABEL, never by the guard text. A locator keyed on
3520            // `?8 > updated_at` would stop finding the statement in exactly the
3521            // mutation run that deletes that conjunct, so the arm would report
3522            // on this fixture's locator instead of on the guard.
3523            let cas = statements
3524                .iter()
3525                .find(|s| s.statement.label.as_deref() == Some("entity-replace-if-unchanged"))
3526                .expect("the plan must carry the guarded entity replacement");
3527            let read = |i: usize| match &cas.statement.params[i] {
3528                SqlValue::Integer(v) => *v,
3529                other => panic!("param {i} must be an integer revision, got {other:?}"),
3530            };
3531            let read_marker = |i: usize| match &cas.statement.params[i] {
3532                SqlValue::Null => None,
3533                SqlValue::Integer(v) => Some(*v),
3534                other => panic!("param {i} must be a deletion marker, got {other:?}"),
3535            };
3536            let read_text = |i: usize| match &cas.statement.params[i] {
3537                SqlValue::Text(v) => v.clone(),
3538                other => panic!("param {i} must be a text id, got {other:?}"),
3539            };
3540            (read(7), read_text(11), read(12), read_marker(13))
3541        };
3542        // The identity conjunct, on the same footing as the revision and the
3543        // deletion marker. `id = ?12` is live in the same UPDATE, so a plan
3544        // that bound any other row's id would affect zero rows and roll the
3545        // unit back for a reason this test does not name — an outcome
3546        // indistinguishable from the one it does name.
3547        assert_eq!(
3548            plan_target_id,
3549            id.to_string(),
3550            "fixture premise: the plan's `?12` must be the row under test, otherwise \
3551             `id = ?12` refuses on identity and the rollback stops being attributable to \
3552             the expected-revision guard"
3553        );
3554
3555        // A concurrent writer commits BEFORE the plan runs, advancing the
3556        // row's revision past what the plan's guard expects.
3557        runtime
3558            .update_entity(
3559                &token,
3560                id,
3561                crate::curation::EntityPatch {
3562                    name: Some("ConcurrentWriterWon".to_string()),
3563                    ..Default::default()
3564                },
3565            )
3566            .await
3567            .expect("concurrent writer update");
3568
3569        // Pin the stored revision one microsecond BELOW the plan's replacement.
3570        // This is what makes the test specific to the guard it names. Both the
3571        // plan and the concurrent writer derive their revision from
3572        // `max(now, expected + 1)`, so left alone the concurrent write lands at
3573        // or past the plan's own replacement and BOTH conjuncts refuse — the
3574        // test would then stay green if either guard were deleted. Pinning
3575        // leaves `?8 > updated_at` satisfied, so it cannot be the refuser,
3576        // while `updated_at = ?13` is violated, which is the single condition
3577        // this test names. The shape is reachable in production whenever the
3578        // concurrent writer's clock trails the preparing writer's.
3579        let stored_pinned = planned_replacement - 1;
3580        assert_ne!(
3581            stored_pinned, plan_expected,
3582            "fixture premise: the pinned revision must differ from the plan's expected \
3583             revision, otherwise `updated_at = ?13` would MATCH and nothing would refuse \
3584             the plan"
3585        );
3586        {
3587            let mut writer = runtime.sql().writer().await.expect("writer");
3588            let affected = writer
3589                .execute(SqlStatement {
3590                    sql: "UPDATE entities SET updated_at = ?1 WHERE id = ?2".to_string(),
3591                    params: vec![
3592                        SqlValue::Integer(stored_pinned),
3593                        SqlValue::Text(id.to_string()),
3594                    ],
3595                    label: Some("test-pin-stored-revision".to_string()),
3596                })
3597                .await
3598                .expect("pin the stored revision");
3599            assert_eq!(affected, 1, "the pin must touch exactly the seeded row");
3600        }
3601        assert!(
3602            planned_replacement > stored_pinned,
3603            "fixture premise: the plan's replacement must still strictly advance past the \
3604             stored revision, otherwise `?8 > updated_at` would refuse and this stops being \
3605             a test of the expected-revision guard"
3606        );
3607        // The remaining non-target conjunct. `deleted_at IS ?14` is live in the
3608        // same UPDATE, so without this read the fixture would stay green if the
3609        // deletion marker were the actual refuser — the refusal would look
3610        // identical. Read the row as it stands at DML time, after both the
3611        // concurrent writer and the pin.
3612        {
3613            let stored = runtime
3614                .get_entity_including_deleted(&token, id)
3615                .await
3616                .expect("read the stored row")
3617                .expect("the seeded row is present before the plan runs");
3618            assert_eq!(
3619                stored.updated_at, stored_pinned,
3620                "fixture premise: the pin must be what the guard reads, so the stored \
3621                 revision is the pinned value and nothing re-advanced it"
3622            );
3623            assert_eq!(
3624                stored.deleted_at, plan_expected_deleted,
3625                "fixture premise: the stored deletion marker must MATCH the plan's `?14`, \
3626                 otherwise `deleted_at IS ?14` refuses too and this stops being a test of \
3627                 the expected-revision guard alone"
3628            );
3629        }
3630
3631        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3632            .await
3633            .expect("the seam call itself must not error; the unit rolls back cleanly");
3634        match outcome {
3635            crate::atomic_runner::AtomicRunOutcome::RolledBack {
3636                failed_op_index,
3637                failure,
3638            } => {
3639                assert_eq!(
3640                    failed_op_index, 0,
3641                    "the sole op's guard must be the one that fails"
3642                );
3643                // Attribution rather than inference. The premises above
3644                // establish that every non-target conjunct holds; this names
3645                // the statement that actually refused. Without it a unit that
3646                // rolled back at some other statement reads identically from
3647                // the outside, which is the whole failure mode those premises
3648                // were approximating.
3649                assert_eq!(
3650                    failure,
3651                    crate::atomic_runner::AtomicOpFailure::GuardFailed {
3652                        statement_label: Some("entity-replace-if-unchanged".to_string()),
3653                        expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
3654                        observed: 0,
3655                    },
3656                    "the guarded entity replacement must be the statement whose guard refused"
3657                );
3658            }
3659            other => panic!(
3660                "a stale entity plan must roll back, not silently overwrite the concurrent \
3661                 writer's change: {other:?}"
3662            ),
3663        }
3664
3665        let after = runtime.get_entity(&token, id).await.expect("get_entity");
3666        assert_eq!(
3667            after.name, "ConcurrentWriterWon",
3668            "the concurrent writer's committed name must survive the rolled-back stale plan"
3669        );
3670        assert_eq!(
3671            after.description, None,
3672            "the stale plan's description patch must NOT have landed"
3673        );
3674    }
3675
3676    /// Edge counterpart of `atomic_entity_update_plan_stale_revision_rolls_back_unit`:
3677    /// a non-symmetric edge atomic update plan prepared from one revision
3678    /// must roll back the whole unit when a concurrent writer advances the
3679    /// row first, rather than silently overwriting that writer's change.
3680    #[tokio::test]
3681    async fn atomic_edge_update_plan_stale_revision_rolls_back_unit() {
3682        let runtime = scratch_runtime();
3683        let token = runtime
3684            .authorize(Namespace::parse("local").expect("ns"))
3685            .expect("authorize");
3686        let entities = runtime.entities(&token).expect("entities store");
3687        let a = khive_storage::Entity::new("local", "concept", "StaleEdgePlanA");
3688        let b = khive_storage::Entity::new("local", "concept", "StaleEdgePlanB");
3689        let (a_id, b_id) = (a.id, b.id);
3690        entities.upsert_entity(a).await.expect("seed a");
3691        entities.upsert_entity(b).await.expect("seed b");
3692
3693        let edge = runtime
3694            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3695            .await
3696            .expect("seed edge");
3697        let edge_id = Uuid::from(edge.id);
3698
3699        // PREPARE time: build the plan from the current (soon-to-be-stale)
3700        // revision.
3701        let plan = prepare_update(
3702            &runtime,
3703            &token,
3704            &json!({"id": edge_id.to_string(), "properties": {"note": "from the stale plan"}}),
3705            None,
3706        )
3707        .await
3708        .expect("prepare update edge plan");
3709
3710        // Read the plan's OWN bound values, so the isolation below is
3711        // derived from the plan rather than assumed about it. Per
3712        // `edge_replace_if_unchanged_statement`, `?6` (index 5) is the
3713        // replacement revision, `?10` (index 9) the target id, `?11`
3714        // (index 10) the expected revision, and `?12` (index 11) the expected
3715        // deletion marker.
3716        let (planned_replacement, plan_target_id, plan_expected, plan_expected_deleted) = {
3717            let statements = match &plan {
3718                AtomicOpPlan::Update(p) => p.statements.clone(),
3719                other => panic!("expected an Update plan, got {other:?}"),
3720            };
3721            // Locate by LABEL, never by the guard text — see the entity sibling
3722            // above: a locator keyed on the conjunct disappears in exactly the
3723            // mutation run that deletes it.
3724            let cas = statements
3725                .iter()
3726                .find(|s| s.statement.label.as_deref() == Some("edge-replace-if-unchanged"))
3727                .expect("the plan must carry the guarded edge replacement");
3728            let read = |i: usize| match &cas.statement.params[i] {
3729                SqlValue::Integer(v) => *v,
3730                other => panic!("param {i} must be an integer revision, got {other:?}"),
3731            };
3732            let read_marker = |i: usize| match &cas.statement.params[i] {
3733                SqlValue::Null => None,
3734                SqlValue::Integer(v) => Some(*v),
3735                other => panic!("param {i} must be a deletion marker, got {other:?}"),
3736            };
3737            let read_text = |i: usize| match &cas.statement.params[i] {
3738                SqlValue::Text(v) => v.clone(),
3739                other => panic!("param {i} must be a text id, got {other:?}"),
3740            };
3741            (read(5), read_text(9), read(10), read_marker(11))
3742        };
3743        // The identity conjunct, for the same reason as the entity sibling:
3744        // `id = ?10` is live in the same UPDATE and a misbound target refuses
3745        // indistinguishably.
3746        assert_eq!(
3747            plan_target_id,
3748            edge_id.to_string(),
3749            "fixture premise: the plan's `?10` must be the edge under test, otherwise \
3750             `id = ?10` refuses on identity and the rollback stops being attributable to \
3751             the expected-revision guard"
3752        );
3753
3754        // A concurrent writer commits BEFORE the plan runs, advancing the
3755        // row's revision past what the plan's guard expects.
3756        runtime
3757            .update_edge(
3758                &token,
3759                edge_id,
3760                crate::curation::EdgePatch {
3761                    weight: Some(0.75),
3762                    ..Default::default()
3763                },
3764            )
3765            .await
3766            .expect("concurrent writer update");
3767
3768        // Pin the stored revision one microsecond BELOW the plan's replacement,
3769        // for the same reason as the entity sibling above: both the plan and
3770        // the concurrent writer derive their revision from
3771        // `max(now, expected + 1)`, so left alone BOTH conjuncts refuse and the
3772        // test would stay green if either guard were deleted. Pinning leaves
3773        // `?6 > updated_at` satisfied, so it cannot be the refuser, while
3774        // `updated_at = ?11` is violated — the single condition this test names.
3775        let stored_pinned = planned_replacement - 1;
3776        assert_ne!(
3777            stored_pinned, plan_expected,
3778            "fixture premise: the pinned revision must differ from the plan's expected \
3779             revision, otherwise `updated_at = ?11` would MATCH and nothing would refuse \
3780             the plan"
3781        );
3782        {
3783            let mut writer = runtime.sql().writer().await.expect("writer");
3784            let affected = writer
3785                .execute(SqlStatement {
3786                    sql: "UPDATE graph_edges SET updated_at = ?1 WHERE id = ?2".to_string(),
3787                    params: vec![
3788                        SqlValue::Integer(stored_pinned),
3789                        SqlValue::Text(edge_id.to_string()),
3790                    ],
3791                    label: Some("test-pin-stored-revision".to_string()),
3792                })
3793                .await
3794                .expect("pin the stored revision");
3795            assert_eq!(affected, 1, "the pin must touch exactly the seeded edge");
3796        }
3797        assert!(
3798            planned_replacement > stored_pinned,
3799            "fixture premise: the plan's replacement must still strictly advance past the \
3800             stored revision, otherwise `?6 > updated_at` would refuse and this stops being \
3801             a test of the expected-revision guard"
3802        );
3803        // The remaining non-target conjunct, for the same reason as the entity
3804        // sibling: `deleted_at IS ?12` is live in the same UPDATE and would
3805        // produce an indistinguishable refusal.
3806        {
3807            let stored = runtime
3808                .get_edge_including_deleted(&token, edge_id)
3809                .await
3810                .expect("read the stored edge")
3811                .expect("the seeded edge is present before the plan runs");
3812            assert_eq!(
3813                stored.updated_at.timestamp_micros(),
3814                stored_pinned,
3815                "fixture premise: the pin must be what the guard reads, so the stored \
3816                 revision is the pinned value and nothing re-advanced it"
3817            );
3818            assert_eq!(
3819                stored.deleted_at.map(|d| d.timestamp_micros()),
3820                plan_expected_deleted,
3821                "fixture premise: the stored deletion marker must MATCH the plan's `?12`, \
3822                 otherwise `deleted_at IS ?12` refuses too and this stops being a test of \
3823                 the expected-revision guard alone"
3824            );
3825        }
3826
3827        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3828            .await
3829            .expect("the seam call itself must not error; the unit rolls back cleanly");
3830        match outcome {
3831            crate::atomic_runner::AtomicRunOutcome::RolledBack {
3832                failed_op_index,
3833                failure,
3834            } => {
3835                assert_eq!(
3836                    failed_op_index, 0,
3837                    "the sole op's guard must be the one that fails"
3838                );
3839                // Attribution rather than inference — see the entity sibling.
3840                assert_eq!(
3841                    failure,
3842                    crate::atomic_runner::AtomicOpFailure::GuardFailed {
3843                        statement_label: Some("edge-replace-if-unchanged".to_string()),
3844                        expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
3845                        observed: 0,
3846                    },
3847                    "the guarded edge replacement must be the statement whose guard refused"
3848                );
3849            }
3850            other => panic!(
3851                "a stale edge plan must roll back, not silently overwrite the concurrent \
3852                 writer's change: {other:?}"
3853            ),
3854        }
3855
3856        let after = runtime
3857            .get_edge(&token, edge_id)
3858            .await
3859            .expect("get_edge")
3860            .expect("edge still exists");
3861        assert!(
3862            (after.weight - 0.75).abs() < 0.001,
3863            "the concurrent writer's committed weight must survive the rolled-back stale plan: {after:?}"
3864        );
3865        assert!(
3866            after.metadata.is_none(),
3867            "the stale plan's properties patch must NOT have landed: {after:?}"
3868        );
3869    }
3870
3871    /// A soft-deleted surviving canonical row must not be resurrected by a
3872    /// conflicting symmetric-relation update (ADR-039 DO NOTHING; khive#1213):
3873    /// the requested edge is still deleted (conflict absorbed), but the
3874    /// tombstoned survivor must stay tombstoned.
3875    #[tokio::test]
3876    async fn atomic_update_edge_symmetric_conflict_does_not_resurrect_tombstoned_survivor() {
3877        let runtime = scratch_runtime();
3878        let token = runtime
3879            .authorize(Namespace::parse("local").expect("ns"))
3880            .expect("authorize");
3881        let entities = runtime.entities(&token).expect("entities store");
3882        let a = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombA");
3883        let b = khive_storage::Entity::new("local", "concept", "GapEdgeSymTombB");
3884        let (a_id, b_id) = (a.id, b.id);
3885        entities.upsert_entity(a).await.expect("seed a");
3886        entities.upsert_entity(b).await.expect("seed b");
3887
3888        let requested_edge = runtime
3889            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3890            .await
3891            .expect("seed requested edge");
3892        let requested_id = Uuid::from(requested_edge.id);
3893
3894        let canonical_edge = runtime
3895            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3896            .await
3897            .expect("seed canonical edge");
3898        let canonical_id = Uuid::from(canonical_edge.id);
3899        runtime
3900            .delete_edge(&token, canonical_id, false)
3901            .await
3902            .expect("soft-delete canonical edge");
3903
3904        let plan = prepare_update(
3905            &runtime,
3906            &token,
3907            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3908            None,
3909        )
3910        .await
3911        .expect("prepare update edge (symmetric conflict over tombstone)");
3912
3913        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
3914            .await
3915            .expect("seam call ok");
3916        assert!(
3917            matches!(
3918                outcome,
3919                crate::atomic_runner::AtomicRunOutcome::Committed { .. }
3920            ),
3921            "expected a clean symmetric-conflict-absorption commit: {outcome:?}"
3922        );
3923
3924        let requested_after = runtime
3925            .get_edge_including_deleted(&token, requested_id)
3926            .await
3927            .expect("get_edge_including_deleted");
3928        assert!(
3929            requested_after.is_none(),
3930            "the non-canonical requested row must be deleted, not just tombstoned"
3931        );
3932
3933        let canonical_after = runtime
3934            .get_edge(&token, canonical_id)
3935            .await
3936            .expect("get_edge");
3937        assert!(
3938            canonical_after.is_none(),
3939            "a tombstoned survivor must not be resurrected by a conflicting update"
3940        );
3941    }
3942
3943    /// The same-unit race: `[delete(X), update(X -> competes_with)]` where
3944    /// an already-existing canonical row sits at the post-update natural
3945    /// key. Both ops' async prepare passes run before either commits, so at
3946    /// prepare time `X` still exists and both plans build. At commit time
3947    /// `delete(X)` removes it first; `update(X -> competes_with)`'s own
3948    /// commit-time statements must then fail loud (its target no longer
3949    /// exists) rather than silently absorbing into the pre-existing
3950    /// canonical row it never causally touched. The whole atomic unit must
3951    /// roll back — parity with canonical `update_edge`'s `NotFound` for a
3952    /// missing edge, expressed here as the unit-level abort for any op
3953    /// whose commit-time guard fails.
3954    #[tokio::test]
3955    async fn atomic_update_edge_symmetric_same_unit_delete_race_aborts_the_unit() {
3956        let runtime = scratch_runtime();
3957        let token = runtime
3958            .authorize(Namespace::parse("local").expect("ns"))
3959            .expect("authorize");
3960        let entities = runtime.entities(&token).expect("entities store");
3961        let a = khive_storage::Entity::new("local", "concept", "GapEdgeRaceA");
3962        let b = khive_storage::Entity::new("local", "concept", "GapEdgeRaceB");
3963        let (a_id, b_id) = (a.id, b.id);
3964        entities.upsert_entity(a).await.expect("seed a");
3965        entities.upsert_entity(b).await.expect("seed b");
3966
3967        // The row op 1 will try to update — deleted by op 0 in the SAME unit.
3968        let requested_edge = runtime
3969            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
3970            .await
3971            .expect("seed requested edge");
3972        let requested_id = Uuid::from(requested_edge.id);
3973
3974        // The pre-existing canonical row the buggy `id = ?2 OR natural-key`
3975        // predicate used to silently absorb into.
3976        let canonical_edge = runtime
3977            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
3978            .await
3979            .expect("seed canonical edge");
3980        let canonical_id = Uuid::from(canonical_edge.id);
3981
3982        let delete_plan = prepare_delete(
3983            &runtime,
3984            &token,
3985            &json!({"id": requested_id.to_string(), "hard": true}),
3986            None,
3987        )
3988        .await
3989        .expect("prepare delete edge");
3990        let update_plan = prepare_update(
3991            &runtime,
3992            &token,
3993            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
3994            None,
3995        )
3996        .await
3997        .expect("prepare update edge (both prepares run before either commits)");
3998
3999        let outcome = crate::atomic_runner::run_atomic_unit(
4000            runtime.sql().as_ref(),
4001            vec![delete_plan, update_plan],
4002        )
4003        .await
4004        .expect("the seam call itself must not error — the unit rolls back cleanly");
4005        match outcome {
4006            crate::atomic_runner::AtomicRunOutcome::RolledBack {
4007                failed_op_index, ..
4008            } => {
4009                assert_eq!(
4010                    failed_op_index, 1,
4011                    "op 1 (the update) must be the one whose guard fails"
4012                );
4013            }
4014            other => panic!("expected the whole unit to roll back, got {other:?}"),
4015        }
4016
4017        // Whole-unit rollback: op 0's delete must be undone too.
4018        let requested_after = runtime
4019            .get_edge(&token, requested_id)
4020            .await
4021            .expect("get_edge");
4022        assert!(
4023            requested_after.is_some(),
4024            "delete(X) must have rolled back along with the failed update"
4025        );
4026        // The pre-existing canonical row must be completely untouched.
4027        let canonical_after = runtime
4028            .get_edge(&token, canonical_id)
4029            .await
4030            .expect("get_edge")
4031            .expect("canonical row must still be present");
4032        assert_eq!(
4033            canonical_after.weight, 0.6,
4034            "the pre-existing canonical row must never have been touched by the aborted update"
4035        );
4036    }
4037
4038    /// The symmetric absorption delete's atomic commit-time statement
4039    /// (`edge_symmetric_delete_if_conflict_statement`) must refuse a plan
4040    /// built from a since-changed snapshot, exactly like the non-symmetric
4041    /// `atomic_edge_update_plan_stale_revision_rolls_back_unit` case above —
4042    /// even though a genuine canonical survivor exists at the target natural
4043    /// key. `E`'s own revision changes (via an unrelated production
4044    /// `update_edge` call) AFTER `prepare_update` captured its snapshot but
4045    /// BEFORE the plan runs; the whole atomic unit must roll back rather than
4046    /// silently absorbing `E` into the survivor and discarding the
4047    /// concurrent write.
4048    #[tokio::test]
4049    async fn atomic_update_edge_symmetric_absorption_plan_stale_revision_rolls_back_unit() {
4050        let runtime = scratch_runtime();
4051        let token = runtime
4052            .authorize(Namespace::parse("local").expect("ns"))
4053            .expect("authorize");
4054        let entities = runtime.entities(&token).expect("entities store");
4055        let a = khive_storage::Entity::new("local", "concept", "StaleAbsorbA");
4056        let b = khive_storage::Entity::new("local", "concept", "StaleAbsorbB");
4057        let (a_id, b_id) = (a.id, b.id);
4058        entities.upsert_entity(a).await.expect("seed a");
4059        entities.upsert_entity(b).await.expect("seed b");
4060
4061        // The pre-existing canonical row this plan will try to absorb into.
4062        let canonical_edge = runtime
4063            .link(&token, a_id, b_id, EdgeRelation::CompetesWith, 0.6, None)
4064            .await
4065            .expect("seed canonical edge");
4066        let canonical_id = Uuid::from(canonical_edge.id);
4067
4068        // E: the requested edge under test.
4069        let requested_edge = runtime
4070            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.2, None)
4071            .await
4072            .expect("seed requested edge");
4073        let requested_id = Uuid::from(requested_edge.id);
4074
4075        // PREPARE time: build the plan from the current (soon-to-be-stale)
4076        // revision.
4077        let plan = prepare_update(
4078            &runtime,
4079            &token,
4080            &json!({"id": requested_id.to_string(), "relation": "competes_with", "weight": 0.9}),
4081            None,
4082        )
4083        .await
4084        .expect("prepare update edge (symmetric absorption)");
4085
4086        // A concurrent writer commits BEFORE the plan runs, advancing E's
4087        // revision past what the plan's guard expects. Relation stays
4088        // `extends` (non-symmetric), so this lands via the already-guarded
4089        // replace path — independent of the absorption bug under test.
4090        let concurrent = runtime
4091            .update_edge(
4092                &token,
4093                requested_id,
4094                crate::curation::EdgePatch {
4095                    weight: Some(0.77),
4096                    ..Default::default()
4097                },
4098            )
4099            .await
4100            .expect("concurrent writer update");
4101        assert!((concurrent.weight - 0.77).abs() < 1e-9);
4102
4103        // Statement 2's in-place arm carries a strict-advance conjunct
4104        // (`?7 > updated_at`) beside the expected-revision conjunct
4105        // (`updated_at = ?10`) this test names. Both the plan and the
4106        // concurrent writer derive their revision from `max(now, expected + 1)`
4107        // and the concurrent writer ran LATER, so left alone the stored
4108        // revision sits at or past the plan's replacement and BOTH conjuncts
4109        // refuse — the test would stay green with either one deleted. Pin the
4110        // stored revision one microsecond below the plan's replacement, the
4111        // same treatment the entity and edge siblings above already carry.
4112        let (absorb_replacement, absorb_expected, absorb_expected_deleted, absorb_ns, absorb_id) = {
4113            let statements = match &plan {
4114                AtomicOpPlan::Update(p) => p.statements.clone(),
4115                other => panic!("expected an Update plan, got {other:?}"),
4116            };
4117            let s = statements
4118                .iter()
4119                .find(|st| {
4120                    st.statement.label.as_deref() == Some("edge-symmetric-absorb-or-update-inplace")
4121                })
4122                .expect("the plan must carry the guarded symmetric in-place absorb");
4123            let int = |i: usize| match &s.statement.params[i] {
4124                SqlValue::Integer(v) => *v,
4125                other => panic!("param {i} must be an integer revision, got {other:?}"),
4126            };
4127            let marker = |i: usize| match &s.statement.params[i] {
4128                SqlValue::Null => None,
4129                SqlValue::Integer(v) => Some(*v),
4130                other => panic!("param {i} must be a deletion marker, got {other:?}"),
4131            };
4132            let txt = |i: usize| match &s.statement.params[i] {
4133                SqlValue::Text(v) => v.clone(),
4134                other => panic!("param {i} must be text, got {other:?}"),
4135            };
4136            (int(6), int(9), marker(10), txt(0), txt(1))
4137        };
4138        let stored_pinned = absorb_replacement - 1;
4139        assert_ne!(
4140            stored_pinned, absorb_expected,
4141            "fixture premise: the pinned revision must differ from the plan's `?10`, otherwise \
4142             `updated_at = ?10` would MATCH and nothing would refuse the in-place arm (and the \
4143             guarded delete's `updated_at = ?6`, bound to the same value, would MATCH too and \
4144             fire, leaving `changes() = 1` and selecting the absorbed arm instead)"
4145        );
4146        {
4147            let mut writer = runtime.sql().writer().await.expect("writer");
4148            let affected = writer
4149                .execute(SqlStatement {
4150                    sql: "UPDATE graph_edges SET updated_at = ?1 WHERE id = ?2".to_string(),
4151                    params: vec![
4152                        SqlValue::Integer(stored_pinned),
4153                        SqlValue::Text(requested_id.to_string()),
4154                    ],
4155                    label: Some("test-pin-stored-revision".to_string()),
4156                })
4157                .await
4158                .expect("pin the stored revision");
4159            assert_eq!(affected, 1, "the pin must touch exactly the requested edge");
4160        }
4161        assert!(
4162            absorb_replacement > stored_pinned,
4163            "fixture premise: the plan's `?7` must still strictly advance past the stored \
4164             revision, otherwise `?7 > updated_at` refuses too and the refusal stops being \
4165             attributable to `updated_at = ?10`"
4166        );
4167
4168        // A symmetric plan carries TWO guarded statements, and it matters
4169        // which one refuses.
4170        //
4171        //   1. `edge-symmetric-delete-if-conflict`, guarded
4172        //      `{expected_min: 0, expected_max: Some(1)}` — a zero-row delete
4173        //      SATISFIES this guard. It does not roll the unit back. Its
4174        //      effect here is to leave SQLite's `changes()` at 0.
4175        //   2. `edge-symmetric-absorb-or-update-inplace`, guarded
4176        //      `exactly(1)` — this is the statement that refuses and rolls the
4177        //      unit back, through its in-place arm
4178        //      `(id = ?2 AND changes() = 0 AND updated_at = ?10 AND
4179        //        deleted_at IS ?11 AND ?7 > updated_at)`,
4180        //      whose `updated_at = ?10` is the stale-revision guard under
4181        //      test. The absorbed arm needs `changes() = 1`, so the delete
4182        //      refusing is what selects the in-place arm.
4183        //
4184        // So the premises come in two layers. The delete's own predicates
4185        // (`?6`, `?7`, and the EXISTS survivor at `?3`/`?4`/`?5`) are premised
4186        // because they decide WHETHER the delete fires, and therefore which
4187        // arm of statement 2 is live. Statement 2's remaining conjuncts are
4188        // premised because each of them refuses identically to the revision
4189        // guard this test names. Read the plans' own bound values and check
4190        // the world against them, immediately before the DML.
4191        {
4192            let statements = match &plan {
4193                AtomicOpPlan::Update(p) => p.statements.clone(),
4194                other => panic!("expected an Update plan, got {other:?}"),
4195            };
4196            // By LABEL, for the same reason as the siblings above.
4197            let del = statements
4198                .iter()
4199                .find(|s| s.statement.label.as_deref() == Some("edge-symmetric-delete-if-conflict"))
4200                .expect("the plan must carry the guarded symmetric delete");
4201            let text = |i: usize| match &del.statement.params[i] {
4202                SqlValue::Text(v) => v.clone(),
4203                other => panic!("param {i} must be text, got {other:?}"),
4204            };
4205            let plan_expected_updated = match &del.statement.params[5] {
4206                SqlValue::Integer(v) => *v,
4207                other => panic!("param 5 must be the expected revision, got {other:?}"),
4208            };
4209            let plan_expected_deleted = match &del.statement.params[6] {
4210                SqlValue::Null => None,
4211                SqlValue::Integer(v) => Some(*v),
4212                other => panic!("param 6 must be a deletion marker, got {other:?}"),
4213            };
4214
4215            // The delete's OWN identity conjuncts. Reading them into the
4216            // survivor-count panic message below is not asserting them: point
4217            // `?1` or `?2` at a row that does not exist and the delete still
4218            // affects zero rows, its `0..=1` guard still accepts that, and
4219            // statement 2 still refuses on the pinned stale revision — so the
4220            // test stays green while establishing nothing about which row the
4221            // named delete attempted.
4222            assert_eq!(
4223                text(0),
4224                "local",
4225                "fixture premise: the delete's `?1` must be the namespace the row lives in, \
4226                 otherwise `namespace = ?1` refuses on its own"
4227            );
4228            assert_eq!(
4229                text(1),
4230                requested_id.to_string(),
4231                "fixture premise: the delete's `?2` must be the edge under test, otherwise \
4232                 `id = ?2` refuses on identity and the delete never attempted the requested row"
4233            );
4234
4235            let requested_now = runtime
4236                .get_edge_including_deleted(&token, requested_id)
4237                .await
4238                .expect("read the requested edge")
4239                .expect("the requested edge is present before the plan runs");
4240            assert_ne!(
4241                requested_now.updated_at.timestamp_micros(),
4242                plan_expected_updated,
4243                "fixture premise: the concurrent writer must actually have moved the \
4244                 revision past the plan's `?6`, otherwise nothing refuses the delete"
4245            );
4246            assert_eq!(
4247                requested_now.deleted_at.map(|d| d.timestamp_micros()),
4248                plan_expected_deleted,
4249                "fixture premise: the stored deletion marker must MATCH the plan's `?7`, \
4250                 otherwise `deleted_at IS ?7` refuses too and the refusal is not \
4251                 attributable to the revision guard"
4252            );
4253
4254            // The EXISTS arm. A missing survivor refuses the delete on its own
4255            // and looks identical from outside, so the premise has to be that
4256            // arm's OWN question. Do not reconstruct it from the seeded row's
4257            // endpoints: the natural key the plan binds is the canonical
4258            // ordering, which need not equal the order the survivor was stored
4259            // in, and a hand-built comparison would be asserting my model of
4260            // canonicalisation rather than the predicate. Run the subquery
4261            // verbatim against the plan's own bound parameters instead.
4262            assert_ne!(
4263                canonical_id, requested_id,
4264                "fixture premise: the survivor must be a DIFFERENT row, since the EXISTS \
4265                 arm excludes the requested id"
4266            );
4267            let survivors = {
4268                let mut reader = runtime.sql().reader().await.expect("sql reader");
4269                reader
4270                    .query_scalar(SqlStatement {
4271                        sql: "SELECT count(*) FROM graph_edges \
4272                              WHERE namespace = ?1 AND source_id = ?3 AND target_id = ?4 \
4273                                AND relation = ?5 AND id != ?2"
4274                            .to_string(),
4275                        params: del.statement.params[0..5].to_vec(),
4276                        label: Some("test-survivor-exists-premise".to_string()),
4277                    })
4278                    .await
4279                    .expect("run the plan's own EXISTS predicate")
4280            };
4281            let survivors = match survivors {
4282                Some(SqlValue::Integer(n)) => n,
4283                other => panic!("count(*) must come back as an integer, got {other:?}"),
4284            };
4285            assert_eq!(
4286                survivors,
4287                1,
4288                "fixture premise: exactly one survivor must satisfy the plan's own EXISTS \
4289                 predicate (namespace {}, source {}, target {}, relation {}, id != {}), \
4290                 otherwise the delete refuses on the survivor arm and the refusal is not \
4291                 attributable to the revision guard",
4292                text(0),
4293                text(2),
4294                text(3),
4295                text(4),
4296                text(1),
4297            );
4298        }
4299
4300        // Statement 2's remaining conjuncts. Each of these refuses the in-place
4301        // arm identically to the revision guard this test names, so each has to
4302        // be shown satisfied for the attribution to hold.
4303        assert_eq!(
4304            absorb_ns, "local",
4305            "fixture premise: the plan's `?1` must be the namespace the row lives in, \
4306             otherwise the outer `namespace = ?1` refuses on its own"
4307        );
4308        assert_eq!(
4309            absorb_id,
4310            requested_id.to_string(),
4311            "fixture premise: the plan's `?2` must be the edge under test, otherwise the \
4312             in-place arm's `id = ?2` refuses on identity"
4313        );
4314        {
4315            let stored = runtime
4316                .get_edge_including_deleted(&token, requested_id)
4317                .await
4318                .expect("read the requested edge")
4319                .expect("the requested edge is present before the plan runs");
4320            assert_eq!(
4321                stored.updated_at.timestamp_micros(),
4322                stored_pinned,
4323                "fixture premise: the pin must be what the guard reads at DML time, so the \
4324                 stored revision is the pinned value and nothing re-advanced it"
4325            );
4326            assert_eq!(
4327                stored.deleted_at.map(|d| d.timestamp_micros()),
4328                absorb_expected_deleted,
4329                "fixture premise: the stored deletion marker must MATCH the plan's `?11`, \
4330                 otherwise `deleted_at IS ?11` refuses too and the refusal stops being \
4331                 attributable to `updated_at = ?10`"
4332            );
4333        }
4334
4335        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4336            .await
4337            .expect("the seam call itself must not error; the unit rolls back cleanly");
4338        match outcome {
4339            crate::atomic_runner::AtomicRunOutcome::RolledBack {
4340                failed_op_index,
4341                failure,
4342            } => {
4343                assert_eq!(
4344                    failed_op_index, 0,
4345                    "the sole op's guard must be the one that fails"
4346                );
4347                // The decisive attribution, and the reason the two-layer
4348                // premise stack above exists: `failed_op_index` cannot
4349                // distinguish the two statements, because both live in op 0.
4350                // Naming the label is what says the in-place absorb refused
4351                // rather than the delete — and the delete's `0..=1` guard
4352                // means it CANNOT be the refuser, so a run that reported it
4353                // here would be evidence the guards had been rewired.
4354                assert_eq!(
4355                    failure,
4356                    crate::atomic_runner::AtomicOpFailure::GuardFailed {
4357                        statement_label: Some(
4358                            "edge-symmetric-absorb-or-update-inplace".to_string()
4359                        ),
4360                        expected: crate::atomic_plan::AffectedRowGuard::exactly(1),
4361                        observed: 0,
4362                    },
4363                    "the guarded in-place absorb must be the statement whose guard refused"
4364                );
4365            }
4366            other => panic!(
4367                "a stale absorption plan must roll back, not silently absorb E into the \
4368                 survivor and discard the concurrent writer's change: {other:?}"
4369            ),
4370        }
4371
4372        let requested_after = runtime
4373            .get_edge(&token, requested_id)
4374            .await
4375            .expect("get_edge")
4376            .expect("E must still exist after the rolled-back absorption");
4377        assert_eq!(
4378            requested_after.relation,
4379            EdgeRelation::Extends,
4380            "E must be untouched by the rolled-back absorption: {requested_after:?}"
4381        );
4382        assert!(
4383            (requested_after.weight - 0.77).abs() < 1e-9,
4384            "the concurrent writer's committed weight must survive the rolled-back plan: \
4385             {requested_after:?}"
4386        );
4387
4388        let canonical_after = runtime
4389            .get_edge(&token, canonical_id)
4390            .await
4391            .expect("get_edge")
4392            .expect("S must still exist after the rolled-back absorption");
4393        assert_eq!(
4394            canonical_after.weight, 0.6,
4395            "the survivor must never have been touched by the aborted absorption"
4396        );
4397    }
4398
4399    /// `update` rejects an entity/note-only field (`name`) on an edge
4400    /// target, mirroring
4401    /// `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
4402    /// `KindSpec::Edge` arm.
4403    #[tokio::test]
4404    async fn atomic_update_edge_rejects_entity_only_field_name() {
4405        let runtime = scratch_runtime();
4406        let token = runtime
4407            .authorize(Namespace::parse("local").expect("ns"))
4408            .expect("authorize");
4409        let entities = runtime.entities(&token).expect("entities store");
4410        let a = khive_storage::Entity::new("local", "concept", "GapEdgeRejectA");
4411        let b = khive_storage::Entity::new("local", "concept", "GapEdgeRejectB");
4412        let (a_id, b_id) = (a.id, b.id);
4413        entities.upsert_entity(a).await.expect("seed a");
4414        entities.upsert_entity(b).await.expect("seed b");
4415        let edge = runtime
4416            .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
4417            .await
4418            .expect("seed edge");
4419        let edge_id = Uuid::from(edge.id);
4420
4421        let err = prepare_update(
4422            &runtime,
4423            &token,
4424            &json!({"id": edge_id.to_string(), "name": "not-a-valid-edge-field"}),
4425            None,
4426        )
4427        .await
4428        .expect_err("edge update with an entity-only field must be rejected");
4429        let message = err.to_string();
4430        assert!(
4431            message.contains("name") && message.contains("edge"),
4432            "error must name the offending field and the substrate: {message}"
4433        );
4434    }
4435
4436    /// `delete` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`; this
4437    /// asserts `prepare_delete` actually builds a plan for one on both soft
4438    /// and hard delete, matching `operations::delete_edge`'s row-mode DML
4439    /// and unconditional `EdgeDeleted` event.
4440    #[tokio::test]
4441    async fn atomic_delete_edge_soft_and_hard_appends_edge_deleted_event() {
4442        let runtime = scratch_runtime();
4443        let token = runtime
4444            .authorize(Namespace::parse("local").expect("ns"))
4445            .expect("authorize");
4446
4447        for hard in [false, true] {
4448            let entities = runtime.entities(&token).expect("entities store");
4449            let a = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelA{hard}"));
4450            let b = khive_storage::Entity::new("local", "concept", format!("GapEdgeDelB{hard}"));
4451            let (a_id, b_id) = (a.id, b.id);
4452            entities.upsert_entity(a).await.expect("seed a");
4453            entities.upsert_entity(b).await.expect("seed b");
4454            let edge = runtime
4455                .link(&token, a_id, b_id, EdgeRelation::Extends, 0.5, None)
4456                .await
4457                .expect("seed edge");
4458            let edge_id = Uuid::from(edge.id);
4459
4460            let args = if hard {
4461                json!({"id": edge_id.to_string(), "hard": true})
4462            } else {
4463                json!({"id": edge_id.to_string()})
4464            };
4465            let plan = prepare_delete(&runtime, &token, &args, None)
4466                .await
4467                .unwrap_or_else(|e| panic!("prepare delete edge (hard={hard}): {e}"));
4468            let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4469                .await
4470                .unwrap_or_else(|e| panic!("edge delete commit (hard={hard}): {e}"));
4471            assert!(
4472                matches!(
4473                    outcome,
4474                    crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4475                ),
4476                "expected a clean edge delete commit (hard={hard}): {outcome:?}"
4477            );
4478
4479            let after = runtime
4480                .get_edge_including_deleted(&token, edge_id)
4481                .await
4482                .expect("get_edge_including_deleted");
4483            if hard {
4484                assert!(after.is_none(), "hard delete must purge the row entirely");
4485            } else {
4486                assert!(
4487                    after.as_ref().is_some_and(|e| e.deleted_at.is_some()),
4488                    "soft delete must tombstone, not purge"
4489                );
4490            }
4491
4492            let events = events_for_target(&runtime, &token, edge_id, EventKind::EdgeDeleted).await;
4493            assert_eq!(
4494                events.len(),
4495                1,
4496                "expected exactly one EdgeDeleted event for {edge_id} (hard={hard})"
4497            );
4498            assert_eq!(events[0].payload["hard"], json!(hard));
4499        }
4500    }
4501
4502    /// Parity boundary: atomic `update` of a note must append no event:
4503    /// canonical `update_note` never calls `append_event` (unlike
4504    /// `update_entity`, which always does).
4505    #[tokio::test]
4506    async fn atomic_update_note_appends_no_event() {
4507        let runtime = scratch_runtime();
4508        let token = runtime
4509            .authorize(Namespace::parse("local").expect("ns"))
4510            .expect("authorize");
4511        let mut note = khive_storage::note::Note::new("local", "observation", "gap1-note-noevent");
4512        note.name = Some("gap1-note-noevent".to_string());
4513        let note_id = note.id;
4514        runtime
4515            .notes(&token)
4516            .expect("notes store")
4517            .upsert_note(note)
4518            .await
4519            .expect("seed note");
4520
4521        let plan = prepare_update(
4522            &runtime,
4523            &token,
4524            &json!({"id": note_id.to_string(), "content": "gap1-note-noevent, revised"}),
4525            None,
4526        )
4527        .await
4528        .expect("prepare update");
4529        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4530            .await
4531            .expect("seam call ok");
4532        assert!(matches!(
4533            outcome,
4534            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4535        ));
4536
4537        let event_store = runtime.events(&token).expect("event store");
4538        let page = event_store
4539            .query_events(
4540                khive_storage::EventFilter::default(),
4541                khive_storage::types::PageRequest::default(),
4542            )
4543            .await
4544            .expect("query_events");
4545        assert!(
4546            page.items.iter().all(|e| e.target_id != Some(note_id)),
4547            "update_note must append no event; found: {:?}",
4548            page.items
4549                .iter()
4550                .filter(|e| e.target_id == Some(note_id))
4551                .collect::<Vec<_>>()
4552        );
4553    }
4554
4555    /// Parity boundary: atomic `link` must append no event: canonical
4556    /// `link` never calls `append_event`.
4557    #[tokio::test]
4558    async fn atomic_link_appends_no_event() {
4559        let runtime = scratch_runtime();
4560        let token = runtime
4561            .authorize(Namespace::parse("local").expect("ns"))
4562            .expect("authorize");
4563        let source = khive_storage::Entity::new("local", "concept", "gap1-link-source");
4564        let target = khive_storage::Entity::new("local", "concept", "gap1-link-target");
4565        let (source_id, target_id) = (source.id, target.id);
4566        runtime
4567            .entities(&token)
4568            .expect("entities store")
4569            .upsert_entity(source)
4570            .await
4571            .expect("seed source");
4572        runtime
4573            .entities(&token)
4574            .expect("entities store")
4575            .upsert_entity(target)
4576            .await
4577            .expect("seed target");
4578
4579        let plan = prepare_link(
4580            &runtime,
4581            &token,
4582            &json!({
4583                "source_id": source_id.to_string(),
4584                "target_id": target_id.to_string(),
4585                "relation": "extends",
4586            }),
4587        )
4588        .await
4589        .expect("prepare link");
4590        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
4591            .await
4592            .expect("seam call ok");
4593        assert!(matches!(
4594            outcome,
4595            crate::atomic_runner::AtomicRunOutcome::Committed { .. }
4596        ));
4597
4598        let event_store = runtime.events(&token).expect("event store");
4599        let page = event_store
4600            .query_events(
4601                khive_storage::EventFilter::default(),
4602                khive_storage::types::PageRequest::default(),
4603            )
4604            .await
4605            .expect("query_events");
4606        assert!(
4607            page.items.is_empty(),
4608            "link must append no event; found: {:?}",
4609            page.items
4610        );
4611    }
4612
4613    // ------------------------------------------------------------------
4614    // AddEntity and AddNote plans alongside link
4615    // ------------------------------------------------------------------
4616
4617    #[tokio::test]
4618    async fn prepare_add_entity_rejects_whitespace_only_name() {
4619        let runtime = scratch_runtime();
4620        let token = runtime
4621            .authorize(Namespace::parse("local").expect("ns"))
4622            .expect("authorize");
4623
4624        let err = prepare_add_entity(&runtime, &token, &json!({"kind": "concept", "name": "   "}))
4625            .await
4626            .expect_err("whitespace-only entity name must fail prepare");
4627
4628        assert!(matches!(
4629            err,
4630            RuntimeError::InvalidInput(message) if message.contains("name must not be empty")
4631        ));
4632    }
4633
4634    #[tokio::test]
4635    async fn prepare_add_entity_rejects_non_string_description() {
4636        let runtime = scratch_runtime();
4637        let token = runtime
4638            .authorize(Namespace::parse("local").expect("ns"))
4639            .expect("authorize");
4640
4641        let err = prepare_add_entity(
4642            &runtime,
4643            &token,
4644            &json!({"kind": "concept", "name": "Valid", "description": 42}),
4645        )
4646        .await
4647        .expect_err("non-string entity description must fail prepare");
4648
4649        assert!(matches!(
4650            err,
4651            RuntimeError::InvalidInput(message)
4652                if message.contains("description must be a string or null")
4653        ));
4654    }
4655
4656    #[tokio::test]
4657    async fn prepare_add_note_rejects_non_string_name() {
4658        let runtime = scratch_runtime();
4659        let token = runtime
4660            .authorize(Namespace::parse("local").expect("ns"))
4661            .expect("authorize");
4662
4663        let err = prepare_add_note(
4664            &runtime,
4665            &token,
4666            &json!({"kind": "observation", "content": "Valid", "name": 42}),
4667        )
4668        .await
4669        .expect_err("non-string note name must fail prepare");
4670
4671        assert!(matches!(
4672            err,
4673            RuntimeError::InvalidInput(message) if message.contains("name must be a string or null")
4674        ));
4675    }
4676
4677    /// ADR-115 Amendment 1 §3: proposal materialization (`prepare_add_entity`)
4678    /// must reject the reserved `khive:secret_gate` property key the same way
4679    /// canonical `create` does — proposal apply is reservation-only, never an
4680    /// exemption-consuming path.
4681    #[tokio::test]
4682    async fn prepare_add_entity_rejects_reserved_secret_gate_property() {
4683        let runtime = scratch_runtime();
4684        let token = runtime
4685            .authorize(Namespace::parse("local").expect("ns"))
4686            .expect("authorize");
4687
4688        let err = prepare_add_entity(
4689            &runtime,
4690            &token,
4691            &json!({
4692                "kind": "concept",
4693                "name": "ReservedKeyEntity",
4694                "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
4695            }),
4696        )
4697        .await
4698        .expect_err("a caller-supplied reserved key on a new entity must be rejected");
4699        assert!(
4700            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
4701            "expected a reservation rejection, got: {err:?}"
4702        );
4703    }
4704
4705    /// Note-substrate counterpart of
4706    /// `prepare_add_entity_rejects_reserved_secret_gate_property`.
4707    #[tokio::test]
4708    async fn prepare_add_note_rejects_reserved_secret_gate_property() {
4709        let runtime = scratch_runtime();
4710        let token = runtime
4711            .authorize(Namespace::parse("local").expect("ns"))
4712            .expect("authorize");
4713
4714        let err = prepare_add_note(
4715            &runtime,
4716            &token,
4717            &json!({
4718                "kind": "observation",
4719                "content": "a note carrying a reserved property key",
4720                "properties": {"khive:secret_gate": "exempted:content-sha256-manifest-v1"},
4721            }),
4722        )
4723        .await
4724        .expect_err("a caller-supplied reserved key on a new note must be rejected");
4725        assert!(
4726            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate") && msg.contains("runtime-owned")),
4727            "expected a reservation rejection, got: {err:?}"
4728        );
4729    }
4730
4731    #[tokio::test]
4732    async fn atomic_proposal_vectors_materialize_only_after_successful_commit() {
4733        let runtime = scratch_runtime();
4734        runtime.register_embedder(StubProvider);
4735        let token = runtime
4736            .authorize(Namespace::parse("local").expect("ns"))
4737            .expect("authorize");
4738        let vec_store = runtime
4739            .vectors_for_model(&token, STUB_MODEL)
4740            .expect("vec store");
4741        let entities = runtime.entities(&token).expect("entities store");
4742        let a = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkA");
4743        let b = khive_storage::Entity::new("local", "concept", "ProposalPlanLinkB");
4744        let (a_id, b_id) = (a.id, b.id);
4745        entities.upsert_entity(a).await.expect("seed a");
4746        entities.upsert_entity(b).await.expect("seed b");
4747
4748        let add_entity_plan = prepare_add_entity(
4749            &runtime,
4750            &token,
4751            &json!({"kind": "concept", "name": "ProposalPlanNewEntity", "description": "created atomically"}),
4752        )
4753        .await
4754        .expect("prepare add_entity");
4755        let link_plan = prepare_link(
4756            &runtime,
4757            &token,
4758            &json!({"source_id": a_id.to_string(), "target_id": b_id.to_string(), "relation": "extends"}),
4759        )
4760        .await
4761        .expect("prepare link");
4762        let add_note_plan = prepare_add_note(
4763            &runtime,
4764            &token,
4765            &json!({"kind": "observation", "content": "created atomically alongside the entity"}),
4766        )
4767        .await
4768        .expect("prepare add_note");
4769
4770        let entity_id = match &add_entity_plan {
4771            AtomicOpPlan::AddEntity(p) => p.entity_id,
4772            other => panic!("expected an AddEntity plan, got {other:?}"),
4773        };
4774        let note_id = match &add_note_plan {
4775            AtomicOpPlan::AddNote(p) => p.note_id,
4776            other => panic!("expected an AddNote plan, got {other:?}"),
4777        };
4778
4779        let outcome = crate::atomic_runner::run_atomic_unit(
4780            runtime.sql().as_ref(),
4781            vec![add_entity_plan, link_plan, add_note_plan],
4782        )
4783        .await
4784        .expect("seam call ok");
4785        let post_commit = match outcome {
4786            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
4787            other => panic!("expected the whole unit to commit: {other:?}"),
4788        };
4789        assert_eq!(
4790            post_commit.as_slice(),
4791            &[
4792                PostCommitEffect::ReindexEntity { entity_id },
4793                PostCommitEffect::ReindexNote { note_id },
4794            ],
4795            "prepare-derived effects must reach the committed token unchanged"
4796        );
4797        assert_eq!(
4798            vec_store.count().await.expect("count before effects"),
4799            0,
4800            "commit returns deferred effects without materializing vectors"
4801        );
4802        let entity = runtime
4803            .entities(&token)
4804            .expect("entities store")
4805            .get_entity(entity_id)
4806            .await
4807            .expect("get_entity")
4808            .expect("entity must exist after commit");
4809        assert_eq!(entity.name, "ProposalPlanNewEntity");
4810        assert!(
4811            runtime
4812                .text(&token)
4813                .expect("text store")
4814                .get_document("local", entity_id)
4815                .await
4816                .expect("get_document")
4817                .is_some(),
4818            "entity's FTS document must exist after commit"
4819        );
4820
4821        let (edge_count, _, _, edge_deleted_at) =
4822            probe_edge_natural_key(&runtime, "local", a_id, b_id, "extends").await;
4823        assert_eq!(
4824            edge_count, 1,
4825            "the edge must be committed alongside the entity/note"
4826        );
4827        assert!(edge_deleted_at.is_none());
4828
4829        let note = runtime
4830            .notes(&token)
4831            .expect("notes store")
4832            .get_note(note_id)
4833            .await
4834            .expect("get_note")
4835            .expect("note must exist after commit");
4836        assert_eq!(note.content, "created atomically alongside the entity");
4837        assert!(
4838            runtime
4839                .text_for_notes(&token)
4840                .expect("text store")
4841                .get_document("local", note_id)
4842                .await
4843                .expect("get_document")
4844                .is_some(),
4845            "note's FTS document must exist after commit"
4846        );
4847
4848        apply_post_commit_effects(&runtime, &token, post_commit)
4849            .await
4850            .expect("apply post-commit effects");
4851
4852        assert_eq!(
4853            vec_store.count().await.expect("count after"),
4854            2,
4855            "post-commit reindex must have embedded both the new entity and the new note"
4856        );
4857    }
4858
4859    #[tokio::test]
4860    async fn atomic_proposal_abort_leaves_zero_vector_rows() {
4861        let runtime = scratch_runtime();
4862        runtime.register_embedder(StubProvider);
4863        let token = runtime
4864            .authorize(Namespace::parse("local").expect("ns"))
4865            .expect("authorize");
4866        let vec_store = runtime
4867            .vectors_for_model(&token, STUB_MODEL)
4868            .expect("vec store");
4869        let entities = runtime.entities(&token).expect("entities store");
4870        let a = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackA");
4871        let x = khive_storage::Entity::new("local", "concept", "ProposalPlanRollbackX");
4872        let (a_id, x_id) = (a.id, x.id);
4873        entities.upsert_entity(a).await.expect("seed a");
4874        entities.upsert_entity(x.clone()).await.expect("seed x");
4875
4876        let add_entity_plan = prepare_add_entity(
4877            &runtime,
4878            &token,
4879            &json!({"kind": "concept", "name": "ProposalPlanRollbackNewEntity"}),
4880        )
4881        .await
4882        .expect("prepare add_entity");
4883        let add_note_plan = prepare_add_note(
4884            &runtime,
4885            &token,
4886            &json!({"kind": "observation", "content": "must not survive the rollback"}),
4887        )
4888        .await
4889        .expect("prepare add_note");
4890        let delete_plan = prepare_delete(
4891            &runtime,
4892            &token,
4893            &json!({"id": x_id.to_string(), "hard": true}),
4894            None,
4895        )
4896        .await
4897        .expect("prepare delete x");
4898        // Prepare sees x before the transaction; the guarded link must detect
4899        // that the preceding hard delete removed it inside the transaction.
4900        let link_plan = prepare_link(
4901            &runtime,
4902            &token,
4903            &json!({"source_id": a_id.to_string(), "target_id": x_id.to_string(), "relation": "extends"}),
4904        )
4905        .await
4906        .expect("prepare link (endpoint still exists at prepare time)");
4907
4908        let entity_id = match &add_entity_plan {
4909            AtomicOpPlan::AddEntity(p) => p.entity_id,
4910            other => panic!("expected an AddEntity plan, got {other:?}"),
4911        };
4912        let note_id = match &add_note_plan {
4913            AtomicOpPlan::AddNote(p) => p.note_id,
4914            other => panic!("expected an AddNote plan, got {other:?}"),
4915        };
4916
4917        let outcome = crate::atomic_runner::run_atomic_unit(
4918            runtime.sql().as_ref(),
4919            vec![add_entity_plan, add_note_plan, delete_plan, link_plan],
4920        )
4921        .await
4922        .expect("the seam call itself must not error; the unit rolls back cleanly");
4923        match outcome {
4924            crate::atomic_runner::AtomicRunOutcome::RolledBack {
4925                failed_op_index, ..
4926            } => {
4927                assert_eq!(
4928                    failed_op_index, 3,
4929                    "the trailing link (index 3) must be the op whose guard fails"
4930                );
4931            }
4932            other => panic!("expected the whole unit to roll back, got {other:?}"),
4933        }
4934
4935        assert_eq!(
4936            vec_store
4937                .count()
4938                .await
4939                .expect("vector count after rollback"),
4940            0,
4941            "a rolled-back atomic apply must not materialize vectors"
4942        );
4943
4944        assert!(
4945            runtime
4946                .get_entity_including_deleted(&token, entity_id)
4947                .await
4948                .expect("get_entity_including_deleted")
4949                .is_none(),
4950            "the new entity must leave zero trace after rollback"
4951        );
4952        assert!(
4953            runtime
4954                .text(&token)
4955                .expect("text store")
4956                .get_document("local", entity_id)
4957                .await
4958                .expect("get_document")
4959                .is_none(),
4960            "the new entity's FTS document must leave zero trace after rollback"
4961        );
4962        assert!(
4963            runtime
4964                .get_note_including_deleted(&token, note_id)
4965                .await
4966                .expect("get_note_including_deleted")
4967                .is_none(),
4968            "the new note must leave zero trace after rollback"
4969        );
4970        assert!(
4971            runtime
4972                .text_for_notes(&token)
4973                .expect("text store")
4974                .get_document("local", note_id)
4975                .await
4976                .expect("get_document")
4977                .is_none(),
4978            "the new note's FTS document must leave zero trace after rollback"
4979        );
4980
4981        let x_after = runtime
4982            .get_entity_including_deleted(&token, x_id)
4983            .await
4984            .expect("get_entity_including_deleted")
4985            .expect("x must still be present because its delete rolled back too");
4986        assert!(
4987            x_after.deleted_at.is_none(),
4988            "x's delete must have rolled back along with the failed link"
4989        );
4990
4991        let (edge_count, _, _, _) =
4992            probe_edge_natural_key(&runtime, "local", a_id, x_id, "extends").await;
4993        assert_eq!(edge_count, 0, "no edge may have been committed");
4994    }
4995
4996    /// ADR-014 tri-state on the atomic path: `entity_type: null` must
4997    /// explicitly CLEAR a stored entity type (and reindex), not collapse to
4998    /// "unchanged" like the old `optional_create_string` did.
4999    #[tokio::test]
5000    async fn atomic_update_entity_type_null_clears_stored_type() {
5001        let runtime = scratch_runtime();
5002        runtime.install_entity_type_validator(std::sync::Arc::new(|kind, entity_type| {
5003            let Some(raw) = entity_type else {
5004                return Ok(None);
5005            };
5006            let normalized = raw.trim().to_ascii_lowercase();
5007            if kind == "concept" && normalized == "algorithm" {
5008                Ok(Some(normalized))
5009            } else {
5010                Err(RuntimeError::InvalidInput(format!(
5011                    "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
5012                )))
5013            }
5014        }));
5015        let token = runtime
5016            .authorize(Namespace::parse("local").expect("ns"))
5017            .expect("authorize");
5018        let mut entity = khive_storage::Entity::new("local", "concept", "AtomicNullClear");
5019        entity.entity_type = Some("algorithm".to_string());
5020        let entity_id = entity.id;
5021        runtime
5022            .entities(&token)
5023            .expect("entities store")
5024            .upsert_entity(entity)
5025            .await
5026            .expect("seed entity");
5027
5028        let plan = prepare_update(
5029            &runtime,
5030            &token,
5031            &json!({"id": entity_id.to_string(), "entity_type": null}),
5032            None,
5033        )
5034        .await
5035        .expect("atomic prepare must accept entity_type: null");
5036        let outcome = crate::atomic_runner::run_atomic_unit(runtime.sql().as_ref(), vec![plan])
5037            .await
5038            .expect("atomic update must run");
5039        let post_commit = match outcome {
5040            crate::atomic_runner::AtomicRunOutcome::Committed { post_commit } => post_commit,
5041            other => panic!("expected Committed, got {other:?}"),
5042        };
5043        assert_eq!(
5044            post_commit.as_slice(),
5045            &[PostCommitEffect::ReindexEntity { entity_id }],
5046            "a type clear that differs from the prior value must reindex"
5047        );
5048
5049        let updated = runtime
5050            .get_entity(&token, entity_id)
5051            .await
5052            .expect("read updated entity");
5053        assert_eq!(
5054            updated.entity_type, None,
5055            "entity_type: null must clear the stored type"
5056        );
5057        assert_eq!(updated.name, "AtomicNullClear");
5058    }
5059
5060    /// ADR-014 tri-state on the atomic path: a PRESENT `entity_type` key,
5061    /// including JSON `null`, must be rejected on note and edge targets
5062    /// (parity with `khive-pack-kg`'s `reject_inapplicable_fields`).
5063    #[tokio::test]
5064    async fn atomic_update_null_entity_type_rejected_for_note_and_edge() {
5065        let runtime = scratch_runtime();
5066        let token = runtime
5067            .authorize(Namespace::parse("local").expect("ns"))
5068            .expect("authorize");
5069        let note = runtime
5070            .create_note(
5071                &token,
5072                "observation",
5073                None,
5074                "note body for entity_type guard",
5075                Some(0.5),
5076                None,
5077                vec![],
5078            )
5079            .await
5080            .expect("create note");
5081
5082        let note_err = prepare_update(
5083            &runtime,
5084            &token,
5085            &json!({"id": note.id.to_string(), "entity_type": null}),
5086            Some(crate::atomic_prepare::AtomicUpdateKind::Note { specific: None }),
5087        )
5088        .await
5089        .expect_err("entity_type: null on a note must be rejected");
5090        assert!(
5091            matches!(note_err, RuntimeError::InvalidInput(ref msg) if msg.contains("entity_type") && msg.contains("not valid for a note")),
5092            "expected an InvalidInput naming entity_type for a note, got: {note_err:?}"
5093        );
5094
5095        let source = khive_storage::Entity::new("local", "concept", "AtomicNullTypeEdgeSource");
5096        let target = khive_storage::Entity::new("local", "concept", "AtomicNullTypeEdgeTarget");
5097        let source_id = source.id;
5098        let target_id = target.id;
5099        runtime
5100            .entities(&token)
5101            .expect("entities store")
5102            .upsert_entity(source)
5103            .await
5104            .expect("seed source");
5105        runtime
5106            .entities(&token)
5107            .expect("entities store")
5108            .upsert_entity(target)
5109            .await
5110            .expect("seed target");
5111        let edge = runtime
5112            .link(
5113                &token,
5114                source_id,
5115                target_id,
5116                "supports".parse().expect("relation"),
5117                0.5,
5118                None,
5119            )
5120            .await
5121            .expect("create edge");
5122
5123        let edge_err = prepare_update(
5124            &runtime,
5125            &token,
5126            &json!({"id": edge.id.to_string(), "entity_type": null}),
5127            Some(crate::atomic_prepare::AtomicUpdateKind::Edge),
5128        )
5129        .await
5130        .expect_err("entity_type: null on an edge must be rejected");
5131        assert!(
5132            matches!(edge_err, RuntimeError::InvalidInput(ref msg) if msg.contains("entity_type") && msg.contains("not valid for an edge")),
5133            "expected an InvalidInput naming entity_type for an edge, got: {edge_err:?}"
5134        );
5135    }
5136}