Skip to main content

khive_runtime/
operations.rs

1// See docs/operations.md#module-layout.
2//! High-level operations composing storage capabilities into user-facing verbs.
3//!
4//! Fault-injection arming uses scoped guards only — see docs/operations.md#fault-injection-arm-migration.
5
6use std::collections::HashMap;
7use std::str::FromStr;
8
9use chrono::Utc;
10use serde::Serialize;
11use uuid::Uuid;
12
13#[cfg(test)]
14use khive_score::DeterministicScore;
15use khive_storage::entity::EntityTypeCounts;
16#[cfg(test)]
17use khive_storage::graph::{SymmetricEdgeUpdateOutcome, SymmetricEdgeUpdateRequest};
18use khive_storage::note::Note;
19#[cfg(test)]
20use khive_storage::types::DeleteMode;
21use khive_storage::types::{
22    DirectedNeighborHit, Direction, EdgeUpsertDisposition, EdgeUpsertRefusal, EdgeUpsertRequest,
23    EdgeUpsertResult, GraphPath, GuardedEdgeUpsertOutcome, LinkId, NeighborCursor, NeighborHit,
24    NeighborQuery, PageRequest, SqlStatement, SqlValue, TextFilter, TextQueryMode,
25    TextSearchRequest, TraversalRequest,
26};
27use khive_storage::{
28    Attachment, AttachmentSubstrate, Edge, EdgeRelation, Entity, EntityFilter, Event, EventFilter,
29    NewAttachment,
30};
31use khive_types::{EdgeEndpointRule, EndpointKind, EventKind, KhiveError, SubstrateKind};
32
33use khive_db::stores::entity::entity_upsert_statement;
34
35use khive_db::stores::graph::{
36    compose_graph_mutation_events, GraphMutationOutcome, GraphMutationPreconditions,
37    GraphMutationRequest,
38};
39
40use khive_db::stores::text::insert_document_statements;
41
42mod note_search;
43mod quarantine_note_retention;
44
45#[cfg(test)]
46mod batch_edge_tests;
47
48struct EdgeReadWindow {
49    outcomes: Vec<Option<RuntimeResult<Option<Edge>>>>,
50    groups: Vec<(khive_types::Namespace, Vec<usize>)>,
51}
52
53/// The restore unit committed the row and its text index; only the
54/// post-commit embedding rebuild failed. Name that, so the caller does not
55/// read an ordinary restore failure over a record that is already live.
56fn restore_reindex_failed(kind: &str, id: Uuid, error: RuntimeError) -> RuntimeError {
57    RuntimeError::Internal(format!(
58        "{kind} {id} is restored and text-indexed, but its embedding rebuild failed \
59         and will be retried by the next reindex: {error}"
60    ))
61}
62
63fn merge_tombstone_restore_refused(id: Uuid, kept_id: impl std::fmt::Display) -> RuntimeError {
64    KhiveError::conflict(format!(
65        "merge_tombstone: {id} was merged into {kept_id}; a merge tombstone is not restorable, query the kept id"
66    ))
67    .with_details(khive_types::Details::new_owned([
68        ("reason", "merge_tombstone".into()),
69        ("merged_into", kept_id.to_string()),
70    ]))
71    .into()
72}
73
74/// The entity total and optional type report consumed together by `stats`.
75#[derive(Debug, PartialEq, Eq)]
76pub struct EntityStatsCounts {
77    pub entities: u64,
78    pub entities_by_type: Option<EntityTypeCounts>,
79}
80
81/// The live edge total and its two breakdowns consumed together by `stats`.
82#[derive(Debug, Default, PartialEq, Eq)]
83pub struct EdgeStatsCounts {
84    pub edges: u64,
85    pub edges_by_relation: HashMap<String, u64>,
86    pub edges_by_endpoint_base: khive_storage::types::EdgeEndpointBaseCounts,
87}
88
89/// Count caller-visible live entities through one store. A supported breakdown
90/// supplies its own scalar total; only an unavailable report uses legacy counting.
91pub async fn entity_stats_counts(
92    store: &dyn khive_storage::EntityStore,
93    token: &NamespaceToken,
94) -> RuntimeResult<EntityStatsCounts> {
95    let namespaces: Vec<String> = token
96        .visible_namespaces()
97        .iter()
98        .map(|namespace| namespace.as_str().to_owned())
99        .collect();
100    match store.count_entities_by_type(&namespaces).await? {
101        Some(groups) => {
102            let entities = groups.iter().try_fold(0_u64, |total, (_, count)| {
103                total.checked_add(*count).ok_or_else(|| {
104                    RuntimeError::Internal(
105                        "entity type counts exceed the scalar count range".into(),
106                    )
107                })
108            })?;
109            Ok(EntityStatsCounts {
110                entities,
111                entities_by_type: Some(groups),
112            })
113        }
114        None => {
115            let entities = store
116                .count_entities(
117                    token.namespace().as_str(),
118                    EntityFilter {
119                        namespaces,
120                        ..EntityFilter::default()
121                    },
122                )
123                .await?;
124            Ok(EntityStatsCounts {
125                entities,
126                entities_by_type: None,
127            })
128        }
129    }
130}
131
132/// Inputs for a store-owned entity identity. Unlike ordinary creation, a
133/// competing insert must leave the existing row untouched.
134pub struct EntityClaimSpec {
135    pub id: Uuid,
136    pub kind: String,
137    pub entity_type: Option<String>,
138    pub name: String,
139    pub description: Option<String>,
140    pub properties: Option<serde_json::Value>,
141    pub tags: Vec<String>,
142    pub identity_tag: String,
143}
144
145fn live_merged_entity_refused(id: Uuid, kept_id: impl std::fmt::Display) -> RuntimeError {
146    KhiveError::conflict(format!(
147        "live_merged_entity: {id} is live but still carries merged_into {kept_id}; a row an \
148         earlier restore left live over its merge is not restorable, re-tombstone it or query the \
149         kept id"
150    ))
151    .with_details(khive_types::Details::new_owned([
152        ("reason", "live_merged_entity".into()),
153        ("merged_into", kept_id.to_string()),
154    ]))
155    .into()
156}
157
158fn restore_key_conflict(key: &str, holder: &Note) -> RuntimeError {
159    KhiveError::conflict(format!(
160        "restore_key_conflict: key {key:?} is already held by live note {}",
161        holder.id
162    ))
163    .with_details(khive_types::Details::new_owned([
164        ("reason", "restore_key_conflict".into()),
165        ("key", key.to_owned()),
166        ("existing_id", holder.id.to_string()),
167    ]))
168    .into()
169}
170
171use crate::atomic_plan::{
172    AddEntityPlan, AffectedRowGuard, PlanStatement, PostCommitEffect, UpdatePlan,
173};
174use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
175use crate::curation::{entity_fts_document, note_embedding_text_ref, note_fts_document};
176use crate::error::{GuardedWriteFailure, RuntimeError, RuntimeResult};
177use crate::runtime::{KhiveRuntime, NamespaceToken};
178
179/// A non-retryable failure after a substrate mutation has committed.
180/// Callers can report the committed id/result and this diagnostic together.
181#[derive(Clone, Debug, Serialize)]
182pub struct PostCommitDegradation {
183    pub stage: &'static str,
184    pub error: String,
185}
186
187impl PostCommitDegradation {
188    fn new(stage: &'static str, error: impl ToString) -> Self {
189        Self {
190            stage,
191            error: error.to_string(),
192        }
193    }
194}
195
196// One list declares the stages, so the variants, `ALL` and the labels cannot drift apart.
197macro_rules! conditional_insert_stages {
198    ($($stage:ident => $label:literal),+ $(,)?) => {
199        /// The post-commit stages a conditional note insert reports in its committed
200        /// `post_commit_degraded` outcome. The comm ingest decoder accepts a stage only
201        /// when it is the label of a member of [`ConditionalInsertStage::ALL`], and the
202        /// insert can record a stage only through this type, so every label the
203        /// runtime emits is one the decoder accepts.
204        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
205        pub enum ConditionalInsertStage {
206            $($stage,)+
207        }
208
209        impl ConditionalInsertStage {
210            /// Every stage, generated from the same list as the variants.
211            pub const ALL: &'static [Self] = &[$(Self::$stage,)+];
212
213            pub const fn label(self) -> &'static str {
214                match self {
215                    $(Self::$stage => $label,)+
216                }
217            }
218        }
219    };
220}
221
222conditional_insert_stages! {
223    FtsAcquisition => "fts_acquisition",
224    FtsUpsert => "fts_upsert",
225    Embedding => "embedding",
226    VectorAcquisition => "vector_acquisition",
227    VectorInsert => "vector_insert",
228}
229
230impl ConditionalInsertStage {
231    pub fn from_label(label: &str) -> Option<Self> {
232        Self::ALL
233            .iter()
234            .copied()
235            .find(|stage| stage.label() == label)
236    }
237}
238
239fn record_conditional_insert_degradation(
240    degradations: &mut Vec<PostCommitDegradation>,
241    id: Uuid,
242    stage: ConditionalInsertStage,
243    error: impl ToString,
244) {
245    record_post_commit_degradation(degradations, "try_create_note", id, stage.label(), error);
246}
247
248fn record_post_commit_degradation(
249    degradations: &mut Vec<PostCommitDegradation>,
250    operation: &'static str,
251    id: Uuid,
252    stage: &'static str,
253    error: impl ToString,
254) {
255    let degradation = PostCommitDegradation::new(stage, error);
256    tracing::warn!(%operation, %id, stage, error = %degradation.error,
257        "substrate mutation committed with post-commit degradation");
258    degradations.push(degradation);
259}
260
261/// Legacy methods cannot return both their original result and the new report.
262/// Give direct callers a typed, non-retryable error with the committed record
263/// handle and every failed stage instead of silently dropping the report.
264pub(crate) fn legacy_post_commit_result<T>(
265    operation: &'static str,
266    id: Uuid,
267    value: T,
268    degradations: Vec<PostCommitDegradation>,
269) -> RuntimeResult<T> {
270    if degradations.is_empty() {
271        return Ok(value);
272    }
273    let failures = serde_json::Value::Array(
274        degradations
275            .iter()
276            .map(|failure| {
277                serde_json::json!({"stage": failure.stage, "error": failure.error.as_str()})
278            })
279            .collect(),
280    );
281    Err(KhiveError::internal(format!(
282        "{operation} committed record {id}, but post-commit work failed; do not retry the mutation; reconcile by record_id"
283    ))
284    .with_details(khive_types::Details::new_owned([
285        ("reason", "post_commit_degraded".to_string()),
286        ("operation", operation.to_string()),
287        ("record_id", id.to_string()),
288        ("committed", "true".to_string()),
289        ("retryable", "false".to_string()),
290        ("post_commit_degradations", failures.to_string()),
291    ]))
292    .into())
293}
294
295pub(crate) fn legacy_post_commit_result_with_embedding<T>(
296    operation: &'static str,
297    id: Uuid,
298    value: T,
299    embedding: crate::retrieval::EmbeddingTruncationReport,
300    degradations: Vec<PostCommitDegradation>,
301) -> RuntimeResult<T> {
302    if !embedding.any_truncated() {
303        return legacy_post_commit_result(operation, id, value, degradations);
304    }
305    let failures = serde_json::Value::Array(
306        degradations
307            .iter()
308            .map(|failure| {
309                serde_json::json!({"stage": failure.stage, "error": failure.error.as_str()})
310            })
311            .collect(),
312    );
313    Err(KhiveError::internal(format!(
314        "{operation} committed record {id}, but embedding input was truncated; do not retry the mutation; reconcile by record_id"
315    ))
316    .with_details(khive_types::Details::new_owned([
317        ("reason", "embedding_input_truncated".to_string()),
318        ("operation", operation.to_string()),
319        ("record_id", id.to_string()),
320        ("committed", "true".to_string()),
321        ("retryable", "false".to_string()),
322        (
323            "embedding_truncation_report",
324            serde_json::json!(embedding).to_string(),
325        ),
326        ("post_commit_degradations", failures.to_string()),
327    ]))
328    .into())
329}
330
331mod attachments;
332mod entity_aliases;
333pub(crate) use entity_aliases::{
334    apply_entity_alias_change, entity_updated_payload, unguarded as unguarded_alias_statements,
335};
336pub use entity_aliases::{validate_entity_alias, EntityAliasChange, EntityAliasReport};
337mod entity_bulk;
338mod entity_create;
339mod entity_key_add;
340pub use entity_key_add::{
341    entity_key_add_plans, EntityKeyAdd, ENTITY_KEY_ADD_HELD_LABEL, ENTITY_KEY_ADD_LIVE_LABEL,
342};
343mod entity_keys;
344pub(crate) use entity_keys::validate_entity_key;
345pub use entity_keys::{
346    entity_carries_create_payload, entity_key_conflict, keyed_replay_assertion_plan,
347    same_create_payload, KeyedEntityCreate, KeyedEntityReload, PendingEntityId,
348};
349mod entity_indexes;
350#[cfg(any(test, feature = "fault-injection"))]
351mod fault_injection;
352mod resolve_prefix_in;
353mod resolve_uuid_or_prefix;
354
355mod delete_restore;
356mod edge_query;
357mod graph_rules;
358mod identity_reads;
359mod link_ops;
360mod read_helpers;
361mod record_ops;
362mod traversal;
363
364use read_helpers::{
365    direction_sort_rank, drain_embed_join_set, normalize_symmetric_direction, note_snippet,
366    note_title, resolve_prefix_statement, salience_weighted_rank,
367};
368pub use read_helpers::{
369    hex_prefix_to_uuid_pattern, uuid_prefix_bounds, NoteSearchHit, NoteSearchOutcome, Resolved,
370};
371pub use record_ops::NoteCreateSpec;
372
373pub use edge_query::QueryResult;
374use graph_rules::{accepted_entity_relations_description, static_impossible_edge_pattern_warnings};
375pub use graph_rules::{
376    accepted_entity_relations_for_entities, accepted_pack_relations_for_entities,
377    allowed_pairs_for_relation_description, dependency_kind_inference_hint, merge_entry_metadata,
378};
379pub(crate) use graph_rules::{
380    canonical_edge_endpoint_kinds, canonical_edge_endpoints, merge_dependency_kind,
381    pack_rule_allows, validate_edge_metadata, validate_edge_weight,
382};
383#[cfg(test)]
384use link_ops::guarded_link_batch_failure;
385#[cfg(test)]
386use traversal::merge_traversal_paths_by_root;
387
388#[cfg(any(test, feature = "fault-injection"))]
389pub use fault_injection::{
390    arm_entity_compensation_fail_scoped, arm_fts_fail_many_partial_scoped,
391    arm_fts_fail_many_scoped, arm_fts_fail_scoped, arm_fts_search_fail,
392    arm_prefix_resolve_fail_scoped, arm_rollback_cleanup_fail, arm_vector_fail_after,
393    arm_vector_fail_scoped, FaultInjectionArm,
394};
395#[cfg(test)]
396use fault_injection::{arm_fault, FaultArmSet, LINK_FAIL_AFTER};
397#[cfg(any(test, feature = "fault-injection"))]
398use fault_injection::{
399    consume_fault, ENTITY_COMPENSATION_FAIL_NS, FTS_FAIL_MANY_NS, FTS_FAIL_MANY_PARTIAL_NS,
400    FTS_FAIL_NS, FTS_SEARCH_FAIL_NS, PREFIX_RESOLVE_FAIL_NS, ROLLBACK_CLEANUP_FAIL_NS,
401    VECTOR_FAIL_AFTER, VECTOR_FAIL_NS,
402};
403#[cfg(any(test, feature = "fault-injection"))]
404pub(crate) use fault_injection::{consume_fts_fail_fault, consume_vector_fail_fault};
405pub use resolve_prefix_in::PrefixScope;
406
407/// A by-ID edge-endpoint substrate kind, including `Edge` itself.
408///
409/// Unlike [`Resolved`], this carries no record data — it is used where only
410/// the substrate classification is needed (coordinator locate/link parity
411/// with `get`, ADR-002 rule 1: `annotates` target may be entity, note, edge,
412/// or event).
413#[derive(Clone, Copy, Debug, Eq, PartialEq)]
414pub enum EdgeEndpointKind {
415    Entity,
416    Note,
417    Event,
418    Edge,
419}
420
421impl EdgeEndpointKind {
422    /// Wire name carried by a link lifecycle event for this endpoint.
423    pub const fn name(self) -> &'static str {
424        match self {
425            Self::Entity => "entity",
426            Self::Note => "note",
427            Self::Event => "event",
428            Self::Edge => "edge",
429        }
430    }
431}
432
433/// Map a resolved endpoint to its `(substrate, kind, entity_type)` triple, or
434/// `None` if the substrate is not a valid edge endpoint (events, edges).
435///
436/// `entity_type` carries the pack-owned granular subtype (`Entity::entity_type`,
437/// e.g. `"theorem"`); it is `None` for notes and for entities with no subtype.
438fn resolved_pair(r: Option<&Resolved>) -> Option<(&'static str, &str, Option<&str>)> {
439    match r? {
440        Resolved::Entity(e) => Some(("entity", e.kind.as_str(), e.entity_type.as_deref())),
441        Resolved::Note(n) => Some(("note", n.kind.as_str(), None)),
442        Resolved::Event(_) => None,
443        Resolved::PackRecord { .. } => None,
444    }
445}
446
447pub use khive_types::{
448    base_entity_endpoint_rules, base_entity_rule_allows, endpoint_matches,
449    BASE_ENTITY_ENDPOINT_RULES,
450};
451
452impl KhiveRuntime {
453    // ---- Note operations ----
454
455    /// Create and persist a note, optionally with properties and annotation targets.
456    ///
457    /// After creating the note:
458    /// - Always indexes into FTS5 at the `notes_<namespace>` key.
459    /// - If an embedding model is configured, indexes into the vector store with
460    ///   `SubstrateKind::Note`.
461    /// - For each UUID in `annotates`, creates an `EdgeRelation::Annotates` edge from
462    ///   the note to that target.
463    ///
464    /// A bounded embedding returns a non-retryable error carrying the committed
465    /// note ID and truncation report. The report-aware embedding-content variant
466    /// accepts `None` to retain the same default input selection.
467    // REASON: note creation requires kind, name, content, salience, properties, annotates,
468    // and namespace token — mirrors the MCP verb surface; a builder would not reduce
469    // caller complexity for pack handler callers.
470    #[allow(clippy::too_many_arguments)]
471    pub async fn create_note(
472        &self,
473        token: &NamespaceToken,
474        kind: &str,
475        name: Option<&str>,
476        content: &str,
477        salience: Option<f64>,
478        properties: Option<serde_json::Value>,
479        annotates: Vec<Uuid>,
480    ) -> RuntimeResult<Note> {
481        let (note, embedding, degradations, _) = self
482            .create_note_inner(
483                token, kind, name, content, None, salience, None, properties, annotates, None,
484                false, false,
485            )
486            .await?;
487        legacy_post_commit_result_with_embedding(
488            "create_note",
489            note.id,
490            note,
491            embedding,
492            degradations,
493        )
494    }
495
496    /// Publish a network receipt with provenance that generic note writes
497    /// cannot supply. The web pack provides only the request record and the
498    /// annotation targets; this entry point fixes the note kind, tag, and
499    /// provenance before the first storage write.
500    pub async fn create_web_receipt_note(
501        &self,
502        token: &NamespaceToken,
503        summary: &str,
504        request: serde_json::Value,
505        annotates: Vec<Uuid>,
506    ) -> RuntimeResult<Note> {
507        let properties = serde_json::json!({
508            "tags": ["web.receipt"],
509            "request": request,
510        });
511        let (note, _, degradations, _) = self
512            .create_note_inner(
513                token,
514                "observation",
515                None,
516                summary,
517                None,
518                None,
519                None,
520                Some(properties),
521                annotates,
522                None,
523                false,
524                true,
525            )
526            .await?;
527        legacy_post_commit_result("create_web_receipt_note", note.id, note, degradations)
528    }
529
530    /// Like [`Self::create_note`], but lets the caller supply a smaller text
531    /// to send to the vector embedder while the note's stored/FTS-indexed
532    /// `content` remains the full text.
533    ///
534    /// `embedding_content`, when `Some`, must be non-empty and a proper
535    /// prefix of `content` — anything else is rejected with `InvalidInput`
536    /// before any write. `None` behaves exactly like [`Self::create_note`].
537    /// Use this when `content` may exceed an embedder's input cap (e.g. a
538    /// very long commit message) and only a capped head prefix should be
539    /// embedded, while the full text is still stored and searchable via FTS.
540    #[allow(clippy::too_many_arguments)]
541    pub async fn create_note_with_embedding_content(
542        &self,
543        token: &NamespaceToken,
544        kind: &str,
545        name: Option<&str>,
546        content: &str,
547        embedding_content: Option<&str>,
548        salience: Option<f64>,
549        properties: Option<serde_json::Value>,
550        annotates: Vec<Uuid>,
551    ) -> RuntimeResult<Note> {
552        let (note, embedding, degradations, _) = self
553            .create_note_inner(
554                token,
555                kind,
556                name,
557                content,
558                embedding_content,
559                salience,
560                None,
561                properties,
562                annotates,
563                None,
564                false,
565                false,
566            )
567            .await?;
568        legacy_post_commit_result_with_embedding(
569            "create_note_with_embedding_content",
570            note.id,
571            note,
572            embedding,
573            degradations,
574        )
575    }
576
577    #[allow(clippy::too_many_arguments)]
578    pub async fn create_note_with_embedding_content_and_report(
579        &self,
580        token: &NamespaceToken,
581        kind: &str,
582        name: Option<&str>,
583        content: &str,
584        embedding_content: Option<&str>,
585        salience: Option<f64>,
586        properties: Option<serde_json::Value>,
587        annotates: Vec<Uuid>,
588    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
589        let (note, embedding, degradations, _) = self
590            .create_note_inner(
591                token,
592                kind,
593                name,
594                content,
595                embedding_content,
596                salience,
597                None,
598                properties,
599                annotates,
600                None,
601                false,
602                false,
603            )
604            .await?;
605        legacy_post_commit_result(
606            "create_note_with_embedding_content_and_report",
607            note.id,
608            (note, embedding),
609            degradations,
610        )
611    }
612
613    /// The committed note and its non-retryable post-commit diagnostics.
614    #[allow(clippy::too_many_arguments)]
615    pub async fn create_note_with_embedding_content_and_post_commit_report(
616        &self,
617        token: &NamespaceToken,
618        kind: &str,
619        name: Option<&str>,
620        content: &str,
621        embedding_content: Option<&str>,
622        salience: Option<f64>,
623        properties: Option<serde_json::Value>,
624        annotates: Vec<Uuid>,
625    ) -> RuntimeResult<(
626        Note,
627        crate::retrieval::EmbeddingTruncationReport,
628        Vec<PostCommitDegradation>,
629    )> {
630        let (note, embedding, degradations, _) = self
631            .create_note_inner(
632                token,
633                kind,
634                name,
635                content,
636                embedding_content,
637                salience,
638                None,
639                properties,
640                annotates,
641                None,
642                false,
643                false,
644            )
645            .await?;
646        Ok((note, embedding, degradations))
647    }
648
649    /// Like [`Self::create_note`] but also sets a non-zero decay factor on the note.
650    // REASON: extends create_note with an additional decay_factor parameter; same
651    // rationale — mirrors the MCP surface and reduces an extra builder layer.
652    #[allow(clippy::too_many_arguments)]
653    pub async fn create_note_with_decay(
654        &self,
655        token: &NamespaceToken,
656        kind: &str,
657        name: Option<&str>,
658        content: &str,
659        salience: Option<f64>,
660        decay_factor: f64,
661        properties: Option<serde_json::Value>,
662        annotates: Vec<Uuid>,
663    ) -> RuntimeResult<Note> {
664        self.create_note_with_decay_for_embedding_model(
665            token,
666            kind,
667            name,
668            content,
669            salience,
670            decay_factor,
671            properties,
672            annotates,
673            None,
674        )
675        .await
676    }
677
678    /// Create a note with decay and retain embedding truncation accounting.
679    #[allow(clippy::too_many_arguments)]
680    pub async fn create_note_with_decay_and_report(
681        &self,
682        token: &NamespaceToken,
683        kind: &str,
684        name: Option<&str>,
685        content: &str,
686        salience: Option<f64>,
687        decay_factor: f64,
688        properties: Option<serde_json::Value>,
689        annotates: Vec<Uuid>,
690    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
691        self.create_note_with_decay_for_embedding_model_and_report(
692            token,
693            kind,
694            name,
695            content,
696            salience,
697            decay_factor,
698            properties,
699            annotates,
700            None,
701        )
702        .await
703    }
704
705    /// Like [`Self::create_note_with_decay`] but targets a specific embedding model.
706    // REASON: adds an embedding_model parameter to the decay variant; the full parameter
707    // set is required for correct MCP verb routing and cannot be collapsed without
708    // introducing a separate config struct that would obscure call sites.
709    #[allow(clippy::too_many_arguments)]
710    pub async fn create_note_with_decay_for_embedding_model(
711        &self,
712        token: &NamespaceToken,
713        kind: &str,
714        name: Option<&str>,
715        content: &str,
716        salience: Option<f64>,
717        decay_factor: f64,
718        properties: Option<serde_json::Value>,
719        annotates: Vec<Uuid>,
720        embedding_model: Option<&str>,
721    ) -> RuntimeResult<Note> {
722        let (note, embedding, degradations, _) = self
723            .create_note_inner(
724                token,
725                kind,
726                name,
727                content,
728                None,
729                salience,
730                Some(decay_factor),
731                properties,
732                annotates,
733                embedding_model,
734                false,
735                false,
736            )
737            .await?;
738        legacy_post_commit_result_with_embedding(
739            "create_note_with_decay_for_embedding_model",
740            note.id,
741            note,
742            embedding,
743            degradations,
744        )
745    }
746
747    /// Create a note with decay for a named model and retain embedding truncation accounting.
748    #[allow(clippy::too_many_arguments)]
749    pub async fn create_note_with_decay_for_embedding_model_and_report(
750        &self,
751        token: &NamespaceToken,
752        kind: &str,
753        name: Option<&str>,
754        content: &str,
755        salience: Option<f64>,
756        decay_factor: f64,
757        properties: Option<serde_json::Value>,
758        annotates: Vec<Uuid>,
759        embedding_model: Option<&str>,
760    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
761        let (note, embedding, degradations, _) = self
762            .create_note_inner(
763                token,
764                kind,
765                name,
766                content,
767                None,
768                salience,
769                Some(decay_factor),
770                properties,
771                annotates,
772                embedding_model,
773                false,
774                false,
775            )
776            .await?;
777        legacy_post_commit_result(
778            "create_note_with_decay_for_embedding_model_and_report",
779            note.id,
780            (note, embedding),
781            degradations,
782        )
783    }
784
785    /// Memory-pack receipt form of the decay create. Each returned sequence
786    /// was read inside the transaction that inserted that model's vector and
787    /// ANN upsert log row; a failed or version-rejected vector writes no fence.
788    #[allow(clippy::too_many_arguments)]
789    pub async fn create_note_with_decay_for_embedding_model_with_visibility(
790        &self,
791        token: &NamespaceToken,
792        kind: &str,
793        name: Option<&str>,
794        content: &str,
795        salience: Option<f64>,
796        decay_factor: f64,
797        properties: Option<serde_json::Value>,
798        annotates: Vec<Uuid>,
799        embedding_model: Option<&str>,
800    ) -> RuntimeResult<(Note, Vec<(String, u64)>)> {
801        let (note, _, degradations, fences) = self
802            .create_note_inner(
803                token,
804                kind,
805                name,
806                content,
807                None,
808                salience,
809                Some(decay_factor),
810                properties,
811                annotates,
812                embedding_model,
813                true,
814                false,
815            )
816            .await?;
817        legacy_post_commit_result(
818            "create_note_with_decay_for_embedding_model_with_visibility",
819            note.id,
820            (note, fences),
821            degradations,
822        )
823    }
824
825    /// Memory-pack create returning both its committed vector fences and
826    /// embedding-input truncation accounting. Other post-commit degradations
827    /// retain the same non-retryable error behavior as the receipt-only API.
828    #[allow(clippy::too_many_arguments)]
829    pub async fn create_note_with_decay_for_embedding_model_with_visibility_and_report(
830        &self,
831        token: &NamespaceToken,
832        kind: &str,
833        name: Option<&str>,
834        content: &str,
835        salience: Option<f64>,
836        decay_factor: f64,
837        properties: Option<serde_json::Value>,
838        annotates: Vec<Uuid>,
839        embedding_model: Option<&str>,
840    ) -> RuntimeResult<(
841        Note,
842        Vec<(String, u64)>,
843        crate::retrieval::EmbeddingTruncationReport,
844    )> {
845        let (note, embedding, degradations, fences) = self
846            .create_note_inner(
847                token,
848                kind,
849                name,
850                content,
851                None,
852                salience,
853                Some(decay_factor),
854                properties,
855                annotates,
856                embedding_model,
857                true,
858                false,
859            )
860            .await?;
861        legacy_post_commit_result(
862            "create_note_with_decay_for_embedding_model_with_visibility_and_report",
863            note.id,
864            (note, fences, embedding),
865            degradations,
866        )
867    }
868
869    /// Insert a note using `INSERT OR IGNORE` semantics for atomic deduplication.
870    ///
871    /// Returns `Ok(Some(note))` when the note was newly written.  Returns
872    /// `Ok(None)` when a unique constraint (e.g. the channel-scoped `external_id`
873    /// partial index on comm message notes) was already satisfied by an existing row,
874    /// making this call a no-op. Indexing failures after an insert return a
875    /// typed `post_commit_degraded` error with the committed record ID and
876    /// `retryable=false`. Healthy models still run; the note is not rolled back.
877    ///
878    /// This method is intentionally narrower than `create_note`: it skips
879    /// salience/decay, annotates edges, and embedding-model selection, which
880    /// are not needed for channel-ingest paths.
881    ///
882    /// Rejects the transport-owned properties on a `message` note: the
883    /// `message` entry of the kind-owned property list that the note-store
884    /// accessor guard enforces, so both guards refuse the same keys. These
885    /// properties are transport-owned evidence (`comm.health` trusts the
886    /// quarantine and channel ones at face value), and this fast path (unlike
887    /// the generic `create` verb funnel) is not covered by the
888    /// pack-installed note-write validator. Only the trusted channel-ingest
889    /// path may establish them — see
890    /// [`Self::try_create_note_as_trusted_ingest`].
891    pub async fn try_create_note(
892        &self,
893        token: &NamespaceToken,
894        kind: &str,
895        name: Option<&str>,
896        content: &str,
897        properties: Option<serde_json::Value>,
898    ) -> RuntimeResult<Option<Note>> {
899        self.try_create_note_impl(token, kind, name, content, properties, false, None, None)
900            .await
901    }
902
903    #[allow(clippy::too_many_arguments)]
904    async fn try_create_note_impl(
905        &self,
906        token: &NamespaceToken,
907        kind: &str,
908        name: Option<&str>,
909        content: &str,
910        properties: Option<serde_json::Value>,
911        allow_transport_owned_message_properties: bool,
912        attachment: Option<NewAttachment>,
913        expires_after: Option<std::time::Duration>,
914    ) -> RuntimeResult<Option<Note>> {
915        self.validate_note_kind(kind)?;
916        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
917        crate::secret_gate::check_note_fields_at(content, name, properties.as_ref(), "note")?;
918        if let Some(ref attachment) = attachment {
919            // The note and its owner row must share the main database. A
920            // secondary pack backend cannot atomically root the reference.
921            drop(self.attachments()?);
922            attachment.validate()?;
923            let blob_store = self.blob_store().ok_or_else(|| {
924                RuntimeError::Unconfigured(
925                    "trusted ingest attachment requires an installed BlobStore".to_string(),
926                )
927            })?;
928            if !blob_store.exists(&attachment.content_ref).await? {
929                return Err(RuntimeError::InvalidInput(format!(
930                    "trusted ingest attachment refers to an unpublished blob: {}",
931                    attachment.content_ref
932                )));
933            }
934        }
935        if !allow_transport_owned_message_properties && kind == "message" {
936            if let Some(key) = properties
937                .as_ref()
938                .and_then(serde_json::Value::as_object)
939                .and_then(|supplied| {
940                    crate::curation::kind_owned_properties("message")
941                        .iter()
942                        .copied()
943                        .find(|key| supplied.contains_key(*key))
944                })
945            {
946                return Err(RuntimeError::InvalidInput(format!(
947                    "`{key}` is transport-owned on a `message` note and cannot be supplied \
948                     through `try_create_note`; only the trusted channel-ingest path may \
949                     establish quarantine disposition and channel provenance"
950                )));
951            }
952        }
953
954        let ns = token.namespace().as_str();
955        let mut note = Note::new(ns, kind, content);
956        if let Some(retention) = expires_after {
957            let duration_us = i64::try_from(retention.as_micros()).map_err(|_| {
958                RuntimeError::InvalidInput(
959                    "trusted ingest retention exceeds i64 microseconds".into(),
960                )
961            })?;
962            note.expires_at = Some(note.created_at.checked_add(duration_us).ok_or_else(|| {
963                RuntimeError::InvalidInput("trusted ingest expiry exceeds i64 microseconds".into())
964            })?);
965        }
966        if let Some(n) = name {
967            note = note.with_name(n);
968        }
969        if let Some(p) = properties {
970            note = note.with_properties(p);
971        }
972
973        // Bypasses the `notes()` accessor's PolicyEnforcingNoteStore wrapper —
974        // the reserved-transport-property check above already enforces the
975        // identical policy, conditionally allowing the trusted-ingest path,
976        // so this reaches storage directly rather than duplicate the check
977        // through a wrapper that cannot see the trust decision this function
978        // just made.
979        let inserted = if let Some(attachment) = attachment {
980            self.raw_notes(token)?
981                .try_insert_note_with_attachments(
982                    note.clone(),
983                    vec![Attachment::from_new(
984                        note.id,
985                        AttachmentSubstrate::Note,
986                        attachment,
987                        note.created_at,
988                    )],
989                )
990                .await?
991        } else {
992            self.raw_notes(token)?.try_insert_note(note.clone()).await?
993        };
994        if !inserted {
995            return Ok(None);
996        }
997
998        let mut degradations = Vec::new();
999        match self.text_for_notes(token) {
1000            Ok(fts) => {
1001                if let Err(error) = fts.upsert_document(note_fts_document(&note)).await {
1002                    record_conditional_insert_degradation(
1003                        &mut degradations,
1004                        note.id,
1005                        ConditionalInsertStage::FtsUpsert,
1006                        error,
1007                    );
1008                }
1009            }
1010            Err(error) => record_conditional_insert_degradation(
1011                &mut degradations,
1012                note.id,
1013                ConditionalInsertStage::FtsAcquisition,
1014                error,
1015            ),
1016        }
1017
1018        let embed_model_names = self.embedding_models_for_note_kind(kind);
1019        for model_name in &embed_model_names {
1020            match self
1021                .embed_document_with_model_outcome_for_token(
1022                    token,
1023                    model_name,
1024                    note_embedding_text_ref(&note),
1025                )
1026                .await
1027            {
1028                Ok(outcome) => {
1029                    if outcome.truncated {
1030                        tracing::warn!(
1031                            note_id = %note.id,
1032                            model = %outcome.model_name,
1033                            source_bytes = outcome.source_bytes,
1034                            embedded_bytes = outcome.embedded_bytes,
1035                            "try_create_note: embedding input truncated; full content stored unchanged"
1036                        );
1037                    }
1038                    match self.vectors_for_model(token, model_name) {
1039                        Ok(vs) => {
1040                            if let Err(error) = vs
1041                                .insert(
1042                                    note.id,
1043                                    SubstrateKind::Note,
1044                                    ns,
1045                                    "note.content",
1046                                    vec![outcome.vector],
1047                                )
1048                                .await
1049                            {
1050                                record_conditional_insert_degradation(
1051                                    &mut degradations,
1052                                    note.id,
1053                                    ConditionalInsertStage::VectorInsert,
1054                                    format!("model {model_name}: {error}"),
1055                                );
1056                            }
1057                        }
1058                        Err(error) => record_conditional_insert_degradation(
1059                            &mut degradations,
1060                            note.id,
1061                            ConditionalInsertStage::VectorAcquisition,
1062                            format!("model {model_name}: {error}"),
1063                        ),
1064                    }
1065                }
1066                Err(error) => record_conditional_insert_degradation(
1067                    &mut degradations,
1068                    note.id,
1069                    ConditionalInsertStage::Embedding,
1070                    format!("model {model_name}: {error}"),
1071                ),
1072            }
1073        }
1074
1075        legacy_post_commit_result("try_create_note", note.id, Some(note), degradations)
1076    }
1077
1078    // REASON: private inner function unifies all create_note variants; it receives every
1079    // optional parameter individually so that public variants can pass None without
1080    // requiring callers to construct an intermediate struct.
1081    #[allow(clippy::too_many_arguments)]
1082    async fn create_note_inner(
1083        &self,
1084        token: &NamespaceToken,
1085        kind: &str,
1086        name: Option<&str>,
1087        content: &str,
1088        embedding_content: Option<&str>,
1089        salience: Option<f64>,
1090        decay_factor: Option<f64>,
1091        properties: Option<serde_json::Value>,
1092        annotates: Vec<Uuid>,
1093        embedding_model: Option<&str>,
1094        capture_visibility: bool,
1095        web_receipt: bool,
1096    ) -> RuntimeResult<(
1097        Note,
1098        crate::retrieval::EmbeddingTruncationReport,
1099        Vec<PostCommitDegradation>,
1100        Vec<(String, u64)>,
1101    )> {
1102        self.validate_note_kind(kind)?;
1103        // Owned identity properties are derived from the authorization token
1104        // before anything else touches them, so every caller of this function —
1105        // the generic `create` verb and direct Rust callers alike — stores the
1106        // same derived values. Runs before the secret gate so the gate scans
1107        // exactly what will be written.
1108        let mut properties = self.derive_note_write_properties(kind, token, properties)?;
1109        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
1110        if web_receipt {
1111            let map = properties
1112                .as_mut()
1113                .and_then(serde_json::Value::as_object_mut)
1114                .expect("web receipt properties are constructed as an object");
1115            map.insert(
1116                crate::secret_gate::RESERVED_WEB_RECEIPT_KEY.to_string(),
1117                serde_json::Value::String(
1118                    crate::secret_gate::WEB_RECEIPT_PROVENANCE_VALUE.to_string(),
1119                ),
1120            );
1121        }
1122        // Secret gate: scan content, optional name, and structured properties.
1123        crate::secret_gate::check_note_fields_at(content, name, properties.as_ref(), "note")?;
1124        // `embedding_content` is a caller-supplied alternate vector-embedding
1125        // input: it must be a non-empty proper prefix of `content` (never a
1126        // superset, an unrelated string, or the full text) and passes the
1127        // same secret gate as any other stored/embedded text. Rejected
1128        // before any write, same as the checks above.
1129        if let Some(ec) = embedding_content {
1130            if ec.is_empty() {
1131                return Err(RuntimeError::InvalidInput(
1132                    "embedding_content must not be empty".into(),
1133                ));
1134            }
1135            if ec.len() >= content.len() || !content.starts_with(ec) {
1136                return Err(RuntimeError::InvalidInput(
1137                    "embedding_content must be a proper prefix of content".into(),
1138                ));
1139            }
1140            crate::secret_gate::check_at(ec, "note", "embedding_content")?;
1141        }
1142        let ns = token.namespace().as_str();
1143
1144        // Validate all annotates targets before any write (atomicity: all-or-nothing).
1145        // Endpoint resolution is by-ID and namespace-agnostic.
1146        for &target_id in &annotates {
1147            if !self.substrate_exists_by_id(token, target_id).await? {
1148                return Err(RuntimeError::NotFound(format!(
1149                    "create_note annotates target {target_id} not found"
1150                )));
1151            }
1152        }
1153
1154        // Reject non-finite or out-of-range salience/decay at the runtime boundary
1155        // rather than letting storage silently clamp them (coding-standards §508-516).
1156        if let Some(s) = salience {
1157            if !s.is_finite() || !(0.0..=1.0).contains(&s) {
1158                return Err(RuntimeError::InvalidInput(format!(
1159                    "salience must be a finite value in [0.0, 1.0]; got {s}"
1160                )));
1161            }
1162        }
1163        if let Some(d) = decay_factor {
1164            if !d.is_finite() || d < 0.0 {
1165                return Err(RuntimeError::InvalidInput(format!(
1166                    "decay_factor must be a finite value >= 0.0; got {d}"
1167                )));
1168            }
1169        }
1170
1171        // Resolve embedding_model BEFORE any note/FTS/vector write so unknown-model
1172        // errors are atomic at the runtime layer, not just at one pack handler.
1173        // Direct Rust callers (other packs, integration tests) get the same guarantee.
1174        if let Some(model_name) = embedding_model {
1175            self.resolve_embedding_model(Some(model_name))?;
1176        }
1177
1178        let mut note = Note::new(ns, kind, content);
1179        if let Some(s) = salience {
1180            note = note.with_salience(s);
1181        }
1182        if let Some(df) = decay_factor {
1183            note = note.with_decay(df);
1184        }
1185        if let Some(n) = name {
1186            note = note.with_name(n);
1187        }
1188        if let Some(p) = properties {
1189            note = note.with_properties(p);
1190        }
1191        let notes = if web_receipt {
1192            self.raw_notes(token)?
1193        } else {
1194            self.notes(token)?
1195        };
1196        notes.upsert_note(note.clone()).await?;
1197
1198        // From here on, any error must compensate by removing the note row, its
1199        // FTS document, and any vector entries already inserted — the same
1200        // cleanup used by the annotates-edge block below.
1201
1202        // Decide which embedding models to use (before touching FTS/vectors).
1203        let embed_model_names: Vec<String> = if let Some(m) = embedding_model {
1204            vec![m.to_string()]
1205        } else {
1206            self.embedding_models_for_note_kind(kind)
1207        };
1208
1209        // FTS step — compensate note row on failure.
1210        {
1211            // Injection: check FTS_FAIL_NS (armed by `arm_fts_fail_scoped(ns)`).
1212            // Fires only when `ns` is in the armed set, removing it on the way
1213            // out (one-shot, atomic check-and-remove under the mutex). No lock
1214            // acquisition in release builds — the cfg(not) branch is a const
1215            // false so the compiler eliminates the if-branch entirely.
1216            #[cfg(any(test, feature = "fault-injection"))]
1217            let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
1218            #[cfg(not(any(test, feature = "fault-injection")))]
1219            let fts_inject = false;
1220            let fts_result: RuntimeResult<()> = if fts_inject {
1221                Err(RuntimeError::Internal("injected FTS failure".to_string()))
1222            } else {
1223                let statements =
1224                    khive_db::stores::text::delete_document_statements("fts_notes", ns, note.id)
1225                        .into_iter()
1226                        .chain(khive_db::stores::text::insert_document_statements(
1227                            "fts_notes",
1228                            &note_fts_document(&note),
1229                        ))
1230                        .collect();
1231                self.apply_note_index_revision(&note, statements)
1232                    .await
1233                    .map(|_| ())
1234            };
1235
1236            if let Err(e) = fts_result {
1237                self.compensate_note_creation(&note).await;
1238                return Err(e);
1239            }
1240        }
1241
1242        // Vector embedding + insert step — compensate note row + FTS doc on failure.
1243        // Multi-model vector embedding:
1244        //   - explicit embedding_model → single model (existing behaviour)
1245        //   - None → the note kind's declared model policy
1246        //   - None + no models configured → skip (text-only)
1247        // The effective text sent to every embedder: the caller-supplied
1248        // capped override when present, otherwise the full stored content.
1249        // FTS indexing above always used the full `note.content` — this cap
1250        // affects only the vector-embedding input.
1251        let canonical_embed_text = note_embedding_text_ref(&note);
1252        let embed_text = embedding_content.unwrap_or(canonical_embed_text);
1253
1254        let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
1255        let mut vector_fences = Vec::with_capacity(embed_model_names.len());
1256        if embed_model_names.len() == 1 {
1257            // Single-model path: preserves original sequential behaviour.
1258            let model_name = &embed_model_names[0];
1259            let vec_result = self
1260                .embed_document_with_model_outcome_for_token(token, model_name, embed_text)
1261                .await;
1262
1263            // Injection: check VECTOR_FAIL_NS (armed by `arm_vector_fail_scoped(ns)`) or
1264            // VECTOR_FAIL_AFTER (armed by `arm_vector_fail_after(n)`). The former
1265            // fires only when the armed namespace matches this note's namespace;
1266            // callers that cannot guarantee no concurrently-running test also
1267            // writes a note into that same namespace (e.g. a test suite whose
1268            // fixtures share one default namespace) should prefer the latter,
1269            // thread-local count instead — see its doc comment. Either clears
1270            // (one-shot) once it fires. No lock/cell access in release builds —
1271            // the cfg(not) branch is a const false eliminating the if-branch.
1272            #[cfg(any(test, feature = "fault-injection"))]
1273            let vec_inject = {
1274                let ns_inject = consume_fault(&VECTOR_FAIL_NS, ns);
1275                let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
1276                    Some(0) => {
1277                        cell.set(None);
1278                        true
1279                    }
1280                    Some(n) => {
1281                        cell.set(Some(n - 1));
1282                        false
1283                    }
1284                    None => false,
1285                });
1286                ns_inject || count_inject
1287            };
1288            #[cfg(not(any(test, feature = "fault-injection")))]
1289            let vec_inject = false;
1290            let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
1291                if vec_inject {
1292                    Err(RuntimeError::Internal(
1293                        "injected vector failure".to_string(),
1294                    ))
1295                } else {
1296                    vec_result
1297                };
1298
1299            let single_model_result: RuntimeResult<()> = match vec_result {
1300                Ok(outcome) => {
1301                    embedding_report.observe(&outcome);
1302                    if capture_visibility {
1303                        match self
1304                            .publish_note_vector_revision_with_seq(
1305                                token,
1306                                &note,
1307                                model_name,
1308                                &outcome.vector,
1309                            )
1310                            .await
1311                        {
1312                            Ok(Some(seq)) => {
1313                                vector_fences.push((model_name.clone(), seq));
1314                                Ok(())
1315                            }
1316                            Ok(None) => Ok(()),
1317                            Err(error) => Err(error),
1318                        }
1319                    } else {
1320                        self.publish_note_vector_revision(token, &note, model_name, &outcome.vector)
1321                            .await
1322                            .map(|_| ())
1323                    }
1324                }
1325                Err(e) => Err(e),
1326            };
1327            if let Err(e) = single_model_result {
1328                self.compensate_note_creation(&note).await;
1329                return Err(e);
1330            }
1331        } else if !embed_model_names.is_empty() {
1332            // Multi-model path: embed with each model in parallel via spawned tasks,
1333            // then insert one VectorRecord per model.
1334            let rt_clone = self.clone();
1335            // JoinSet tasks require owned text; an Arc keeps this to one
1336            // content-sized allocation rather than one clone per model.
1337            let content_owned: std::sync::Arc<str> = std::sync::Arc::from(embed_text);
1338            let usage_ctx = crate::usage::current();
1339            let mut join_set = tokio::task::JoinSet::new();
1340            for (idx, model_name) in embed_model_names.iter().enumerate() {
1341                let rt = rt_clone.clone();
1342                let text = std::sync::Arc::clone(&content_owned);
1343                let name = model_name.clone();
1344                let ctx = usage_ctx.clone();
1345                let token = (*token).clone();
1346                join_set.spawn(crate::runtime::inherit_request_embedder_scope(async move {
1347                    let fut = rt.embed_document_with_model_outcome_for_token(
1348                        &token,
1349                        &name,
1350                        text.as_ref(),
1351                    );
1352                    let result = match ctx {
1353                        Some(ctx) => crate::usage::scope(ctx, fut).await,
1354                        None => fut.await,
1355                    };
1356                    (idx, result)
1357                }));
1358            }
1359            // The first failed or panicked handle aborts and detaches its
1360            // siblings. Embed usage is counted at dispatch, so a synchronous
1361            // provider winding down in the background cannot change it.
1362            let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
1363                Ok(outcomes) => outcomes,
1364                Err(e) => {
1365                    self.compensate_note_creation(&note).await;
1366                    return Err(e);
1367                }
1368            };
1369            // TODO(P2): parallelize vector inserts
1370            for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
1371                embedding_report.observe(&outcome);
1372                let insert_result = if capture_visibility {
1373                    self.publish_note_vector_revision_with_seq(
1374                        token,
1375                        &note,
1376                        model_name,
1377                        &outcome.vector,
1378                    )
1379                    .await
1380                    .map(|seq| {
1381                        if let Some(seq) = seq {
1382                            vector_fences.push((model_name.clone(), seq));
1383                        }
1384                    })
1385                } else {
1386                    self.publish_note_vector_revision(token, &note, model_name, &outcome.vector)
1387                        .await
1388                        .map(|_| ())
1389                };
1390                if let Err(e) = insert_result {
1391                    self.compensate_note_creation(&note).await;
1392                    return Err(e);
1393                }
1394            }
1395        }
1396
1397        // Create annotates edges, compensating on failure to preserve atomicity.
1398        // Pre-validation (above) ensures all targets exist, so link failures are
1399        // unexpected. If one occurs, purge incident edges and the note in one
1400        // transaction; a failed purge retains the live note as their source.
1401        let mut created_edges: Vec<Uuid> = Vec::with_capacity(annotates.len());
1402
1403        // In test builds, iterate with an index so the failure-injection hook can
1404        // target a specific call.  In release builds, skip the enumerate overhead.
1405        #[cfg(test)]
1406        let annotates_iter: Vec<(usize, Uuid)> = annotates
1407            .iter()
1408            .enumerate()
1409            .map(|(i, &id)| (i, id))
1410            .collect();
1411        #[cfg(test)]
1412        macro_rules! next_target {
1413            ($pair:expr) => {
1414                $pair.1
1415            };
1416        }
1417        #[cfg(not(test))]
1418        let annotates_iter: Vec<Uuid> = annotates.to_vec();
1419        #[cfg(not(test))]
1420        macro_rules! next_target {
1421            ($pair:expr) => {
1422                $pair
1423            };
1424        }
1425
1426        for pair in annotates_iter {
1427            let target_id = next_target!(pair);
1428
1429            // Test-only: inject a failure on the configured call index (1-based).
1430            #[cfg(test)]
1431            let injected_err: Option<RuntimeError> = {
1432                let call_idx = pair.0;
1433                LINK_FAIL_AFTER.with(|cell| {
1434                    let n = cell.get();
1435                    if n > 0 && call_idx + 1 == n {
1436                        cell.set(0); // reset so subsequent calls are unaffected
1437                        Some(RuntimeError::Internal("injected link failure".to_string()))
1438                    } else {
1439                        None
1440                    }
1441                })
1442            };
1443            #[cfg(not(test))]
1444            let injected_err: Option<RuntimeError> = None;
1445
1446            let link_result = if let Some(e) = injected_err {
1447                Err(e)
1448            } else {
1449                self.link(
1450                    token,
1451                    note.id,
1452                    target_id,
1453                    EdgeRelation::Annotates,
1454                    1.0,
1455                    None,
1456                )
1457                .await
1458            };
1459
1460            match link_result {
1461                Ok(edge) => created_edges.push(edge.id.into()),
1462                Err(e) => {
1463                    // The graph purge, index cleanup, and note removal share
1464                    // one writer transaction. If the edge purge fails, its
1465                    // transaction rolls back, preserving a live source note
1466                    // for the surviving edges instead of orphaning them.
1467                    let edge_ids = created_edges
1468                        .iter()
1469                        .map(Uuid::to_string)
1470                        .collect::<Vec<_>>()
1471                        .join(", ");
1472                    match self.compensate_note_creation_with_edges(&note).await {
1473                        Ok(true) => return Err(e),
1474                        Ok(false) => {
1475                            return Err(RuntimeError::Internal(format!(
1476                                "create_note: annotates link failed: {e}; note {} changed before \
1477                                 compensation, retaining its incident edges [{edge_ids}]",
1478                                note.id
1479                            )));
1480                        }
1481                        Err(cleanup_error) => {
1482                            return Err(RuntimeError::Internal(format!(
1483                                "create_note: annotates link failed: {e}; compensation failed \
1484                                 for note {} and retained edges [{edge_ids}]: {cleanup_error}; \
1485                                 note and edges remain for reconciliation",
1486                                note.id
1487                            )));
1488                        }
1489                    }
1490                }
1491            }
1492        }
1493
1494        // Same contract as the entity arrival event above: after compensation,
1495        // so a rolled-back create leaves no event. This is the single funnel for
1496        // every note create in the product, which is why the memory pack's own
1497        // note_created emitter was removed rather than left beside it.
1498        let created_event = khive_storage::event::Event::new(
1499            note.namespace.clone(),
1500            "create",
1501            EventKind::NoteCreated,
1502            SubstrateKind::Note,
1503            "",
1504        )
1505        .with_target(note.id)
1506        .with_payload(serde_json::json!({
1507            "id": note.id,
1508            "namespace": note.namespace,
1509            "kind": note.kind,
1510            "salience": note.salience,
1511        }));
1512        let event_result = match self.events(token) {
1513            Ok(store) => store
1514                .append_event(created_event)
1515                .await
1516                .map_err(RuntimeError::from),
1517            Err(error) => Err(error),
1518        };
1519        let mut degradations = Vec::new();
1520        if let Err(error) = event_result {
1521            record_post_commit_degradation(
1522                &mut degradations,
1523                "create_note",
1524                note.id,
1525                "event_append",
1526                error,
1527            );
1528        }
1529
1530        vector_fences.sort_by(|a, b| a.0.cmp(&b.0));
1531        Ok((note, embedding_report, degradations, vector_fences))
1532    }
1533
1534    /// Search notes using a hybrid FTS5 + vector pipeline with salience weighting.
1535    ///
1536    /// Pipeline:
1537    /// 1. FTS5 query against `notes_<namespace>`.
1538    /// 2. If embedding model is configured: vector search filtered to `kind="note"`.
1539    /// 3. RRF fusion (k=60).
1540    /// 4. Salience-weighted rerank: `score *= (0.5 + 0.5 * note.salience)`.
1541    /// 5. Filter soft-deleted notes, apply optional kind / tag / properties predicates.
1542    ///    Tags and properties are pushed into the per-note fetch loop BEFORE truncation
1543    ///    so that matching notes ranked beyond `limit` in the raw fusion are not silently
1544    ///    dropped.
1545    /// 6. Truncate to `limit`.
1546    ///
1547    /// `tags_any`: when non-empty, only notes that have at least one of these tags
1548    /// (stored in `properties["tags"]`, case-insensitive match) are retained. The
1549    /// check happens inside the alive-note loop, before `hits.truncate(limit)`.
1550    ///
1551    /// `properties_filter`: when `Some`, only notes whose `properties` JSON object is
1552    /// a superset of the given filter object are retained. Also applied before truncation.
1553    #[allow(clippy::too_many_arguments)]
1554    pub async fn search_notes(
1555        &self,
1556        token: &NamespaceToken,
1557        query_text: &str,
1558        query_vector: Option<Vec<f32>>,
1559        limit: u32,
1560        note_kind: Option<&str>,
1561        include_superseded: bool,
1562        tags_any: &[String],
1563        properties_filter: Option<&serde_json::Value>,
1564    ) -> RuntimeResult<Vec<NoteSearchHit>> {
1565        self.search_notes_with_text_mode(
1566            token,
1567            query_text,
1568            query_vector,
1569            limit,
1570            note_kind,
1571            include_superseded,
1572            tags_any,
1573            properties_filter,
1574            TextQueryMode::Plain,
1575        )
1576        .await
1577    }
1578
1579    /// Note search with an explicit lexical mode for the text arm.
1580    #[allow(clippy::too_many_arguments)]
1581    pub async fn search_notes_with_text_mode(
1582        &self,
1583        token: &NamespaceToken,
1584        query_text: &str,
1585        query_vector: Option<Vec<f32>>,
1586        limit: u32,
1587        note_kind: Option<&str>,
1588        include_superseded: bool,
1589        tags_any: &[String],
1590        properties_filter: Option<&serde_json::Value>,
1591        text_mode: TextQueryMode,
1592    ) -> RuntimeResult<Vec<NoteSearchHit>> {
1593        let (hits, _note_status_dropped) = self
1594            .search_notes_with_text_mode_and_status(
1595                token,
1596                query_text,
1597                query_vector,
1598                limit,
1599                note_kind,
1600                include_superseded,
1601                tags_any,
1602                properties_filter,
1603                text_mode,
1604                khive_storage::note::NoteStatusSelector::Active,
1605                None,
1606            )
1607            .await?;
1608        Ok(hits)
1609    }
1610
1611    /// Coordinator fan-out variant of [`Self::search_notes`]: the text arm
1612    /// still fails loud, but a vector-arm failure after a successful text leg
1613    /// is captured instead of discarding the text hits — mirrors
1614    /// [`Self::hybrid_search_outcome`]'s contract for the entity substrate.
1615    /// Reserved for `SubstrateCoordinator::fan_out_search_with_visibility`;
1616    /// every other caller keeps the fail-loud [`Self::search_notes`] contract.
1617    #[allow(clippy::too_many_arguments)]
1618    pub async fn search_notes_outcome(
1619        &self,
1620        token: &NamespaceToken,
1621        query_text: &str,
1622        limit: u32,
1623        note_kind: Option<&str>,
1624        include_superseded: bool,
1625        tags_any: &[String],
1626        properties_filter: Option<&serde_json::Value>,
1627    ) -> RuntimeResult<NoteSearchOutcome> {
1628        self.search_notes_outcome_with_text_mode(
1629            token,
1630            query_text,
1631            limit,
1632            note_kind,
1633            include_superseded,
1634            tags_any,
1635            properties_filter,
1636            TextQueryMode::Plain,
1637        )
1638        .await
1639    }
1640
1641    /// Coordinator note-search variant with an explicit lexical mode.
1642    #[allow(clippy::too_many_arguments)]
1643    pub async fn search_notes_outcome_with_text_mode(
1644        &self,
1645        token: &NamespaceToken,
1646        query_text: &str,
1647        limit: u32,
1648        note_kind: Option<&str>,
1649        include_superseded: bool,
1650        tags_any: &[String],
1651        properties_filter: Option<&serde_json::Value>,
1652        text_mode: TextQueryMode,
1653    ) -> RuntimeResult<NoteSearchOutcome> {
1654        let (outcome, _note_status_dropped) = self
1655            .search_notes_outcome_with_text_mode_and_status(
1656                token,
1657                query_text,
1658                limit,
1659                note_kind,
1660                include_superseded,
1661                tags_any,
1662                properties_filter,
1663                text_mode,
1664                khive_storage::note::NoteStatusSelector::Active,
1665                None,
1666            )
1667            .await?;
1668        Ok(outcome)
1669    }
1670
1671    /// Restore a note tombstone owned by the caller's primary namespace.
1672    ///
1673    /// A live note holding the tombstone's `(namespace, kind, key)` refuses
1674    /// the operation before any row changes. The same condition is repeated
1675    /// in the guarded restore statement for the concurrent race.
1676    pub async fn restore_note(
1677        &self,
1678        token: &NamespaceToken,
1679        id: Uuid,
1680    ) -> RuntimeResult<Option<(Note, bool)>> {
1681        let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? else {
1682            return Ok(None);
1683        };
1684        if note.namespace != token.namespace().as_str() {
1685            return Ok(None);
1686        }
1687        if note.deleted_at.is_none() {
1688            return Ok(Some((note, false)));
1689        }
1690        if let Some(key) = note.key.as_deref() {
1691            if let Some(holder) = self
1692                .notes(token)?
1693                .get_live_notes_by_key(&note.namespace, key, Some(&note.kind))
1694                .await?
1695                .into_iter()
1696                .find(|holder| holder.id != note.id)
1697            {
1698                return Err(restore_key_conflict(key, &holder));
1699            }
1700        }
1701        let updated_at =
1702            Utc::now()
1703                .timestamp_micros()
1704                .max(note.updated_at.checked_add(1).ok_or_else(|| {
1705                    RuntimeError::Internal(format!(
1706                        "note {id} updated_at is already at i64::MAX and cannot advance"
1707                    ))
1708                })?);
1709        let mut params = vec![
1710            SqlValue::Text("active".into()),
1711            SqlValue::Integer(updated_at),
1712            SqlValue::Text(id.to_string()),
1713            SqlValue::Text(note.namespace.clone()),
1714            SqlValue::Text(note.kind.clone()),
1715        ];
1716        let key_clause = if let Some(key) = note.key.as_deref() {
1717            params.push(SqlValue::Text(key.to_owned()));
1718            format!(
1719                " AND (key IS NULL OR NOT EXISTS (SELECT 1 FROM notes live \
1720                          WHERE live.namespace=?4 AND live.kind=?5 AND live.key=?{} \
1721                            AND live.deleted_at IS NULL AND live.id != notes.id))",
1722                params.len()
1723            )
1724        } else {
1725            String::new()
1726        };
1727        let mut restored = note.clone();
1728        restored.status = "active".into();
1729        restored.deleted_at = None;
1730        restored.updated_at = updated_at;
1731        restored.version = restored
1732            .version
1733            .checked_add(1)
1734            .ok_or_else(|| RuntimeError::Internal(format!("note {id} version is exhausted")))?;
1735        let mut statements = vec![PlanStatement {
1736            statement: SqlStatement {
1737                sql: format!(
1738                    "UPDATE notes SET status=?1, deleted_at=NULL, updated_at=?2 \
1739                     WHERE id=?3 AND namespace=?4 AND kind=?5 AND deleted_at IS NOT NULL{key_clause}"
1740                ),
1741                params,
1742                label: Some("note-restore".into()),
1743            },
1744            guard: Some(AffectedRowGuard::exactly(1)),
1745        }];
1746        // Text index published in the same unit as the row; see restore_entity.
1747        for statement in
1748            khive_db::stores::text::delete_document_statements("fts_notes", &restored.namespace, id)
1749                .into_iter()
1750                .chain(insert_document_statements(
1751                    "fts_notes",
1752                    &note_fts_document(&restored),
1753                ))
1754        {
1755            statements.push(PlanStatement {
1756                statement,
1757                guard: None,
1758            });
1759        }
1760        let plan = AtomicOpPlan::Update(Box::new(UpdatePlan {
1761            graph_effects: Vec::new(),
1762            target_id: id,
1763            statements,
1764            post_commit: PostCommitEffect::None,
1765            edge_natural_key: None,
1766            idempotent_noop: false,
1767            entity_guard: None,
1768            note_guard: None,
1769            note_vector_purge: None,
1770            note_embedding_inheritance: None,
1771        }));
1772        match run_atomic_unit(self.sql().as_ref(), vec![plan]).await {
1773            Ok(AtomicRunOutcome::Committed { .. }) => {
1774                #[cfg(any(test, feature = "fault-injection"))]
1775                if consume_fault(&FTS_FAIL_NS, &restored.namespace) {
1776                    return Err(restore_reindex_failed(
1777                        "note",
1778                        id,
1779                        RuntimeError::Internal("injected FTS failure".to_string()),
1780                    ));
1781                }
1782                let reindexed = self.reindex_note_with_report(token, &restored).await;
1783                let report = reindexed.map_err(|e| restore_reindex_failed("note", id, e))?;
1784                let degradations = report.post_commit_degradations();
1785                legacy_post_commit_result("restore_note", id, Some((restored, true)), degradations)
1786            }
1787            Ok(AtomicRunOutcome::RolledBack {
1788                failure: AtomicOpFailure::GuardFailed { .. },
1789                ..
1790            }) => {
1791                if let Some(key) = note.key.as_deref() {
1792                    if let Some(holder) = self
1793                        .notes(token)?
1794                        .get_live_notes_by_key(&note.namespace, key, Some(&note.kind))
1795                        .await?
1796                        .into_iter()
1797                        .find(|holder| holder.id != note.id)
1798                    {
1799                        return Err(restore_key_conflict(key, &holder));
1800                    }
1801                }
1802                Err(RuntimeError::NotFound(format!(
1803                    "note {id} is no longer a caller-owned tombstone"
1804                )))
1805            }
1806            Ok(AtomicRunOutcome::RolledBack { failure, .. }) => Err(RuntimeError::Internal(
1807                format!("note restore rolled back: {failure:?}"),
1808            )),
1809            Err(error) => Err(RuntimeError::Storage(error.0)),
1810        }
1811    }
1812}
1813
1814/// Fully specified edge creation request — input to [`KhiveRuntime::build_edge`]
1815/// and [`KhiveRuntime::link_many`].
1816#[derive(Clone, Debug)]
1817pub struct LinkSpec {
1818    pub namespace: Option<String>,
1819    pub source_id: Uuid,
1820    pub target_id: Uuid,
1821    pub relation: EdgeRelation,
1822    pub weight: f64,
1823    pub metadata: Option<serde_json::Value>,
1824    pub resurrect: bool,
1825}
1826
1827/// Fully specified entity creation request — input to [`KhiveRuntime::create_many`].
1828///
1829/// `entity_type` is validated at the runtime layer by the pack-installed
1830/// entity-type validator. When a validator
1831/// is installed (e.g. by `KgPack`), unknown types are rejected with the valid
1832/// set listed. When no validator is installed (bare runtime without packs),
1833/// the value passes through — the handler layer is the primary enforcement point.
1834#[derive(Clone, Debug)]
1835pub struct EntityCreateSpec {
1836    pub kind: String,
1837    pub entity_type: Option<String>,
1838    pub name: String,
1839    pub description: Option<String>,
1840    pub properties: Option<serde_json::Value>,
1841    pub tags: Vec<String>,
1842    /// Caller aliases (ADR-221 section 2), validated before anything is
1843    /// read. An alias equal to `name` is not stored.
1844    pub aliases: Vec<String>,
1845}
1846
1847// INLINE TEST JUSTIFICATION: tests here exercise private helpers (canonical_edge_endpoints,
1848// validate_edge_metadata, merge_dependency_kind, link-fail injection) and runtime methods
1849// that require pub(crate) KhiveRuntime construction. Moving them to tests/ would require
1850// pub-exporting those private helpers, which would widen the crate's public API surface
1851// undesirably. Broad behavioral tests live in tests/integration.rs.
1852#[cfg(test)]
1853#[path = "operations_tests.rs"]
1854mod tests;