Skip to main content

khive_runtime/
note_create.rs

1//! Shared note creation with explicit key-publication order.
2
3use khive_storage::types::{Edge, LinkId, SqlValue};
4use khive_storage::{EdgeRelation, SqlStatement};
5use serde_json::{json, Value};
6use uuid::Uuid;
7
8use crate::atomic_message::{
9    prepare_atomic_notes, AtomicNoteOptions, AtomicNoteSpec, PreparedAtomicNotes,
10};
11use crate::atomic_plan::{AffectedRowGuard, PlanStatement};
12use crate::atomic_runner::AtomicOpPlan;
13use crate::{KhiveRuntime, RuntimeError, RuntimeResult};
14
15/// The effective tags for note creation, retaining their source so writers can
16/// preserve the original properties when no top-level override is needed.
17pub enum EffectiveCreateTags<'a> {
18    TopLevel(&'a [String]),
19    Properties(Option<&'a Value>),
20}
21
22impl EffectiveCreateTags<'_> {
23    /// Project only the selected tags for a kind-specific validator. Property
24    /// values remain untyped here; each note kind owns their validation.
25    pub fn to_value(&self) -> Value {
26        match self {
27            Self::TopLevel(tags) => json!(tags),
28            Self::Properties(tags) => tags.cloned().unwrap_or(Value::Null),
29        }
30    }
31}
32
33/// Resolve create-tag precedence once for writers and kind hooks.
34///
35/// Nonempty top-level tags override `properties.tags`; absent, null (already
36/// deserialized as `None`), or empty top-level tags preserve that property.
37/// This differs from update semantics, where an empty tag array clears tags.
38pub fn effective_create_tags<'a>(
39    tags: Option<&'a [String]>,
40    properties: Option<&'a Value>,
41) -> EffectiveCreateTags<'a> {
42    match tags {
43        Some(tags) if !tags.is_empty() => EffectiveCreateTags::TopLevel(tags),
44        _ => EffectiveCreateTags::Properties(properties.and_then(|value| value.get("tags"))),
45    }
46}
47
48pub(crate) enum KeyPublication {
49    AtInsert,
50    AfterDependents,
51}
52
53pub(crate) const KEY_CLAIM: &str = "memory-key-claim";
54pub(crate) const KEYED_ANNOTATION_ENDPOINT: &str = "memory-annotation-endpoint";
55
56pub(crate) enum NoteCreatePrepareError {
57    MissingAnnotation(Uuid),
58    Other(RuntimeError),
59}
60
61impl From<RuntimeError> for NoteCreatePrepareError {
62    fn from(error: RuntimeError) -> Self {
63        Self::Other(error)
64    }
65}
66
67impl NoteCreatePrepareError {
68    pub(crate) fn into_runtime(self) -> RuntimeError {
69        match self {
70            Self::MissingAnnotation(target) => {
71                RuntimeError::NotFound(format!("create_note annotates target {target} not found"))
72            }
73            Self::Other(error) => error,
74        }
75    }
76}
77
78pub(crate) async fn prepare_note_create(
79    runtime: &KhiveRuntime,
80    spec: AtomicNoteSpec<'_>,
81    options: AtomicNoteOptions<'_>,
82    annotates: &[Uuid],
83    publication: KeyPublication,
84) -> RuntimeResult<(PreparedAtomicNotes, Vec<Uuid>)> {
85    prepare_note_create_classified(runtime, spec, options, annotates, publication)
86        .await
87        .map_err(NoteCreatePrepareError::into_runtime)
88}
89
90pub(crate) async fn prepare_note_create_classified(
91    runtime: &KhiveRuntime,
92    spec: AtomicNoteSpec<'_>,
93    mut options: AtomicNoteOptions<'_>,
94    annotates: &[Uuid],
95    publication: KeyPublication,
96) -> Result<(PreparedAtomicNotes, Vec<Uuid>), NoteCreatePrepareError> {
97    if let Some(key) = options.key {
98        crate::secret_gate::check_at(key, "note", "key")?;
99    }
100    for target in annotates {
101        if !runtime.substrate_exists_by_id(spec.token, *target).await? {
102            return Err(NoteCreatePrepareError::MissingAnnotation(*target));
103        }
104    }
105    let claim_last = match publication {
106        KeyPublication::AtInsert => None,
107        KeyPublication::AfterDependents => Some(
108            options
109                .key
110                .take()
111                .ok_or_else(|| {
112                    RuntimeError::InvalidInput("deferred key publication requires a key".into())
113                })?
114                .to_owned(),
115        ),
116    };
117    let mut prepared = prepare_atomic_notes(runtime, vec![spec], options).await?;
118    let note = &prepared.notes[0];
119    crate::secret_gate::reject_reserved_secret_gate_property(note.properties.as_ref())?;
120    let AtomicOpPlan::AddNote(plan) = &mut prepared.plans[0] else {
121        return Err(RuntimeError::Internal("expected prepared note creation".into()).into());
122    };
123    if claim_last.is_some() {
124        plan.statements[0].statement =
125            khive_db::stores::note::note_insert_if_absent_statement(note);
126    }
127    let mut annotation_ids = Vec::with_capacity(annotates.len());
128    for target in annotates {
129        let now = chrono::Utc::now();
130        let id = Uuid::new_v4();
131        let edge = Edge {
132            id: LinkId::from(id),
133            namespace: note.namespace.clone(),
134            source_id: note.id,
135            target_id: *target,
136            relation: EdgeRelation::Annotates,
137            weight: 1.0,
138            created_at: now,
139            updated_at: now,
140            deleted_at: None,
141            metadata: None,
142            target_backend: None,
143        };
144        let mut statement =
145            khive_db::stores::graph::edge_insert_only_guarded_by_endpoints_statement(&edge);
146        if claim_last.is_some() {
147            statement.label = Some(KEYED_ANNOTATION_ENDPOINT.into());
148        }
149        plan.statements.push(PlanStatement {
150            statement,
151            guard: Some(AffectedRowGuard::exactly(1)),
152        });
153        annotation_ids.push(id);
154    }
155    if let Some(key) = claim_last {
156        plan.statements.push(PlanStatement {
157            statement: SqlStatement {
158                sql: "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
159                      AND kind = ?4 AND key IS NULL AND deleted_at IS NULL"
160                    .into(),
161                params: vec![
162                    SqlValue::Text(key),
163                    SqlValue::Text(note.id.to_string()),
164                    SqlValue::Text(note.namespace.clone()),
165                    SqlValue::Text(note.kind.clone()),
166                ],
167                label: Some(KEY_CLAIM.into()),
168            },
169            guard: Some(AffectedRowGuard::exactly(1)),
170        });
171    }
172    Ok((prepared, annotation_ids))
173}
174
175#[cfg(test)]
176#[path = "note_create_tests.rs"]
177mod tests;