Skip to main content

khive_runtime/atomic_prepare/
add_update.rs

1#[cfg(doc)]
2use super::AtomicDeleteKind;
3use super::{
4    entity_fts_document, entity_name_patch, entity_replace_if_unchanged_statement,
5    entity_upsert_statement, event_append_statements, insert_document_statements,
6    note_fts_document, note_upsert_statement, obj, optional_create_string,
7    optional_entity_type_patch, optional_f64_patch, optional_properties, optional_str,
8    optional_string_patch, optional_tags, prepare_delete, prepare_delete_edge, prepare_link,
9    prepare_merge, prepare_update_edge, prepare_update_entity_plan_with_version,
10    refuse_pack_registry_tags, require_str, require_uuid, AddEntityPlan, AddNotePlan,
11    AffectedRowGuard, AtomicOpPlan, EdgeUpsertDisposition, EventKind, KhiveRuntime, NamespaceToken,
12    PlanStatement, PostCommitEffect, Resolved, RuntimeError, RuntimeResult, SubstrateKind,
13    UpdatePlan, Uuid, Value,
14};
15
16#[cfg(test)]
17#[path = "import_entity_tests.rs"]
18mod import_entity_tests;
19
20// ---------------------------------------------------------------------------
21// dispatch
22// ---------------------------------------------------------------------------
23
24/// Build the prepared [`AtomicOpPlan`] for one KG-substrate admissible op
25/// (`update`, `delete`, `link`, `merge`). Returns a loud [`RuntimeError`] for
26/// `propose`/`review`/`withdraw` (known scope gap, see module doc) and any
27/// other verb (the CLI boundary must reject those before calling this — a
28/// verb reaching here is either KG-substrate-admissible or a bug upstream).
29pub async fn prepare_op(
30    runtime: &KhiveRuntime,
31    token: &NamespaceToken,
32    tool: &str,
33    args: &Value,
34) -> RuntimeResult<AtomicOpPlan> {
35    match tool {
36        // `expected_kind: None` here — same reasoning as the `"delete"` arm
37        // below: callers that need `update(kind=...)` parity must resolve
38        // the kind spec themselves (it needs a `VerbRegistry`, unreachable
39        // from this crate: see `AtomicUpdateKind`'s doc comment) and call
40        // `prepare_update` directly with the resolved value; `kkernel`'s
41        // `--atomic` seam does exactly this and bypasses this dispatch arm.
42        // A caller reaching `prepare_op("update", ...)` without going
43        // through that seam gets kind-unchecked behavior.
44        "update" => prepare_update(runtime, token, args, None).await,
45        // `expected_kind: None` here — callers that need `delete(kind=...)`
46        // parity must resolve the kind spec themselves (it needs a
47        // `VerbRegistry`, unreachable from this crate: see
48        // `AtomicDeleteKind`'s doc comment) and call `prepare_delete`
49        // directly with the resolved value; `kkernel`'s `--atomic` seam does
50        // exactly this and bypasses this dispatch arm. A caller reaching
51        // `prepare_op("delete", ...)` without going through that seam gets
52        // kind-unchecked behavior.
53        "delete" => prepare_delete(runtime, token, args, None).await,
54        "link" => prepare_link(runtime, token, args).await,
55        "merge" => prepare_merge(runtime, token, args).await,
56        "propose" | "review" | "withdraw" => prepare_governance_unimplemented(tool),
57        other => Err(RuntimeError::InvalidInput(format!(
58            "{other:?} has no atomic_prepare::prepare_op implementation; the CLI \
59             admissibility check should have rejected this before prepare"
60        ))),
61    }
62}
63
64fn prepare_governance_unimplemented(tool: &str) -> RuntimeResult<AtomicOpPlan> {
65    Err(RuntimeError::InvalidInput(format!(
66        "{tool:?} is on the ADR-099 v1 admissible verb list but has no --atomic \
67         prepare/apply implementation yet: its lifecycle (ADR-046) is an \
68         event-sourced changeset-interpreter over a dedicated `proposals_open` \
69         table, not a small guarded-DML plan — a faithful non-stub atomic \
70         prepare for it is tracked as ADR-099 follow-up work, not implemented \
71         in slice B3. No write was attempted."
72    )))
73}
74
75// ---------------------------------------------------------------------------
76// create (AddEntity / AddNote)
77// ---------------------------------------------------------------------------
78
79/// Build the prepared plan for an `AddEntity` proposal change. The entity
80/// row and FTS document are committed together; vector indexing is deferred
81/// until after commit because embedding may suspend. `kind` must already be
82/// canonicalized by the caller because pack-aware resolution requires a
83/// `VerbRegistry`.
84pub async fn prepare_add_entity(
85    runtime: &KhiveRuntime,
86    token: &NamespaceToken,
87    args: &Value,
88) -> RuntimeResult<AtomicOpPlan> {
89    prepare_add_entity_record(runtime, token, args, None)
90        .await
91        .map(|(_, plan)| plan)
92}
93
94pub(crate) async fn prepare_add_entity_record(
95    runtime: &KhiveRuntime,
96    token: &NamespaceToken,
97    args: &Value,
98    canonical_id: Option<Uuid>,
99) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
100    let kind = require_str(args, "kind")?;
101    let name = require_str(args, "name")?;
102    runtime.validate_entity_kind(kind)?;
103    if name.trim().is_empty() {
104        return Err(RuntimeError::InvalidInput(
105            "name must not be empty".to_string(),
106        ));
107    }
108
109    let description = optional_create_string(args, "description")?;
110    let properties = optional_properties(args, "properties")?;
111    let tags = optional_tags(args)?.unwrap_or_default();
112
113    crate::secret_gate::check_at(name, "entity", "name")?;
114    if let Some(ref d) = description {
115        crate::secret_gate::check_at(d, "entity", "description")?;
116    }
117    if let Some(ref p) = properties {
118        crate::secret_gate::check_json_at(p, "entity", "properties")?;
119    }
120    crate::secret_gate::check_tags_at(&tags, "entity", "tags")?;
121    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
122
123    let ns = token.namespace().as_str();
124    let mut entity = khive_storage::Entity::new(ns, kind, name);
125    if let Some(id) = canonical_id {
126        entity.id = id;
127        entity.entity_type =
128            runtime.validate_entity_type_for_kind(kind, optional_str(args, "entity_type"))?;
129    }
130    if let Some(d) = description {
131        entity = entity.with_description(d);
132    }
133    if let Some(p) = properties {
134        entity = entity.with_properties(p);
135    }
136    if !tags.is_empty() {
137        entity = entity.with_tags(tags);
138    }
139
140    let plan = add_entity_plan(&entity, canonical_id.is_some())?;
141    Ok((entity, plan))
142}
143
144/// Prepare one fresh archive entity without regenerating its identity or timestamps.
145///
146/// The caller validates the complete archive vocabulary before preparing any plans.
147/// `PreserveUnknown` therefore retains an admitted kind and subtype verbatim; the
148/// pack's subtype normalizer is not an archive transformation. Destination-state
149/// checks and this plan's conditional insert are applied by the owning import unit.
150pub(crate) fn prepare_import_entity_record(
151    runtime: &KhiveRuntime,
152    token: &NamespaceToken,
153    entity: khive_storage::Entity,
154    policy: khive_types::ImportKindPolicy,
155) -> RuntimeResult<AtomicOpPlan> {
156    validate_import_entity_record(runtime, token, &entity, policy)?;
157    add_entity_plan(&entity, true)
158}
159
160/// Validate an exact archive entity without building a plan or accessing storage.
161pub(crate) fn validate_import_entity_record(
162    runtime: &KhiveRuntime,
163    token: &NamespaceToken,
164    entity: &khive_storage::Entity,
165    policy: khive_types::ImportKindPolicy,
166) -> RuntimeResult<()> {
167    if entity.namespace != token.namespace().as_str() {
168        return Err(RuntimeError::InvalidInput(
169            "import entity namespace must match the authorized namespace".into(),
170        ));
171    }
172    if entity.deleted_at.is_some()
173        || entity.merged_into.is_some()
174        || entity.merge_event_id.is_some()
175    {
176        return Err(RuntimeError::InvalidInput(
177            "import entity must be a live record without merge tombstone fields".into(),
178        ));
179    }
180    if entity.version != 1 || entity.content_ref.is_some() {
181        return Err(RuntimeError::InvalidInput(
182            "import entity must have revision one and no attachment projection".into(),
183        ));
184    }
185    if entity.kind.trim().is_empty() {
186        return Err(RuntimeError::InvalidInput(
187            "import entity kind must not be empty".into(),
188        ));
189    }
190    if entity.name.trim().is_empty() {
191        return Err(RuntimeError::InvalidInput("name must not be empty".into()));
192    }
193    if policy == khive_types::ImportKindPolicy::Strict {
194        runtime.validate_entity_kind(&entity.kind)?;
195    }
196    refuse_pack_registry_tags(&entity.tags, "import")?;
197    crate::secret_gate::check_at(&entity.name, "entity", "name")?;
198    if let Some(description) = &entity.description {
199        crate::secret_gate::check_at(description, "entity", "description")?;
200    }
201    if let Some(properties) = &entity.properties {
202        crate::secret_gate::check_json_at(properties, "entity", "properties")?;
203    }
204    crate::secret_gate::check_tags_at(&entity.tags, "entity", "tags")?;
205    crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
206
207    Ok(())
208}
209
210/// The plan of a canonical change-set create that names a key or aliases
211/// (ADR-221 sections 1 and 2). The aliases are projected onto `entity` before
212/// its row and text document are built, so both carry them, and they are
213/// written in the same unit. The key claim runs first under an exactly-one
214/// guard, so a key another live entity took after preparation rolls the whole
215/// change set back.
216pub(crate) fn canonical_entity_create_plan(
217    entity: &mut khive_storage::Entity,
218    key: Option<&str>,
219    aliases: &crate::EntityAliasChange,
220) -> RuntimeResult<AtomicOpPlan> {
221    let at = entity.created_at;
222    let (_, alias_statements, _) =
223        crate::operations::apply_entity_alias_change(entity, aliases, at, None);
224    let mut plan = add_entity_record_plan(entity, true)?;
225    if let Some(key) = key {
226        plan.statements.insert(
227            0,
228            PlanStatement {
229                statement: khive_db::stores::entity::entity_key_claim_statement(
230                    &entity.namespace,
231                    &entity.kind,
232                    key,
233                    entity.id,
234                    at,
235                ),
236                guard: Some(AffectedRowGuard::exactly(1)),
237            },
238        );
239    }
240    plan.statements
241        .extend(crate::operations::unguarded_alias_statements(
242            alias_statements,
243        ));
244    Ok(AtomicOpPlan::AddEntity(plan))
245}
246
247fn add_entity_plan(
248    entity: &khive_storage::Entity,
249    insert_if_absent: bool,
250) -> RuntimeResult<AtomicOpPlan> {
251    add_entity_record_plan(entity, insert_if_absent).map(AtomicOpPlan::AddEntity)
252}
253
254fn add_entity_record_plan(
255    entity: &khive_storage::Entity,
256    insert_if_absent: bool,
257) -> RuntimeResult<AddEntityPlan> {
258    // Keep the check at the write owner as well as the callers' early validation
259    // boundaries, which preserve their established refusal order.
260    crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
261    let mut statements = vec![PlanStatement {
262        statement: if insert_if_absent {
263            khive_db::stores::entity::entity_insert_if_absent_statement(entity)
264        } else {
265            entity_upsert_statement(entity)
266        },
267        guard: Some(AffectedRowGuard::exactly(1)),
268    }];
269    // Order-sensitive pair — see `insert_document_statements`'s adjacency
270    // contract: the map upsert's `last_insert_rowid()` must read back the
271    // FTS insert immediately before it.
272    for statement in insert_document_statements("fts_entities", &entity_fts_document(entity)) {
273        statements.push(PlanStatement {
274            statement,
275            guard: None,
276        });
277    }
278
279    Ok(AddEntityPlan {
280        entity_id: entity.id,
281        statements,
282        post_commit: PostCommitEffect::ReindexEntity {
283            entity_id: entity.id,
284        },
285    })
286}
287
288/// Build the prepared plan for an `AddNote` proposal change. Mirrors
289/// [`prepare_add_entity`]'s shape and the same
290/// `kind`-already-canonicalized split. `annotates` is out of scope: the
291/// proposal `NoteDraft` this backs carries no annotates targets, unlike
292/// `KhiveRuntime::create_note`'s general-purpose signature.
293pub async fn prepare_add_note(
294    runtime: &KhiveRuntime,
295    token: &NamespaceToken,
296    args: &Value,
297) -> RuntimeResult<AtomicOpPlan> {
298    prepare_add_note_record(runtime, token, args, None)
299        .await
300        .map(|(_, plan)| plan)
301}
302
303pub(crate) async fn prepare_add_note_record(
304    runtime: &KhiveRuntime,
305    token: &NamespaceToken,
306    args: &Value,
307    canonical_id: Option<Uuid>,
308) -> RuntimeResult<(khive_storage::Note, AtomicOpPlan)> {
309    let kind = require_str(args, "kind")?;
310    let content = require_str(args, "content")?;
311    runtime.validate_note_kind(kind)?;
312
313    let name = optional_create_string(args, "name")?;
314    let properties = optional_properties(args, "properties")?;
315    // Same note-write validator `create_note_inner` runs: this path builds its
316    // args itself and dispatches no pack hook, so without this call a proposal
317    // changeset would be the one note-write that stores caller-supplied owned
318    // identity properties verbatim. The token here is the applying caller's
319    // (threaded in by the apply worker), not the proposer's.
320    let properties = runtime.derive_note_write_properties(kind, token, properties)?;
321
322    crate::secret_gate::check_note_fields_at(
323        content,
324        name.as_deref(),
325        properties.as_ref(),
326        "note",
327    )?;
328    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
329
330    let ns = token.namespace().as_str();
331    let mut note = khive_storage::note::Note::new(ns, kind, content);
332    if let Some(id) = canonical_id {
333        note.id = id;
334        note.salience = optional_f64_patch(args, "salience")?.flatten();
335        note.decay_factor = optional_f64_patch(args, "decay_factor")?.flatten();
336        if note
337            .salience
338            .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
339            || note
340                .decay_factor
341                .is_some_and(|value| !value.is_finite() || value < 0.0)
342        {
343            return Err(RuntimeError::InvalidInput(
344                "invalid canonical note salience or decay_factor".into(),
345            ));
346        }
347    }
348    if let Some(n) = name {
349        note = note.with_name(n);
350    }
351    if let Some(p) = properties {
352        note = note.with_properties(p);
353    }
354
355    let mut statements = vec![PlanStatement {
356        statement: if canonical_id.is_some() {
357            khive_db::stores::note::note_insert_if_absent_statement(&note)
358        } else {
359            note_upsert_statement(&note)
360        },
361        guard: Some(AffectedRowGuard::exactly(1)),
362    }];
363    // Order-sensitive pair — see `insert_document_statements`'s adjacency
364    // contract.
365    for statement in insert_document_statements("fts_notes", &note_fts_document(&note)) {
366        statements.push(PlanStatement {
367            statement,
368            guard: None,
369        });
370    }
371
372    Ok((
373        note.clone(),
374        AtomicOpPlan::AddNote(Box::new(AddNotePlan {
375            note_guard: None,
376            note_id: note.id,
377            statements,
378            post_commit: PostCommitEffect::ReindexNote {
379                note_id: note.id,
380                version: note.version,
381            },
382        })),
383    ))
384}
385
386// ---------------------------------------------------------------------------
387// update
388// ---------------------------------------------------------------------------
389
390/// Mirrors `khive-pack-kg::handlers::update::reject_inapplicable_fields`: a
391/// hard `InvalidInput` when a caller passes a field that does not apply to
392/// the resolved substrate (e.g. `salience` on an entity, or
393/// `description` on a note). That function has no dependency edge
394/// back to `khive-runtime`, so its exact field-applicability check list and
395/// error message shape are reimplemented here rather than imported: same
396/// pattern as `optional_string_patch` above. Presence is checked directly on
397/// the raw args object (this module has no `UpdateParams` struct). Nullable
398/// description, salience, decay_factor, and entity_type preserve key presence;
399/// the remaining field checks retain their existing rules.
400pub(super) fn reject_inapplicable_update_fields(
401    args: &Value,
402    substrate: &str,
403) -> RuntimeResult<()> {
404    let o = obj(args)?;
405    if substrate == "edge" && o.get("expected_version").is_some_and(|v| !v.is_null()) {
406        return Err(RuntimeError::InvalidInput(
407            "expected_version applies only to entities and notes".into(),
408        ));
409    }
410    if substrate != "note"
411        && ["embed", "fence"]
412            .iter()
413            .any(|field| o.contains_key(*field))
414    {
415        return Err(RuntimeError::InvalidInput(
416            "embed and fence apply only to notes".into(),
417        ));
418    }
419    let present = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
420    let (bad_field, valid): (Option<&str>, &str) = match substrate {
421        "entity" => {
422            let bad = if present("content") {
423                Some("content")
424            } else if o.contains_key("salience") {
425                Some("salience")
426            } else if o.contains_key("decay_factor") {
427                Some("decay_factor")
428            } else if present("relation") {
429                Some("relation")
430            } else if present("weight") {
431                Some("weight")
432            } else {
433                None
434            };
435            (
436                bad,
437                "name, description, tags, properties, entity_type, add_aliases, remove_aliases, keep_old_name",
438            )
439        }
440        "note" => {
441            let bad = if o.contains_key("description") {
442                Some("description")
443            } else if present("add_aliases") {
444                Some("add_aliases")
445            } else if present("remove_aliases") {
446                Some("remove_aliases")
447            } else if present("keep_old_name") {
448                Some("keep_old_name")
449            } else if present("relation") {
450                Some("relation")
451            } else if present("weight") {
452                Some("weight")
453            } else if o.contains_key("entity_type") {
454                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
455                // the explicit clear) is inapplicable to notes.
456                Some("entity_type")
457            } else {
458                None
459            };
460            (
461                bad,
462                "name, content, salience, decay_factor, properties, tags",
463            )
464        }
465        // `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, so
466        // this arm must reject entity/note-only fields (e.g. `name`) on an
467        // edge update rather than silently skip the guard, mirroring
468        // `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
469        // `KindSpec::Edge` arm.
470        "edge" => {
471            let bad = if present("name") {
472                Some("name")
473            } else if o.contains_key("description") {
474                Some("description")
475            } else if present("content") {
476                Some("content")
477            } else if present("tags") {
478                Some("tags")
479            } else if present("add_aliases") {
480                Some("add_aliases")
481            } else if present("remove_aliases") {
482                Some("remove_aliases")
483            } else if present("keep_old_name") {
484                Some("keep_old_name")
485            } else if o.contains_key("salience") {
486                Some("salience")
487            } else if o.contains_key("decay_factor") {
488                Some("decay_factor")
489            } else if o.contains_key("entity_type") {
490                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
491                // the explicit clear) is inapplicable to edges.
492                Some("entity_type")
493            } else {
494                None
495            };
496            (bad, "relation, weight, properties")
497        }
498        _ => (None, ""),
499    };
500    if let Some(field) = bad_field {
501        let substrate_label = match substrate {
502            "entity" => "an entity",
503            "note" => "a note",
504            "edge" => "an edge",
505            other => other,
506        };
507        return Err(RuntimeError::InvalidInput(format!(
508            "field '{field}' is not valid for {substrate_label}; valid fields: {valid}"
509        )));
510    }
511    Ok(())
512}
513
514/// Caller-supplied update-kind expectation, resolved via the canonical
515/// `resolve_kind_spec` at the kkernel `--atomic` seam: the same pattern
516/// [`AtomicDeleteKind`] uses. Without this check, `update(kind="document",
517/// id=<concept>)` would be canonically `NotFound` but the atomic path would
518/// ignore the explicit kind and mutate the resolved entity anyway.
519/// `khive-runtime` must not depend on `khive-pack-kg`, so this is a plain
520/// substrate-level shape rather than `khive_pack_kg::handlers::KindSpec`
521/// itself: the kkernel seam does the pack-aware resolution and passes down
522/// only what `prepare_update` needs to enforce the mismatch check.
523pub enum AtomicUpdateKind {
524    Entity {
525        specific: Option<String>,
526        entity_type: Option<String>,
527    },
528    Note {
529        specific: Option<String>,
530    },
531    Edge,
532}
533
534/// Enforce a caller's explicit update-kind discriminator against a resolved
535/// note before any pack hook can inspect or normalize the request. Canonical
536/// KG dispatch performs this mismatch check before its hook; the atomic
537/// adapter calls this same helper to preserve that error ordering.
538pub fn validate_note_update_expected_kind(
539    note: &khive_storage::note::Note,
540    expected_kind: &Option<AtomicUpdateKind>,
541) -> RuntimeResult<()> {
542    let id = note.id;
543    match expected_kind {
544        None => Ok(()),
545        Some(AtomicUpdateKind::Note {
546            specific: Some(expected),
547        }) if &note.kind != expected => Err(RuntimeError::NotFound(format!("note {id}"))),
548        Some(AtomicUpdateKind::Note { .. }) => Ok(()),
549        Some(AtomicUpdateKind::Entity { .. }) => {
550            Err(RuntimeError::NotFound(format!("entity {id}")))
551        }
552        Some(AtomicUpdateKind::Edge) => Err(RuntimeError::NotFound(format!("edge {id}"))),
553    }
554}
555
556async fn prepare_note_update_plan_from_snapshot(
557    runtime: &KhiveRuntime,
558    token: &NamespaceToken,
559    args: &Value,
560    expected_kind: &Option<AtomicUpdateKind>,
561    note: khive_storage::note::Note,
562    policy: crate::NoteUpdatePolicy,
563    registry: Option<&crate::VerbRegistry>,
564) -> RuntimeResult<(khive_storage::Note, UpdatePlan)> {
565    let id = require_uuid(args, "id")?;
566    if note.id != id {
567        return Err(RuntimeError::NotFound(format!("note {id}")));
568    }
569    validate_note_update_expected_kind(&note, expected_kind)?;
570
571    reject_inapplicable_update_fields(args, "note")?;
572    let mut normalized_args = args.clone();
573    crate::curation::normalize_note_update_tags(&mut normalized_args)?;
574    let args = &normalized_args;
575    let name = optional_string_patch(args, "name")?;
576    let content = optional_str(args, "content").map(str::to_string);
577    let properties = optional_properties(args, "properties")?;
578    let salience = optional_f64_patch(args, "salience")?;
579    let decay_factor = optional_f64_patch(args, "decay_factor")?;
580    let options = crate::note_write::NoteWriteOptions {
581        expected_version: obj(args)?
582            .get("expected_version")
583            .filter(|v| !v.is_null())
584            .map(|v| {
585                v.as_i64().ok_or_else(|| {
586                    RuntimeError::InvalidInput("expected_version must be an integer".into())
587                })
588            })
589            .transpose()?,
590        fence: obj(args)?
591            .get("fence")
592            .map(|v| {
593                serde_json::from_value(v.clone())
594                    .map_err(|error| RuntimeError::InvalidInput(format!("invalid fence: {error}")))
595            })
596            .transpose()?,
597        embed: obj(args)?
598            .get("embed")
599            .filter(|v| !v.is_null())
600            .map(|v| {
601                v.as_bool()
602                    .ok_or_else(|| RuntimeError::InvalidInput("embed must be boolean".into()))
603            })
604            .transpose()?,
605        key: None,
606    };
607    let patch = crate::curation::NotePatch::new(name, content, salience, decay_factor, properties)
608        .with_update_policy(policy)
609        .with_write_options(options);
610    let (updated, mut plan) = runtime
611        .prepare_versioned_note_update(token, note.clone(), patch.clone())
612        .await?;
613    if let Some(registry) = registry {
614        attach_note_update_effects(runtime, token, registry, &note, &patch, &mut plan).await?;
615    }
616    Ok((updated, plan))
617}
618
619/// Build an atomic update plan from the exact note snapshot already supplied
620/// to a pack update hook. Persistence is guarded by that snapshot's revision
621/// and deletion marker, so hook normalization cannot race a second read. The
622/// caller must first run the registry normalizer/validator against this snapshot.
623/// This shared canonical/atomic seam prepares all patch fields with the owning
624/// kind's property policy (the value `VerbRegistry::prepare_note_update_policy`
625/// returned for this snapshot), then derives and attaches the owner's typed
626/// graph effects. It returns the projected note and one atomic plan, preserving
627/// the caller's operation index.
628pub async fn prepare_update_from_note_snapshot(
629    runtime: &KhiveRuntime,
630    token: &NamespaceToken,
631    args: &Value,
632    expected_kind: Option<AtomicUpdateKind>,
633    note: khive_storage::note::Note,
634    policy: crate::NoteUpdatePolicy,
635    registry: &crate::VerbRegistry,
636) -> RuntimeResult<(khive_storage::Note, AtomicOpPlan)> {
637    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
638        return Err(RuntimeError::InvalidInput(
639            "entity_kind is immutable; to change kind, delete then re-create the entity, \
640             or use merge() if this is a deduplication correction"
641                .into(),
642        ));
643    }
644    let (note, plan) = prepare_note_update_plan_from_snapshot(
645        runtime,
646        token,
647        args,
648        &expected_kind,
649        note,
650        policy,
651        Some(registry),
652    )
653    .await?;
654    Ok((note, AtomicOpPlan::Update(Box::new(plan))))
655}
656
657/// The only companion attachment site. Canonical, CLI atomic, and stream note
658/// updates all enter through `prepare_update_from_note_snapshot` after running
659/// the registry's normalizer/validator on the same snapshot.
660pub(crate) async fn attach_note_update_effects(
661    runtime: &KhiveRuntime,
662    token: &NamespaceToken,
663    registry: &crate::VerbRegistry,
664    snapshot: &khive_storage::Note,
665    patch: &crate::curation::NotePatch,
666    plan: &mut UpdatePlan,
667) -> RuntimeResult<()> {
668    use crate::atomic_plan::NoteUpdateStatement;
669    use crate::NoteUpdateEffect;
670
671    let Some(hook) = registry.find_kind_hook(&snapshot.kind) else {
672        return Ok(());
673    };
674    // Refuse already-known stale input before asking the owner to derive effects.
675    // A change after this read remains protected by the note's first CAS statement.
676    if let Some(expected) = patch.write_options.expected_version {
677        if expected != snapshot.version {
678            return Err(crate::note_write::NoteWriteConflict::Version {
679                expected,
680                current: snapshot.version,
681            }
682            .into_error()
683            .into());
684        }
685    }
686    let current = runtime.notes(token)?.get_note(snapshot.id).await?;
687    if !current.is_some_and(|current| {
688        current.updated_at == snapshot.updated_at
689            && current.deleted_at == snapshot.deleted_at
690            && current.version == snapshot.version
691    }) {
692        return Err(crate::curation::stale_note_snapshot_error(snapshot.id));
693    }
694    let effects = hook
695        .note_update_effects(runtime, token, snapshot, patch)
696        .await?;
697    if plan.idempotent_noop && !effects.is_empty() {
698        return Err(RuntimeError::InvalidInput(
699            "an unchanged note update cannot carry graph effects".into(),
700        ));
701    }
702    let edge_token = token.with_namespace(
703        crate::Namespace::parse(&snapshot.namespace)
704            .map_err(|error| RuntimeError::Internal(format!("invalid note namespace: {error}")))?,
705    );
706    for effect in effects {
707        match effect {
708            NoteUpdateEffect::Link(spec) => {
709                if spec.source_id != snapshot.id
710                    || spec
711                        .namespace
712                        .as_deref()
713                        .is_some_and(|ns| ns != snapshot.namespace)
714                {
715                    return Err(RuntimeError::InvalidInput(
716                        "note update links must originate from the note in its namespace".into(),
717                    ));
718                }
719                let mut args = serde_json::json!({
720                    "source_id": spec.source_id, "target_id": spec.target_id,
721                    "relation": spec.relation, "weight": spec.weight,
722                    "resurrect": spec.resurrect,
723                });
724                if let Some(metadata) = spec.metadata {
725                    args["metadata"] = metadata;
726                }
727                let AtomicOpPlan::Link(link) = prepare_link(runtime, &edge_token, &args).await?
728                else {
729                    return Err(RuntimeError::Internal("expected a link plan".into()));
730                };
731                // A live annotation inserted between the owner's read and this
732                // lookup belongs to that writer. Refuse instead of replacing its
733                // weight/metadata; a fresh preparation can preserve it explicitly.
734                if link.disposition == EdgeUpsertDisposition::Updated {
735                    return Err(khive_types::KhiveError::conflict(
736                        "a live edge appeared while preparing the note update; retry with fresh state",
737                    ).into());
738                }
739                plan.graph_effects
740                    .extend(link.statements.into_iter().map(NoteUpdateStatement::Write));
741            }
742            NoteUpdateEffect::DeleteEdge(edge) => {
743                let id = Uuid::from(edge.id);
744                if edge.source_id != snapshot.id
745                    || edge.namespace != snapshot.namespace
746                    || edge.deleted_at.is_some()
747                {
748                    return Err(RuntimeError::InvalidInput(
749                        "note update deletes must select an outgoing edge in the note namespace"
750                            .into(),
751                    ));
752                }
753                plan.graph_effects
754                    .push(NoteUpdateStatement::Assert(PlanStatement {
755                        statement: khive_db::stores::graph::edge_snapshot_assertion_statement(
756                            &edge, false,
757                        ),
758                        guard: Some(AffectedRowGuard::exactly(1)),
759                    }));
760                let actor = format!("{}:{}", token.actor().kind, token.actor().id);
761                let AtomicOpPlan::Delete(delete) =
762                    prepare_delete_edge(&edge_token, id, edge, false, &actor).await?
763                else {
764                    return Err(RuntimeError::Internal(
765                        "expected an edge delete plan".into(),
766                    ));
767                };
768                if delete.post_commit != PostCommitEffect::None {
769                    return Err(RuntimeError::Internal(
770                        "edge delete has a deferred effect".into(),
771                    ));
772                }
773                plan.graph_effects.extend(
774                    delete
775                        .statements
776                        .into_iter()
777                        .map(NoteUpdateStatement::Write),
778                );
779            }
780            NoteUpdateEffect::AssertLink(edge) => {
781                if edge.source_id != snapshot.id
782                    || edge.namespace != snapshot.namespace
783                    || edge.deleted_at.is_some()
784                {
785                    return Err(RuntimeError::InvalidInput(
786                        "note update assertions must select a live outgoing edge in the note namespace".into(),
787                    ));
788                }
789                plan.graph_effects
790                    .push(NoteUpdateStatement::Assert(PlanStatement {
791                        statement: khive_db::stores::graph::edge_snapshot_assertion_statement(
792                            &edge, true,
793                        ),
794                        guard: Some(AffectedRowGuard::exactly(1)),
795                    }));
796            }
797        }
798    }
799    Ok(())
800}
801
802/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
803/// with canonical's own optional discriminator); `Some(_)` enforces an
804/// exact-parity mismatch check against the resolved record's actual
805/// substrate/specific kind, mirroring `handle_update`'s
806/// `entity.kind != *k` / note kind checks (update.rs:200-201, :229-234).
807/// Task notes must pass the GTD pack hook before this or
808/// `prepare_op("update", ..)`; neither runs it.
809pub async fn prepare_update(
810    runtime: &KhiveRuntime,
811    token: &NamespaceToken,
812    args: &Value,
813    expected_kind: Option<AtomicUpdateKind>,
814) -> RuntimeResult<AtomicOpPlan> {
815    let id = require_uuid(args, "id")?;
816
817    // Mirrors update.rs's entity_kind immutability guard: entity_kind is a
818    // legacy top-level field, independent of the `kind` substrate
819    // discriminator handled elsewhere.
820    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
821        return Err(RuntimeError::InvalidInput(
822            "entity_kind is immutable; to change kind, delete then re-create the entity, \
823             or use merge() if this is a deduplication correction"
824                .into(),
825        ));
826    }
827
828    // ADR-221 section 2: every alias is validated and secret-gated before
829    // the target is read, as the kg update handler does.
830    let keep_old_name = match obj(args)?.get("keep_old_name") {
831        None | Some(Value::Null) => true,
832        Some(Value::Bool(keep)) => *keep,
833        Some(_) => {
834            return Err(RuntimeError::InvalidInput(
835                "keep_old_name must be a boolean".into(),
836            ))
837        }
838    };
839    let aliases = crate::EntityAliasChange::update(
840        &optional_alias_list(args, "add_aliases")?,
841        &optional_alias_list(args, "remove_aliases")?,
842    )?
843    .keeping_old_name(keep_old_name);
844
845    match runtime.resolve_by_id(token, id).await? {
846        Some(Resolved::Entity(entity)) => {
847            match &expected_kind {
848                None => {}
849                Some(AtomicUpdateKind::Entity {
850                    specific: Some(expected),
851                    ..
852                }) if &entity.kind != expected => {
853                    return Err(RuntimeError::NotFound(format!("entity {id}")));
854                }
855                Some(AtomicUpdateKind::Entity { .. }) => {}
856                Some(AtomicUpdateKind::Note { .. }) => {
857                    return Err(RuntimeError::NotFound(format!("note {id}")));
858                }
859                Some(AtomicUpdateKind::Edge) => {
860                    return Err(RuntimeError::NotFound(format!("edge {id}")));
861                }
862            }
863            if let Some(AtomicUpdateKind::Entity {
864                entity_type: Some(expected),
865                ..
866            }) = &expected_kind
867            {
868                if entity
869                    .entity_type
870                    .as_deref()
871                    .is_some_and(|actual| actual != expected.as_str())
872                {
873                    return Err(RuntimeError::NotFound(format!("entity {id}")));
874                }
875            }
876            refuse_pack_registry_tags(&entity.tags, "update")?;
877            // Decide step lives in curation.rs's `prepare_update_entity_with_previous_name` —
878            // the SAME function canonical `update_entity` calls. Only the
879            // arg-extraction (raw JSON -> `EntityPatch`) and the plan-shape
880            // wiring are atomic-path-specific: the domain object becomes a
881            // `PlanStatement` via `entity_replace_if_unchanged_statement`,
882            // whose CAS predicate binds the snapshot's revision and deletion
883            // marker, under an exactly-one affected-row guard.
884            reject_inapplicable_update_fields(args, "entity")?;
885            let name = entity_name_patch(args)?;
886            let description = optional_entity_type_patch(args, "description")?;
887            let properties = optional_properties(args, "properties")?;
888            let tags = optional_tags(args)?;
889            if let Some(ref tags) = tags {
890                refuse_pack_registry_tags(tags, "update")?;
891            }
892            let entity_type = optional_entity_type_patch(args, "entity_type")?;
893
894            let expected_version = obj(args)?
895                .get("expected_version")
896                .filter(|v| !v.is_null())
897                .map(|value| {
898                    value.as_i64().ok_or_else(|| {
899                        RuntimeError::InvalidInput("expected_version must be an integer".into())
900                    })
901                })
902                .transpose()?;
903            let required_entity_type = match &expected_kind {
904                Some(AtomicUpdateKind::Entity { entity_type, .. }) => entity_type.as_deref(),
905                _ => None,
906            };
907            prepare_update_entity_record_with_version_and_type(
908                runtime,
909                token,
910                id,
911                crate::curation::EntityPatch {
912                    name,
913                    description,
914                    properties,
915                    tags,
916                    entity_type,
917                },
918                &[],
919                &aliases,
920                expected_version,
921                required_entity_type,
922            )
923            .await
924            .map(|(_, plan)| plan)
925        }
926        Some(Resolved::Note(note)) => {
927            // Patch application lives in curation.rs's
928            // `prepare_update_note_from_snapshot` — the same implementation
929            // canonical guarded update calls, including salience/decay range
930            // validation. The plan retains this exact snapshot's revision.
931            let (_, plan) = prepare_note_update_plan_from_snapshot(
932                runtime,
933                token,
934                args,
935                &expected_kind,
936                note,
937                crate::NoteUpdatePolicy::default(),
938                None,
939            )
940            .await?;
941            Ok(AtomicOpPlan::Update(Box::new(plan)))
942        }
943        Some(_) => Err(RuntimeError::InvalidInput(format!(
944            "update target {id} must be an entity, note, or edge"
945        ))),
946        // `Resolved` (khive-runtime::operations) has no `Edge` variant — an
947        // id that isn't an entity/note/pack-private/event record is checked
948        // against the graph store directly, mirroring
949        // `khive-pack-kg::handlers::KgPack::infer_kind_from_uuid`'s own
950        // entity/note-then-edge fallback order. `update` admits
951        // `kind="edge"`, so this arm must be able to build a plan for one.
952        None => match &expected_kind {
953            Some(AtomicUpdateKind::Entity { .. }) => {
954                Err(RuntimeError::NotFound(format!("entity/note {id}")))
955            }
956            Some(AtomicUpdateKind::Note { .. }) => {
957                Err(RuntimeError::NotFound(format!("entity/note {id}")))
958            }
959            Some(AtomicUpdateKind::Edge) | None => match runtime.get_edge(token, id).await? {
960                Some(edge) => prepare_update_edge(runtime, token, id, edge, args).await,
961                None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
962            },
963        },
964    }
965}
966
967/// Build an entity update plan from a typed patch. Proposal changesets use
968/// this entry point to preserve the typed patch directly, without translating
969/// it through raw verb parameters. `aliases` carries the caller's choice of
970/// whether a rename keeps the old name (ADR-221 section 3).
971pub async fn prepare_update_entity_plan(
972    runtime: &KhiveRuntime,
973    token: &NamespaceToken,
974    id: Uuid,
975    patch: crate::curation::EntityPatch,
976    aliases: &crate::EntityAliasChange,
977) -> RuntimeResult<AtomicOpPlan> {
978    prepare_update_entity_plan_with_version(runtime, token, id, patch, aliases, None).await
979}
980
981pub(super) async fn prepare_update_entity_plan_with_version_and_type(
982    runtime: &KhiveRuntime,
983    token: &NamespaceToken,
984    id: Uuid,
985    patch: crate::curation::EntityPatch,
986    aliases: &crate::EntityAliasChange,
987    expected_version: Option<i64>,
988    required_entity_type: Option<&str>,
989) -> RuntimeResult<AtomicOpPlan> {
990    prepare_update_entity_record_with_version_and_type(
991        runtime,
992        token,
993        id,
994        patch,
995        &[],
996        aliases,
997        expected_version,
998        required_entity_type,
999    )
1000    .await
1001    .map(|(_, plan)| plan)
1002}
1003
1004/// An `add_aliases` or `remove_aliases` list: absent or `null` is empty.
1005fn optional_alias_list(args: &Value, field: &str) -> RuntimeResult<Vec<String>> {
1006    let invalid = || RuntimeError::InvalidInput(format!("{field} must be an array of strings"));
1007    match obj(args)?.get(field) {
1008        None | Some(Value::Null) => Ok(Vec::new()),
1009        Some(Value::Array(items)) => items
1010            .iter()
1011            .map(|item| item.as_str().map(str::to_owned).ok_or_else(invalid))
1012            .collect(),
1013        Some(_) => Err(invalid()),
1014    }
1015}
1016
1017/// Return the canonical prepared record together with the plan bound to it.
1018///
1019/// Import uses this projection for endpoint validation without applying the
1020/// patch or invoking kind hooks again. Its version remains the captured row
1021/// revision; applying the plan advances the persisted revision once.
1022/// `aliases` carries the caller's choice of whether a rename keeps the old
1023/// name (ADR-221 section 3).
1024pub(crate) async fn prepare_update_entity_record(
1025    runtime: &KhiveRuntime,
1026    token: &NamespaceToken,
1027    id: Uuid,
1028    patch: crate::curation::EntityPatch,
1029    aliases: &crate::EntityAliasChange,
1030    expected_version: Option<i64>,
1031) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
1032    prepare_update_entity_record_with_version_and_type(
1033        runtime,
1034        token,
1035        id,
1036        patch,
1037        &[],
1038        aliases,
1039        expected_version,
1040        None,
1041    )
1042    .await
1043}
1044
1045/// The update a keyed reload joins to a bulk create's unit (ADR-221
1046/// section 1): `patch` applied, then the caller property keys in
1047/// `remove_properties` dropped and the caller aliases replaced by `aliases`,
1048/// bound to `expected_version` so a holder that changed since it was read
1049/// rolls the unit back. The returned record's version is the captured one;
1050/// applying the plan advances it once.
1051pub(crate) async fn prepare_keyed_reload_entity_record(
1052    runtime: &KhiveRuntime,
1053    token: &NamespaceToken,
1054    id: Uuid,
1055    patch: crate::curation::EntityPatch,
1056    remove_properties: &[&str],
1057    expected_version: i64,
1058    aliases: &crate::EntityAliasChange,
1059) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
1060    prepare_update_entity_record_with_version_and_type(
1061        runtime,
1062        token,
1063        id,
1064        patch,
1065        remove_properties,
1066        aliases,
1067        Some(expected_version),
1068        None,
1069    )
1070    .await
1071}
1072
1073#[allow(clippy::too_many_arguments)]
1074async fn prepare_update_entity_record_with_version_and_type(
1075    runtime: &KhiveRuntime,
1076    token: &NamespaceToken,
1077    id: Uuid,
1078    patch: crate::curation::EntityPatch,
1079    remove_properties: &[&str],
1080    aliases: &crate::EntityAliasChange,
1081    expected_version: Option<i64>,
1082    required_entity_type: Option<&str>,
1083) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
1084    crate::entity_write::validate_expected_version(expected_version)?;
1085    let alias_only = patch.is_empty() && remove_properties.is_empty() && !aliases.is_empty();
1086    let explicit_entity_type_patch = patch.entity_type.is_some();
1087    let (
1088        (
1089            mut entity,
1090            mut reindex_required,
1091            mut changed_fields,
1092            expected_updated_at,
1093            expected_deleted_at,
1094        ),
1095        previous_name,
1096    ) = runtime
1097        .prepare_update_entity_with_previous_name(token, id, patch, remove_properties)
1098        .await?;
1099    if required_entity_type.is_some_and(|expected| {
1100        (explicit_entity_type_patch || entity.entity_type.is_some())
1101            && entity.entity_type.as_deref() != Some(expected)
1102    }) {
1103        return Err(RuntimeError::InvalidInput(
1104            "kind subtype contradicts the requested entity_type update".into(),
1105        ));
1106    }
1107    // ADR-221 section 2: the alias change lands on the row whose name is
1108    // final, and reindexes the entity as a name change does.
1109    let updated_at = entity.updated_at;
1110    let (aliases_changed, alias_statements, _) = crate::operations::apply_entity_alias_change(
1111        &mut entity,
1112        aliases,
1113        updated_at,
1114        Some(&previous_name),
1115    );
1116    if aliases_changed {
1117        reindex_required = true;
1118        changed_fields.push("aliases");
1119    }
1120    // An update that asks only for alias changes and changes none writes
1121    // nothing: the plan only asserts the row is still the one read.
1122    if alias_only
1123        && !aliases_changed
1124        && expected_version.is_none_or(|expected| expected == entity.version)
1125    {
1126        entity.updated_at = expected_updated_at;
1127        entity.deleted_at = expected_deleted_at;
1128        let plan = crate::canonical_apply::unchanged_entity_assertion_plan(
1129            &entity,
1130            "alias-noop-assertion",
1131        );
1132        return Ok((entity, plan));
1133    }
1134    let mut statements = vec![PlanStatement {
1135        statement: entity_replace_if_unchanged_statement(
1136            &entity,
1137            expected_updated_at,
1138            expected_deleted_at,
1139        ),
1140        guard: Some(AffectedRowGuard::exactly(1)),
1141    }];
1142    statements.extend(crate::operations::unguarded_alias_statements(
1143        alias_statements,
1144    ));
1145    statements.extend(event_append_statements(
1146        token,
1147        &entity.namespace,
1148        "update",
1149        EventKind::EntityUpdated,
1150        SubstrateKind::Entity,
1151        id,
1152        crate::operations::entity_updated_payload(&entity, &changed_fields, Some(&previous_name)),
1153    )?);
1154    let post_commit = if reindex_required {
1155        PostCommitEffect::ReindexEntity { entity_id: id }
1156    } else {
1157        PostCommitEffect::None
1158    };
1159    let plan = AtomicOpPlan::Update(Box::new(UpdatePlan {
1160        graph_effects: Vec::new(),
1161        note_vector_purge: None,
1162        note_embedding_inheritance: None,
1163        entity_guard: expected_version.map(|expected_version| {
1164            crate::entity_write::EntityWriteGuard {
1165                id,
1166                expected_version,
1167            }
1168        }),
1169        note_guard: None,
1170        target_id: id,
1171        statements,
1172        post_commit,
1173        edge_natural_key: None,
1174        idempotent_noop: false,
1175    }));
1176    Ok((entity, plan))
1177}