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
210fn add_entity_plan(
211    entity: &khive_storage::Entity,
212    insert_if_absent: bool,
213) -> RuntimeResult<AtomicOpPlan> {
214    // Keep the check at the write owner as well as the callers' early validation
215    // boundaries, which preserve their established refusal order.
216    crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
217    let mut statements = vec![PlanStatement {
218        statement: if insert_if_absent {
219            khive_db::stores::entity::entity_insert_if_absent_statement(entity)
220        } else {
221            entity_upsert_statement(entity)
222        },
223        guard: Some(AffectedRowGuard::exactly(1)),
224    }];
225    // Order-sensitive pair — see `insert_document_statements`'s adjacency
226    // contract: the map upsert's `last_insert_rowid()` must read back the
227    // FTS insert immediately before it.
228    for statement in insert_document_statements("fts_entities", &entity_fts_document(entity)) {
229        statements.push(PlanStatement {
230            statement,
231            guard: None,
232        });
233    }
234
235    Ok(AtomicOpPlan::AddEntity(AddEntityPlan {
236        entity_id: entity.id,
237        statements,
238        post_commit: PostCommitEffect::ReindexEntity {
239            entity_id: entity.id,
240        },
241    }))
242}
243
244/// Build the prepared plan for an `AddNote` proposal change. Mirrors
245/// [`prepare_add_entity`]'s shape and the same
246/// `kind`-already-canonicalized split. `annotates` is out of scope: the
247/// proposal `NoteDraft` this backs carries no annotates targets, unlike
248/// `KhiveRuntime::create_note`'s general-purpose signature.
249pub async fn prepare_add_note(
250    runtime: &KhiveRuntime,
251    token: &NamespaceToken,
252    args: &Value,
253) -> RuntimeResult<AtomicOpPlan> {
254    prepare_add_note_record(runtime, token, args, None)
255        .await
256        .map(|(_, plan)| plan)
257}
258
259pub(crate) async fn prepare_add_note_record(
260    runtime: &KhiveRuntime,
261    token: &NamespaceToken,
262    args: &Value,
263    canonical_id: Option<Uuid>,
264) -> RuntimeResult<(khive_storage::Note, AtomicOpPlan)> {
265    let kind = require_str(args, "kind")?;
266    let content = require_str(args, "content")?;
267    runtime.validate_note_kind(kind)?;
268
269    let name = optional_create_string(args, "name")?;
270    let properties = optional_properties(args, "properties")?;
271    // Same note-write validator `create_note_inner` runs: this path builds its
272    // args itself and dispatches no pack hook, so without this call a proposal
273    // changeset would be the one note-write that stores caller-supplied owned
274    // identity properties verbatim. The token here is the applying caller's
275    // (threaded in by the apply worker), not the proposer's.
276    let properties = runtime.derive_note_write_properties(kind, token, properties)?;
277
278    crate::secret_gate::check_note_fields_at(
279        content,
280        name.as_deref(),
281        properties.as_ref(),
282        "note",
283    )?;
284    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
285
286    let ns = token.namespace().as_str();
287    let mut note = khive_storage::note::Note::new(ns, kind, content);
288    if let Some(id) = canonical_id {
289        note.id = id;
290        note.salience = optional_f64_patch(args, "salience")?.flatten();
291        note.decay_factor = optional_f64_patch(args, "decay_factor")?.flatten();
292        if note
293            .salience
294            .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
295            || note
296                .decay_factor
297                .is_some_and(|value| !value.is_finite() || value < 0.0)
298        {
299            return Err(RuntimeError::InvalidInput(
300                "invalid canonical note salience or decay_factor".into(),
301            ));
302        }
303    }
304    if let Some(n) = name {
305        note = note.with_name(n);
306    }
307    if let Some(p) = properties {
308        note = note.with_properties(p);
309    }
310
311    let mut statements = vec![PlanStatement {
312        statement: if canonical_id.is_some() {
313            khive_db::stores::note::note_insert_if_absent_statement(&note)
314        } else {
315            note_upsert_statement(&note)
316        },
317        guard: Some(AffectedRowGuard::exactly(1)),
318    }];
319    // Order-sensitive pair — see `insert_document_statements`'s adjacency
320    // contract.
321    for statement in insert_document_statements("fts_notes", &note_fts_document(&note)) {
322        statements.push(PlanStatement {
323            statement,
324            guard: None,
325        });
326    }
327
328    Ok((
329        note.clone(),
330        AtomicOpPlan::AddNote(Box::new(AddNotePlan {
331            note_guard: None,
332            note_id: note.id,
333            statements,
334            post_commit: PostCommitEffect::ReindexNote {
335                note_id: note.id,
336                version: note.version,
337            },
338        })),
339    ))
340}
341
342// ---------------------------------------------------------------------------
343// update
344// ---------------------------------------------------------------------------
345
346/// Mirrors `khive-pack-kg::handlers::update::reject_inapplicable_fields`: a
347/// hard `InvalidInput` when a caller passes a field that does not apply to
348/// the resolved substrate (e.g. `salience` on an entity, or
349/// `description` on a note). That function has no dependency edge
350/// back to `khive-runtime`, so its exact field-applicability check list and
351/// error message shape are reimplemented here rather than imported: same
352/// pattern as `optional_string_patch` above. Presence is checked directly on
353/// the raw args object (this module has no `UpdateParams` struct). Nullable
354/// description, salience, decay_factor, and entity_type preserve key presence;
355/// the remaining field checks retain their existing rules.
356pub(super) fn reject_inapplicable_update_fields(
357    args: &Value,
358    substrate: &str,
359) -> RuntimeResult<()> {
360    let o = obj(args)?;
361    if substrate == "edge" && o.get("expected_version").is_some_and(|v| !v.is_null()) {
362        return Err(RuntimeError::InvalidInput(
363            "expected_version applies only to entities and notes".into(),
364        ));
365    }
366    if substrate != "note"
367        && ["embed", "fence"]
368            .iter()
369            .any(|field| o.contains_key(*field))
370    {
371        return Err(RuntimeError::InvalidInput(
372            "embed and fence apply only to notes".into(),
373        ));
374    }
375    let present = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
376    let (bad_field, valid): (Option<&str>, &str) = match substrate {
377        "entity" => {
378            let bad = if present("content") {
379                Some("content")
380            } else if o.contains_key("salience") {
381                Some("salience")
382            } else if o.contains_key("decay_factor") {
383                Some("decay_factor")
384            } else if present("relation") {
385                Some("relation")
386            } else if present("weight") {
387                Some("weight")
388            } else {
389                None
390            };
391            (bad, "name, description, tags, properties, entity_type")
392        }
393        "note" => {
394            let bad = if o.contains_key("description") {
395                Some("description")
396            } else if present("relation") {
397                Some("relation")
398            } else if present("weight") {
399                Some("weight")
400            } else if o.contains_key("entity_type") {
401                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
402                // the explicit clear) is inapplicable to notes.
403                Some("entity_type")
404            } else {
405                None
406            };
407            (
408                bad,
409                "name, content, salience, decay_factor, properties, tags",
410            )
411        }
412        // `update` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, so
413        // this arm must reject entity/note-only fields (e.g. `name`) on an
414        // edge update rather than silently skip the guard, mirroring
415        // `khive-pack-kg::handlers::update::reject_inapplicable_fields`'s
416        // `KindSpec::Edge` arm.
417        "edge" => {
418            let bad = if present("name") {
419                Some("name")
420            } else if o.contains_key("description") {
421                Some("description")
422            } else if present("content") {
423                Some("content")
424            } else if present("tags") {
425                Some("tags")
426            } else if o.contains_key("salience") {
427                Some("salience")
428            } else if o.contains_key("decay_factor") {
429                Some("decay_factor")
430            } else if o.contains_key("entity_type") {
431                // ADR-014 tri-state: a PRESENT key (including JSON `null`,
432                // the explicit clear) is inapplicable to edges.
433                Some("entity_type")
434            } else {
435                None
436            };
437            (bad, "relation, weight, properties")
438        }
439        _ => (None, ""),
440    };
441    if let Some(field) = bad_field {
442        let substrate_label = match substrate {
443            "entity" => "an entity",
444            "note" => "a note",
445            "edge" => "an edge",
446            other => other,
447        };
448        return Err(RuntimeError::InvalidInput(format!(
449            "field '{field}' is not valid for {substrate_label}; valid fields: {valid}"
450        )));
451    }
452    Ok(())
453}
454
455/// Caller-supplied update-kind expectation, resolved via the canonical
456/// `resolve_kind_spec` at the kkernel `--atomic` seam: the same pattern
457/// [`AtomicDeleteKind`] uses. Without this check, `update(kind="document",
458/// id=<concept>)` would be canonically `NotFound` but the atomic path would
459/// ignore the explicit kind and mutate the resolved entity anyway.
460/// `khive-runtime` must not depend on `khive-pack-kg`, so this is a plain
461/// substrate-level shape rather than `khive_pack_kg::handlers::KindSpec`
462/// itself: the kkernel seam does the pack-aware resolution and passes down
463/// only what `prepare_update` needs to enforce the mismatch check.
464pub enum AtomicUpdateKind {
465    Entity {
466        specific: Option<String>,
467        entity_type: Option<String>,
468    },
469    Note {
470        specific: Option<String>,
471    },
472    Edge,
473}
474
475/// Enforce a caller's explicit update-kind discriminator against a resolved
476/// note before any pack hook can inspect or normalize the request. Canonical
477/// KG dispatch performs this mismatch check before its hook; the atomic
478/// adapter calls this same helper to preserve that error ordering.
479pub fn validate_note_update_expected_kind(
480    note: &khive_storage::note::Note,
481    expected_kind: &Option<AtomicUpdateKind>,
482) -> RuntimeResult<()> {
483    let id = note.id;
484    match expected_kind {
485        None => Ok(()),
486        Some(AtomicUpdateKind::Note {
487            specific: Some(expected),
488        }) if &note.kind != expected => Err(RuntimeError::NotFound(format!("note {id}"))),
489        Some(AtomicUpdateKind::Note { .. }) => Ok(()),
490        Some(AtomicUpdateKind::Entity { .. }) => {
491            Err(RuntimeError::NotFound(format!("entity {id}")))
492        }
493        Some(AtomicUpdateKind::Edge) => Err(RuntimeError::NotFound(format!("edge {id}"))),
494    }
495}
496
497async fn prepare_note_update_plan_from_snapshot(
498    runtime: &KhiveRuntime,
499    token: &NamespaceToken,
500    args: &Value,
501    expected_kind: &Option<AtomicUpdateKind>,
502    note: khive_storage::note::Note,
503    policy: crate::NoteUpdatePolicy,
504    registry: Option<&crate::VerbRegistry>,
505) -> RuntimeResult<(khive_storage::Note, UpdatePlan)> {
506    let id = require_uuid(args, "id")?;
507    if note.id != id {
508        return Err(RuntimeError::NotFound(format!("note {id}")));
509    }
510    validate_note_update_expected_kind(&note, expected_kind)?;
511
512    reject_inapplicable_update_fields(args, "note")?;
513    let mut normalized_args = args.clone();
514    crate::curation::normalize_note_update_tags(&mut normalized_args)?;
515    let args = &normalized_args;
516    let name = optional_string_patch(args, "name")?;
517    let content = optional_str(args, "content").map(str::to_string);
518    let properties = optional_properties(args, "properties")?;
519    let salience = optional_f64_patch(args, "salience")?;
520    let decay_factor = optional_f64_patch(args, "decay_factor")?;
521    let options = crate::note_write::NoteWriteOptions {
522        expected_version: obj(args)?
523            .get("expected_version")
524            .filter(|v| !v.is_null())
525            .map(|v| {
526                v.as_i64().ok_or_else(|| {
527                    RuntimeError::InvalidInput("expected_version must be an integer".into())
528                })
529            })
530            .transpose()?,
531        fence: obj(args)?
532            .get("fence")
533            .map(|v| {
534                serde_json::from_value(v.clone())
535                    .map_err(|error| RuntimeError::InvalidInput(format!("invalid fence: {error}")))
536            })
537            .transpose()?,
538        embed: obj(args)?
539            .get("embed")
540            .filter(|v| !v.is_null())
541            .map(|v| {
542                v.as_bool()
543                    .ok_or_else(|| RuntimeError::InvalidInput("embed must be boolean".into()))
544            })
545            .transpose()?,
546        key: None,
547    };
548    let patch = crate::curation::NotePatch::new(name, content, salience, decay_factor, properties)
549        .with_update_policy(policy)
550        .with_write_options(options);
551    let (updated, mut plan) = runtime
552        .prepare_versioned_note_update(token, note.clone(), patch.clone())
553        .await?;
554    if let Some(registry) = registry {
555        attach_note_update_effects(runtime, token, registry, &note, &patch, &mut plan).await?;
556    }
557    Ok((updated, plan))
558}
559
560/// Build an atomic update plan from the exact note snapshot already supplied
561/// to a pack update hook. Persistence is guarded by that snapshot's revision
562/// and deletion marker, so hook normalization cannot race a second read. The
563/// caller must first run the registry normalizer/validator against this snapshot.
564/// This shared canonical/atomic seam prepares all patch fields with the owning
565/// kind's property policy (the value `VerbRegistry::prepare_note_update_policy`
566/// returned for this snapshot), then derives and attaches the owner's typed
567/// graph effects. It returns the projected note and one atomic plan, preserving
568/// the caller's operation index.
569pub async fn prepare_update_from_note_snapshot(
570    runtime: &KhiveRuntime,
571    token: &NamespaceToken,
572    args: &Value,
573    expected_kind: Option<AtomicUpdateKind>,
574    note: khive_storage::note::Note,
575    policy: crate::NoteUpdatePolicy,
576    registry: &crate::VerbRegistry,
577) -> RuntimeResult<(khive_storage::Note, AtomicOpPlan)> {
578    if obj(args)?.get("entity_kind").is_some_and(|v| !v.is_null()) {
579        return Err(RuntimeError::InvalidInput(
580            "entity_kind is immutable; to change kind, delete then re-create the entity, \
581             or use merge() if this is a deduplication correction"
582                .into(),
583        ));
584    }
585    let (note, plan) = prepare_note_update_plan_from_snapshot(
586        runtime,
587        token,
588        args,
589        &expected_kind,
590        note,
591        policy,
592        Some(registry),
593    )
594    .await?;
595    Ok((note, AtomicOpPlan::Update(Box::new(plan))))
596}
597
598/// The only companion attachment site. Canonical, CLI atomic, and stream note
599/// updates all enter through `prepare_update_from_note_snapshot` after running
600/// the registry's normalizer/validator on the same snapshot.
601pub(crate) async fn attach_note_update_effects(
602    runtime: &KhiveRuntime,
603    token: &NamespaceToken,
604    registry: &crate::VerbRegistry,
605    snapshot: &khive_storage::Note,
606    patch: &crate::curation::NotePatch,
607    plan: &mut UpdatePlan,
608) -> RuntimeResult<()> {
609    use crate::atomic_plan::NoteUpdateStatement;
610    use crate::NoteUpdateEffect;
611
612    let Some(hook) = registry.find_kind_hook(&snapshot.kind) else {
613        return Ok(());
614    };
615    // Refuse already-known stale input before asking the owner to derive effects.
616    // A change after this read remains protected by the note's first CAS statement.
617    if let Some(expected) = patch.write_options.expected_version {
618        if expected != snapshot.version {
619            return Err(crate::note_write::NoteWriteConflict::Version {
620                expected,
621                current: snapshot.version,
622            }
623            .into_error()
624            .into());
625        }
626    }
627    let current = runtime.notes(token)?.get_note(snapshot.id).await?;
628    if !current.is_some_and(|current| {
629        current.updated_at == snapshot.updated_at
630            && current.deleted_at == snapshot.deleted_at
631            && current.version == snapshot.version
632    }) {
633        return Err(crate::curation::stale_note_snapshot_error(snapshot.id));
634    }
635    let effects = hook
636        .note_update_effects(runtime, token, snapshot, patch)
637        .await?;
638    if plan.idempotent_noop && !effects.is_empty() {
639        return Err(RuntimeError::InvalidInput(
640            "an unchanged note update cannot carry graph effects".into(),
641        ));
642    }
643    let edge_token = token.with_namespace(
644        crate::Namespace::parse(&snapshot.namespace)
645            .map_err(|error| RuntimeError::Internal(format!("invalid note namespace: {error}")))?,
646    );
647    for effect in effects {
648        match effect {
649            NoteUpdateEffect::Link(spec) => {
650                if spec.source_id != snapshot.id
651                    || spec
652                        .namespace
653                        .as_deref()
654                        .is_some_and(|ns| ns != snapshot.namespace)
655                {
656                    return Err(RuntimeError::InvalidInput(
657                        "note update links must originate from the note in its namespace".into(),
658                    ));
659                }
660                let mut args = serde_json::json!({
661                    "source_id": spec.source_id, "target_id": spec.target_id,
662                    "relation": spec.relation, "weight": spec.weight,
663                    "resurrect": spec.resurrect,
664                });
665                if let Some(metadata) = spec.metadata {
666                    args["metadata"] = metadata;
667                }
668                let AtomicOpPlan::Link(link) = prepare_link(runtime, &edge_token, &args).await?
669                else {
670                    return Err(RuntimeError::Internal("expected a link plan".into()));
671                };
672                // A live annotation inserted between the owner's read and this
673                // lookup belongs to that writer. Refuse instead of replacing its
674                // weight/metadata; a fresh preparation can preserve it explicitly.
675                if link.disposition == EdgeUpsertDisposition::Updated {
676                    return Err(khive_types::KhiveError::conflict(
677                        "a live edge appeared while preparing the note update; retry with fresh state",
678                    ).into());
679                }
680                plan.graph_effects
681                    .extend(link.statements.into_iter().map(NoteUpdateStatement::Write));
682            }
683            NoteUpdateEffect::DeleteEdge(edge) => {
684                let id = Uuid::from(edge.id);
685                if edge.source_id != snapshot.id
686                    || edge.namespace != snapshot.namespace
687                    || edge.deleted_at.is_some()
688                {
689                    return Err(RuntimeError::InvalidInput(
690                        "note update deletes must select an outgoing edge in the note namespace"
691                            .into(),
692                    ));
693                }
694                plan.graph_effects
695                    .push(NoteUpdateStatement::Assert(PlanStatement {
696                        statement: khive_db::stores::graph::edge_snapshot_assertion_statement(
697                            &edge, false,
698                        ),
699                        guard: Some(AffectedRowGuard::exactly(1)),
700                    }));
701                let actor = format!("{}:{}", token.actor().kind, token.actor().id);
702                let AtomicOpPlan::Delete(delete) =
703                    prepare_delete_edge(&edge_token, id, edge, false, &actor).await?
704                else {
705                    return Err(RuntimeError::Internal(
706                        "expected an edge delete plan".into(),
707                    ));
708                };
709                if delete.post_commit != PostCommitEffect::None {
710                    return Err(RuntimeError::Internal(
711                        "edge delete has a deferred effect".into(),
712                    ));
713                }
714                plan.graph_effects.extend(
715                    delete
716                        .statements
717                        .into_iter()
718                        .map(NoteUpdateStatement::Write),
719                );
720            }
721            NoteUpdateEffect::AssertLink(edge) => {
722                if edge.source_id != snapshot.id
723                    || edge.namespace != snapshot.namespace
724                    || edge.deleted_at.is_some()
725                {
726                    return Err(RuntimeError::InvalidInput(
727                        "note update assertions must select a live outgoing edge in the note namespace".into(),
728                    ));
729                }
730                plan.graph_effects
731                    .push(NoteUpdateStatement::Assert(PlanStatement {
732                        statement: khive_db::stores::graph::edge_snapshot_assertion_statement(
733                            &edge, true,
734                        ),
735                        guard: Some(AffectedRowGuard::exactly(1)),
736                    }));
737            }
738        }
739    }
740    Ok(())
741}
742
743/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
744/// with canonical's own optional discriminator); `Some(_)` enforces an
745/// exact-parity mismatch check against the resolved record's actual
746/// substrate/specific kind, mirroring `handle_update`'s
747/// `entity.kind != *k` / note kind checks (update.rs:200-201, :229-234).
748/// Task notes must pass the GTD pack hook before this or
749/// `prepare_op("update", ..)`; neither runs it.
750pub async fn prepare_update(
751    runtime: &KhiveRuntime,
752    token: &NamespaceToken,
753    args: &Value,
754    expected_kind: Option<AtomicUpdateKind>,
755) -> RuntimeResult<AtomicOpPlan> {
756    let id = require_uuid(args, "id")?;
757
758    // Mirrors update.rs's entity_kind immutability guard: entity_kind is a
759    // legacy top-level field, independent of the `kind` substrate
760    // discriminator handled elsewhere.
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
769    match runtime.resolve_by_id(token, id).await? {
770        Some(Resolved::Entity(entity)) => {
771            match &expected_kind {
772                None => {}
773                Some(AtomicUpdateKind::Entity {
774                    specific: Some(expected),
775                    ..
776                }) if &entity.kind != expected => {
777                    return Err(RuntimeError::NotFound(format!("entity {id}")));
778                }
779                Some(AtomicUpdateKind::Entity { .. }) => {}
780                Some(AtomicUpdateKind::Note { .. }) => {
781                    return Err(RuntimeError::NotFound(format!("note {id}")));
782                }
783                Some(AtomicUpdateKind::Edge) => {
784                    return Err(RuntimeError::NotFound(format!("edge {id}")));
785                }
786            }
787            if let Some(AtomicUpdateKind::Entity {
788                entity_type: Some(expected),
789                ..
790            }) = &expected_kind
791            {
792                if entity
793                    .entity_type
794                    .as_deref()
795                    .is_some_and(|actual| actual != expected.as_str())
796                {
797                    return Err(RuntimeError::NotFound(format!("entity {id}")));
798                }
799            }
800            refuse_pack_registry_tags(&entity.tags, "update")?;
801            // Decide step lives in curation.rs's `prepare_update_entity` —
802            // the SAME function canonical `update_entity` calls. Only the
803            // arg-extraction (raw JSON -> `EntityPatch`) and the plan-shape
804            // wiring are atomic-path-specific: the domain object becomes a
805            // `PlanStatement` via `entity_replace_if_unchanged_statement`,
806            // whose CAS predicate binds the snapshot's revision and deletion
807            // marker, under an exactly-one affected-row guard.
808            reject_inapplicable_update_fields(args, "entity")?;
809            let name = entity_name_patch(args)?;
810            let description = optional_entity_type_patch(args, "description")?;
811            let properties = optional_properties(args, "properties")?;
812            let tags = optional_tags(args)?;
813            if let Some(ref tags) = tags {
814                refuse_pack_registry_tags(tags, "update")?;
815            }
816            let entity_type = optional_entity_type_patch(args, "entity_type")?;
817
818            let expected_version = obj(args)?
819                .get("expected_version")
820                .filter(|v| !v.is_null())
821                .map(|value| {
822                    value.as_i64().ok_or_else(|| {
823                        RuntimeError::InvalidInput("expected_version must be an integer".into())
824                    })
825                })
826                .transpose()?;
827            let required_entity_type = match &expected_kind {
828                Some(AtomicUpdateKind::Entity { entity_type, .. }) => entity_type.as_deref(),
829                _ => None,
830            };
831            prepare_update_entity_plan_with_version_and_type(
832                runtime,
833                token,
834                id,
835                crate::curation::EntityPatch {
836                    name,
837                    description,
838                    properties,
839                    tags,
840                    entity_type,
841                },
842                expected_version,
843                required_entity_type,
844            )
845            .await
846        }
847        Some(Resolved::Note(note)) => {
848            // Patch application lives in curation.rs's
849            // `prepare_update_note_from_snapshot` — the same implementation
850            // canonical guarded update calls, including salience/decay range
851            // validation. The plan retains this exact snapshot's revision.
852            let (_, plan) = prepare_note_update_plan_from_snapshot(
853                runtime,
854                token,
855                args,
856                &expected_kind,
857                note,
858                crate::NoteUpdatePolicy::default(),
859                None,
860            )
861            .await?;
862            Ok(AtomicOpPlan::Update(Box::new(plan)))
863        }
864        Some(_) => Err(RuntimeError::InvalidInput(format!(
865            "update target {id} must be an entity, note, or edge"
866        ))),
867        // `Resolved` (khive-runtime::operations) has no `Edge` variant — an
868        // id that isn't an entity/note/pack-private/event record is checked
869        // against the graph store directly, mirroring
870        // `khive-pack-kg::handlers::KgPack::infer_kind_from_uuid`'s own
871        // entity/note-then-edge fallback order. `update` admits
872        // `kind="edge"`, so this arm must be able to build a plan for one.
873        None => match &expected_kind {
874            Some(AtomicUpdateKind::Entity { .. }) => {
875                Err(RuntimeError::NotFound(format!("entity/note {id}")))
876            }
877            Some(AtomicUpdateKind::Note { .. }) => {
878                Err(RuntimeError::NotFound(format!("entity/note {id}")))
879            }
880            Some(AtomicUpdateKind::Edge) | None => match runtime.get_edge(token, id).await? {
881                Some(edge) => prepare_update_edge(runtime, token, id, edge, args).await,
882                None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
883            },
884        },
885    }
886}
887
888/// Build an entity update plan from a typed patch. Proposal changesets use
889/// this entry point to preserve the typed patch directly, without translating
890/// it through raw verb parameters.
891pub async fn prepare_update_entity_plan(
892    runtime: &KhiveRuntime,
893    token: &NamespaceToken,
894    id: Uuid,
895    patch: crate::curation::EntityPatch,
896) -> RuntimeResult<AtomicOpPlan> {
897    prepare_update_entity_plan_with_version(runtime, token, id, patch, None).await
898}
899
900pub(super) async fn prepare_update_entity_plan_with_version_and_type(
901    runtime: &KhiveRuntime,
902    token: &NamespaceToken,
903    id: Uuid,
904    patch: crate::curation::EntityPatch,
905    expected_version: Option<i64>,
906    required_entity_type: Option<&str>,
907) -> RuntimeResult<AtomicOpPlan> {
908    prepare_update_entity_record_with_version_and_type(
909        runtime,
910        token,
911        id,
912        patch,
913        expected_version,
914        required_entity_type,
915    )
916    .await
917    .map(|(_, plan)| plan)
918}
919
920/// Return the canonical prepared record together with the plan bound to it.
921///
922/// Import uses this projection for endpoint validation without applying the
923/// patch or invoking kind hooks again. Its version remains the captured row
924/// revision; applying the plan advances the persisted revision once.
925pub(crate) async fn prepare_update_entity_record(
926    runtime: &KhiveRuntime,
927    token: &NamespaceToken,
928    id: Uuid,
929    patch: crate::curation::EntityPatch,
930    expected_version: Option<i64>,
931) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
932    prepare_update_entity_record_with_version_and_type(
933        runtime,
934        token,
935        id,
936        patch,
937        expected_version,
938        None,
939    )
940    .await
941}
942
943async fn prepare_update_entity_record_with_version_and_type(
944    runtime: &KhiveRuntime,
945    token: &NamespaceToken,
946    id: Uuid,
947    patch: crate::curation::EntityPatch,
948    expected_version: Option<i64>,
949    required_entity_type: Option<&str>,
950) -> RuntimeResult<(khive_storage::Entity, AtomicOpPlan)> {
951    crate::entity_write::validate_expected_version(expected_version)?;
952    let explicit_entity_type_patch = patch.entity_type.is_some();
953    let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
954        runtime.prepare_update_entity(token, id, patch).await?;
955    if required_entity_type.is_some_and(|expected| {
956        (explicit_entity_type_patch || entity.entity_type.is_some())
957            && entity.entity_type.as_deref() != Some(expected)
958    }) {
959        return Err(RuntimeError::InvalidInput(
960            "kind subtype contradicts the requested entity_type update".into(),
961        ));
962    }
963    let mut statements = vec![PlanStatement {
964        statement: entity_replace_if_unchanged_statement(
965            &entity,
966            expected_updated_at,
967            expected_deleted_at,
968        ),
969        guard: Some(AffectedRowGuard::exactly(1)),
970    }];
971    statements.extend(event_append_statements(
972        token,
973        &entity.namespace,
974        "update",
975        EventKind::EntityUpdated,
976        SubstrateKind::Entity,
977        id,
978        serde_json::json!({
979            "id": id,
980            "namespace": &entity.namespace,
981            "changed_fields": changed_fields,
982        }),
983    )?);
984    let post_commit = if reindex_required {
985        PostCommitEffect::ReindexEntity { entity_id: id }
986    } else {
987        PostCommitEffect::None
988    };
989    let plan = AtomicOpPlan::Update(Box::new(UpdatePlan {
990        graph_effects: Vec::new(),
991        note_vector_purge: None,
992        note_embedding_inheritance: None,
993        entity_guard: expected_version.map(|expected_version| {
994            crate::entity_write::EntityWriteGuard {
995                id,
996                expected_version,
997            }
998        }),
999        note_guard: None,
1000        target_id: id,
1001        statements,
1002        post_commit,
1003        edge_natural_key: None,
1004        idempotent_noop: false,
1005    }));
1006    Ok((entity, plan))
1007}