Skip to main content

khive_runtime/
operations.rs

1// See docs/operations.md#why-this-file-is-not-split-into-submodules.
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 serde::Serialize;
10use uuid::Uuid;
11
12use khive_score::DeterministicScore;
13use khive_storage::note::Note;
14use khive_storage::types::{
15    DeleteMode, DirectedNeighborHit, Direction, EdgeSortField, GraphPath, LinkId, NeighborHit,
16    NeighborQuery, Page, PageRequest, SeekCursor, SortOrder, SqlRow, SqlStatement, SqlValue,
17    TextFilter, TextQueryMode, TextSearchRequest, TraversalRequest,
18};
19use khive_storage::{
20    Attachment, AttachmentSubstrate, Edge, EdgeRelation, Entity, EntityFilter, Event, EventFilter,
21    NewAttachment,
22};
23use khive_types::{EdgeEndpointRule, EndpointKind, EventKind, KhiveError, SubstrateKind};
24
25use khive_db::stores::entity::{entity_hard_delete_statement, entity_upsert_statement};
26use khive_db::stores::event::hard_delete_lineage_warning_statements;
27use khive_db::stores::graph::{edge_hard_delete_statement, purge_incident_edges_statement};
28use khive_db::stores::note::note_hard_delete_statement;
29use khive_db::stores::text::insert_document_statement;
30use khive_db::SqliteError;
31use rusqlite::OptionalExtension;
32
33use crate::atomic_plan::{
34    AddEntityPlan, AffectedRowGuard, DeletePlan, PlanStatement, PostCommitEffect,
35};
36use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
37use crate::curation::{entity_fts_document, note_embedding_text_ref, note_fts_document};
38use crate::error::{GuardedWriteFailure, RuntimeError, RuntimeResult};
39use crate::runtime::{KhiveRuntime, NamespaceToken};
40
41// Test-only fault-injection state; see docs/operations.md#fault-injection-static-state.
42#[cfg(test)]
43std::thread_local! {
44    static LINK_FAIL_AFTER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
45}
46
47#[cfg(any(test, feature = "fault-injection"))]
48std::thread_local! {
49    static VECTOR_FAIL_AFTER: std::cell::Cell<Option<usize>> =
50        const { std::cell::Cell::new(None) };
51}
52
53/// Arm the count-targetable vector-INSERT fault: let `n` inserts succeed, then fail
54/// the next one. See docs/operations.md#fault-injection-static-state.
55#[cfg(any(test, feature = "fault-injection"))]
56pub fn arm_vector_fail_after(n: usize) {
57    VECTOR_FAIL_AFTER.with(|cell| cell.set(Some(n)));
58}
59
60// Namespace-keyed one-shot arm sets — see docs/operations.md#fault-injection-static-state
61// (rationale for keying by namespace instead of a single Option<String> slot, #1095).
62#[cfg(any(test, feature = "fault-injection"))]
63type FaultArmSet = std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<()>>>;
64#[cfg(any(test, feature = "fault-injection"))]
65const MAX_FAULT_ARMS: usize = 64;
66#[cfg(any(test, feature = "fault-injection"))]
67static FTS_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
68    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
69#[cfg(any(test, feature = "fault-injection"))]
70static VECTOR_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
71    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
72/// Entity-create compensation failure injection; see docs/operations.md#fault-injection-static-state.
73#[cfg(any(test, feature = "fault-injection"))]
74static ENTITY_COMPENSATION_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
75    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
76/// `create_many` FTS failure injection, kept separate from `FTS_FAIL_NS` (#1263); see
77/// docs/operations.md#fault-injection-static-state.
78#[cfg(any(test, feature = "fault-injection"))]
79static FTS_FAIL_MANY_NS: std::sync::LazyLock<FaultArmSet> =
80    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
81/// `create_many` FTS partial-failure injection (exercises the `summary.failed > 0` rollback
82/// branch); see docs/operations.md#fault-injection-static-state.
83#[cfg(any(test, feature = "fault-injection"))]
84static FTS_FAIL_MANY_PARTIAL_NS: std::sync::LazyLock<FaultArmSet> =
85    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
86/// `resolve_prefix_inner` storage-failure injection, keyed by the scanned prefix string
87/// rather than a namespace (the `resolve_prefix_unfiltered*` entry points pass
88/// `namespaces: None` by contract, so there is no namespace to key on); see
89/// docs/operations.md#fault-injection-static-state.
90#[cfg(any(test, feature = "fault-injection"))]
91static PREFIX_RESOLVE_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
92    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
93
94/// Scoped ownership of a process-wide fault-injection arm.
95#[cfg(any(test, feature = "fault-injection"))]
96#[must_use = "the fault injection is disarmed when this guard is dropped"]
97pub struct FaultInjectionArm {
98    namespace: String,
99    token: std::sync::Arc<()>,
100    arms: &'static FaultArmSet,
101}
102
103#[cfg(any(test, feature = "fault-injection"))]
104impl Drop for FaultInjectionArm {
105    fn drop(&mut self) {
106        let mut arms = self.arms.lock().unwrap();
107        if arms
108            .get(&self.namespace)
109            .is_some_and(|token| std::sync::Arc::ptr_eq(token, &self.token))
110        {
111            arms.remove(&self.namespace);
112        }
113    }
114}
115
116#[cfg(any(test, feature = "fault-injection"))]
117fn arm_fault(arms: &'static FaultArmSet, namespace: &str, max_arms: usize) -> FaultInjectionArm {
118    let token = std::sync::Arc::new(());
119    let refusal = {
120        let mut active = arms.lock().unwrap();
121        if active.contains_key(namespace) {
122            Some("the namespace is already armed")
123        } else if active.len() >= max_arms {
124            Some("the arm set is at capacity")
125        } else {
126            active.insert(namespace.to_string(), std::sync::Arc::clone(&token));
127            None
128        }
129    };
130    if let Some(reason) = refusal {
131        panic!("cannot arm fault injection for namespace `{namespace}`: {reason}");
132    }
133    FaultInjectionArm {
134        namespace: namespace.to_string(),
135        token,
136        arms,
137    }
138}
139
140#[cfg(any(test, feature = "fault-injection"))]
141fn consume_fault(arms: &FaultArmSet, namespace: &str) -> bool {
142    arms.lock().unwrap().remove(namespace).is_some()
143}
144/// Non-parser FTS *search*-leg failure injection for `search_notes`: distinct
145/// from `FTS_FAIL_NS` (which injects at the FTS *upsert*/write step of
146/// `create_note_inner`). Injects a `StorageError::Timeout` at the `search()`
147/// call the FTS fail-open arm guards, so the arm's `is_fts5_syntax_error()`
148/// gate can be exercised against a genuine non-parser failure and asserted to
149/// propagate rather than degrade.
150#[cfg(any(test, feature = "fault-injection"))]
151static FTS_SEARCH_FAIL_NS: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
152
153/// Arm a one-shot FTS failure injection for `create_note_inner`/`create_entity_inner`
154/// targeting namespace `ns`.
155///
156/// The next `create_note` or `create_entity` call whose namespace equals `ns` returns
157/// an injected error at the FTS upsert step (after the row is committed), then disarms
158/// — only that namespace's entry is consumed. The arm is process-wide and thread
159/// independent: it may be set from one OS thread and consumed by a `create_note`/
160/// `create_entity` call running on another (e.g. inside `tokio::spawn`). Concurrent
161/// arms of distinct namespaces do not interfere with each other.
162/// Keep the returned guard alive until the triggering call completes; dropping it
163/// disarms an unconsumed injection.
164/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
165#[cfg(any(test, feature = "fault-injection"))]
166pub fn arm_fts_fail_scoped(ns: &str) -> FaultInjectionArm {
167    arm_fault(&FTS_FAIL_NS, ns, MAX_FAULT_ARMS)
168}
169
170/// Arm the FTS failure injection for `create_many` targeting namespace `ns`.
171///
172/// The next `create_many` call whose namespace equals `ns` returns an injected
173/// error at the first FTS statement inside the atomic batch, then disarms.
174/// Calls on other namespaces are unaffected, and concurrent arms of distinct
175/// namespaces do not overwrite each other.
176/// Keep the returned guard alive until the triggering call completes; dropping it
177/// disarms an unconsumed injection.
178/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
179#[cfg(any(test, feature = "fault-injection"))]
180pub fn arm_fts_fail_many_scoped(ns: &str) -> FaultInjectionArm {
181    arm_fault(&FTS_FAIL_MANY_NS, ns, MAX_FAULT_ARMS)
182}
183
184/// Arm a mid-batch FTS failure for `create_many` targeting namespace `ns`.
185///
186/// The next matching call fails the second FTS statement when the batch contains at
187/// least two entities, after one entity/FTS pair has executed in the transaction.
188/// A one-entity batch fails its first FTS statement. Then disarms only that namespace.
189/// Keep the returned guard alive until the triggering call completes; dropping it
190/// disarms an unconsumed injection.
191/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
192#[cfg(any(test, feature = "fault-injection"))]
193pub fn arm_fts_fail_many_partial_scoped(ns: &str) -> FaultInjectionArm {
194    arm_fault(&FTS_FAIL_MANY_PARTIAL_NS, ns, MAX_FAULT_ARMS)
195}
196
197/// Arm a non-parser FTS *search*-leg failure injection for `search_notes` targeting
198/// any call whose visible namespaces include `ns`.
199///
200/// The next `search_notes` call touching `ns` returns `StorageError::Timeout` from
201/// the FTS leg instead of calling the real `TextSearch::search`, then disarms.
202/// Used to prove the fail-open arm in `search_notes` propagates non-parser
203/// `StorageError`s instead of silently degrading them the way a genuine FTS5
204/// parser syntax error is degraded.
205/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
206#[cfg(any(test, feature = "fault-injection"))]
207pub fn arm_fts_search_fail(ns: &str) {
208    *FTS_SEARCH_FAIL_NS.lock().unwrap() = Some(ns.to_string());
209}
210
211/// Arm the vector insertion failure injection for `create_note_inner` targeting `ns`.
212///
213/// The next `create_note` call whose note namespace equals `ns` returns an injected
214/// error at the first vector insert step, then disarms.  Calls on other namespaces
215/// are unaffected, and concurrent arms of distinct namespaces do not overwrite
216/// each other.
217/// Keep the returned guard alive until the triggering call completes; dropping it
218/// disarms an unconsumed injection.
219/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
220#[cfg(any(test, feature = "fault-injection"))]
221pub fn arm_vector_fail_scoped(ns: &str) -> FaultInjectionArm {
222    arm_fault(&VECTOR_FAIL_NS, ns, MAX_FAULT_ARMS)
223}
224
225/// Arm a one-shot entity-row cleanup failure for `create_entity`
226/// compensation in namespace `ns`.
227#[cfg(any(test, feature = "fault-injection"))]
228pub fn arm_entity_compensation_fail_scoped(ns: &str) -> FaultInjectionArm {
229    arm_fault(&ENTITY_COMPENSATION_FAIL_NS, ns, MAX_FAULT_ARMS)
230}
231
232/// Arm a one-shot storage failure injection for `resolve_prefix_inner` targeting the
233/// exact `prefix` string.
234///
235/// The next `resolve_prefix`/`resolve_prefix_unfiltered`/`resolve_prefix_including_deleted`/
236/// `resolve_prefix_unfiltered_including_deleted` call scanning this `prefix` returns an
237/// injected `StorageError::Timeout` instead of performing the table scan, then disarms.
238/// Keyed by prefix rather than namespace because the unfiltered entry points pass no
239/// namespace at all.
240/// Keep the returned guard alive until the triggering call completes; dropping it
241/// disarms an unconsumed injection.
242/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
243#[cfg(any(test, feature = "fault-injection"))]
244pub fn arm_prefix_resolve_fail_scoped(prefix: &str) -> FaultInjectionArm {
245    arm_fault(&PREFIX_RESOLVE_FAIL_NS, prefix, MAX_FAULT_ARMS)
246}
247
248/// Failure injection for `delete_note_row_first_for_compensation`'s post-row-removal
249/// cleanup step: distinct from `FTS_FAIL_NS`/`VECTOR_FAIL_NS`, which target
250/// `create_note_inner`. Lets tests prove that a rollback compensation's cleanup
251/// failure still leaves the note row (and thus the live message) gone.
252#[cfg(any(test, feature = "fault-injection"))]
253static ROLLBACK_CLEANUP_FAIL_NS: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
254
255/// Arm the rollback-compensation cleanup failure injection targeting `ns`.
256///
257/// The next `delete_note_row_first_for_compensation` call whose note namespace
258/// equals `ns` removes the row as usual, then returns an injected cleanup error
259/// instead of running the real graph/FTS/vector cleanup, then disarms.
260/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
261#[cfg(any(test, feature = "fault-injection"))]
262pub fn arm_rollback_cleanup_fail(ns: &str) {
263    *ROLLBACK_CLEANUP_FAIL_NS.lock().unwrap() = Some(ns.to_string());
264}
265
266/// `atomic_message::create_notes_atomic` equivalents of the `FTS_FAIL_NS`/
267/// `VECTOR_FAIL_NS` checks above, reusing the SAME arm sets (and thus the
268/// SAME `arm_fts_fail_scoped`/`arm_vector_fail_scoped` test API) so a test
269/// can arm one call and exercise either write path. `create_notes_atomic`
270/// builds raw `PlanStatement`s instead of calling `text_for_notes()`/
271/// `vectors_for_model().insert()`, so it cannot reuse `consume_fault`
272/// in-line the way `create_note_inner` does above; these wrappers are the
273/// seam that lets it check the same arms.
274#[cfg(any(test, feature = "fault-injection"))]
275pub(crate) fn consume_fts_fail_fault(ns: &str) -> bool {
276    consume_fault(&FTS_FAIL_NS, ns)
277}
278#[cfg(any(test, feature = "fault-injection"))]
279pub(crate) fn consume_vector_fail_fault(ns: &str) -> bool {
280    consume_fault(&VECTOR_FAIL_NS, ns)
281}
282
283/// A note search result with UUID, salience-weighted RRF score, and display text.
284#[derive(Clone, Debug)]
285pub struct NoteSearchHit {
286    pub note_id: Uuid,
287    pub score: DeterministicScore,
288    pub source: crate::SearchSource,
289    pub title: Option<String>,
290    pub snippet: Option<String>,
291}
292
293/// Re-insert hyphens at canonical UUID positions (8-4-4-4-12) into a
294/// hyphen-free hex prefix, so a `LIKE '<pattern>%'` scan against the
295/// hyphenated `id` column matches correctly. Prefixes that already
296/// contain a hyphen are passed through unchanged. No-op for len <= 8
297/// (already correct). Input longer than 32 hex chars is NOT truncated: the
298/// extra hex chars are appended past the canonical 12-char final segment
299/// with no further hyphen, so the resulting `LIKE` pattern requires literal
300/// characters beyond position 36 that no real (36-char) UUID string can
301/// ever have — the scan naturally fails closed instead of silently
302/// resolving `<valid-32-hex><extra-hex>` to the valid UUID.
303pub fn hex_prefix_to_uuid_pattern(prefix: &str) -> String {
304    if prefix.contains('-') {
305        return prefix.to_string();
306    }
307    const BOUNDARIES: [usize; 4] = [8, 13, 18, 23]; // post-hyphen-insertion offsets
308    let mut out = String::with_capacity(36);
309    for c in prefix.chars() {
310        if BOUNDARIES.contains(&out.len()) {
311            out.push('-');
312        }
313        out.push(c);
314    }
315    out
316}
317
318/// Return the inclusive lower and exclusive upper bounds for a UUID prefix
319/// stored as a canonical lowercase UUID string under SQLite's BINARY collation.
320///
321/// Compact hexadecimal prefixes and prefixes of the canonical dashed spelling
322/// are accepted. The returned bounds are canonicalized to lowercase; malformed
323/// dashed spellings and prefixes longer than one UUID fail closed. The upper
324/// bound is the shortest lexicographic successor, so a trailing run of `f`
325/// digits carries into the preceding digit. `g` is the exclusive sentinel when
326/// the prefix is all `f`, because canonical UUID strings contain only `0`-`f`.
327pub fn uuid_prefix_bounds(prefix: &str) -> Option<(String, String)> {
328    const HYPHEN_POSITIONS: [usize; 4] = [8, 13, 18, 23];
329
330    let compact = if prefix.contains('-') {
331        if prefix.len() > 36 {
332            return None;
333        }
334        let mut compact = String::with_capacity(32);
335        for (index, byte) in prefix.bytes().enumerate() {
336            if HYPHEN_POSITIONS.contains(&index) {
337                if byte != b'-' {
338                    return None;
339                }
340            } else if byte.is_ascii_hexdigit() {
341                compact.push(char::from(byte.to_ascii_lowercase()));
342            } else {
343                return None;
344            }
345        }
346        compact
347    } else {
348        if prefix.is_empty()
349            || prefix.len() > 32
350            || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit())
351        {
352            return None;
353        }
354        prefix.to_ascii_lowercase()
355    };
356
357    if compact.is_empty() || compact.len() > 32 {
358        return None;
359    }
360
361    let lower = hex_prefix_to_uuid_pattern(&compact);
362    let mut successor = compact.into_bytes();
363    let mut carried_past_start = true;
364    for index in (0..successor.len()).rev() {
365        let next = match successor[index] {
366            b'0'..=b'8' | b'a'..=b'e' => Some(successor[index] + 1),
367            b'9' => Some(b'a'),
368            b'f' => None,
369            _ => return None,
370        };
371        if let Some(next) = next {
372            successor[index] = next;
373            successor.truncate(index + 1);
374            carried_past_start = false;
375            break;
376        }
377    }
378
379    let upper = if carried_past_start {
380        "g".to_string()
381    } else {
382        let compact_upper = String::from_utf8(successor).ok()?;
383        hex_prefix_to_uuid_pattern(&compact_upper)
384    };
385    Some((lower, upper))
386}
387
388fn resolve_prefix_statement(
389    table: &str,
390    has_deleted_at: bool,
391    include_deleted: bool,
392    namespaces: Option<&[String]>,
393    lower: &str,
394    upper: &str,
395) -> SqlStatement {
396    let namespace_clause = namespaces.map(|namespaces| {
397        let placeholders: Vec<String> = (0..namespaces.len())
398            .map(|index| format!("?{}", index + 3))
399            .collect();
400        format!(" AND namespace IN ({})", placeholders.join(", "))
401    });
402    let deleted_filter = if has_deleted_at && !include_deleted {
403        " AND deleted_at IS NULL"
404    } else {
405        ""
406    };
407    let mut params = vec![
408        SqlValue::Text(lower.to_owned()),
409        SqlValue::Text(upper.to_owned()),
410    ];
411    if let Some(namespaces) = namespaces {
412        params.extend(
413            namespaces
414                .iter()
415                .map(|namespace| SqlValue::Text(namespace.clone())),
416        );
417    }
418
419    SqlStatement {
420        sql: format!(
421            "SELECT id FROM {table} \
422             WHERE id >= ?1 AND id < ?2{namespace_clause}{deleted_filter} LIMIT 2",
423            namespace_clause = namespace_clause.as_deref().unwrap_or("")
424        ),
425        params,
426        label: Some("resolve_prefix".into()),
427    }
428}
429
430fn text_preview(text: &str, max_chars: usize) -> Option<String> {
431    let trimmed = text.trim();
432    if trimmed.is_empty() {
433        None
434    } else {
435        Some(trimmed.chars().take(max_chars).collect())
436    }
437}
438
439/// Symmetric relations (`competes_with`, `composed_with`) are stored with a
440/// canonical source (lower UUID wins), so a directed `Out` or `In` query may
441/// miss results. When the relations filter is non-empty and contains **only**
442/// symmetric relations, override direction to `Both` so callers always see all
443/// edges for these relations regardless of storage canonicalization.
444fn normalize_symmetric_direction(
445    direction: Direction,
446    relations: Option<&[EdgeRelation]>,
447) -> Direction {
448    let Some(rels) = relations else {
449        return direction;
450    };
451    if rels.is_empty() {
452        return direction;
453    }
454    let all_symmetric = rels
455        .iter()
456        .all(|r| matches!(r, EdgeRelation::CompetesWith | EdgeRelation::ComposedWith));
457    if all_symmetric {
458        Direction::Both
459    } else {
460        direction
461    }
462}
463
464/// Stable tie-break rank for [`Direction`] — `Out` before `In` — used to make
465/// the both-direction sort/dedup key total over self-loop edges. A self-loop
466/// (`source_id == target_id == node_id`) produces two `UNION ALL` rows with
467/// the same `(node_id, edge_id)` but opposite directions; without direction in
468/// the key, sort-then-dedup collapses them to one and drops the direction
469/// parity a separate `Out` call plus a separate `In` call would preserve.
470fn direction_sort_rank(direction: &Direction) -> u8 {
471    match direction {
472        Direction::Out => 0,
473        Direction::In => 1,
474        Direction::Both => 2,
475    }
476}
477
478fn note_title(note: &Note) -> Option<String> {
479    note.name
480        .clone()
481        .filter(|s| !s.trim().is_empty())
482        .or_else(|| Some(format!("[{}]", note.kind.as_str())))
483}
484
485fn note_snippet(note: &Note) -> Option<String> {
486    text_preview(&note.content, 200)
487}
488
489/// Message properties established only by the trusted channel-ingest path.
490///
491/// Mirrors `khive-pack-comm`'s `TRANSPORT_OWNED_MESSAGE_PROPERTIES`. Duplicated
492/// here rather than imported because `khive-runtime` sits below `khive-pack-comm`
493/// in the dependency chain (`runtime → packs`); this list is the one place in
494/// the runtime layer that needs to know the shape of comm's trust boundary,
495/// guarding [`KhiveRuntime::try_create_note`]'s fast path.
496const TRANSPORT_OWNED_MESSAGE_PROPERTIES: &[&str] =
497    &["quarantined", "channel_kind", "channel_slug"];
498
499fn transport_owned_message_property_named_in(
500    properties: &serde_json::Map<String, serde_json::Value>,
501) -> Option<&'static str> {
502    TRANSPORT_OWNED_MESSAGE_PROPERTIES
503        .iter()
504        .copied()
505        .find(|key| properties.contains_key(*key))
506}
507
508/// Result of resolving a UUID to its substrate kind.
509#[derive(Clone, Debug)]
510pub enum Resolved {
511    Entity(Entity),
512    Note(Note),
513    Event(Event),
514    /// A record owned by a pack's private tables.
515    ///
516    /// `pack` identifies the owning pack by name, `kind` is the pack-local
517    /// record type (e.g. "domain", "atom"), and `data` is the full record as
518    /// a JSON Value. Pack-private records are not valid edge endpoints,
519    /// annotates sources, or task context entities.
520    PackRecord {
521        pack: String,
522        kind: String,
523        data: serde_json::Value,
524    },
525}
526
527/// A by-ID edge-endpoint substrate kind, including `Edge` itself.
528///
529/// Unlike [`Resolved`], this carries no record data — it is used where only
530/// the substrate classification is needed (coordinator locate/link parity
531/// with `get`, ADR-002 rule 1: `annotates` target may be entity, note, edge,
532/// or event).
533#[derive(Clone, Copy, Debug, Eq, PartialEq)]
534pub enum EdgeEndpointKind {
535    Entity,
536    Note,
537    Event,
538    Edge,
539}
540
541/// Map a resolved endpoint to its `(substrate, kind, entity_type)` triple, or
542/// `None` if the substrate is not a valid edge endpoint (events, edges).
543///
544/// `entity_type` carries the pack-owned granular subtype (`Entity::entity_type`,
545/// e.g. `"theorem"`); it is `None` for notes and for entities with no subtype.
546fn resolved_pair(r: Option<&Resolved>) -> Option<(&'static str, &str, Option<&str>)> {
547    match r? {
548        Resolved::Entity(e) => Some(("entity", e.kind.as_str(), e.entity_type.as_deref())),
549        Resolved::Note(n) => Some(("note", n.kind.as_str(), None)),
550        Resolved::Event(_) => None,
551        Resolved::PackRecord { .. } => None,
552    }
553}
554
555/// `true` if `spec` matches the given substrate + kind + entity_type triple.
556///
557/// Pure and DB-free — exposed so offline consumers (e.g. `kkernel kg
558/// validate`, which parses `(substrate, kind, entity_type)` straight out of
559/// NDJSON with no live record to resolve) can apply the exact same
560/// `EdgeEndpointRule` matching semantics `pack_rule_allows` uses internally,
561/// instead of re-deriving a parallel matcher that could drift out of sync.
562pub fn endpoint_matches(
563    spec: &EndpointKind,
564    substrate: &str,
565    kind: &str,
566    entity_type: Option<&str>,
567) -> bool {
568    match spec {
569        EndpointKind::EntityOfKind(k) => substrate == "entity" && *k == kind,
570        EndpointKind::NoteOfKind(k) => substrate == "note" && *k == kind,
571        EndpointKind::EntityOfType {
572            kind: k,
573            entity_type: t,
574        } => substrate == "entity" && *k == kind && entity_type == Some(*t),
575    }
576}
577
578/// `true` if `spec` matches the given substrate + kind + entity_type triple,
579/// treating an *absent* `entity_type` on the query side as unconstrained
580/// rather than an exact match against "no subtype".
581///
582/// Used only by the static GQL impossibility hint (`static_impossible_edge_pattern_warnings`,
583/// `accepted_entity_kind_pairs_for_relation`), which reasons over a *pattern*
584/// endpoint, not a resolved entity. A pattern endpoint that names a kind but
585/// no `entity_type` (`(a:concept)-[:depends_on]->(b:concept)`) has not ruled
586/// out any subtype, so an `EntityOfType` rule for that kind still makes the
587/// triple possible — unlike `endpoint_matches`, which the live link
588/// validator applies to *resolved* entities, where a `None` `entity_type`
589/// means the entity genuinely has no subtype and must be an exact miss
590/// against a typed rule. Do not use this for validation.
591fn pattern_endpoint_matches(
592    spec: &EndpointKind,
593    substrate: &str,
594    kind: &str,
595    entity_type: Option<&str>,
596) -> bool {
597    match spec {
598        EndpointKind::EntityOfType {
599            kind: k,
600            entity_type: t,
601        } => substrate == "entity" && *k == kind && entity_type.is_none_or(|et| et == *t),
602        _ => endpoint_matches(spec, substrate, kind, entity_type),
603    }
604}
605
606/// Relations that a composed pack `EDGE_RULES` set accepts for a given
607/// `(entity_kind, entity_type)` endpoint pair, using the EXACT SAME
608/// `endpoint_matches` semantics `pack_rule_allows` applies internally
609/// (`EntityOfKind`, `EntityOfType`, `NoteOfKind`) — never a re-filtered copy.
610///
611/// Both endpoints are treated as entities (substrate `"entity"`), matching
612/// the only case pack-layer error-hint code needs (issue #543): a rejected
613/// `link` between two already-resolved entities. `entity_type` is the
614/// pack-owned granular subtype (e.g. `"theorem"`); pass `None` for
615/// untyped entities. Exposed so `khive-pack-kg`'s hint derivation cannot
616/// silently diverge from the validator by only matching `EntityOfKind` and
617/// missing pack rules declared via `EntityOfType` (e.g. `khive-pack-formal`'s
618/// typed `theorem -> definition` `depends_on` rules).
619pub fn accepted_pack_relations_for_entities(
620    rules: &[EdgeEndpointRule],
621    src_kind: &str,
622    src_entity_type: Option<&str>,
623    tgt_kind: &str,
624    tgt_entity_type: Option<&str>,
625) -> Vec<EdgeRelation> {
626    let mut relations: Vec<EdgeRelation> = rules
627        .iter()
628        .filter(|r| {
629            endpoint_matches(&r.source, "entity", src_kind, src_entity_type)
630                && endpoint_matches(&r.target, "entity", tgt_kind, tgt_entity_type)
631        })
632        .map(|r| r.relation)
633        .collect();
634    relations.sort_by_key(|r| r.as_str());
635    relations.dedup();
636    relations
637}
638
639/// Relations accepted for one resolved entity endpoint pair under the full
640/// live contract: the base allowlist plus the loaded packs' additive rules.
641///
642/// This is the pair-oriented counterpart to the private
643/// `accepted_entity_kind_pairs_for_relation` helper. It is shared by validation
644/// errors and pack-layer hints so every write path can tell a caller which
645/// relations would be legal without maintaining a second endpoint table.
646/// Pack declarations for relations with dedicated substrate branches are
647/// excluded because the live validator resolves `annotates` and the three
648/// same-substrate special relations before pack rules are consulted.
649pub fn accepted_entity_relations_for_entities(
650    rules: &[EdgeEndpointRule],
651    src_kind: &str,
652    src_entity_type: Option<&str>,
653    tgt_kind: &str,
654    tgt_entity_type: Option<&str>,
655) -> Vec<EdgeRelation> {
656    let mut relations: Vec<EdgeRelation> = BASE_ENTITY_ENDPOINT_RULES
657        .iter()
658        .filter(|(src, _relation, tgt)| (*src == "*" || *src == src_kind) && *tgt == tgt_kind)
659        .map(|(_src, relation, _tgt)| *relation)
660        .collect();
661    relations.extend(
662        accepted_pack_relations_for_entities(
663            rules,
664            src_kind,
665            src_entity_type,
666            tgt_kind,
667            tgt_entity_type,
668        )
669        .into_iter()
670        .filter(|relation| {
671            *relation != EdgeRelation::Annotates && !crate::pack::is_special_relation(*relation)
672        }),
673    );
674    relations.sort_by_key(|relation| relation.as_str());
675    relations.dedup();
676    relations
677}
678
679fn accepted_entity_relations_description(
680    rules: &[EdgeEndpointRule],
681    src_kind: &str,
682    src_entity_type: Option<&str>,
683    tgt_kind: &str,
684    tgt_entity_type: Option<&str>,
685) -> String {
686    let relations = accepted_entity_relations_for_entities(
687        rules,
688        src_kind,
689        src_entity_type,
690        tgt_kind,
691        tgt_entity_type,
692    );
693    if relations.is_empty() {
694        "none".to_string()
695    } else {
696        relations
697            .iter()
698            .map(EdgeRelation::as_str)
699            .collect::<Vec<_>>()
700            .join(", ")
701    }
702}
703
704/// Hint-only counterpart to [`accepted_pack_relations_for_entities`] that
705/// matches via [`pattern_endpoint_matches`] instead of [`endpoint_matches`],
706/// so an absent `entity_type` is treated as unconstrained rather than an
707/// exact-match miss against `EntityOfType` rules. Used exclusively by the
708/// static GQL impossibility hint — never by validation.
709fn accepted_pack_relations_for_pattern_entities(
710    rules: &[EdgeEndpointRule],
711    src_kind: &str,
712    src_entity_type: Option<&str>,
713    tgt_kind: &str,
714    tgt_entity_type: Option<&str>,
715) -> Vec<EdgeRelation> {
716    let mut relations: Vec<EdgeRelation> = rules
717        .iter()
718        .filter(|r| {
719            pattern_endpoint_matches(&r.source, "entity", src_kind, src_entity_type)
720                && pattern_endpoint_matches(&r.target, "entity", tgt_kind, tgt_entity_type)
721        })
722        .map(|r| r.relation)
723        .collect();
724    relations.sort_by_key(|r| r.as_str());
725    relations.dedup();
726    relations
727}
728
729/// All `(source_kind, target_kind)` entity-kind pairs — restricted to the closed
730/// 8-kind base [`khive_types::EntityKind`] taxonomy — that accept `relation`
731/// under the composed base allowlist plus pack `EDGE_RULES`. Reuses
732/// [`base_entity_rule_allows`] and [`accepted_pack_relations_for_pattern_entities`]
733/// over the closed kind set rather than re-deriving a parallel table (for GQL
734/// query-pattern hint derivation). Pack rules are skipped when
735/// `crate::pack::is_special_relation` is true (supersedes/supports/refutes):
736/// those relations are resolved by the live validator's special-relation branch
737/// before `pack_rule_allows` is ever reached — see `pack.rs`'s
738/// `edge_endpoint_table` doc comment.
739fn accepted_entity_kind_pairs_for_relation(
740    pack_rules: &[EdgeEndpointRule],
741    relation: EdgeRelation,
742) -> Vec<(&'static str, &'static str)> {
743    let mut pairs = Vec::new();
744    for src in khive_types::EntityKind::ALL {
745        for tgt in khive_types::EntityKind::ALL {
746            let allowed = base_entity_rule_allows(src.name(), relation, tgt.name())
747                || (!crate::pack::is_special_relation(relation)
748                    && accepted_pack_relations_for_pattern_entities(
749                        pack_rules,
750                        src.name(),
751                        None,
752                        tgt.name(),
753                        None,
754                    )
755                    .contains(&relation));
756            if allowed {
757                pairs.push((src.name(), tgt.name()));
758            }
759        }
760    }
761    pairs
762}
763
764/// Scans a GQL `MATCH` pattern for edges that name an explicit relation and
765/// explicit entity kinds on both endpoints — a single mandatory hop, a fixed
766/// direction — where the `(source_kind, relation, target_kind)` triple can
767/// never match under the composed edge endpoint contract. Returns one warning
768/// per statically-impossible edge.
769///
770/// Deliberately conservative: unlabeled nodes, unlabeled/multi-relation edges,
771/// undirected edges, variable-length hops, and note-kind endpoints are left
772/// unchecked, since none of those name a single static triple to test against
773/// the validator (issue #593).
774///
775/// Mirrors the validator's special-relation precedence for `supersedes` /
776/// `supports` / `refutes` (see [`accepted_entity_kind_pairs_for_relation`]):
777/// pack rules never make those triples possible, only the base allowlist does.
778fn static_impossible_edge_pattern_warnings(
779    language: khive_query::QueryLanguage,
780    pattern: &khive_query::ast::MatchPattern,
781    pack_rules: &[EdgeEndpointRule],
782) -> Vec<String> {
783    use khive_query::ast::{EdgeDirection, PatternElement};
784
785    if language != khive_query::QueryLanguage::Gql {
786        return Vec::new();
787    }
788
789    let elements = &pattern.elements;
790    let mut warnings = Vec::new();
791
792    for (i, el) in elements.iter().enumerate() {
793        let PatternElement::Edge(edge) = el else {
794            continue;
795        };
796        if edge.relations.len() != 1 || edge.min_hops != 1 || edge.max_hops != 1 {
797            continue;
798        }
799        let (left, right) = match (elements.get(i.wrapping_sub(1)), elements.get(i + 1)) {
800            (Some(PatternElement::Node(l)), Some(PatternElement::Node(r))) => (l, r),
801            _ => continue,
802        };
803        let (src_node, tgt_node) = match edge.direction {
804            EdgeDirection::Out => (left, right),
805            EdgeDirection::In => (right, left),
806            EdgeDirection::Both => continue,
807        };
808        let (Some(src_raw), Some(tgt_raw)) = (src_node.kind.as_deref(), tgt_node.kind.as_deref())
809        else {
810            continue;
811        };
812        let (Ok(src_kind), Ok(tgt_kind)) = (
813            src_raw.parse::<khive_types::EntityKind>(),
814            tgt_raw.parse::<khive_types::EntityKind>(),
815        ) else {
816            continue;
817        };
818        let Ok(relation) = edge.relations[0].parse::<EdgeRelation>() else {
819            continue;
820        };
821
822        let possible = base_entity_rule_allows(src_kind.name(), relation, tgt_kind.name())
823            || (!crate::pack::is_special_relation(relation)
824                && accepted_pack_relations_for_pattern_entities(
825                    pack_rules,
826                    src_kind.name(),
827                    src_node.entity_type.as_deref(),
828                    tgt_kind.name(),
829                    tgt_node.entity_type.as_deref(),
830                )
831                .contains(&relation));
832        if possible {
833            continue;
834        }
835
836        let accepted = accepted_entity_kind_pairs_for_relation(pack_rules, relation);
837        let accepted_str = if accepted.is_empty() {
838            "none".to_string()
839        } else {
840            accepted
841                .iter()
842                .map(|(s, t)| format!("{s}->{t}"))
843                .collect::<Vec<_>>()
844                .join(", ")
845        };
846        warnings.push(format!(
847            "pattern ({src})-[:{relation}]->({tgt}) can never match: '{relation}' does not accept \
848             {src}->{tgt} endpoints; accepted source->target kinds for '{relation}': {accepted_str}",
849            src = src_kind.name(),
850            tgt = tgt_kind.name(),
851        ));
852    }
853
854    warnings
855}
856
857/// `true` if any pack-declared edge endpoint rule allows the
858/// `(source, relation, target)` triple. Pack rules are additive only.
859fn pack_rule_allows(
860    rules: &[EdgeEndpointRule],
861    relation: EdgeRelation,
862    src: Option<&Resolved>,
863    tgt: Option<&Resolved>,
864) -> bool {
865    let Some((src_sub, src_kind, src_type)) = resolved_pair(src) else {
866        return false;
867    };
868    let Some((tgt_sub, tgt_kind, tgt_type)) = resolved_pair(tgt) else {
869        return false;
870    };
871    rules.iter().any(|r| {
872        r.relation == relation
873            && endpoint_matches(&r.source, src_sub, src_kind, src_type)
874            && endpoint_matches(&r.target, tgt_sub, tgt_kind, tgt_type)
875    })
876}
877
878/// Base entity endpoint allowlist — the closed set of permitted entity→entity
879/// relation triples.
880///
881/// Each entry `(src_kind, relation, tgt_kind)` explicitly allows that combination.
882/// `"*"` as `src_kind` means "any entity kind" (used by `instance_of` whose source
883/// is unrestricted).
884///
885/// Pack rules (via `EDGE_RULES`) are additive — they cannot remove rows here.
886/// Exposed via `base_entity_endpoint_rules()` for the ADR-076 certificate tests.
887pub const BASE_ENTITY_ENDPOINT_RULES: &[(&str, EdgeRelation, &str)] = &[
888    // Structure
889    ("concept", EdgeRelation::Contains, "concept"),
890    ("project", EdgeRelation::Contains, "project"),
891    ("project", EdgeRelation::Contains, "artifact"),
892    ("org", EdgeRelation::Contains, "project"),
893    ("org", EdgeRelation::Contains, "service"),
894    ("concept", EdgeRelation::PartOf, "concept"),
895    ("project", EdgeRelation::PartOf, "project"),
896    ("project", EdgeRelation::PartOf, "org"),
897    ("*", EdgeRelation::InstanceOf, "concept"),
898    ("service", EdgeRelation::InstanceOf, "project"),
899    // Derivation
900    ("concept", EdgeRelation::Extends, "concept"),
901    ("concept", EdgeRelation::VariantOf, "concept"),
902    ("artifact", EdgeRelation::VariantOf, "artifact"),
903    ("concept", EdgeRelation::IntroducedBy, "document"),
904    ("concept", EdgeRelation::IntroducedBy, "person"),
905    ("artifact", EdgeRelation::IntroducedBy, "document"),
906    // ADR-002 amendment (ADR-167): service provenance — the document that
907    // introduced a service (its ADR or design record).
908    ("service", EdgeRelation::IntroducedBy, "document"),
909    ("document", EdgeRelation::IntroducedBy, "person"),
910    ("document", EdgeRelation::IntroducedBy, "org"),
911    ("concept", EdgeRelation::IntroducedBy, "org"),
912    // Provenance
913    ("artifact", EdgeRelation::DerivedFrom, "dataset"),
914    ("artifact", EdgeRelation::DerivedFrom, "document"),
915    ("artifact", EdgeRelation::DerivedFrom, "project"),
916    ("artifact", EdgeRelation::DerivedFrom, "artifact"),
917    // ADR-002 amendment 2026-07-27: publication provenance — a curated or
918    // filtered publication copy points at the canonical source document.
919    ("document", EdgeRelation::DerivedFrom, "document"),
920    // Temporal
921    ("document", EdgeRelation::Precedes, "document"),
922    ("dataset", EdgeRelation::Precedes, "dataset"),
923    ("artifact", EdgeRelation::Precedes, "artifact"),
924    ("service", EdgeRelation::Precedes, "service"),
925    ("project", EdgeRelation::Precedes, "project"),
926    // Dependency
927    ("project", EdgeRelation::DependsOn, "project"),
928    ("service", EdgeRelation::DependsOn, "project"),
929    ("service", EdgeRelation::DependsOn, "service"),
930    ("service", EdgeRelation::DependsOn, "artifact"),
931    ("service", EdgeRelation::DependsOn, "dataset"),
932    ("artifact", EdgeRelation::DependsOn, "project"),
933    ("artifact", EdgeRelation::DependsOn, "service"),
934    ("document", EdgeRelation::DependsOn, "document"),
935    ("concept", EdgeRelation::Enables, "concept"),
936    ("service", EdgeRelation::Enables, "concept"),
937    ("dataset", EdgeRelation::Enables, "concept"),
938    // Implementation
939    ("project", EdgeRelation::Implements, "concept"),
940    ("service", EdgeRelation::Implements, "concept"),
941    // Lateral
942    ("concept", EdgeRelation::CompetesWith, "concept"),
943    ("project", EdgeRelation::CompetesWith, "project"),
944    ("service", EdgeRelation::CompetesWith, "service"),
945    ("concept", EdgeRelation::ComposedWith, "concept"),
946    ("project", EdgeRelation::ComposedWith, "project"),
947    // Versioning (Supersedes — Concept/Document/Artifact/Service/Dataset only)
948    ("concept", EdgeRelation::Supersedes, "concept"),
949    ("document", EdgeRelation::Supersedes, "document"),
950    ("artifact", EdgeRelation::Supersedes, "artifact"),
951    ("service", EdgeRelation::Supersedes, "service"),
952    ("dataset", EdgeRelation::Supersedes, "dataset"),
953    // Epistemic (Supports/Refutes — evidence sources → Concept claim only)
954    ("concept", EdgeRelation::Supports, "concept"),
955    ("document", EdgeRelation::Supports, "concept"),
956    ("dataset", EdgeRelation::Supports, "concept"),
957    ("artifact", EdgeRelation::Supports, "concept"),
958    ("concept", EdgeRelation::Refutes, "concept"),
959    ("document", EdgeRelation::Refutes, "concept"),
960    ("dataset", EdgeRelation::Refutes, "concept"),
961    ("artifact", EdgeRelation::Refutes, "concept"),
962];
963
964/// Returns the base entity endpoint allowlist.
965///
966/// The returned slice is the same data that `base_entity_rule_allows` consults at
967/// runtime. Exposed for the ADR-076 certificate tests in `khive-pack-kg`, which
968/// must audit live rules rather than hand-copied snapshots.
969pub fn base_entity_endpoint_rules() -> &'static [(&'static str, EdgeRelation, &'static str)] {
970    BASE_ENTITY_ENDPOINT_RULES
971}
972
973/// `true` if `(src_kind, relation, tgt_kind)` is in the base entity endpoint
974/// allowlist. Pure and DB-free — exposed alongside [`base_entity_endpoint_rules`]
975/// so offline consumers (e.g. `kkernel kg validate`) can apply the exact same
976/// base-table membership test the live validator uses, instead of re-deriving
977/// a parallel `.any()` predicate over a hand-copied allowlist.
978pub fn base_entity_rule_allows(src_kind: &str, relation: EdgeRelation, tgt_kind: &str) -> bool {
979    BASE_ENTITY_ENDPOINT_RULES.iter().any(|(src, rel, tgt)| {
980        *rel == relation && (*src == "*" || *src == src_kind) && *tgt == tgt_kind
981    })
982}
983
984/// Canonical endpoint order for symmetric relations (F012).
985///
986/// For `competes_with` and `composed_with`, normalises direction so that
987/// `source_uuid < target_uuid` (lexicographic on the UUID bytes). This
988/// collapses A→B and B→A into a single canonical row, preventing duplicates.
989pub(crate) fn canonical_edge_endpoints(
990    relation: EdgeRelation,
991    source_id: Uuid,
992    target_id: Uuid,
993) -> (Uuid, Uuid) {
994    if relation.is_symmetric() && target_id < source_id {
995        (target_id, source_id)
996    } else {
997        (source_id, target_id)
998    }
999}
1000
1001/// Infer the default `dependency_kind` from endpoint entity kinds.
1002///
1003/// `pub(crate)` so `crate::atomic_prepare::prepare_link` can reuse this exact
1004/// inference table, keeping `--atomic link` byte-for-byte consistent with the
1005/// non-atomic `link()` rather than re-deriving the table.
1006pub(crate) fn infer_dependency_kind(src_kind: &str, tgt_kind: &str) -> Option<&'static str> {
1007    match (src_kind, tgt_kind) {
1008        ("project", "project") => Some("build"),
1009        ("service", "service") => Some("runtime"),
1010        ("service", "dataset") => Some("data"),
1011        ("service", "artifact") => Some("artifact"),
1012        ("artifact", "project") | ("artifact", "service") => Some("tooling"),
1013        ("document", "document") => Some("normative"),
1014        _ => None,
1015    }
1016}
1017
1018/// Merge an inferred `dependency_kind` into `depends_on` edge metadata.
1019///
1020/// If `metadata` already carries a `dependency_kind` key the existing value is
1021/// preserved. If the key is absent and the endpoint pair has a known default,
1022/// the inferred value is added. Returns `metadata` unchanged for all other
1023/// cases (no matching default, or metadata already has the key).
1024///
1025/// `pub(crate)` so `crate::atomic_prepare::prepare_link` can reuse it for
1026/// atomic/non-atomic parity.
1027pub(crate) fn merge_dependency_kind(
1028    src_kind: &str,
1029    tgt_kind: &str,
1030    metadata: Option<serde_json::Value>,
1031) -> Option<serde_json::Value> {
1032    if let Some(ref m) = metadata {
1033        if m.get("dependency_kind").is_some() {
1034            return metadata;
1035        }
1036    }
1037    let inferred = infer_dependency_kind(src_kind, tgt_kind)?;
1038    let mut obj = metadata.unwrap_or_else(|| serde_json::json!({}));
1039    if let Some(o) = obj.as_object_mut() {
1040        o.insert("dependency_kind".to_string(), serde_json::json!(inferred));
1041    }
1042    Some(obj)
1043}
1044
1045/// Merge a caller-supplied top-level `dependency_kind` param into an edge's
1046/// `metadata` object, filling the key only if `metadata` doesn't already
1047/// carry one. This is distinct from `merge_dependency_kind` above (which
1048/// infers a default from endpoint entity kinds when no explicit value was
1049/// given at all) — this one folds in an EXPLICIT `dependency_kind` argument
1050/// the caller passed alongside `metadata`.
1051///
1052/// `pub`: the single source both `khive-pack-kg::handlers::link::handle_link`
1053/// (via `khive_runtime::merge_entry_metadata`) and
1054/// `crate::atomic_prepare::prepare_link` call. Lives in `khive-runtime` (not
1055/// pack-kg) because packs depend on `khive-runtime`, never the reverse: the
1056/// only direction that lets both call sites share one copy instead of a
1057/// hand-duplicated block.
1058pub fn merge_entry_metadata(
1059    metadata: Option<serde_json::Value>,
1060    dependency_kind: Option<String>,
1061) -> RuntimeResult<Option<serde_json::Value>> {
1062    let Some(dk) = dependency_kind else {
1063        return Ok(metadata);
1064    };
1065    let mut obj = metadata.unwrap_or_else(|| serde_json::json!({}));
1066    let map = obj
1067        .as_object_mut()
1068        .ok_or_else(|| RuntimeError::InvalidInput("metadata must be a JSON object".into()))?;
1069    map.entry("dependency_kind".to_string())
1070        .or_insert_with(|| serde_json::json!(dk));
1071    Ok(Some(obj))
1072}
1073
1074/// Valid `dependency_kind` values for `depends_on` edges.
1075const VALID_DEPENDENCY_KINDS: &[&str] = &[
1076    "build",
1077    "runtime",
1078    "data",
1079    "artifact",
1080    "tooling",
1081    "normative",
1082];
1083
1084/// Validate that an edge weight is finite and within `[0.0, 1.0]`.
1085///
1086/// Rejects NaN, infinities, negative values, and values exceeding 1.0.
1087/// Used by `link` and `import_kg` to enforce the weight invariant consistently
1088/// across all edge creation paths.
1089pub(crate) fn validate_edge_weight(weight: f64) -> RuntimeResult<()> {
1090    if !weight.is_finite() || !(0.0..=1.0).contains(&weight) {
1091        return Err(RuntimeError::InvalidInput(format!(
1092            "edge weight must be finite and in [0.0, 1.0], got {weight}"
1093        )));
1094    }
1095    Ok(())
1096}
1097
1098/// Validate governed edge metadata keys.
1099///
1100/// Currently enforces:
1101/// - `dependency_kind` is only valid on `depends_on` edges.
1102/// - `dependency_kind`, when present, must be one of the governed values.
1103pub(crate) fn validate_edge_metadata(
1104    relation: EdgeRelation,
1105    metadata: Option<&serde_json::Value>,
1106) -> RuntimeResult<()> {
1107    let Some(meta) = metadata else {
1108        return Ok(());
1109    };
1110    if let Some(dk) = meta.get("dependency_kind") {
1111        if relation != EdgeRelation::DependsOn {
1112            return Err(RuntimeError::InvalidInput(format!(
1113                "dependency_kind is only valid on depends_on edges (got {})",
1114                relation.as_str()
1115            )));
1116        }
1117        let dk_str = dk
1118            .as_str()
1119            .ok_or_else(|| RuntimeError::InvalidInput("dependency_kind must be a string".into()))?;
1120        if !VALID_DEPENDENCY_KINDS.contains(&dk_str) {
1121            return Err(RuntimeError::InvalidInput(format!(
1122                "unknown dependency_kind {dk_str:?}; valid: {}",
1123                VALID_DEPENDENCY_KINDS.join(" | ")
1124            )));
1125        }
1126    }
1127    Ok(())
1128}
1129
1130/// Returns `true` when `note_props` is a superset of all key-value pairs in `filter`.
1131///
1132/// Mirrors the semantics of `khive_pack_kg::handlers::common::props_match` so that the
1133/// storage-leg predicate in `search_notes` is identical to the handler-side post-filter.
1134fn note_props_match(note_props: Option<&serde_json::Value>, filter: &serde_json::Value) -> bool {
1135    let required = match filter.as_object() {
1136        Some(obj) if !obj.is_empty() => obj,
1137        _ => return true,
1138    };
1139    let actual = match note_props.and_then(serde_json::Value::as_object) {
1140        Some(obj) => obj,
1141        None => return false,
1142    };
1143    required
1144        .iter()
1145        .all(|(k, v)| actual.get(k).is_some_and(|av| av == v))
1146}
1147
1148fn note_graph_name(note: &Note) -> String {
1149    note.name
1150        .as_deref()
1151        .filter(|name| !name.trim().is_empty())
1152        .map(str::to_owned)
1153        .unwrap_or_else(|| format!("[{}]", note.kind))
1154}
1155
1156/// Collapse per-namespace `GraphPath`s from [`KhiveRuntime::traverse`] down to exactly
1157/// one entry per distinct `root_id`, merging by `(root_id, node_id)` (shallowest depth
1158/// wins), BFS-ordering the result, and re-applying `limit`. See
1159/// docs/operations.md#merge_traversal_paths_by_root for why naive concatenation is unsound.
1160fn merge_traversal_paths_by_root(paths: Vec<GraphPath>, limit: Option<u32>) -> Vec<GraphPath> {
1161    let mut order: Vec<Uuid> = Vec::new();
1162    let mut merged: HashMap<Uuid, GraphPath> = HashMap::new();
1163    // root_id -> (node_id -> index into merged[root_id].nodes), so a
1164    // shallower depth for an already-seen node updates in place instead of
1165    // rebuilding a seen-set from every prior namespace's contribution.
1166    let mut node_index: HashMap<Uuid, HashMap<Uuid, usize>> = HashMap::new();
1167
1168    for path in paths {
1169        let existing = merged.entry(path.root_id).or_insert_with(|| {
1170            order.push(path.root_id);
1171            GraphPath {
1172                root_id: path.root_id,
1173                nodes: Vec::new(),
1174                total_weight: 0.0,
1175            }
1176        });
1177        let index = node_index.entry(path.root_id).or_default();
1178        for node in path.nodes {
1179            match index.get(&node.node_id) {
1180                Some(&i) => {
1181                    if node.depth < existing.nodes[i].depth {
1182                        existing.nodes[i] = node;
1183                    }
1184                }
1185                None => {
1186                    index.insert(node.node_id, existing.nodes.len());
1187                    existing.nodes.push(node);
1188                }
1189            }
1190        }
1191    }
1192
1193    order
1194        .into_iter()
1195        .filter_map(|root_id| merged.remove(&root_id))
1196        .map(|mut path| {
1197            // BFS order: ascending depth, stable within a depth.
1198            path.nodes.sort_by_key(|n| n.depth);
1199            if let Some(lim) = limit {
1200                let lim = lim as usize;
1201                let mut non_root_kept = 0usize;
1202                path.nodes.retain(|n| {
1203                    if n.depth == 0 {
1204                        return true;
1205                    }
1206                    if non_root_kept < lim {
1207                        non_root_kept += 1;
1208                        true
1209                    } else {
1210                        false
1211                    }
1212                });
1213            }
1214            recompute_total_weight(&mut path);
1215            path
1216        })
1217        .collect()
1218}
1219
1220/// Set `total_weight` to the maximum cumulative path weight among the nodes
1221/// the path currently holds, matching how storage derives it for a
1222/// single-namespace traversal.
1223///
1224/// Call this after any edit to `nodes`. Carrying a weight across an edit is
1225/// what lets the field describe a node the caller was never shown: the
1226/// highest-weighted candidate is exactly the one a `limit` or a
1227/// soft-delete screen can remove while the summary keeps quoting it.
1228fn recompute_total_weight(path: &mut GraphPath) {
1229    path.total_weight = path.nodes.iter().map(|n| n.weight).fold(0.0_f64, f64::max);
1230}
1231
1232/// Await every spawned multi-model embed task in `join_set`, returning one
1233/// vector per model (in model order) on full success.
1234///
1235/// `join_set` entries are `(model_index, embed_result)` — the index lets
1236/// completion order (which is arrival order, not spawn order) be reassembled
1237/// into the caller's model order. On the first failure (an embed error or a
1238/// task panic), every remaining handle is aborted and detached so the error
1239/// return is not gated on a sibling reaching a cancellation point. A sibling
1240/// already inside synchronous native inference may finish that call in the
1241/// background. Embed calls are counted when issued, before the provider
1242/// await, so detached completion cannot change the operation's usage count.
1243/// Each task owns cloned runtime/provider state and only computes an embedding;
1244/// storage writes remain in the parent after this drain succeeds.
1245async fn drain_embed_join_set<T: Send + 'static>(
1246    mut join_set: tokio::task::JoinSet<(usize, RuntimeResult<T>)>,
1247    model_count: usize,
1248) -> RuntimeResult<Vec<T>> {
1249    let mut vectors: Vec<Option<T>> = (0..model_count).map(|_| None).collect();
1250
1251    while let Some(joined) = join_set.join_next().await {
1252        match joined {
1253            Ok((idx, Ok(vector))) => vectors[idx] = Some(vector),
1254            Ok((_idx, Err(e))) => {
1255                join_set.abort_all();
1256                return Err(e);
1257            }
1258            Err(join_err) => {
1259                join_set.abort_all();
1260                return Err(RuntimeError::Internal(format!(
1261                    "embed task panicked: {join_err}"
1262                )));
1263            }
1264        }
1265    }
1266
1267    Ok(vectors
1268        .into_iter()
1269        .map(|v| v.expect("every model index observed exactly once by join_set drain"))
1270        .collect())
1271}
1272
1273impl KhiveRuntime {
1274    // ---- Entity operations ----
1275
1276    async fn compensate_entity_create(
1277        &self,
1278        token: &NamespaceToken,
1279        entity_id: Uuid,
1280        namespace: &str,
1281        vector_models: &[String],
1282    ) -> Vec<String> {
1283        let mut cleanup_errors = Vec::new();
1284
1285        #[cfg(any(test, feature = "fault-injection"))]
1286        let entity_delete_injected = consume_fault(&ENTITY_COMPENSATION_FAIL_NS, namespace);
1287        #[cfg(not(any(test, feature = "fault-injection")))]
1288        let entity_delete_injected = false;
1289
1290        if entity_delete_injected {
1291            cleanup_errors.push("entity row delete: injected compensation failure".to_string());
1292        } else {
1293            match self.entities(token) {
1294                Ok(store) => {
1295                    if let Err(error) = store.delete_entity(entity_id, DeleteMode::Hard).await {
1296                        cleanup_errors.push(format!("entity row delete: {error}"));
1297                    }
1298                }
1299                Err(error) => cleanup_errors.push(format!("entity store access: {error}")),
1300            }
1301        }
1302
1303        match self.text(token) {
1304            Ok(fts) => {
1305                if let Err(error) = fts.delete_document(namespace, entity_id).await {
1306                    cleanup_errors.push(format!("FTS document delete: {error}"));
1307                }
1308            }
1309            Err(error) => cleanup_errors.push(format!("FTS store access: {error}")),
1310        }
1311
1312        for model_name in vector_models {
1313            match self.vectors_for_model(token, model_name) {
1314                Ok(vectors) => {
1315                    if let Err(error) = vectors.delete(entity_id).await {
1316                        cleanup_errors
1317                            .push(format!("vector delete for model {model_name}: {error}"));
1318                    }
1319                }
1320                Err(error) => cleanup_errors.push(format!(
1321                    "vector store access for model {model_name}: {error}"
1322                )),
1323            }
1324        }
1325
1326        cleanup_errors
1327    }
1328
1329    fn entity_create_failure(
1330        entity_id: Uuid,
1331        primary: RuntimeError,
1332        cleanup_errors: Vec<String>,
1333    ) -> RuntimeError {
1334        if cleanup_errors.is_empty() {
1335            primary
1336        } else {
1337            RuntimeError::Khive(KhiveError::internal(format!(
1338                "create_entity indexing failed for record {entity_id}; primary failure: \
1339                 {primary}; compensation failure(s): {}; partial persistence is possible; \
1340                 inspect and reconcile this record before retrying",
1341                cleanup_errors.join("; ")
1342            )))
1343        }
1344    }
1345
1346    /// Create and persist a new entity.
1347    ///
1348    /// Indexing failures trigger compensation across the entity row, FTS
1349    /// document, and any vector models touched by this call. If compensation
1350    /// also fails, the returned structured internal error identifies possible
1351    /// partial persistence, includes both failure classes, and carries the
1352    /// entity ID as a reconciliation handle.
1353    // REASON: entity creation requires kind, type, name, description, properties, tags, and
1354    // namespace token — refactoring into a builder would add indirection without reducing
1355    // caller complexity; this signature mirrors the MCP verb surface directly.
1356    #[allow(clippy::too_many_arguments)]
1357    pub async fn create_entity(
1358        &self,
1359        token: &NamespaceToken,
1360        kind: &str,
1361        entity_type: Option<&str>,
1362        name: &str,
1363        description: Option<&str>,
1364        properties: Option<serde_json::Value>,
1365        tags: Vec<String>,
1366    ) -> RuntimeResult<Entity> {
1367        Ok(self
1368            .create_entity_with_embedding_report_inner(
1369                token,
1370                kind,
1371                entity_type,
1372                name,
1373                description,
1374                properties,
1375                tags,
1376                Vec::new(),
1377            )
1378            .await?
1379            .0)
1380    }
1381
1382    /// Create an entity with role-keyed bytes already published to `BlobStore`.
1383    ///
1384    /// Every [`NewAttachment`] carries a typed content reference, so malformed
1385    /// references cannot enter through this consumer seam. Blob existence is
1386    /// checked before the database write. The entity row and all attachment rows
1387    /// then commit in one storage transaction; the FTS/vector compensation path
1388    /// hard-deletes the entity and its attachments together if a later indexing
1389    /// step fails. Published bytes remain recoverable by the BlobStore grace-period
1390    /// orphan policy when any post-publication step fails.
1391    #[allow(clippy::too_many_arguments)]
1392    pub async fn create_entity_with_attachments(
1393        &self,
1394        token: &NamespaceToken,
1395        kind: &str,
1396        entity_type: Option<&str>,
1397        name: &str,
1398        description: Option<&str>,
1399        properties: Option<serde_json::Value>,
1400        tags: Vec<String>,
1401        attachments: Vec<NewAttachment>,
1402    ) -> RuntimeResult<Entity> {
1403        // Attachment rows are the process-wide BlobStore's liveness authority.
1404        // Validate placement before existence probes or any record write: pack
1405        // runtimes bound to a secondary backend must explicitly call `core()`.
1406        drop(self.attachments()?);
1407        let blob_store = self.blob_store().ok_or_else(|| {
1408            RuntimeError::Unconfigured(
1409                "create_entity_with_attachments requires an installed BlobStore".to_string(),
1410            )
1411        })?;
1412        let mut roles = std::collections::HashSet::with_capacity(attachments.len());
1413        for attachment in &attachments {
1414            attachment.validate()?;
1415            if !roles.insert(attachment.role.as_str()) {
1416                return Err(RuntimeError::InvalidInput(format!(
1417                    "duplicate attachment role {:?}",
1418                    attachment.role
1419                )));
1420            }
1421        }
1422        for attachment in &attachments {
1423            if !blob_store.exists(&attachment.content_ref).await? {
1424                return Err(RuntimeError::InvalidInput(format!(
1425                    "create_entity_with_attachments requires a published blob; no object exists for {}",
1426                    attachment.content_ref
1427                )));
1428            }
1429        }
1430        let validated_type = self.validate_entity_type_for_kind(kind, entity_type)?;
1431        Ok(self
1432            .create_entity_with_embedding_report_inner(
1433                token,
1434                kind,
1435                validated_type.as_deref(),
1436                name,
1437                description,
1438                properties,
1439                tags,
1440                attachments,
1441            )
1442            .await?
1443            .0)
1444    }
1445
1446    #[allow(clippy::too_many_arguments)]
1447    pub async fn create_entity_with_embedding_report(
1448        &self,
1449        token: &NamespaceToken,
1450        kind: &str,
1451        entity_type: Option<&str>,
1452        name: &str,
1453        description: Option<&str>,
1454        properties: Option<serde_json::Value>,
1455        tags: Vec<String>,
1456    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
1457        self.create_entity_with_embedding_report_inner(
1458            token,
1459            kind,
1460            entity_type,
1461            name,
1462            description,
1463            properties,
1464            tags,
1465            Vec::new(),
1466        )
1467        .await
1468    }
1469
1470    #[allow(clippy::too_many_arguments)]
1471    async fn create_entity_with_embedding_report_inner(
1472        &self,
1473        token: &NamespaceToken,
1474        kind: &str,
1475        entity_type: Option<&str>,
1476        name: &str,
1477        description: Option<&str>,
1478        properties: Option<serde_json::Value>,
1479        tags: Vec<String>,
1480        attachments: Vec<NewAttachment>,
1481    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
1482        self.validate_entity_kind(kind)?;
1483        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
1484        // Secret gate: scan name, description, structured properties, and tags.
1485        crate::secret_gate::check(name)?;
1486        if let Some(d) = description {
1487            crate::secret_gate::check(d)?;
1488        }
1489        if let Some(ref p) = properties {
1490            crate::secret_gate::check_json(p)?;
1491        }
1492        crate::secret_gate::check_tags(&tags)?;
1493        let ns = token.namespace().as_str();
1494        let mut entity = Entity::new(ns, kind, name).with_entity_type(entity_type);
1495        if let Some(d) = description {
1496            entity = entity.with_description(d);
1497        }
1498        if let Some(p) = properties {
1499            entity = entity.with_properties(p);
1500        }
1501        if !tags.is_empty() {
1502            entity = entity.with_tags(tags);
1503        }
1504        let projected_content_ref = attachments
1505            .iter()
1506            .find(|attachment| attachment.role == "content")
1507            .map(|attachment| attachment.content_ref.to_string());
1508        let attachment_rows = attachments
1509            .into_iter()
1510            .map(|attachment| {
1511                Attachment::from_new(
1512                    entity.id,
1513                    AttachmentSubstrate::Entity,
1514                    attachment,
1515                    entity.created_at,
1516                )
1517            })
1518            .collect();
1519        self.entities(token)?
1520            .upsert_entity_with_attachments(entity.clone(), attachment_rows)
1521            .await?;
1522        entity.content_ref = projected_content_ref;
1523
1524        let doc = entity_fts_document(&entity);
1525        let embed_body = doc.body.clone();
1526
1527        // FTS step — compensate entity row on failure (mirrors create_note_inner).
1528        {
1529            #[cfg(any(test, feature = "fault-injection"))]
1530            let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
1531            #[cfg(not(any(test, feature = "fault-injection")))]
1532            let fts_inject = false;
1533            let fts_result: RuntimeResult<()> = if fts_inject {
1534                Err(RuntimeError::Internal("injected FTS failure".to_string()))
1535            } else {
1536                match self.text(token) {
1537                    Ok(fts) => fts.upsert_document(doc).await.map_err(RuntimeError::from),
1538                    Err(e) => Err(e),
1539                }
1540            };
1541            if let Err(e) = fts_result {
1542                let cleanup_errors = self
1543                    .compensate_entity_create(token, entity.id, ns, &[])
1544                    .await;
1545                return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1546            }
1547        }
1548
1549        // Vector embedding + insert step — compensate entity row + FTS doc on failure.
1550        // Fan out to ALL registered models (mirrors create_note_inner multi-model path).
1551        let embed_model_names = {
1552            let names = self.registered_embedding_model_names();
1553            if names.is_empty() {
1554                vec![]
1555            } else {
1556                names
1557            }
1558        };
1559
1560        let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
1561        if embed_model_names.len() == 1 {
1562            let model_name = &embed_model_names[0];
1563            let vec_result = self
1564                .embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
1565                .await;
1566
1567            #[cfg(any(test, feature = "fault-injection"))]
1568            let vec_inject = consume_fault(&VECTOR_FAIL_NS, ns);
1569            #[cfg(not(any(test, feature = "fault-injection")))]
1570            let vec_inject = false;
1571            let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
1572                if vec_inject {
1573                    Err(RuntimeError::Internal(
1574                        "injected vector failure".to_string(),
1575                    ))
1576                } else {
1577                    vec_result
1578                };
1579
1580            let single_result: RuntimeResult<()> = match vec_result {
1581                Ok(outcome) => {
1582                    embedding_report.observe(&outcome);
1583                    match self.vectors_for_model(token, model_name) {
1584                        Ok(vs) => vs
1585                            .insert(
1586                                entity.id,
1587                                SubstrateKind::Entity,
1588                                ns,
1589                                "entity.body",
1590                                vec![outcome.vector],
1591                            )
1592                            .await
1593                            .map_err(RuntimeError::from),
1594                        Err(e) => Err(e),
1595                    }
1596                }
1597                Err(e) => Err(e),
1598            };
1599            if let Err(e) = single_result {
1600                let cleanup_errors = self
1601                    .compensate_entity_create(
1602                        token,
1603                        entity.id,
1604                        ns,
1605                        std::slice::from_ref(model_name),
1606                    )
1607                    .await;
1608                return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1609            }
1610        } else if !embed_model_names.is_empty() {
1611            // Multi-model path: embed with each model in parallel, then insert sequentially
1612            // with inserted_models tracking for rollback on partial failure.
1613            let rt_clone = self.clone();
1614            let body_owned = embed_body.clone();
1615            let usage_ctx = crate::usage::current();
1616            let mut join_set = tokio::task::JoinSet::new();
1617            for (idx, model_name) in embed_model_names.iter().enumerate() {
1618                let rt = rt_clone.clone();
1619                let text = body_owned.clone();
1620                let name = model_name.clone();
1621                let ctx = usage_ctx.clone();
1622                let token = (*token).clone();
1623                join_set.spawn(async move {
1624                    let fut = rt.embed_document_with_model_outcome_for_token(&token, &name, &text);
1625                    let result = match ctx {
1626                        Some(ctx) => crate::usage::scope(ctx, fut).await,
1627                        None => fut.await,
1628                    };
1629                    (idx, result)
1630                });
1631            }
1632            // The first failed or panicked handle aborts and detaches its
1633            // siblings. Embed usage is counted at dispatch, so a synchronous
1634            // provider winding down in the background cannot change it.
1635            let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
1636                Ok(outcomes) => outcomes,
1637                Err(e) => {
1638                    let cleanup_errors = self
1639                        .compensate_entity_create(token, entity.id, ns, &[])
1640                        .await;
1641                    return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1642                }
1643            };
1644            // TODO(P2): parallelize vector inserts
1645            let mut inserted_models: Vec<String> = Vec::with_capacity(embed_model_names.len());
1646            for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
1647                embedding_report.observe(&outcome);
1648                // Count-targetable fault injection for multi-model insert path.
1649                #[cfg(any(test, feature = "fault-injection"))]
1650                let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
1651                    Some(0) => {
1652                        cell.set(None);
1653                        true
1654                    }
1655                    Some(n) => {
1656                        cell.set(Some(n - 1));
1657                        false
1658                    }
1659                    None => false,
1660                });
1661                #[cfg(not(any(test, feature = "fault-injection")))]
1662                let count_inject = false;
1663
1664                let insert_result = if count_inject {
1665                    Err(RuntimeError::Internal(
1666                        "injected vector insert failure".to_string(),
1667                    ))
1668                } else {
1669                    match self.vectors_for_model(token, model_name) {
1670                        Ok(vs) => vs
1671                            .insert(
1672                                entity.id,
1673                                SubstrateKind::Entity,
1674                                ns,
1675                                "entity.body",
1676                                vec![outcome.vector],
1677                            )
1678                            .await
1679                            .map_err(RuntimeError::from),
1680                        Err(e) => Err(e),
1681                    }
1682                };
1683                if let Err(e) = insert_result {
1684                    // Include the model whose INSERT returned an error: a backend
1685                    // error does not prove the write had no side effects.
1686                    let mut cleanup_models = inserted_models.clone();
1687                    cleanup_models.push(model_name.clone());
1688                    let cleanup_errors = self
1689                        .compensate_entity_create(token, entity.id, ns, &cleanup_models)
1690                        .await;
1691                    return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1692                }
1693                inserted_models.push(model_name.clone());
1694            }
1695        }
1696
1697        Ok((entity, embedding_report))
1698    }
1699
1700    /// Retrieve an entity by ID.
1701    ///
1702    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1703    ///
1704    /// Interim identifier-continuity disclosure (precedes the full transitive
1705    /// redirect chase): a miss is probed once against the tombstone row. If
1706    /// the id was consumed by `merge(into_id, from_id)` — `merged_into` set —
1707    /// the `NotFound` message names the kept id so the caller can requery it
1708    /// directly. Single-level only: it does not chase a chain of merges and
1709    /// does not return the kept entity in place of the miss. The probe only
1710    /// runs after the live-row lookup misses, so the happy path pays no
1711    /// extra query.
1712    pub async fn get_entity(&self, token: &NamespaceToken, id: Uuid) -> RuntimeResult<Entity> {
1713        let store = self.entities(token)?;
1714        if let Some(entity) = store.get_entity(id).await? {
1715            return Ok(entity);
1716        }
1717        if let Some(tombstone) = store.get_entity_including_deleted(id).await? {
1718            if let Some(kept_id) = tombstone.merged_into {
1719                return Err(RuntimeError::NotFound(format!(
1720                    "{id} was merged into {kept_id}; query the kept id"
1721                )));
1722            }
1723        }
1724        Err(RuntimeError::NotFound(format!("entity {id}")))
1725    }
1726
1727    /// Retrieve an entity by ID including soft-deleted rows.
1728    ///
1729    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1730    pub async fn get_entity_including_deleted(
1731        &self,
1732        token: &NamespaceToken,
1733        id: Uuid,
1734    ) -> RuntimeResult<Option<Entity>> {
1735        self.entities(token)?
1736            .get_entity_including_deleted(id)
1737            .await
1738            .map_err(Into::into)
1739    }
1740
1741    /// Retrieve a note by ID including soft-deleted rows.
1742    ///
1743    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1744    pub async fn get_note_including_deleted(
1745        &self,
1746        token: &NamespaceToken,
1747        id: Uuid,
1748    ) -> RuntimeResult<Option<khive_storage::note::Note>> {
1749        self.notes(token)?
1750            .get_note_including_deleted(id)
1751            .await
1752            .map_err(Into::into)
1753    }
1754
1755    /// Fetch multiple entities by ID, returning only those that exist in the
1756    /// caller's namespace.  Missing or namespace-mismatched IDs are silently
1757    /// omitted so that batch lookups don't abort on a single stale reference.
1758    pub async fn get_entities_by_ids(
1759        &self,
1760        token: &NamespaceToken,
1761        ids: &[Uuid],
1762    ) -> RuntimeResult<Vec<Entity>> {
1763        if ids.is_empty() {
1764            return Ok(vec![]);
1765        }
1766        let filter = EntityFilter {
1767            ids: ids.to_vec(),
1768            ..Default::default()
1769        };
1770        let page = self
1771            .entities(token)?
1772            .query_entities(
1773                token.namespace().as_str(),
1774                filter,
1775                PageRequest {
1776                    offset: 0,
1777                    limit: ids.len() as u32,
1778                },
1779            )
1780            .await?;
1781        Ok(page.items)
1782    }
1783
1784    /// Like `get_entities_by_ids` but scoped to the token's full visible-namespace
1785    /// set (`primary ∪ extra_visible`) instead of primary only.
1786    ///
1787    /// Graph expansion (`neighbors`, `traverse`) iterates over all visible
1788    /// namespaces, so enrichment must use the same scope — otherwise neighbors
1789    /// or path nodes whose entities live in an extra-visible namespace are left
1790    /// with `name = None`, `kind = None`.  Missing or out-of-scope IDs are
1791    /// silently omitted (best-effort, same as `get_entities_by_ids`).
1792    async fn get_entities_by_ids_visible(
1793        &self,
1794        token: &NamespaceToken,
1795        ids: &[Uuid],
1796    ) -> RuntimeResult<Vec<Entity>> {
1797        if ids.is_empty() {
1798            return Ok(vec![]);
1799        }
1800        let namespaces: Vec<String> = token
1801            .visible_namespaces()
1802            .iter()
1803            .map(|ns| ns.as_str().to_owned())
1804            .collect();
1805        let filter = EntityFilter {
1806            ids: ids.to_vec(),
1807            namespaces,
1808            ..Default::default()
1809        };
1810        let page = self
1811            .entities(token)?
1812            .query_entities(
1813                token.namespace().as_str(),
1814                filter,
1815                PageRequest {
1816                    offset: 0,
1817                    limit: ids.len() as u32,
1818                },
1819            )
1820            .await?;
1821        Ok(page.items)
1822    }
1823
1824    /// Enforce that `record_ns` is within the caller's visible namespace set.
1825    ///
1826    /// Returns `Err(NotFound)` when the record namespace is not in the visible
1827    /// set — wrong-namespace and absent UUIDs must be indistinguishable
1828    /// externally (no existence oracle).
1829    ///
1830    /// When the visible set is a single entry equal to `caller_primary_ns`, this
1831    /// is identical to the former strict-equality check (backward-compatible).
1832    pub(crate) fn ensure_namespace(record_ns: &str, caller_primary_ns: &str) -> RuntimeResult<()> {
1833        if record_ns == caller_primary_ns {
1834            return Ok(());
1835        }
1836        Err(RuntimeError::NotFound("not found in this namespace".into()))
1837    }
1838
1839    /// Enforce that `record_ns` is a member of the token's visible namespace set.
1840    ///
1841    /// This is the multi-namespace-aware variant used when the token carries an
1842    /// extended visibility set. For single-namespace tokens (visible == [primary])
1843    /// this degenerates to the same strict-equality check as `ensure_namespace`.
1844    pub(crate) fn ensure_namespace_visible(
1845        record_ns: &str,
1846        token: &NamespaceToken,
1847    ) -> RuntimeResult<()> {
1848        for ns in token.visible_namespaces() {
1849            if record_ns == ns.as_str() {
1850                return Ok(());
1851            }
1852        }
1853        Err(RuntimeError::NotFound("not found in this namespace".into()))
1854    }
1855
1856    /// List entities visible to the token, optionally filtered by kind and entity_type.
1857    ///
1858    /// When the token carries a multi-namespace visible set, entities from all
1859    /// visible namespaces are returned. When the visible set is `[primary]`
1860    /// (the default) this behaves identically to the pre-visibility behaviour.
1861    pub async fn list_entities(
1862        &self,
1863        token: &NamespaceToken,
1864        kind: Option<&str>,
1865        entity_type: Option<&str>,
1866        limit: u32,
1867        offset: u32,
1868    ) -> RuntimeResult<Vec<Entity>> {
1869        let ns_strs: Vec<String> = token
1870            .visible_namespaces()
1871            .iter()
1872            .map(|ns| ns.as_str().to_owned())
1873            .collect();
1874        let filter = EntityFilter {
1875            kinds: match kind {
1876                Some(k) => vec![k.to_string()],
1877                None => vec![],
1878            },
1879            entity_types: match entity_type {
1880                Some(t) => vec![t.to_string()],
1881                None => vec![],
1882            },
1883            namespaces: ns_strs,
1884            ..Default::default()
1885        };
1886        let page = self
1887            .entities(token)?
1888            .query_entities(
1889                token.namespace().as_str(),
1890                filter,
1891                PageRequest {
1892                    offset: offset.into(),
1893                    limit,
1894                },
1895            )
1896            .await?;
1897        Ok(page.items)
1898    }
1899
1900    /// List an immutable insertion-sequence page of visible entities.
1901    ///
1902    /// The public cursor remains the UUID of the last returned entity. We
1903    /// resolve its immutable database-assigned sequence before querying so callers do
1904    /// not need to serialize storage details. A missing or out-of-scope cursor
1905    /// fails explicitly instead of silently resuming from the wrong boundary.
1906    pub async fn list_entities_after(
1907        &self,
1908        token: &NamespaceToken,
1909        kind: Option<&str>,
1910        entity_type: Option<&str>,
1911        tags_any: &[String],
1912        after: Option<Uuid>,
1913        limit: u32,
1914    ) -> RuntimeResult<(Vec<Entity>, Option<Uuid>)> {
1915        let store = self.entities(token)?;
1916        let after = match after {
1917            Some(id) => {
1918                let entity = self
1919                    .get_entity_including_deleted(token, id)
1920                    .await?
1921                    .ok_or_else(|| RuntimeError::NotFound(format!("entity cursor {id}")))?;
1922                Self::ensure_namespace_visible(&entity.namespace, token)?;
1923                let sequence = store.entity_sequence(id).await?.ok_or_else(|| {
1924                    RuntimeError::Internal(format!(
1925                        "entity cursor {id} has no insertion-sequence ledger row"
1926                    ))
1927                })?;
1928                Some(SeekCursor { sequence, id })
1929            }
1930            None => None,
1931        };
1932        let filter = EntityFilter {
1933            kinds: kind
1934                .map(|value| vec![value.to_string()])
1935                .unwrap_or_default(),
1936            entity_types: entity_type
1937                .map(|value| vec![value.to_string()])
1938                .unwrap_or_default(),
1939            tags_any: tags_any.to_vec(),
1940            namespaces: token
1941                .visible_namespaces()
1942                .iter()
1943                .map(|namespace| namespace.as_str().to_owned())
1944                .collect(),
1945            ..Default::default()
1946        };
1947        let page = store
1948            .query_entities_after(token.namespace().as_str(), filter, after, limit)
1949            .await?;
1950        Ok((page.items, page.next_after.map(|cursor| cursor.id)))
1951    }
1952
1953    /// List entities filtered by kind, optional domain tag, limit, and offset.
1954    ///
1955    /// When `domain_tag` is Some, the query is restricted at the storage layer via
1956    /// `EntityFilter::tags_any` so the page result already reflects the domain
1957    /// constraint.  This avoids the silent truncation that occurs when filtering
1958    /// post-page (K-3). Multi-namespace visibility from the token is applied.
1959    pub async fn list_entities_tagged(
1960        &self,
1961        token: &NamespaceToken,
1962        kind: Option<&str>,
1963        domain_tag: Option<&str>,
1964        limit: u32,
1965        offset: u32,
1966    ) -> RuntimeResult<Vec<Entity>> {
1967        let ns_strs: Vec<String> = token
1968            .visible_namespaces()
1969            .iter()
1970            .map(|ns| ns.as_str().to_owned())
1971            .collect();
1972        let filter = EntityFilter {
1973            kinds: match kind {
1974                Some(k) => vec![k.to_string()],
1975                None => vec![],
1976            },
1977            tags_any: match domain_tag {
1978                Some(t) if !t.is_empty() => vec![t.to_string()],
1979                _ => vec![],
1980            },
1981            namespaces: ns_strs,
1982            ..Default::default()
1983        };
1984        let page = self
1985            .entities(token)?
1986            .query_entities(
1987                token.namespace().as_str(),
1988                filter,
1989                PageRequest {
1990                    offset: offset.into(),
1991                    limit,
1992                },
1993            )
1994            .await?;
1995        Ok(page.items)
1996    }
1997
1998    /// Count entities filtered by kind and optional domain tag.
1999    ///
2000    /// Used to report a meaningful `total` alongside a paginated listing (K-6).
2001    /// Multi-namespace visibility from the token is applied.
2002    pub async fn count_entities_tagged(
2003        &self,
2004        token: &NamespaceToken,
2005        kind: Option<&str>,
2006        domain_tag: Option<&str>,
2007    ) -> RuntimeResult<u64> {
2008        let ns_strs: Vec<String> = token
2009            .visible_namespaces()
2010            .iter()
2011            .map(|ns| ns.as_str().to_owned())
2012            .collect();
2013        let filter = EntityFilter {
2014            kinds: match kind {
2015                Some(k) => vec![k.to_string()],
2016                None => vec![],
2017            },
2018            tags_any: match domain_tag {
2019                Some(t) if !t.is_empty() => vec![t.to_string()],
2020                _ => vec![],
2021            },
2022            namespaces: ns_strs,
2023            ..Default::default()
2024        };
2025        Ok(self
2026            .entities(token)?
2027            .count_entities(token.namespace().as_str(), filter)
2028            .await?)
2029    }
2030
2031    /// List events in the namespace proven by the caller token.
2032    pub async fn list_events(
2033        &self,
2034        token: &NamespaceToken,
2035        filter: EventFilter,
2036        page: PageRequest,
2037    ) -> RuntimeResult<Page<Event>> {
2038        self.events(token)?
2039            .query_events(filter, page)
2040            .await
2041            .map_err(Into::into)
2042    }
2043
2044    // ---- Edge operations ----
2045
2046    /// Validate that `source_id` and `target_id` are legal endpoints for `relation`.
2047    ///
2048    /// Centralises the three-case relation contract so that both
2049    /// `link()` and `update_edge()` share identical enforcement:
2050    ///
2051    /// - `annotates`: source MUST be a note; target may be any substrate.
2052    /// - `supersedes` / `supports` / `refutes`: same-substrate only (note→note or entity→entity).
2053    /// - All other 13 relations: both endpoints MUST be entities.
2054    ///
2055    /// Returns `Ok(())` when valid; otherwise `InvalidInput` or `NotFound` with
2056    /// the same messages as the previous inline block (byte-identical behaviour).
2057    ///
2058    /// `pub(crate)`: the atomic prepare pass (`crate::atomic_prepare`) reuses
2059    /// this exact endpoint-type validation during its async prepare step,
2060    /// before building a `LinkPlan`, rather than re-deriving the checks.
2061    pub(crate) async fn validate_edge_relation_endpoints(
2062        &self,
2063        token: &NamespaceToken,
2064        source_id: Uuid,
2065        target_id: Uuid,
2066        relation: EdgeRelation,
2067    ) -> RuntimeResult<()> {
2068        if source_id == target_id {
2069            return Err(RuntimeError::InvalidInput(
2070                "self-loop edges are not allowed: source_id and target_id must be different".into(),
2071            ));
2072        }
2073        if relation == EdgeRelation::Annotates {
2074            // Source must be a note. By-ID endpoint resolution is namespace-agnostic:
2075            // link consumes two by-ID endpoints, so it must resolve exactly what
2076            // get() resolves, regardless of caller namespace.
2077            match self.resolve_edge_endpoint(token, source_id).await? {
2078                Some(Resolved::Note(_)) => {}
2079                Some(_) => {
2080                    return Err(RuntimeError::InvalidInput(format!(
2081                        "annotates source {source_id} must be a note"
2082                    )));
2083                }
2084                None => {
2085                    // Existing edge used as annotates source: wrong kind, not absent.
2086                    if self.get_edge(token, source_id).await?.is_some() {
2087                        return Err(RuntimeError::InvalidInput(format!(
2088                            "annotates source {source_id} must be a note"
2089                        )));
2090                    }
2091                    return Err(RuntimeError::NotFound(format!(
2092                        "link source {source_id} not found"
2093                    )));
2094                }
2095            }
2096            // Target may be any substrate (entity, note, event, or edge) — by-ID, unfiltered.
2097            if !self.substrate_exists_by_id(token, target_id).await? {
2098                return Err(RuntimeError::NotFound(format!(
2099                    "link target {target_id} not found"
2100                )));
2101            }
2102        } else if crate::pack::is_special_relation(relation) {
2103            // supersedes / supports / refutes: same-substrate only (note→note or entity→entity).
2104            // Event and edge endpoints are invalid regardless of the other endpoint.
2105            // Endpoint resolution is by-ID and namespace-agnostic.
2106            let rel_name = relation.as_str();
2107            let src = match self.resolve_edge_endpoint(token, source_id).await? {
2108                Some(r) => r,
2109                None => {
2110                    if self.get_edge(token, source_id).await?.is_some() {
2111                        return Err(RuntimeError::InvalidInput(format!(
2112                            "{rel_name} source {source_id} must be a note or entity (got edge)"
2113                        )));
2114                    }
2115                    return Err(RuntimeError::NotFound(format!(
2116                        "link source {source_id} not found"
2117                    )));
2118                }
2119            };
2120            let tgt = match self.resolve_edge_endpoint(token, target_id).await? {
2121                Some(r) => r,
2122                None => {
2123                    if self.get_edge(token, target_id).await?.is_some() {
2124                        return Err(RuntimeError::InvalidInput(format!(
2125                            "{rel_name} target {target_id} must be a note or entity (got edge)"
2126                        )));
2127                    }
2128                    return Err(RuntimeError::NotFound(format!(
2129                        "link target {target_id} not found"
2130                    )));
2131                }
2132            };
2133            match (&src, &tgt) {
2134                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
2135                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
2136                        let legal_relations = accepted_entity_relations_description(
2137                            &self.pack_edge_rules(),
2138                            &src_e.kind,
2139                            src_e.entity_type.as_deref(),
2140                            &tgt_e.kind,
2141                            tgt_e.entity_type.as_deref(),
2142                        );
2143                        let rule_hint = match relation {
2144                            EdgeRelation::Supports | EdgeRelation::Refutes => {
2145                                "requires concept|document|dataset|artifact -> concept \
2146                                 (or same-substrate note -> note)"
2147                            }
2148                            _ => "requires same-kind entity endpoints",
2149                        };
2150                        return Err(RuntimeError::InvalidInput(format!(
2151                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
2152                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
2153                             {} -> {} under the loaded endpoint rules: {legal_relations}",
2154                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
2155                        )));
2156                    }
2157                }
2158                (Resolved::Note(_), Resolved::Note(_)) => {}
2159                (Resolved::Event(_), _) => {
2160                    return Err(RuntimeError::InvalidInput(format!(
2161                        "{rel_name} does not apply to events; source {source_id} is an event"
2162                    )));
2163                }
2164                (_, Resolved::Event(_)) => {
2165                    return Err(RuntimeError::InvalidInput(format!(
2166                        "{rel_name} does not apply to events; target {target_id} is an event"
2167                    )));
2168                }
2169                (Resolved::Entity(_), Resolved::Note(_)) => {
2170                    return Err(RuntimeError::InvalidInput(format!(
2171                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
2172                         got source={source_id} (entity) target={target_id} (note)"
2173                    )));
2174                }
2175                (Resolved::Note(_), Resolved::Entity(_)) => {
2176                    return Err(RuntimeError::InvalidInput(format!(
2177                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
2178                         got source={source_id} (note) target={target_id} (entity)"
2179                    )));
2180                }
2181                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
2182                    return Err(RuntimeError::InvalidInput(format!(
2183                        "pack-private record is not a valid edge endpoint for {rel_name}"
2184                    )));
2185                }
2186            }
2187        } else {
2188            // All remaining base relations require entity→entity with kind-level
2189            // restrictions (see base allowlist). Packs may extend the allowlist
2190            // additively via EDGE_RULES.
2191            //
2192            // Strategy: resolve both endpoints once (by-ID, unfiltered), consult pack
2193            // rules; on miss, fall through to the original base-rule error messages.
2194            let src_res = self.resolve_edge_endpoint(token, source_id).await?;
2195            let tgt_res = self.resolve_edge_endpoint(token, target_id).await?;
2196            let pack_rules = self.pack_edge_rules();
2197
2198            if pack_rule_allows(&pack_rules, relation, src_res.as_ref(), tgt_res.as_ref()) {
2199                return Ok(());
2200            }
2201
2202            // Substrate check: both endpoints must be entities.
2203            let (src_kind, src_entity_type) = match src_res.as_ref() {
2204                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2205                Some(_) => {
2206                    return Err(RuntimeError::InvalidInput(format!(
2207                        "link source {source_id} must be an entity for relation {relation:?} \
2208                         (only `annotates` crosses substrates)"
2209                    )));
2210                }
2211                None => {
2212                    if self.get_edge(token, source_id).await?.is_some() {
2213                        return Err(RuntimeError::InvalidInput(format!(
2214                            "link source {source_id} must be an entity for relation {relation:?} \
2215                             (only `annotates` crosses substrates)"
2216                        )));
2217                    }
2218                    return Err(RuntimeError::NotFound(format!(
2219                        "link source {source_id} not found"
2220                    )));
2221                }
2222            };
2223            let (tgt_kind, tgt_entity_type) = match tgt_res.as_ref() {
2224                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2225                Some(_) => {
2226                    return Err(RuntimeError::InvalidInput(format!(
2227                        "link target {target_id} must be an entity for relation {relation:?} \
2228                         (only `annotates` crosses substrates)"
2229                    )));
2230                }
2231                None => {
2232                    if self.get_edge(token, target_id).await?.is_some() {
2233                        return Err(RuntimeError::InvalidInput(format!(
2234                            "link target {target_id} must be an entity for relation {relation:?} \
2235                             (only `annotates` crosses substrates)"
2236                        )));
2237                    }
2238                    return Err(RuntimeError::NotFound(format!(
2239                        "link target {target_id} not found"
2240                    )));
2241                }
2242            };
2243            if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
2244                let legal_relations = accepted_entity_relations_description(
2245                    &pack_rules,
2246                    src_kind,
2247                    src_entity_type,
2248                    tgt_kind,
2249                    tgt_entity_type,
2250                );
2251                return Err(RuntimeError::InvalidInput(format!(
2252                    "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
2253                     allowlist; use pack EDGE_RULES to extend the allowlist; currently legal \
2254                     relations for {src_kind} -> {tgt_kind} under the loaded endpoint rules: \
2255                     {legal_relations}",
2256                    relation.as_str()
2257                )));
2258            }
2259        }
2260        Ok(())
2261    }
2262
2263    /// Public delegator for cross-backend link validation.
2264    ///
2265    /// Exposes `validate_edge_relation_endpoints` for the `SubstrateCoordinator`
2266    /// so it can validate the relation before writing the edge on the source backend.
2267    pub async fn validate_link_endpoints(
2268        &self,
2269        token: &NamespaceToken,
2270        source_id: Uuid,
2271        target_id: Uuid,
2272        relation: EdgeRelation,
2273    ) -> RuntimeResult<()> {
2274        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
2275            .await
2276    }
2277
2278    /// Validate an edge relation using pre-fetched endpoint records.
2279    ///
2280    /// For cross-backend links the source and target live on different backends —
2281    /// the source runtime cannot resolve the target. The coordinator fetches each
2282    /// endpoint from its own backend, then calls this method to enforce the
2283    /// kind-pairing rules without a second DB round-trip.
2284    ///
2285    /// `src` and `tgt` are the `resolve_edge_endpoint` results from each backend. The
2286    /// `token` supplies the pack edge rules installed on this (source) runtime;
2287    /// no DB access is performed.
2288    pub fn validate_link_endpoints_by_resolved(
2289        &self,
2290        source_id: Uuid,
2291        target_id: Uuid,
2292        relation: EdgeRelation,
2293        src: Option<&Resolved>,
2294        tgt: Option<&Resolved>,
2295    ) -> RuntimeResult<()> {
2296        if source_id == target_id {
2297            return Err(RuntimeError::InvalidInput(
2298                "self-loop edges are not allowed: source_id and target_id must be different".into(),
2299            ));
2300        }
2301
2302        if relation == EdgeRelation::Annotates {
2303            match src {
2304                Some(Resolved::Note(_)) => {}
2305                Some(_) => {
2306                    return Err(RuntimeError::InvalidInput(format!(
2307                        "annotates source {source_id} must be a note"
2308                    )));
2309                }
2310                None => {
2311                    return Err(RuntimeError::NotFound(format!(
2312                        "link source {source_id} not found"
2313                    )));
2314                }
2315            }
2316            if tgt.is_none() {
2317                return Err(RuntimeError::NotFound(format!(
2318                    "link target {target_id} not found"
2319                )));
2320            }
2321            return Ok(());
2322        }
2323
2324        if crate::pack::is_special_relation(relation) {
2325            let rel_name = relation.as_str();
2326            let src = src.ok_or_else(|| {
2327                RuntimeError::NotFound(format!("link source {source_id} not found"))
2328            })?;
2329            let tgt = tgt.ok_or_else(|| {
2330                RuntimeError::NotFound(format!("link target {target_id} not found"))
2331            })?;
2332            match (src, tgt) {
2333                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
2334                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
2335                        let legal_relations = accepted_entity_relations_description(
2336                            &self.pack_edge_rules(),
2337                            &src_e.kind,
2338                            src_e.entity_type.as_deref(),
2339                            &tgt_e.kind,
2340                            tgt_e.entity_type.as_deref(),
2341                        );
2342                        let rule_hint = match relation {
2343                            EdgeRelation::Supports | EdgeRelation::Refutes => {
2344                                "requires concept|document|dataset|artifact -> concept \
2345                                 (or same-substrate note -> note)"
2346                            }
2347                            _ => "requires same-kind entity endpoints",
2348                        };
2349                        return Err(RuntimeError::InvalidInput(format!(
2350                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
2351                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
2352                             {} -> {} under the loaded endpoint rules: {legal_relations}",
2353                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
2354                        )));
2355                    }
2356                }
2357                (Resolved::Note(_), Resolved::Note(_)) => {}
2358                (Resolved::Entity(_), Resolved::Note(_)) => {
2359                    return Err(RuntimeError::InvalidInput(format!(
2360                        "{rel_name} endpoints must be the same substrate \
2361                         (note→note or entity→entity); got source={source_id} (entity) \
2362                         target={target_id} (note)"
2363                    )));
2364                }
2365                (Resolved::Note(_), Resolved::Entity(_)) => {
2366                    return Err(RuntimeError::InvalidInput(format!(
2367                        "{rel_name} endpoints must be the same substrate \
2368                         (note→note or entity→entity); got source={source_id} (note) \
2369                         target={target_id} (entity)"
2370                    )));
2371                }
2372                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
2373                    return Err(RuntimeError::InvalidInput(format!(
2374                        "pack-private record is not a valid edge endpoint for {rel_name}"
2375                    )));
2376                }
2377                _ => {
2378                    return Err(RuntimeError::InvalidInput(format!(
2379                        "{rel_name} endpoints must be notes or entities (not events)"
2380                    )));
2381                }
2382            }
2383            return Ok(());
2384        }
2385
2386        // All remaining base relations: entity→entity with kind-level restrictions.
2387        // Consult pack rules installed on this (source) runtime first.
2388        let pack_rules = self.pack_edge_rules();
2389        if pack_rule_allows(&pack_rules, relation, src, tgt) {
2390            return Ok(());
2391        }
2392
2393        let (src_kind, src_entity_type) = match src {
2394            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2395            Some(_) => {
2396                return Err(RuntimeError::InvalidInput(format!(
2397                    "link source {source_id} must be an entity for relation {relation:?} \
2398                     (only `annotates` crosses substrates)"
2399                )));
2400            }
2401            None => {
2402                return Err(RuntimeError::NotFound(format!(
2403                    "link source {source_id} not found"
2404                )));
2405            }
2406        };
2407        let (tgt_kind, tgt_entity_type) = match tgt {
2408            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2409            Some(_) => {
2410                return Err(RuntimeError::InvalidInput(format!(
2411                    "link target {target_id} must be an entity for relation {relation:?} \
2412                     (only `annotates` crosses substrates)"
2413                )));
2414            }
2415            None => {
2416                return Err(RuntimeError::NotFound(format!(
2417                    "link target {target_id} not found"
2418                )));
2419            }
2420        };
2421
2422        if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
2423            let legal_relations = accepted_entity_relations_description(
2424                &pack_rules,
2425                src_kind,
2426                src_entity_type,
2427                tgt_kind,
2428                tgt_entity_type,
2429            );
2430            return Err(RuntimeError::InvalidInput(format!(
2431                "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
2432                 allowlist; use pack EDGE_RULES to extend the allowlist; currently legal relations \
2433                 for {src_kind} -> {tgt_kind} under the loaded endpoint rules: {legal_relations}",
2434                relation.as_str()
2435            )));
2436        }
2437
2438        Ok(())
2439    }
2440
2441    /// Validate an `annotates` edge relation using pre-located endpoint kinds.
2442    ///
2443    /// Sibling of [`Self::validate_link_endpoints_by_resolved`] for callers that
2444    /// only have an [`EdgeEndpointKind`] (entity/note/event/edge) rather than a
2445    /// full [`Resolved`] record — the `SubstrateCoordinator`'s cross-backend
2446    /// `locate_endpoint` resolves edge-substrate UUIDs too (matching `get`'s
2447    /// by-ID resolution order), but edges have no `Resolved` variant, so
2448    /// `validate_link_endpoints_by_resolved` cannot express them.
2449    ///
2450    /// `annotates` is the only relation this covers: source must be a note,
2451    /// target may be any substrate (entity, note, event, or edge).
2452    pub fn validate_annotates_endpoint_kinds(
2453        &self,
2454        source_id: Uuid,
2455        target_id: Uuid,
2456        source: Option<EdgeEndpointKind>,
2457        target: Option<EdgeEndpointKind>,
2458    ) -> RuntimeResult<()> {
2459        if source_id == target_id {
2460            return Err(RuntimeError::InvalidInput(
2461                "self-loop edges are not allowed: source_id and target_id must be different".into(),
2462            ));
2463        }
2464        match source {
2465            Some(EdgeEndpointKind::Note) => {}
2466            Some(_) => {
2467                return Err(RuntimeError::InvalidInput(format!(
2468                    "annotates source {source_id} must be a note"
2469                )));
2470            }
2471            None => {
2472                return Err(RuntimeError::NotFound(format!(
2473                    "link source {source_id} not found"
2474                )));
2475            }
2476        }
2477        if target.is_none() {
2478            return Err(RuntimeError::NotFound(format!(
2479                "link target {target_id} not found"
2480            )));
2481        }
2482        Ok(())
2483    }
2484
2485    /// Create a directed edge between two substrates.
2486    ///
2487    /// Enforces the three-case relation contract via
2488    /// `validate_edge_relation_endpoints`. See that method for the full contract.
2489    ///
2490    /// For symmetric relations (`competes_with`, `composed_with`) the endpoint
2491    /// pair is canonicalised to `source_uuid < target_uuid` so that A→B and B→A
2492    /// deduplicate to one row.
2493    ///
2494    /// `metadata` is validated against governed keys; `dependency_kind` is
2495    /// inferred for `depends_on` edges when absent.
2496    ///
2497    /// `target_backend` is always `None` for locally-routed edges written through
2498    /// this path. Both endpoints must exist in the local namespace, so setting
2499    /// `target_backend = None` is the only valid choice.
2500    ///
2501    /// Endpoint existence is a by-ID check and namespace-agnostic: a record
2502    /// that exists in a different namespace than the caller still resolves,
2503    /// exactly as `get()` would.
2504    pub async fn link(
2505        &self,
2506        token: &NamespaceToken,
2507        source_id: Uuid,
2508        target_id: Uuid,
2509        relation: EdgeRelation,
2510        weight: f64,
2511        metadata: Option<serde_json::Value>,
2512    ) -> RuntimeResult<Edge> {
2513        validate_edge_weight(weight)?;
2514        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
2515            .await?;
2516        let (source_id, target_id) = canonical_edge_endpoints(relation, source_id, target_id);
2517        let metadata = if relation == EdgeRelation::DependsOn {
2518            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
2519            // above. The visible-set-scoped `resolve` would silently drop the
2520            // dependency_kind inference for endpoints validation now allows outside
2521            // the caller's visible set.
2522            match (
2523                self.resolve_edge_endpoint(token, source_id).await?,
2524                self.resolve_edge_endpoint(token, target_id).await?,
2525            ) {
2526                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
2527                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
2528                }
2529                _ => metadata,
2530            }
2531        } else {
2532            metadata
2533        };
2534        validate_edge_metadata(relation, metadata.as_ref())?;
2535        let now = chrono::Utc::now();
2536        let ns = token.namespace().as_str();
2537        let edge = Edge {
2538            id: LinkId::from(Uuid::new_v4()),
2539            namespace: ns.to_string(),
2540            source_id,
2541            target_id,
2542            relation,
2543            weight,
2544            created_at: now,
2545            updated_at: now,
2546            deleted_at: None,
2547            metadata,
2548            target_backend: None,
2549        };
2550        // `upsert_edge_guarded` re-checks both endpoints exist as part of the same
2551        // write, not the separate `validate_edge_relation_endpoints` read above: a
2552        // concurrent hard-delete landing between that read and this write can no
2553        // longer create a durably dangling edge. Which endpoint(s) were missing is
2554        // reported by the guard's own in-transaction probe (`GuardedWriteOutcome::
2555        // Refused`), not reconstructed here by re-reading the endpoints after the
2556        // fact: a second concurrent write landing between the refusal and a
2557        // post-hoc read could otherwise misreport which endpoint was actually
2558        // missing at write time.
2559        match self.graph(token)?.upsert_edge_guarded(edge).await? {
2560            khive_storage::GuardedWriteOutcome::Written => {}
2561            khive_storage::GuardedWriteOutcome::Refused(missing) => {
2562                return Err(RuntimeError::GuardedWriteFailed(GuardedWriteFailure {
2563                    entry_index: None,
2564                    missing_source: missing.source.then_some(source_id),
2565                    missing_target: missing.target.then_some(target_id),
2566                }));
2567            }
2568        }
2569
2570        // Read back the persisted row by natural key so the returned
2571        // edge ID is always the one stored in the database, not the locally
2572        // generated UUID that was displaced by an ON CONFLICT DO UPDATE.
2573        // Under parallel calls for the same triple, every caller now returns
2574        // the same persisted edge ID — the winner's insert or the updated row.
2575        let persisted = self
2576            .list_edges(
2577                token,
2578                crate::curation::EdgeListFilter {
2579                    source_id: Some(source_id),
2580                    target_id: Some(target_id),
2581                    relations: vec![relation],
2582                    ..Default::default()
2583                },
2584                1,
2585                0,
2586            )
2587            .await?
2588            .into_iter()
2589            .next()
2590            .ok_or_else(|| {
2591                crate::RuntimeError::Internal(format!(
2592                    "upsert_edge succeeded but natural-key lookup for ({source_id}, {target_id}, {relation}) returned nothing"
2593                ))
2594            })?;
2595        Ok(persisted)
2596    }
2597
2598    /// Write an edge with an explicit `target_backend` stamp (ADR-029 D3).
2599    ///
2600    /// Called by the `SubstrateCoordinator` when source and target are on
2601    /// different backends. The coordinator validates endpoints before calling
2602    /// this method via [`Self::validate_link_endpoints`], so endpoint validation is
2603    /// skipped here. The edge is written on the source backend only.
2604    #[allow(clippy::too_many_arguments)]
2605    pub async fn link_with_target_backend(
2606        &self,
2607        token: &NamespaceToken,
2608        source_id: Uuid,
2609        target_id: Uuid,
2610        relation: EdgeRelation,
2611        weight: f64,
2612        metadata: Option<serde_json::Value>,
2613        target_backend: Option<String>,
2614    ) -> RuntimeResult<Edge> {
2615        validate_edge_weight(weight)?;
2616        let (source_id, target_id) = canonical_edge_endpoints(relation, source_id, target_id);
2617        validate_edge_metadata(relation, metadata.as_ref())?;
2618        let now = chrono::Utc::now();
2619        let ns = token.namespace().as_str();
2620        let edge = Edge {
2621            id: LinkId::from(Uuid::new_v4()),
2622            namespace: ns.to_string(),
2623            source_id,
2624            target_id,
2625            relation,
2626            weight,
2627            created_at: now,
2628            updated_at: now,
2629            deleted_at: None,
2630            metadata,
2631            target_backend,
2632        };
2633        self.graph(token)?.upsert_edge(edge).await?;
2634        let persisted = self
2635            .list_edges(
2636                token,
2637                crate::curation::EdgeListFilter {
2638                    source_id: Some(source_id),
2639                    target_id: Some(target_id),
2640                    relations: vec![relation],
2641                    ..Default::default()
2642                },
2643                1,
2644                0,
2645            )
2646            .await?
2647            .into_iter()
2648            .next()
2649            .ok_or_else(|| {
2650                crate::RuntimeError::Internal(format!(
2651                    "upsert_edge succeeded but natural-key lookup for ({source_id}, {target_id}, {relation}) returned nothing"
2652                ))
2653            })?;
2654        Ok(persisted)
2655    }
2656
2657    /// Returns `true` if `id` resolves to a live substrate record in the
2658    /// caller's visible namespace set.
2659    ///
2660    /// Covers entity, note, event (via `resolve`) and edge (via `get_edge_visible`).
2661    /// Only records that are accessible to the caller (primary or configured visible
2662    /// namespaces) return `true`; absent or foreign-invisible records return `false`.
2663    pub(crate) async fn substrate_exists_in_ns(
2664        &self,
2665        token: &NamespaceToken,
2666        id: Uuid,
2667    ) -> RuntimeResult<bool> {
2668        if self.resolve(token, id).await?.is_some() {
2669            return Ok(true);
2670        }
2671        match self.get_edge_visible(token, id).await {
2672            Ok(Some(_)) => Ok(true),
2673            Ok(None) | Err(RuntimeError::NotFound(_)) => Ok(false),
2674            Err(err) => Err(err),
2675        }
2676    }
2677
2678    /// Returns `true` if `id` resolves to a live substrate record, by ID, with
2679    /// no namespace filter.
2680    ///
2681    /// Used from `annotates` endpoint validation (`link` and `create`'s
2682    /// `annotates` targets), which consume a by-ID endpoint and so must follow
2683    /// the same namespace-agnostic by-ID contract as `get()`.
2684    pub(crate) async fn substrate_exists_by_id(
2685        &self,
2686        token: &NamespaceToken,
2687        id: Uuid,
2688    ) -> RuntimeResult<bool> {
2689        if self.resolve_edge_endpoint(token, id).await?.is_some() {
2690            return Ok(true);
2691        }
2692        match self.get_edge(token, id).await {
2693            Ok(Some(_)) => Ok(true),
2694            Ok(None) | Err(RuntimeError::NotFound(_)) => Ok(false),
2695            Err(err) => Err(err),
2696        }
2697    }
2698
2699    /// Get immediate neighbors of a node, optionally filtered by relation type.
2700    ///
2701    /// Pass `relations: Some(vec![EdgeRelation::Annotates])` to retrieve only
2702    /// annotation edges, enabling cross-substrate navigation.
2703    ///
2704    /// Symmetric relations (`competes_with`, `composed_with`) are stored
2705    /// with the canonical source as the lower UUID. Direction normalization is
2706    /// applied in `neighbors_with_query` so both callers see correct results.
2707    pub async fn neighbors(
2708        &self,
2709        token: &NamespaceToken,
2710        node_id: Uuid,
2711        direction: Direction,
2712        limit: Option<u32>,
2713        relations: Option<Vec<EdgeRelation>>,
2714    ) -> RuntimeResult<Vec<NeighborHit>> {
2715        self.neighbors_with_query(
2716            token,
2717            node_id,
2718            NeighborQuery {
2719                direction,
2720                relations,
2721                limit,
2722                min_weight: None,
2723            },
2724        )
2725        .await
2726    }
2727
2728    /// Get neighbors with full query control (includes `min_weight`).
2729    ///
2730    /// Applies symmetric-relation direction normalization: if the
2731    /// relations filter contains only symmetric relations the direction is
2732    /// overridden to `Both` so edges stored in canonical order are always found.
2733    ///
2734    /// Soft-deleted entity nodes are excluded from results unless the caller
2735    /// explicitly requested them (future: `include_deleted` flag; currently
2736    /// always false).
2737    pub async fn neighbors_with_query(
2738        &self,
2739        token: &NamespaceToken,
2740        node_id: Uuid,
2741        mut query: NeighborQuery,
2742    ) -> RuntimeResult<Vec<NeighborHit>> {
2743        if !self.substrate_exists_in_ns(token, node_id).await? {
2744            return Ok(Vec::new());
2745        }
2746
2747        query.direction =
2748            normalize_symmetric_direction(query.direction, query.relations.as_deref());
2749        let mut hits = Vec::new();
2750        for ns in token.visible_namespaces() {
2751            let temp = NamespaceToken::for_namespace(ns.clone());
2752            let mut ns_hits = self.graph(&temp)?.neighbors(node_id, query.clone()).await?;
2753            hits.append(&mut ns_hits);
2754        }
2755        hits.sort_by_key(|h| (h.node_id, h.edge_id));
2756        hits.dedup_by_key(|h| (h.node_id, h.edge_id));
2757        self.enrich_neighbor_hits(token, &mut hits).await;
2758        // Filter out soft-deleted entity nodes.
2759        let candidate_ids: Vec<Uuid> = hits.iter().map(|h| h.node_id).collect();
2760        let deleted = self.deleted_entity_ids(candidate_ids).await;
2761        if !deleted.is_empty() {
2762            hits.retain(|h| !deleted.contains(&h.node_id));
2763        }
2764        // Restore the weight-descending, node_id-ascending order the storage
2765        // layer established (khive-db graph.rs `ORDER BY weight DESC, node_id
2766        // ASC`) — the (node_id, edge_id) sort above exists only to make
2767        // `dedup_by_key` adjacent-comparable and otherwise discards it. This
2768        // ordering contract must hold at every call site of this op (context
2769        // and neighbors verb alike), for every direction.
2770        hits.sort_by(|a, b| {
2771            b.weight
2772                .partial_cmp(&a.weight)
2773                .unwrap_or(std::cmp::Ordering::Equal)
2774                .then(a.node_id.cmp(&b.node_id))
2775        });
2776        Ok(hits)
2777    }
2778
2779    /// Find live `annotates` edges targeting one record without applying a
2780    /// namespace predicate.
2781    ///
2782    /// This is the graph counterpart to the namespace-agnostic by-ID `get`
2783    /// contract (ADR-007 Rev 6). Multi-record neighbor traversal remains
2784    /// visibility-scoped; callers should use this only after resolving a live
2785    /// target through a by-ID operation.
2786    pub async fn annotation_neighbors_by_target_id(
2787        &self,
2788        target_id: Uuid,
2789    ) -> RuntimeResult<Vec<NeighborHit>> {
2790        let mut reader = self.sql().reader().await?;
2791        let rows = reader
2792            .query_all(SqlStatement {
2793                sql: "SELECT source_id, id, weight FROM graph_edges \
2794                      WHERE target_id = ?1 AND relation = ?2 AND deleted_at IS NULL \
2795                      ORDER BY weight DESC, source_id ASC"
2796                    .to_string(),
2797                params: vec![
2798                    SqlValue::Text(target_id.to_string()),
2799                    SqlValue::Text(EdgeRelation::Annotates.to_string()),
2800                ],
2801                label: Some("annotations.by_target_id_unfiltered".into()),
2802            })
2803            .await?;
2804
2805        rows.into_iter()
2806            .map(|row| {
2807                let parse_uuid = |name: &str| match row.get(name) {
2808                    Some(SqlValue::Text(value)) => Uuid::from_str(value).map_err(|error| {
2809                        RuntimeError::Internal(format!("graph_edges.{name} is not a UUID: {error}"))
2810                    }),
2811                    Some(value) => Err(RuntimeError::Internal(format!(
2812                        "graph_edges.{name} has unexpected SQL value {value:?}"
2813                    ))),
2814                    None => Err(RuntimeError::Internal(format!(
2815                        "graph_edges row missing {name}"
2816                    ))),
2817                };
2818                let weight = match row.get("weight") {
2819                    Some(SqlValue::Float(value)) => Ok(*value),
2820                    Some(value) => Err(RuntimeError::Internal(format!(
2821                        "graph_edges.weight has unexpected SQL value {value:?}"
2822                    ))),
2823                    None => Err(RuntimeError::Internal(
2824                        "graph_edges row missing weight".into(),
2825                    )),
2826                }?;
2827
2828                Ok(NeighborHit {
2829                    node_id: parse_uuid("source_id")?,
2830                    edge_id: parse_uuid("id")?,
2831                    relation: EdgeRelation::Annotates,
2832                    weight,
2833                    name: None,
2834                    kind: None,
2835                    entity_type: None,
2836                })
2837            })
2838            .collect()
2839    }
2840
2841    /// Get both-direction neighbors, each tagged with the direction (`Out`/
2842    /// `In`) it was found in, via a single storage query per visible
2843    /// namespace instead of two separate direction-scoped `neighbors_with_query`
2844    /// calls: halving the neighbor SELECT count for `context(direction="both")`
2845    /// expansion. `query.direction` is ignored: always both.
2846    ///
2847    /// Mirrors `neighbors_with_query`'s dedup/enrich/soft-delete-filter/order
2848    /// pipeline exactly, carrying the per-hit direction tag through unchanged.
2849    pub async fn neighbors_with_query_directed(
2850        &self,
2851        token: &NamespaceToken,
2852        node_id: Uuid,
2853        query: NeighborQuery,
2854    ) -> RuntimeResult<Vec<(NeighborHit, Direction)>> {
2855        if !self.substrate_exists_in_ns(token, node_id).await? {
2856            return Ok(Vec::new());
2857        }
2858
2859        let mut hits: Vec<DirectedNeighborHit> = Vec::new();
2860        for ns in token.visible_namespaces() {
2861            let temp = NamespaceToken::for_namespace(ns.clone());
2862            let mut ns_hits = self
2863                .graph(&temp)?
2864                .neighbors_both_directions(node_id, query.clone())
2865                .await?;
2866            hits.append(&mut ns_hits);
2867        }
2868        // Direction is part of the key (not just node_id/edge_id) so a
2869        // self-loop's Out row and In row — same node_id and edge_id, opposite
2870        // direction: sort adjacent but distinct and both survive dedup.
2871        hits.sort_by_key(|h| {
2872            (
2873                h.hit.node_id,
2874                h.hit.edge_id,
2875                direction_sort_rank(&h.direction),
2876            )
2877        });
2878        hits.dedup_by_key(|h| {
2879            (
2880                h.hit.node_id,
2881                h.hit.edge_id,
2882                direction_sort_rank(&h.direction),
2883            )
2884        });
2885
2886        let mut plain_hits: Vec<NeighborHit> = hits.iter().map(|h| h.hit.clone()).collect();
2887        self.enrich_neighbor_hits(token, &mut plain_hits).await;
2888        for (dh, enriched) in hits.iter_mut().zip(plain_hits) {
2889            dh.hit = enriched;
2890        }
2891
2892        // Filter out soft-deleted entity nodes.
2893        let candidate_ids: Vec<Uuid> = hits.iter().map(|h| h.hit.node_id).collect();
2894        let deleted = self.deleted_entity_ids(candidate_ids).await;
2895        if !deleted.is_empty() {
2896            hits.retain(|h| !deleted.contains(&h.hit.node_id));
2897        }
2898        // Same global weight-descending/node_id-ascending restore as
2899        // `neighbors_with_query`: the (node_id, edge_id, direction) sort above
2900        // exists only to make `dedup_by_key` adjacent-comparable.
2901        hits.sort_by(|a, b| {
2902            b.hit
2903                .weight
2904                .partial_cmp(&a.hit.weight)
2905                .unwrap_or(std::cmp::Ordering::Equal)
2906                .then(a.hit.node_id.cmp(&b.hit.node_id))
2907        });
2908        Ok(hits.into_iter().map(|h| (h.hit, h.direction)).collect())
2909    }
2910
2911    /// Traverse the graph from a set of root nodes.
2912    ///
2913    /// Roots in a foreign namespace are silently filtered before storage expansion.
2914    /// Soft-deleted entity nodes are excluded from results.
2915    pub async fn traverse(
2916        &self,
2917        token: &NamespaceToken,
2918        request: TraversalRequest,
2919    ) -> RuntimeResult<Vec<GraphPath>> {
2920        let mut request = request;
2921        request.validate().map_err(RuntimeError::InvalidInput)?;
2922        let mut visible_roots = Vec::with_capacity(request.roots.len());
2923        let mut seen_roots = std::collections::HashSet::with_capacity(request.roots.len());
2924        for root in request.roots.drain(..) {
2925            if seen_roots.insert(root) && self.substrate_exists_in_ns(token, root).await? {
2926                visible_roots.push(root);
2927            }
2928        }
2929        request.roots = visible_roots;
2930        if request.roots.is_empty() {
2931            return Ok(Vec::new());
2932        }
2933
2934        let mut paths = Vec::new();
2935        for ns in token.visible_namespaces() {
2936            let temp = NamespaceToken::for_namespace(ns.clone());
2937            let mut ns_paths = self.graph(&temp)?.traverse(request.clone()).await?;
2938            paths.append(&mut ns_paths);
2939        }
2940        // Reconcile the per-namespace GraphPaths back down to one per
2941        // distinct root_id (see merge_traversal_paths_by_root for why this
2942        // is needed and what it enforces).
2943        let mut paths =
2944            merge_traversal_paths_by_root(paths, Some(request.options.effective_limit()));
2945        self.enrich_path_nodes(token, &mut paths, request.include_properties)
2946            .await;
2947        // Filter out soft-deleted entity nodes from all path nodes.
2948        let all_node_ids: Vec<Uuid> = paths
2949            .iter()
2950            .flat_map(|p| p.nodes.iter().map(|n| n.node_id))
2951            .collect();
2952        let deleted = self.deleted_entity_ids(all_node_ids).await;
2953        if !deleted.is_empty() {
2954            for path in paths.iter_mut() {
2955                path.nodes.retain(|n| !deleted.contains(&n.node_id));
2956                recompute_total_weight(path);
2957            }
2958            paths.retain(|p| !p.nodes.is_empty());
2959        }
2960        Ok(paths)
2961    }
2962
2963    /// Batch-query for soft-deleted UUIDs in `ids`, across BOTH the entities
2964    /// and notes tables.
2965    ///
2966    /// Neighbor/traverse candidates can be note-kind nodes (e.g. reached via
2967    /// `annotates` edges) as well as entities; a screen that only consults
2968    /// `entities` lets soft-deleted note targets leak through and hydrate as
2969    /// blank/missing hits. This is a view-layer read-only screen: it does
2970    /// not touch edges or mutate any data.
2971    ///
2972    /// Returns the subset of `ids` that have `deleted_at IS NOT NULL` in
2973    /// either table. Takes `Vec<Uuid>` (not an iterator) so the async state
2974    /// machine holds only owned data — no iterator borrow across yields.
2975    async fn deleted_entity_ids(&self, ids: Vec<Uuid>) -> std::collections::HashSet<Uuid> {
2976        if ids.is_empty() {
2977            return std::collections::HashSet::new();
2978        }
2979        let id_strs: Vec<String> = ids.iter().map(|u| u.to_string()).collect();
2980        let n = id_strs.len();
2981        // Each UNION half gets its OWN numbered-placeholder block (?1..?n for
2982        // entities, ?(n+1)..?(2n) for notes) — numbered SQLite params bind by
2983        // index, so reusing the same numbers across halves would silently
2984        // collapse to a single shared block instead of binding the full list
2985        // twice (see khive-db/src/stores/graph.rs batch_neighbors: "each half
2986        // is a fully independent positional-parameter block").
2987        let entities_placeholders = (0..n)
2988            .map(|i| format!("?{}", i + 1))
2989            .collect::<Vec<_>>()
2990            .join(",");
2991        let notes_placeholders = (0..n)
2992            .map(|i| format!("?{}", n + i + 1))
2993            .collect::<Vec<_>>()
2994            .join(",");
2995        let sql_str = format!(
2996            "SELECT id FROM entities WHERE id IN ({entities_placeholders}) AND deleted_at IS NOT NULL \
2997             UNION \
2998             SELECT id FROM notes WHERE id IN ({notes_placeholders}) AND deleted_at IS NOT NULL"
2999        );
3000        // Same id list bound twice — once per UNION arm's independent placeholder block.
3001        let params: Vec<SqlValue> = id_strs
3002            .iter()
3003            .chain(id_strs.iter())
3004            .cloned()
3005            .map(SqlValue::Text)
3006            .collect();
3007        let stmt = SqlStatement {
3008            sql: sql_str,
3009            params,
3010            label: Some("deleted_entity_ids".into()),
3011        };
3012        let mut out = std::collections::HashSet::new();
3013        let sql = self.sql();
3014        if let Ok(mut reader) = sql.reader().await {
3015            if let Ok(rows) = reader.query_all(stmt).await {
3016                for row in rows {
3017                    if let Some(col) = row.columns.first() {
3018                        if let SqlValue::Text(s) = &col.value {
3019                            if let Ok(u) = s.parse::<Uuid>() {
3020                                out.insert(u);
3021                            }
3022                        }
3023                    }
3024                }
3025            }
3026            // best-effort: on reader or query error, treat none as deleted
3027        }
3028        out
3029    }
3030
3031    /// Populate `name` and `kind` on each `NeighborHit` from the corresponding
3032    /// entity or note record. Best-effort: unresolved IDs leave the fields `None`.
3033    ///
3034    /// Uses a single batched entity lookup via `get_entities_by_ids_visible`
3035    /// (scoped to the token's full visible-namespace set so that neighbors in
3036    /// extra-visible namespaces are enriched), then a batched note lookup
3037    /// (`get_notes_batch`) for the residual IDs not resolved as entities.
3038    /// Order and identity of hits is preserved via `HashMap` re-index.
3039    async fn enrich_neighbor_hits(&self, token: &NamespaceToken, hits: &mut [NeighborHit]) {
3040        if hits.is_empty() {
3041            return;
3042        }
3043
3044        // Deduplicated IDs for the batch call.
3045        let unique_ids: Vec<Uuid> = {
3046            let mut seen = std::collections::HashSet::new();
3047            hits.iter()
3048                .filter_map(|h| {
3049                    if seen.insert(h.node_id) {
3050                        Some(h.node_id)
3051                    } else {
3052                        None
3053                    }
3054                })
3055                .collect()
3056        };
3057
3058        let entity_map: HashMap<Uuid, Entity> = self
3059            .get_entities_by_ids_visible(token, &unique_ids)
3060            .await
3061            .unwrap_or_default()
3062            .into_iter()
3063            .map(|e| (e.id, e))
3064            .collect();
3065
3066        // Batch note lookup for IDs not found as entities.
3067        let residual_ids: Vec<Uuid> = unique_ids
3068            .iter()
3069            .filter(|id| !entity_map.contains_key(id))
3070            .copied()
3071            .collect();
3072
3073        let note_map: HashMap<Uuid, Note> = if !residual_ids.is_empty() {
3074            if let Ok(store) = self.notes(token) {
3075                store
3076                    .get_notes_batch(&residual_ids)
3077                    .await
3078                    .unwrap_or_default()
3079                    .into_iter()
3080                    .map(|n| (n.id, n))
3081                    .collect()
3082            } else {
3083                HashMap::new()
3084            }
3085        } else {
3086            HashMap::new()
3087        };
3088
3089        for hit in hits.iter_mut() {
3090            if let Some(entity) = entity_map.get(&hit.node_id) {
3091                hit.name = Some(entity.name.clone());
3092                hit.kind = Some(entity.kind.clone());
3093                hit.entity_type = entity.entity_type.clone();
3094            } else if let Some(note) = note_map.get(&hit.node_id) {
3095                hit.name = Some(note_graph_name(note));
3096                hit.kind = Some(note.kind.clone());
3097            }
3098        }
3099    }
3100
3101    /// Populate `name` and `kind` on each `PathNode` from the corresponding
3102    /// entity or note record. Same best-effort policy as `enrich_neighbor_hits`.
3103    ///
3104    /// Uses `get_entities_by_ids_visible` so that path nodes whose entities
3105    /// live in extra-visible namespaces are enriched correctly. Node IDs that
3106    /// repeat across paths are fetched exactly once.
3107    ///
3108    /// `include_properties` gates whether `entity.properties` is cloned onto
3109    /// each node. When `false` (the default), the potentially large JSON blob
3110    /// is never read from the map, keeping the hot path allocation-free.
3111    async fn enrich_path_nodes(
3112        &self,
3113        token: &NamespaceToken,
3114        paths: &mut [GraphPath],
3115        include_properties: bool,
3116    ) {
3117        if paths.is_empty() {
3118            return;
3119        }
3120
3121        // Deduplicate node IDs across all paths before the batch call.
3122        let unique_ids: Vec<Uuid> = {
3123            let mut seen = std::collections::HashSet::new();
3124            paths
3125                .iter()
3126                .flat_map(|p| p.nodes.iter())
3127                .filter_map(|n| {
3128                    if seen.insert(n.node_id) {
3129                        Some(n.node_id)
3130                    } else {
3131                        None
3132                    }
3133                })
3134                .collect()
3135        };
3136
3137        let entity_map: HashMap<Uuid, Entity> = self
3138            .get_entities_by_ids_visible(token, &unique_ids)
3139            .await
3140            .unwrap_or_default()
3141            .into_iter()
3142            .map(|e| (e.id, e))
3143            .collect();
3144
3145        let residual_ids: Vec<Uuid> = unique_ids
3146            .iter()
3147            .filter(|id| !entity_map.contains_key(id))
3148            .copied()
3149            .collect();
3150
3151        let note_map: HashMap<Uuid, Note> = if !residual_ids.is_empty() {
3152            if let Ok(store) = self.notes(token) {
3153                store
3154                    .get_notes_batch(&residual_ids)
3155                    .await
3156                    .unwrap_or_default()
3157                    .into_iter()
3158                    .map(|n| (n.id, n))
3159                    .collect()
3160            } else {
3161                HashMap::new()
3162            }
3163        } else {
3164            HashMap::new()
3165        };
3166
3167        for path in paths.iter_mut() {
3168            for node in path.nodes.iter_mut() {
3169                if let Some(entity) = entity_map.get(&node.node_id) {
3170                    node.name = Some(entity.name.clone());
3171                    node.kind = Some(entity.kind.clone());
3172                    if include_properties {
3173                        node.properties = entity.properties.clone();
3174                    }
3175                } else if let Some(note) = note_map.get(&node.node_id) {
3176                    node.name = Some(note_graph_name(note));
3177                    node.kind = Some(note.kind.clone());
3178                }
3179            }
3180        }
3181    }
3182
3183    // ---- Note operations ----
3184
3185    /// Create and persist a note, optionally with properties and annotation targets.
3186    ///
3187    /// After creating the note:
3188    /// - Always indexes into FTS5 at the `notes_<namespace>` key.
3189    /// - If an embedding model is configured, indexes into the vector store with
3190    ///   `SubstrateKind::Note`.
3191    /// - For each UUID in `annotates`, creates an `EdgeRelation::Annotates` edge from
3192    ///   the note to that target.
3193    // REASON: note creation requires kind, name, content, salience, properties, annotates,
3194    // and namespace token — mirrors the MCP verb surface; a builder would not reduce
3195    // caller complexity for pack handler callers.
3196    #[allow(clippy::too_many_arguments)]
3197    pub async fn create_note(
3198        &self,
3199        token: &NamespaceToken,
3200        kind: &str,
3201        name: Option<&str>,
3202        content: &str,
3203        salience: Option<f64>,
3204        properties: Option<serde_json::Value>,
3205        annotates: Vec<Uuid>,
3206    ) -> RuntimeResult<Note> {
3207        Ok(self
3208            .create_note_inner(
3209                token, kind, name, content, None, salience, None, properties, annotates, None,
3210            )
3211            .await?
3212            .0)
3213    }
3214
3215    /// Like [`Self::create_note`], but lets the caller supply a smaller text
3216    /// to send to the vector embedder while the note's stored/FTS-indexed
3217    /// `content` remains the full text.
3218    ///
3219    /// `embedding_content`, when `Some`, must be non-empty and a proper
3220    /// prefix of `content` — anything else is rejected with `InvalidInput`
3221    /// before any write. `None` behaves exactly like [`Self::create_note`].
3222    /// Use this when `content` may exceed an embedder's input cap (e.g. a
3223    /// very long commit message) and only a capped head prefix should be
3224    /// embedded, while the full text is still stored and searchable via FTS.
3225    #[allow(clippy::too_many_arguments)]
3226    pub async fn create_note_with_embedding_content(
3227        &self,
3228        token: &NamespaceToken,
3229        kind: &str,
3230        name: Option<&str>,
3231        content: &str,
3232        embedding_content: Option<&str>,
3233        salience: Option<f64>,
3234        properties: Option<serde_json::Value>,
3235        annotates: Vec<Uuid>,
3236    ) -> RuntimeResult<Note> {
3237        Ok(self
3238            .create_note_inner(
3239                token,
3240                kind,
3241                name,
3242                content,
3243                embedding_content,
3244                salience,
3245                None,
3246                properties,
3247                annotates,
3248                None,
3249            )
3250            .await?
3251            .0)
3252    }
3253
3254    #[allow(clippy::too_many_arguments)]
3255    pub async fn create_note_with_embedding_content_and_report(
3256        &self,
3257        token: &NamespaceToken,
3258        kind: &str,
3259        name: Option<&str>,
3260        content: &str,
3261        embedding_content: Option<&str>,
3262        salience: Option<f64>,
3263        properties: Option<serde_json::Value>,
3264        annotates: Vec<Uuid>,
3265    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
3266        self.create_note_inner(
3267            token,
3268            kind,
3269            name,
3270            content,
3271            embedding_content,
3272            salience,
3273            None,
3274            properties,
3275            annotates,
3276            None,
3277        )
3278        .await
3279    }
3280
3281    /// Like [`Self::create_note`] but also sets a non-zero decay factor on the note.
3282    // REASON: extends create_note with an additional decay_factor parameter; same
3283    // rationale — mirrors the MCP surface and reduces an extra builder layer.
3284    #[allow(clippy::too_many_arguments)]
3285    pub async fn create_note_with_decay(
3286        &self,
3287        token: &NamespaceToken,
3288        kind: &str,
3289        name: Option<&str>,
3290        content: &str,
3291        salience: Option<f64>,
3292        decay_factor: f64,
3293        properties: Option<serde_json::Value>,
3294        annotates: Vec<Uuid>,
3295    ) -> RuntimeResult<Note> {
3296        self.create_note_with_decay_for_embedding_model(
3297            token,
3298            kind,
3299            name,
3300            content,
3301            salience,
3302            decay_factor,
3303            properties,
3304            annotates,
3305            None,
3306        )
3307        .await
3308    }
3309
3310    /// Like [`Self::create_note_with_decay`] but targets a specific embedding model.
3311    // REASON: adds an embedding_model parameter to the decay variant; the full parameter
3312    // set is required for correct MCP verb routing and cannot be collapsed without
3313    // introducing a separate config struct that would obscure call sites.
3314    #[allow(clippy::too_many_arguments)]
3315    pub async fn create_note_with_decay_for_embedding_model(
3316        &self,
3317        token: &NamespaceToken,
3318        kind: &str,
3319        name: Option<&str>,
3320        content: &str,
3321        salience: Option<f64>,
3322        decay_factor: f64,
3323        properties: Option<serde_json::Value>,
3324        annotates: Vec<Uuid>,
3325        embedding_model: Option<&str>,
3326    ) -> RuntimeResult<Note> {
3327        Ok(self
3328            .create_note_inner(
3329                token,
3330                kind,
3331                name,
3332                content,
3333                None,
3334                salience,
3335                Some(decay_factor),
3336                properties,
3337                annotates,
3338                embedding_model,
3339            )
3340            .await?
3341            .0)
3342    }
3343
3344    /// Insert a note using `INSERT OR IGNORE` semantics for atomic deduplication.
3345    ///
3346    /// Returns `Ok(Some(note))` when the note was newly written.  Returns
3347    /// `Ok(None)` when a unique constraint (e.g. the `external_id` partial
3348    /// index on comm message notes) was already satisfied by an existing row,
3349    /// making this call a no-op.  FTS indexing and vector embedding are
3350    /// attempted on success but treated as best-effort: failures are logged
3351    /// and do not abort the write.
3352    ///
3353    /// This method is intentionally narrower than `create_note`: it skips
3354    /// salience/decay, annotates edges, and embedding-model selection, which
3355    /// are not needed for channel-ingest paths.
3356    ///
3357    /// Rejects `quarantined` / `channel_kind` / `channel_slug` on a `message`
3358    /// note: those three properties are transport-owned evidence that
3359    /// `comm.health` trusts at face value, and this fast path (unlike the
3360    /// generic `create` verb funnel) is not covered by the
3361    /// pack-installed note-write validator. Only the trusted channel-ingest
3362    /// path may establish them — see
3363    /// [`Self::try_create_note_as_trusted_ingest`].
3364    pub async fn try_create_note(
3365        &self,
3366        token: &NamespaceToken,
3367        kind: &str,
3368        name: Option<&str>,
3369        content: &str,
3370        properties: Option<serde_json::Value>,
3371    ) -> RuntimeResult<Option<Note>> {
3372        self.try_create_note_impl(token, kind, name, content, properties, false)
3373            .await
3374    }
3375
3376    /// Like [`Self::try_create_note`] but permits the caller to establish the
3377    /// transport-owned `message` properties (`quarantined`, `channel_kind`,
3378    /// `channel_slug`).
3379    ///
3380    /// This is a deliberately named, separate entry point rather than a flag
3381    /// on `try_create_note` so the trust decision is visible at every call
3382    /// site: `comm.ingest` (`khive-pack-comm/src/handlers.rs`) is the sole
3383    /// legitimate caller, because it is the only code that has just derived
3384    /// quarantine disposition and channel provenance from the inbound
3385    /// transport itself. The caller set is bounded by possession, not
3386    /// documentation: the required [`crate::ChannelIngestCapability`] is
3387    /// constructible only inside this crate and granted at pack registration
3388    /// exclusively to channel-transport packs. Every other write path uses
3389    /// `try_create_note`, which rejects those three properties
3390    /// unconditionally.
3391    pub async fn try_create_note_as_trusted_ingest(
3392        &self,
3393        _capability: &crate::pack::ChannelIngestCapability,
3394        token: &NamespaceToken,
3395        kind: &str,
3396        name: Option<&str>,
3397        content: &str,
3398        properties: Option<serde_json::Value>,
3399    ) -> RuntimeResult<Option<Note>> {
3400        self.try_create_note_impl(token, kind, name, content, properties, true)
3401            .await
3402    }
3403
3404    #[allow(clippy::too_many_arguments)]
3405    async fn try_create_note_impl(
3406        &self,
3407        token: &NamespaceToken,
3408        kind: &str,
3409        name: Option<&str>,
3410        content: &str,
3411        properties: Option<serde_json::Value>,
3412        allow_transport_owned_message_properties: bool,
3413    ) -> RuntimeResult<Option<Note>> {
3414        self.validate_note_kind(kind)?;
3415        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
3416        crate::secret_gate::check(content)?;
3417        if let Some(n) = name {
3418            crate::secret_gate::check(n)?;
3419        }
3420        if let Some(ref p) = properties {
3421            crate::secret_gate::check_json(p)?;
3422        }
3423        if !allow_transport_owned_message_properties && kind == "message" {
3424            if let Some(key) = properties
3425                .as_ref()
3426                .and_then(serde_json::Value::as_object)
3427                .and_then(transport_owned_message_property_named_in)
3428            {
3429                return Err(RuntimeError::InvalidInput(format!(
3430                    "`{key}` is transport-owned on a `message` note and cannot be supplied \
3431                     through `try_create_note`; only the trusted channel-ingest path may \
3432                     establish quarantine disposition and channel provenance"
3433                )));
3434            }
3435        }
3436
3437        let ns = token.namespace().as_str();
3438        let mut note = Note::new(ns, kind, content);
3439        if let Some(n) = name {
3440            note = note.with_name(n);
3441        }
3442        if let Some(p) = properties {
3443            note = note.with_properties(p);
3444        }
3445
3446        // Bypasses the `notes()` accessor's PolicyEnforcingNoteStore wrapper —
3447        // the reserved-transport-property check above already enforces the
3448        // identical policy, conditionally allowing the trusted-ingest path,
3449        // so this reaches storage directly rather than duplicate the check
3450        // through a wrapper that cannot see the trust decision this function
3451        // just made.
3452        let inserted = self.raw_notes(token)?.try_insert_note(note.clone()).await?;
3453        if !inserted {
3454            return Ok(None);
3455        }
3456
3457        // Best-effort FTS: log and continue on failure.
3458        if let Ok(fts) = self.text_for_notes(token) {
3459            if let Err(e) = fts.upsert_document(note_fts_document(&note)).await {
3460                tracing::warn!(
3461                    note_id = %note.id,
3462                    error = %e,
3463                    "try_create_note: FTS indexing failed (non-fatal)"
3464                );
3465            }
3466        }
3467
3468        // Best-effort vector embedding: log and continue on failure.
3469        let embed_model_names = self.registered_embedding_model_names();
3470        for model_name in &embed_model_names {
3471            match self
3472                .embed_document_with_model_outcome_for_token(
3473                    token,
3474                    model_name,
3475                    note_embedding_text_ref(&note),
3476                )
3477                .await
3478            {
3479                Ok(outcome) => {
3480                    if outcome.truncated {
3481                        tracing::warn!(
3482                            note_id = %note.id,
3483                            model = %outcome.model_name,
3484                            source_bytes = outcome.source_bytes,
3485                            embedded_bytes = outcome.embedded_bytes,
3486                            "try_create_note: embedding input truncated; full content stored unchanged"
3487                        );
3488                    }
3489                    if let Ok(vs) = self.vectors_for_model(token, model_name) {
3490                        if let Err(e) = vs
3491                            .insert(
3492                                note.id,
3493                                SubstrateKind::Note,
3494                                ns,
3495                                "note.content",
3496                                vec![outcome.vector],
3497                            )
3498                            .await
3499                        {
3500                            tracing::warn!(
3501                                note_id = %note.id,
3502                                model = %model_name,
3503                                error = %e,
3504                                "try_create_note: vector insert failed (non-fatal)"
3505                            );
3506                        }
3507                    }
3508                }
3509                Err(e) => {
3510                    tracing::warn!(
3511                        note_id = %note.id,
3512                        model = %model_name,
3513                        error = %e,
3514                        "try_create_note: embedding failed (non-fatal)"
3515                    );
3516                }
3517            }
3518        }
3519
3520        Ok(Some(note))
3521    }
3522
3523    // REASON: private inner function unifies all create_note variants; it receives every
3524    // optional parameter individually so that public variants can pass None without
3525    // requiring callers to construct an intermediate struct.
3526    #[allow(clippy::too_many_arguments)]
3527    async fn create_note_inner(
3528        &self,
3529        token: &NamespaceToken,
3530        kind: &str,
3531        name: Option<&str>,
3532        content: &str,
3533        embedding_content: Option<&str>,
3534        salience: Option<f64>,
3535        decay_factor: Option<f64>,
3536        properties: Option<serde_json::Value>,
3537        annotates: Vec<Uuid>,
3538        embedding_model: Option<&str>,
3539    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
3540        self.validate_note_kind(kind)?;
3541        // Owned identity properties are derived from the authorization token
3542        // before anything else touches them, so every caller of this function —
3543        // the generic `create` verb and direct Rust callers alike — stores the
3544        // same derived values. Runs before the secret gate so the gate scans
3545        // exactly what will be written.
3546        let properties = self.derive_note_write_properties(kind, token, properties)?;
3547        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
3548        // Secret gate: scan content, optional name, and structured properties.
3549        crate::secret_gate::check(content)?;
3550        if let Some(n) = name {
3551            crate::secret_gate::check(n)?;
3552        }
3553        if let Some(ref p) = properties {
3554            crate::secret_gate::check_json(p)?;
3555        }
3556        // `embedding_content` is a caller-supplied alternate vector-embedding
3557        // input: it must be a non-empty proper prefix of `content` (never a
3558        // superset, an unrelated string, or the full text) and passes the
3559        // same secret gate as any other stored/embedded text. Rejected
3560        // before any write, same as the checks above.
3561        if let Some(ec) = embedding_content {
3562            if ec.is_empty() {
3563                return Err(RuntimeError::InvalidInput(
3564                    "embedding_content must not be empty".into(),
3565                ));
3566            }
3567            if ec.len() >= content.len() || !content.starts_with(ec) {
3568                return Err(RuntimeError::InvalidInput(
3569                    "embedding_content must be a proper prefix of content".into(),
3570                ));
3571            }
3572            crate::secret_gate::check(ec)?;
3573        }
3574        let ns = token.namespace().as_str();
3575
3576        // Validate all annotates targets before any write (atomicity: all-or-nothing).
3577        // Endpoint resolution is by-ID and namespace-agnostic.
3578        for &target_id in &annotates {
3579            if !self.substrate_exists_by_id(token, target_id).await? {
3580                return Err(RuntimeError::NotFound(format!(
3581                    "create_note annotates target {target_id} not found"
3582                )));
3583            }
3584        }
3585
3586        // Reject non-finite or out-of-range salience/decay at the runtime boundary
3587        // rather than letting storage silently clamp them (coding-standards §508-516).
3588        if let Some(s) = salience {
3589            if !s.is_finite() || !(0.0..=1.0).contains(&s) {
3590                return Err(RuntimeError::InvalidInput(format!(
3591                    "salience must be a finite value in [0.0, 1.0]; got {s}"
3592                )));
3593            }
3594        }
3595        if let Some(d) = decay_factor {
3596            if !d.is_finite() || d < 0.0 {
3597                return Err(RuntimeError::InvalidInput(format!(
3598                    "decay_factor must be a finite value >= 0.0; got {d}"
3599                )));
3600            }
3601        }
3602
3603        // Resolve embedding_model BEFORE any note/FTS/vector write so unknown-model
3604        // errors are atomic at the runtime layer, not just at one pack handler.
3605        // Direct Rust callers (other packs, integration tests) get the same guarantee.
3606        if let Some(model_name) = embedding_model {
3607            self.resolve_embedding_model(Some(model_name))?;
3608        }
3609
3610        let mut note = Note::new(ns, kind, content);
3611        if let Some(s) = salience {
3612            note = note.with_salience(s);
3613        }
3614        if let Some(df) = decay_factor {
3615            note = note.with_decay(df);
3616        }
3617        if let Some(n) = name {
3618            note = note.with_name(n);
3619        }
3620        if let Some(p) = properties {
3621            note = note.with_properties(p);
3622        }
3623        self.notes(token)?.upsert_note(note.clone()).await?;
3624
3625        // From here on, any error must compensate by removing the note row, its
3626        // FTS document, and any vector entries already inserted — the same
3627        // cleanup used by the annotates-edge block below.
3628
3629        // Decide which embedding models to use (before touching FTS/vectors).
3630        let embed_model_names: Vec<String> = if let Some(m) = embedding_model {
3631            vec![m.to_string()]
3632        } else {
3633            // Fan out to ALL registered models — includes both lattice models
3634            // from RuntimeConfig and any custom providers added via
3635            // register_embedder(). Gate on the registry, not
3636            // config().embedding_model, so that custom-only runtimes (no
3637            // lattice model in config) also fan out.
3638            let names = self.registered_embedding_model_names();
3639            if names.is_empty() {
3640                // No models configured at all — skip vector embedding.
3641                vec![]
3642            } else {
3643                names
3644            }
3645        };
3646
3647        // FTS step — compensate note row on failure.
3648        {
3649            // Injection: check FTS_FAIL_NS (armed by `arm_fts_fail_scoped(ns)`).
3650            // Fires only when `ns` is in the armed set, removing it on the way
3651            // out (one-shot, atomic check-and-remove under the mutex). No lock
3652            // acquisition in release builds — the cfg(not) branch is a const
3653            // false so the compiler eliminates the if-branch entirely.
3654            #[cfg(any(test, feature = "fault-injection"))]
3655            let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
3656            #[cfg(not(any(test, feature = "fault-injection")))]
3657            let fts_inject = false;
3658            let fts_result: RuntimeResult<()> = if fts_inject {
3659                Err(RuntimeError::Internal("injected FTS failure".to_string()))
3660            } else {
3661                match self.text_for_notes(token) {
3662                    Ok(fts) => fts
3663                        .upsert_document(note_fts_document(&note))
3664                        .await
3665                        .map_err(RuntimeError::from),
3666                    Err(e) => Err(e),
3667                }
3668            };
3669
3670            if let Err(e) = fts_result {
3671                // Best-effort compensation — ignore cleanup errors.
3672                if let Ok(store) = self.notes(token) {
3673                    let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3674                }
3675                return Err(e);
3676            }
3677        }
3678
3679        // Vector embedding + insert step — compensate note row + FTS doc on failure.
3680        // Multi-model vector embedding:
3681        //   - explicit embedding_model → single model (existing behaviour)
3682        //   - None + any models registered → ALL registered models in parallel
3683        //   - None + no models configured → skip (text-only)
3684        // The effective text sent to every embedder: the caller-supplied
3685        // capped override when present, otherwise the full stored content.
3686        // FTS indexing above always used the full `note.content` — this cap
3687        // affects only the vector-embedding input.
3688        let canonical_embed_text = note_embedding_text_ref(&note);
3689        let embed_text = embedding_content.unwrap_or(canonical_embed_text);
3690
3691        let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
3692        if embed_model_names.len() == 1 {
3693            // Single-model path: preserves original sequential behaviour.
3694            let model_name = &embed_model_names[0];
3695            let vec_result = self
3696                .embed_document_with_model_outcome_for_token(token, model_name, embed_text)
3697                .await;
3698
3699            // Injection: check VECTOR_FAIL_NS (armed by `arm_vector_fail_scoped(ns)`) or
3700            // VECTOR_FAIL_AFTER (armed by `arm_vector_fail_after(n)`). The former
3701            // fires only when the armed namespace matches this note's namespace;
3702            // callers that cannot guarantee no concurrently-running test also
3703            // writes a note into that same namespace (e.g. a test suite whose
3704            // fixtures share one default namespace) should prefer the latter,
3705            // thread-local count instead — see its doc comment. Either clears
3706            // (one-shot) once it fires. No lock/cell access in release builds —
3707            // the cfg(not) branch is a const false eliminating the if-branch.
3708            #[cfg(any(test, feature = "fault-injection"))]
3709            let vec_inject = {
3710                let ns_inject = consume_fault(&VECTOR_FAIL_NS, ns);
3711                let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
3712                    Some(0) => {
3713                        cell.set(None);
3714                        true
3715                    }
3716                    Some(n) => {
3717                        cell.set(Some(n - 1));
3718                        false
3719                    }
3720                    None => false,
3721                });
3722                ns_inject || count_inject
3723            };
3724            #[cfg(not(any(test, feature = "fault-injection")))]
3725            let vec_inject = false;
3726            let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
3727                if vec_inject {
3728                    Err(RuntimeError::Internal(
3729                        "injected vector failure".to_string(),
3730                    ))
3731                } else {
3732                    vec_result
3733                };
3734
3735            let single_model_result: RuntimeResult<()> = match vec_result {
3736                Ok(outcome) => {
3737                    embedding_report.observe(&outcome);
3738                    match self.vectors_for_model(token, model_name) {
3739                        Ok(vs) => vs
3740                            .insert(
3741                                note.id,
3742                                SubstrateKind::Note,
3743                                ns,
3744                                "note.content",
3745                                vec![outcome.vector],
3746                            )
3747                            .await
3748                            .map_err(RuntimeError::from),
3749                        Err(e) => Err(e),
3750                    }
3751                }
3752                Err(e) => Err(e),
3753            };
3754            if let Err(e) = single_model_result {
3755                // Compensate note row + FTS.
3756                if let Ok(store) = self.notes(token) {
3757                    let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3758                }
3759                if let Ok(fts) = self.text_for_notes(token) {
3760                    let _ = fts.delete_document(ns, note.id).await;
3761                }
3762                return Err(e);
3763            }
3764        } else if !embed_model_names.is_empty() {
3765            // Multi-model path: embed with each model in parallel via spawned tasks,
3766            // then insert one VectorRecord per model.
3767            let rt_clone = self.clone();
3768            // JoinSet tasks require owned text; an Arc keeps this to one
3769            // content-sized allocation rather than one clone per model.
3770            let content_owned: std::sync::Arc<str> = std::sync::Arc::from(embed_text);
3771            let usage_ctx = crate::usage::current();
3772            let mut join_set = tokio::task::JoinSet::new();
3773            for (idx, model_name) in embed_model_names.iter().enumerate() {
3774                let rt = rt_clone.clone();
3775                let text = std::sync::Arc::clone(&content_owned);
3776                let name = model_name.clone();
3777                let ctx = usage_ctx.clone();
3778                let token = (*token).clone();
3779                join_set.spawn(async move {
3780                    let fut = rt.embed_document_with_model_outcome_for_token(
3781                        &token,
3782                        &name,
3783                        text.as_ref(),
3784                    );
3785                    let result = match ctx {
3786                        Some(ctx) => crate::usage::scope(ctx, fut).await,
3787                        None => fut.await,
3788                    };
3789                    (idx, result)
3790                });
3791            }
3792            // The first failed or panicked handle aborts and detaches its
3793            // siblings. Embed usage is counted at dispatch, so a synchronous
3794            // provider winding down in the background cannot change it.
3795            let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
3796                Ok(outcomes) => outcomes,
3797                Err(e) => {
3798                    // Compensate note row + FTS (no vectors inserted yet).
3799                    if let Ok(store) = self.notes(token) {
3800                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3801                    }
3802                    if let Ok(fts) = self.text_for_notes(token) {
3803                        let _ = fts.delete_document(ns, note.id).await;
3804                    }
3805                    return Err(e);
3806                }
3807            };
3808            // TODO(P2): parallelize vector inserts
3809            let mut inserted_models: Vec<String> = Vec::with_capacity(embed_model_names.len());
3810            for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
3811                embedding_report.observe(&outcome);
3812                let insert_result = match self.vectors_for_model(token, model_name) {
3813                    Ok(vs) => vs
3814                        .insert(
3815                            note.id,
3816                            SubstrateKind::Note,
3817                            ns,
3818                            "note.content",
3819                            vec![outcome.vector],
3820                        )
3821                        .await
3822                        .map_err(RuntimeError::from),
3823                    Err(e) => Err(e),
3824                };
3825                if let Err(e) = insert_result {
3826                    // Compensate note row + FTS + already-inserted vectors.
3827                    if let Ok(store) = self.notes(token) {
3828                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3829                    }
3830                    if let Ok(fts) = self.text_for_notes(token) {
3831                        let _ = fts.delete_document(ns, note.id).await;
3832                    }
3833                    for m in &inserted_models {
3834                        if let Ok(vs) = self.vectors_for_model(token, m) {
3835                            let _ = vs.delete(note.id).await;
3836                        }
3837                    }
3838                    return Err(e);
3839                }
3840                inserted_models.push(model_name.clone());
3841            }
3842        }
3843
3844        // Create annotates edges, compensating on failure to preserve atomicity.
3845        //
3846        // Pre-validation (above) ensures all targets exist, so link failures are
3847        // unexpected. If one occurs: delete any edges already created, then remove
3848        // the note, its FTS document, and its vector entry.
3849        let mut created_edges: Vec<Uuid> = Vec::with_capacity(annotates.len());
3850
3851        // In test builds, iterate with an index so the failure-injection hook can
3852        // target a specific call.  In release builds, skip the enumerate overhead.
3853        #[cfg(test)]
3854        let annotates_iter: Vec<(usize, Uuid)> = annotates
3855            .iter()
3856            .enumerate()
3857            .map(|(i, &id)| (i, id))
3858            .collect();
3859        #[cfg(test)]
3860        macro_rules! next_target {
3861            ($pair:expr) => {
3862                $pair.1
3863            };
3864        }
3865        #[cfg(not(test))]
3866        let annotates_iter: Vec<Uuid> = annotates.to_vec();
3867        #[cfg(not(test))]
3868        macro_rules! next_target {
3869            ($pair:expr) => {
3870                $pair
3871            };
3872        }
3873
3874        for pair in annotates_iter {
3875            let target_id = next_target!(pair);
3876
3877            // Test-only: inject a failure on the configured call index (1-based).
3878            #[cfg(test)]
3879            let injected_err: Option<RuntimeError> = {
3880                let call_idx = pair.0;
3881                LINK_FAIL_AFTER.with(|cell| {
3882                    let n = cell.get();
3883                    if n > 0 && call_idx + 1 == n {
3884                        cell.set(0); // reset so subsequent calls are unaffected
3885                        Some(RuntimeError::Internal("injected link failure".to_string()))
3886                    } else {
3887                        None
3888                    }
3889                })
3890            };
3891            #[cfg(not(test))]
3892            let injected_err: Option<RuntimeError> = None;
3893
3894            let link_result = if let Some(e) = injected_err {
3895                Err(e)
3896            } else {
3897                self.link(
3898                    token,
3899                    note.id,
3900                    target_id,
3901                    EdgeRelation::Annotates,
3902                    1.0,
3903                    None,
3904                )
3905                .await
3906            };
3907
3908            match link_result {
3909                Ok(edge) => created_edges.push(edge.id.into()),
3910                Err(e) => {
3911                    // Best-effort compensation — ignore cleanup errors.
3912                    for edge_id in created_edges {
3913                        let _ = self.delete_edge(token, edge_id, true).await;
3914                    }
3915                    if let Ok(store) = self.notes(token) {
3916                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3917                    }
3918                    if let Ok(fts) = self.text_for_notes(token) {
3919                        let _ = fts.delete_document(ns, note.id).await;
3920                    }
3921                    for model_name in &embed_model_names {
3922                        if let Ok(vs) = self.vectors_for_model(token, model_name) {
3923                            let _ = vs.delete(note.id).await;
3924                        }
3925                    }
3926                    return Err(e);
3927                }
3928            }
3929        }
3930
3931        Ok((note, embedding_report))
3932    }
3933
3934    /// List notes visible to the token, optionally filtered by kind.
3935    ///
3936    /// When the token carries a multi-namespace visible set, notes from all
3937    /// visible namespaces are returned. When the visible set is `[primary]`
3938    /// (the default) this behaves identically to the pre-visibility behaviour.
3939    pub async fn list_notes(
3940        &self,
3941        token: &NamespaceToken,
3942        kind: Option<&str>,
3943        limit: u32,
3944        offset: u32,
3945    ) -> RuntimeResult<Vec<Note>> {
3946        let visible = token.visible_namespaces();
3947        if visible.len() == 1 {
3948            // Fast path: single namespace — use the dedicated query_notes method.
3949            let page = self
3950                .notes(token)?
3951                .query_notes(
3952                    token.namespace().as_str(),
3953                    kind,
3954                    PageRequest {
3955                        offset: offset.into(),
3956                        limit,
3957                    },
3958                )
3959                .await?;
3960            return Ok(page.items);
3961        }
3962        // Multi-namespace path: use query_notes_filtered with the visible set.
3963        use khive_storage::note::NoteFilter;
3964        let ns_strs: Vec<String> = visible.iter().map(|ns| ns.as_str().to_owned()).collect();
3965        let filter = NoteFilter {
3966            kind: kind.map(|k| k.to_string()),
3967            namespaces: ns_strs,
3968            ..Default::default()
3969        };
3970        let page = self
3971            .notes(token)?
3972            .query_notes_filtered(
3973                token.namespace().as_str(),
3974                &filter,
3975                PageRequest {
3976                    offset: offset.into(),
3977                    limit,
3978                },
3979            )
3980            .await?;
3981        Ok(page.items)
3982    }
3983
3984    /// List an immutable insertion-sequence page of visible notes.
3985    ///
3986    /// Soft-deleting the prior page's last note does not invalidate the
3987    /// cursor because the boundary is resolved including tombstones. A hard
3988    /// deletion makes the cursor unresolvable and returns an explicit error.
3989    pub async fn list_notes_after(
3990        &self,
3991        token: &NamespaceToken,
3992        kind: Option<&str>,
3993        after: Option<Uuid>,
3994        limit: u32,
3995    ) -> RuntimeResult<(Vec<Note>, Option<Uuid>)> {
3996        let store = self.notes(token)?;
3997        let after = match after {
3998            Some(id) => {
3999                let note = self
4000                    .get_note_including_deleted(token, id)
4001                    .await?
4002                    .ok_or_else(|| RuntimeError::NotFound(format!("note cursor {id}")))?;
4003                Self::ensure_namespace_visible(&note.namespace, token)?;
4004                let sequence = store.note_sequence(id).await?.ok_or_else(|| {
4005                    RuntimeError::Internal(format!(
4006                        "note cursor {id} has no insertion-sequence ledger row"
4007                    ))
4008                })?;
4009                Some(SeekCursor { sequence, id })
4010            }
4011            None => None,
4012        };
4013        let filter = khive_storage::note::NoteFilter {
4014            kind: kind.map(str::to_string),
4015            namespaces: token
4016                .visible_namespaces()
4017                .iter()
4018                .map(|namespace| namespace.as_str().to_owned())
4019                .collect(),
4020            ..Default::default()
4021        };
4022        let page = store
4023            .query_notes_filtered_after(token.namespace().as_str(), &filter, after, limit)
4024            .await?;
4025        Ok((page.items, page.next_after.map(|cursor| cursor.id)))
4026    }
4027
4028    /// Count notes matching `kind` across the caller's visible namespaces.
4029    pub async fn count_notes(
4030        &self,
4031        token: &NamespaceToken,
4032        kind: Option<&str>,
4033    ) -> RuntimeResult<u64> {
4034        let namespaces: Vec<String> = token
4035            .visible_namespaces()
4036            .iter()
4037            .map(|namespace| namespace.as_str().to_owned())
4038            .collect();
4039        Ok(self
4040            .notes(token)?
4041            .count_notes_in_namespaces(&namespaces, kind)
4042            .await?)
4043    }
4044
4045    /// Search notes using a hybrid FTS5 + vector pipeline with salience weighting.
4046    ///
4047    /// Pipeline:
4048    /// 1. FTS5 query against `notes_<namespace>`.
4049    /// 2. If embedding model is configured: vector search filtered to `kind="note"`.
4050    /// 3. RRF fusion (k=60).
4051    /// 4. Salience-weighted rerank: `score *= (0.5 + 0.5 * note.salience)`.
4052    /// 5. Filter soft-deleted notes, apply optional kind / tag / properties predicates.
4053    ///    Tags and properties are pushed into the per-note fetch loop BEFORE truncation
4054    ///    so that matching notes ranked beyond `limit` in the raw fusion are not silently
4055    ///    dropped.
4056    /// 6. Truncate to `limit`.
4057    ///
4058    /// `tags_any`: when non-empty, only notes that have at least one of these tags
4059    /// (stored in `properties["tags"]`, case-insensitive match) are retained. The
4060    /// check happens inside the alive-note loop, before `hits.truncate(limit)`.
4061    ///
4062    /// `properties_filter`: when `Some`, only notes whose `properties` JSON object is
4063    /// a superset of the given filter object are retained. Also applied before truncation.
4064    #[allow(clippy::too_many_arguments)]
4065    pub async fn search_notes(
4066        &self,
4067        token: &NamespaceToken,
4068        query_text: &str,
4069        query_vector: Option<Vec<f32>>,
4070        limit: u32,
4071        note_kind: Option<&str>,
4072        include_superseded: bool,
4073        tags_any: &[String],
4074        properties_filter: Option<&serde_json::Value>,
4075    ) -> RuntimeResult<Vec<NoteSearchHit>> {
4076        const RRF_K: usize = 60;
4077        let candidates = limit.saturating_mul(4).max(limit);
4078        let visible_ns: Vec<String> = token
4079            .visible_namespaces()
4080            .iter()
4081            .map(|ns| ns.as_str().to_owned())
4082            .collect();
4083
4084        // FTS5 over the notes index — search all visible namespaces.
4085        //
4086        // `sanitize_fts5_query` strips known-unsafe FTS5 metacharacters, but
4087        // residual punctuation the sanitizer does not strip can still reach
4088        // the FTS5 parser and error. This fails loud instead of degrading to
4089        // vector-only fusion, so callers see the bad query instead of
4090        // silently losing the lexical leg. Errors from any other leg (vector
4091        // search, note hydration) still propagate normally.
4092        //
4093        // Injection: check FTS_SEARCH_FAIL_NS (armed by `arm_fts_search_fail(ns)`),
4094        // exercising the propagate branch above. Fires only when the armed
4095        // namespace is among this call's visible namespaces, then clears (one-shot).
4096        #[cfg(any(test, feature = "fault-injection"))]
4097        let fts_search_inject = {
4098            let mut g = FTS_SEARCH_FAIL_NS.lock().unwrap();
4099            match g.as_deref() {
4100                Some(armed) if visible_ns.iter().any(|ns| ns == armed) => {
4101                    *g = None;
4102                    true
4103                }
4104                _ => false,
4105            }
4106        };
4107        #[cfg(not(any(test, feature = "fault-injection")))]
4108        let fts_search_inject = false;
4109
4110        let text_search_result = if fts_search_inject {
4111            Err(khive_storage::StorageError::Timeout {
4112                operation: "fts_search".into(),
4113            })
4114        } else {
4115            self.text_for_notes(token)?
4116                .search(TextSearchRequest {
4117                    query: query_text.to_string(),
4118                    mode: TextQueryMode::Plain,
4119                    filter: Some(TextFilter {
4120                        namespaces: visible_ns.clone(),
4121                        ..TextFilter::default()
4122                    }),
4123                    top_k: candidates,
4124                    snippet_chars: 200,
4125                })
4126                .await
4127        };
4128
4129        // FtsPasses is counted inside the store's `search()` (khive-db
4130        // stores/text.rs), only once a real FTS5 statement is prepared —
4131        // an empty/fully-sanitized query short-circuits there before any
4132        // statement exists and must not count (nor does the injected-failure
4133        // branch above, which never reaches the store at all).
4134        let text_hits = crate::error::fts_text_leg_or_err(
4135            text_search_result.map_err(RuntimeError::from),
4136            "search_notes",
4137            query_text,
4138        )?;
4139
4140        // Vector search filtered to notes.
4141        let vector_hits = if query_vector.is_some() || self.config().embedding_model.is_some() {
4142            self.vector_search(
4143                token,
4144                query_vector,
4145                Some(query_text),
4146                candidates,
4147                Some(SubstrateKind::Note),
4148            )
4149            .await?
4150        } else {
4151            vec![]
4152        };
4153
4154        // Keep the full text∪vector union through RRF — salience weighting and
4155        // soft-delete/kind filtering happen *after* this, and the final
4156        // `hits.truncate(limit)` is the only result-limiting cut. Truncating to
4157        // `candidates` here would drop a high-salience note ranked just outside
4158        // the raw RRF cutoff before salience ever applied.
4159        let fuse_k = text_hits.len() + vector_hits.len();
4160        let fused = crate::fusion::rrf_fuse_k(self, text_hits, vector_hits, RRF_K, fuse_k).await?;
4161
4162        let candidate_ids: Vec<Uuid> = fused.iter().map(|hit| hit.entity_id).collect();
4163        if candidate_ids.is_empty() {
4164            return Ok(vec![]);
4165        }
4166
4167        // Fetch each candidate note individually to get salience and apply
4168        // soft-delete + (optional) kind filtering. Notes whose `kind` doesn't
4169        // match `note_kind` are dropped post-fetch — they're a small set
4170        // bounded by the text∪vector union (≤ 2×candidates), so the read is cheap.
4171        let note_store = self.notes(token)?;
4172        let mut alive_notes: HashMap<Uuid, Note> = HashMap::new();
4173        for id in &candidate_ids {
4174            if let Some(note) = note_store.get_note(*id).await? {
4175                if note.deleted_at.is_some() {
4176                    continue;
4177                }
4178                if let Some(want_kind) = note_kind {
4179                    if note.kind != want_kind {
4180                        continue;
4181                    }
4182                }
4183                // Apply tag predicate before adding to alive set: tags on notes live
4184                // inside `properties["tags"]` (a JSON array). This pushes the filter
4185                // before truncation so matching notes ranked beyond `limit` in the raw
4186                // fusion are not silently dropped.
4187                if !tags_any.is_empty() {
4188                    let note_tags: Vec<String> = note
4189                        .properties
4190                        .as_ref()
4191                        .and_then(|p| p.get("tags"))
4192                        .and_then(serde_json::Value::as_array)
4193                        .map(|arr| {
4194                            arr.iter()
4195                                .filter_map(serde_json::Value::as_str)
4196                                .map(str::to_owned)
4197                                .collect()
4198                        })
4199                        .unwrap_or_default();
4200                    if !note_tags
4201                        .iter()
4202                        .any(|t| tags_any.iter().any(|w| t.eq_ignore_ascii_case(w)))
4203                    {
4204                        continue;
4205                    }
4206                }
4207                // Apply properties predicate before truncation, same reasoning as tags above.
4208                if let Some(pf) = properties_filter {
4209                    if !note_props_match(note.properties.as_ref(), pf) {
4210                        continue;
4211                    }
4212                }
4213                alive_notes.insert(*id, note);
4214            }
4215        }
4216
4217        // Drop superseded notes unless include_superseded is true: any note targeted
4218        // by a `supersedes` edge is obsolete and excluded from default search.
4219        if !include_superseded && !alive_notes.is_empty() {
4220            let graph = self.graph(token)?;
4221            let note_ids: Vec<Uuid> = alive_notes.keys().copied().collect();
4222            let superseded: std::collections::HashSet<Uuid> = graph
4223                .batch_neighbors(
4224                    &note_ids,
4225                    NeighborQuery {
4226                        direction: Direction::In,
4227                        relations: Some(vec![EdgeRelation::Supersedes]),
4228                        limit: Some(1),
4229                        min_weight: None,
4230                    },
4231                )
4232                .await?
4233                .into_iter()
4234                .map(|(note_id, _)| note_id)
4235                .collect();
4236            alive_notes.retain(|id, _| !superseded.contains(id));
4237        }
4238
4239        // Apply salience weighting and collect final hits.
4240        let mut hits: Vec<NoteSearchHit> = fused
4241            .into_iter()
4242            .filter_map(|hit| {
4243                let note = alive_notes.get(&hit.entity_id)?;
4244                let salience = note.salience.unwrap_or(0.5);
4245                let weight = 0.5 + 0.5 * salience;
4246                let weighted = DeterministicScore::from_f64(hit.score.to_f64() * weight);
4247                Some(NoteSearchHit {
4248                    note_id: hit.entity_id,
4249                    score: weighted,
4250                    source: hit.source,
4251                    title: hit.title.or_else(|| note_title(note)),
4252                    snippet: hit.snippet.or_else(|| note_snippet(note)),
4253                })
4254            })
4255            .collect();
4256
4257        hits.sort_by(|a, b| b.score.cmp(&a.score).then(a.note_id.cmp(&b.note_id)));
4258        hits.truncate(limit as usize);
4259        Ok(hits)
4260    }
4261
4262    /// Resolve a short UUID prefix (8+ hex chars) to a full UUID.
4263    ///
4264    /// Searches entities, notes, and edges tables for a UUID starting with the
4265    /// given prefix, scoped to the caller's primary namespace only. Returns
4266    /// `Ok(Some(uuid))` if exactly one match is found, `Ok(None)` if no
4267    /// matches, or an error if ambiguous (multiple matches).
4268    pub async fn resolve_prefix(
4269        &self,
4270        token: &NamespaceToken,
4271        prefix: &str,
4272    ) -> RuntimeResult<Option<Uuid>> {
4273        let namespaces = [token.namespace().as_str().to_owned()];
4274        self.resolve_prefix_inner(Some(&namespaces), prefix, false)
4275            .await
4276    }
4277
4278    pub async fn resolve_prefix_including_deleted(
4279        &self,
4280        token: &NamespaceToken,
4281        prefix: &str,
4282    ) -> RuntimeResult<Option<Uuid>> {
4283        let namespaces = [token.namespace().as_str().to_owned()];
4284        self.resolve_prefix_inner(Some(&namespaces), prefix, true)
4285            .await
4286    }
4287
4288    /// Resolve a short UUID prefix (8+ hex chars) to a full UUID with NO
4289    /// namespace filter at all: mirrors `resolve_by_id`'s by-ID contract:
4290    /// by-ID resolution is namespace-agnostic, since the Gate (not
4291    /// storage-layer filtering) is the authz seam. Used by the four by-ID
4292    /// CRUD verbs (get/update/delete/merge) so their prefix path matches
4293    /// their already-unfiltered full-UUID path. No token param: unlike
4294    /// `resolve_prefix`, there is no namespace to derive from one.
4295    pub async fn resolve_prefix_unfiltered(&self, prefix: &str) -> RuntimeResult<Option<Uuid>> {
4296        self.resolve_prefix_inner(None, prefix, false).await
4297    }
4298
4299    /// `resolve_prefix_unfiltered`, including soft-deleted rows — used by the
4300    /// hard-delete by-ID path.
4301    pub async fn resolve_prefix_unfiltered_including_deleted(
4302        &self,
4303        prefix: &str,
4304    ) -> RuntimeResult<Option<Uuid>> {
4305        self.resolve_prefix_inner(None, prefix, true).await
4306    }
4307
4308    /// Shared indexed prefix-range lookup over an explicit namespace set.
4309    ///
4310    /// `namespaces` selects the lookup scope: `Some(&[ns])` reproduces the
4311    /// historical primary-only behaviour (`resolve_prefix` /
4312    /// `resolve_prefix_including_deleted`); `None` applies
4313    /// no namespace predicate at all (`resolve_prefix_unfiltered*`).
4314    /// Ambiguity (a prefix matching more than one UUID, even across
4315    /// different namespaces in the set, or across all namespaces when
4316    /// unfiltered) is still an error: UUIDs are globally unique, so two
4317    /// distinct rows sharing a prefix always requires caller disambiguation —
4318    /// no cross-namespace dedup is needed or performed.
4319    async fn resolve_prefix_inner(
4320        &self,
4321        namespaces: Option<&[String]>,
4322        prefix: &str,
4323        include_deleted: bool,
4324    ) -> RuntimeResult<Option<Uuid>> {
4325        // Every caller is expected to pre-validate hex-only input, but this is
4326        // the single choke point every `resolve_prefix*` variant funnels
4327        // through, so re-validate here too. A prefix containing anything other
4328        // than hex digits and canonical hyphen separators (`%`, `_`, or other
4329        // injection-shaped input) never matches a real id and is rejected
4330        // before it can reach the range query.
4331        if !prefix.chars().all(|c| c.is_ascii_hexdigit() || c == '-') {
4332            return Ok(None);
4333        }
4334
4335        // Injection: check PREFIX_RESOLVE_FAIL_NS (armed by
4336        // `arm_prefix_resolve_fail_scoped(prefix)`), exercising the storage-failure path
4337        // a genuine pool checkout timeout or WAL contention would take.
4338        #[cfg(any(test, feature = "fault-injection"))]
4339        if consume_fault(&PREFIX_RESOLVE_FAIL_NS, prefix) {
4340            return Err(RuntimeError::Storage(
4341                khive_storage::StorageError::Timeout {
4342                    operation: "resolve_prefix".into(),
4343                },
4344            ));
4345        }
4346
4347        let Some((lower, upper)) = uuid_prefix_bounds(prefix) else {
4348            return Ok(None);
4349        };
4350
4351        let tables = [
4352            ("entities", true),
4353            ("notes", true),
4354            ("events", false),
4355            ("graph_edges", false),
4356        ];
4357
4358        // A UUID can legitimately exist in more than one scanned table
4359        // (e.g. an entity id string that also happens to be an edge id — the
4360        // lookup is a text-prefix range across independent tables, not a
4361        // substrate-exclusive lookup). Without dedup, a single record hit
4362        // twice across tables inflated `matches.len()` past 1 and produced a
4363        // false `AmbiguousPrefix` naming the SAME UUID twice. `seen` tracks
4364        // UUIDs already pushed so `matches` (and thus every length check,
4365        // including the early-exit below) reflects DISTINCT UUIDs only.
4366        let mut matches: Vec<String> = Vec::new();
4367        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
4368        let mut reader = self.sql().reader().await.map_err(RuntimeError::Storage)?;
4369
4370        for (table, has_deleted_at) in tables {
4371            let sql = resolve_prefix_statement(
4372                table,
4373                has_deleted_at,
4374                include_deleted,
4375                namespaces,
4376                &lower,
4377                &upper,
4378            );
4379            match reader.query_all(sql).await {
4380                Ok(rows) => {
4381                    for row in rows {
4382                        if let Some(col) = row.columns.first() {
4383                            if let SqlValue::Text(s) = &col.value {
4384                                if seen.insert(s.clone()) {
4385                                    matches.push(s.clone());
4386                                }
4387                            }
4388                        }
4389                    }
4390                }
4391                Err(e) => {
4392                    let msg = e.to_string();
4393                    if msg.contains("no such table") {
4394                        continue;
4395                    }
4396                    return Err(RuntimeError::Storage(e));
4397                }
4398            }
4399            if matches.len() > 1 {
4400                break;
4401            }
4402        }
4403
4404        // Sidecar-resident event rows (events-split lane) are invisible to the
4405        // main-store scan above; a prefix naming one must still resolve, and a
4406        // prefix colliding across the two files must still read as ambiguous,
4407        // so the sidecar scan merges into the same `matches`/`seen` set.
4408        if matches.len() <= 1 {
4409            if let Some(sidecar_sql) = self.events_sidecar_sql_read_only()? {
4410                let mut params = vec![SqlValue::Text(lower.clone()), SqlValue::Text(upper.clone())];
4411                if let Some(ns) = namespaces {
4412                    params.extend(ns.iter().map(|n| SqlValue::Text(n.clone())));
4413                }
4414                let namespace_clause = namespaces.map(|namespaces| {
4415                    let placeholders: Vec<String> = (0..namespaces.len())
4416                        .map(|index| format!("?{}", index + 3))
4417                        .collect();
4418                    format!(" AND namespace IN ({})", placeholders.join(", "))
4419                });
4420                let sql = SqlStatement {
4421                    sql: format!(
4422                        "SELECT id FROM events \
4423                         WHERE id >= ?1 AND id < ?2{namespace_clause} LIMIT 2",
4424                        namespace_clause = namespace_clause.as_deref().unwrap_or("")
4425                    ),
4426                    params,
4427                    label: Some("resolve_prefix.events_sidecar".into()),
4428                };
4429                let mut sidecar_reader =
4430                    sidecar_sql.reader().await.map_err(RuntimeError::Storage)?;
4431                match sidecar_reader.query_all(sql).await {
4432                    Ok(rows) => {
4433                        for row in rows {
4434                            if let Some(col) = row.columns.first() {
4435                                if let SqlValue::Text(s) = &col.value {
4436                                    if seen.insert(s.clone()) {
4437                                        matches.push(s.clone());
4438                                    }
4439                                }
4440                            }
4441                        }
4442                    }
4443                    Err(e) => {
4444                        let msg = e.to_string();
4445                        if !msg.contains("no such table") {
4446                            return Err(RuntimeError::Storage(e));
4447                        }
4448                    }
4449                }
4450            }
4451        }
4452
4453        match matches.len() {
4454            0 => Ok(None),
4455            1 => {
4456                let uuid = Uuid::from_str(&matches[0])
4457                    .map_err(|e| RuntimeError::Internal(format!("stored UUID is invalid: {e}")))?;
4458                Ok(Some(uuid))
4459            }
4460            _ => {
4461                let uuids: Vec<uuid::Uuid> = matches
4462                    .iter()
4463                    .filter_map(|s| Uuid::from_str(s).ok())
4464                    .collect();
4465                Err(RuntimeError::AmbiguousPrefix {
4466                    prefix: prefix.to_string(),
4467                    matches: uuids,
4468                })
4469            }
4470        }
4471    }
4472
4473    /// Resolve a UUID to its substrate kind with NO namespace filter.
4474    ///
4475    /// By-ID contract: UUID v4 is globally unique: by-ID substrate
4476    /// inference must return the record regardless of caller namespace.  Used by
4477    /// the public `update` and `delete` verb handlers when no explicit `kind` is
4478    /// supplied.
4479    ///
4480    /// Does NOT consult the visible set or the primary-namespace check.  The
4481    /// token is still required to route to the correct backend pool but its
4482    /// namespace value is not used as a filter.
4483    pub async fn resolve_by_id(
4484        &self,
4485        token: &NamespaceToken,
4486        id: Uuid,
4487    ) -> RuntimeResult<Option<Resolved>> {
4488        // Entity: direct by-UUID fetch (ID-only, no namespace check).
4489        if let Some(entity) = self.entities(token)?.get_entity(id).await? {
4490            return Ok(Some(Resolved::Entity(entity)));
4491        }
4492
4493        // Note: direct by-UUID fetch (ID-only).
4494        if let Some(note) = self.notes(token)?.get_note(id).await? {
4495            return Ok(Some(Resolved::Note(note)));
4496        }
4497
4498        // Edges and events are not returned here; the caller's `_` arm handles
4499        // those with a separate get_edge / get_event check.
4500        Ok(None)
4501    }
4502
4503    /// Resolve a UUID to its substrate kind with NO namespace filter, including
4504    /// soft-deleted rows.
4505    ///
4506    /// Used by the hard-delete path when no explicit `kind` is supplied, so
4507    /// already-soft-deleted records can still be located by UUID alone.
4508    pub async fn resolve_by_id_including_deleted(
4509        &self,
4510        token: &NamespaceToken,
4511        id: Uuid,
4512    ) -> RuntimeResult<Option<Resolved>> {
4513        // Entity: including soft-deleted, no namespace check.
4514        if let Some(entity) = self
4515            .entities(token)?
4516            .get_entity_including_deleted(id)
4517            .await?
4518        {
4519            return Ok(Some(Resolved::Entity(entity)));
4520        }
4521
4522        // Note: including soft-deleted, no namespace check.
4523        if let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? {
4524            return Ok(Some(Resolved::Note(note)));
4525        }
4526
4527        // Edges and events are not returned here; the caller's `_` arm handles
4528        // those with a separate get_edge_including_deleted check.
4529        Ok(None)
4530    }
4531
4532    /// Resolve a UUID to its substrate kind by trying entity, then note, then event stores.
4533    ///
4534    /// Returns `None` if the UUID is not found in any substrate.
4535    /// Cost: at most 3 store lookups per call (cheap for v0.1).
4536    pub async fn resolve(
4537        &self,
4538        token: &NamespaceToken,
4539        id: Uuid,
4540    ) -> RuntimeResult<Option<Resolved>> {
4541        // Entity: use the namespace-checked getter (errors on mismatch/absent).
4542        match self.get_entity(token, id).await {
4543            Ok(entity) => return Ok(Some(Resolved::Entity(entity))),
4544            Err(RuntimeError::NotFound(_) | RuntimeError::NamespaceMismatch { .. }) => {}
4545            Err(e) => return Err(e),
4546        }
4547
4548        // Note: storage get_note is ID-only — verify against visible set.
4549        if let Some(note) = self.notes(token)?.get_note(id).await? {
4550            if Self::ensure_namespace_visible(&note.namespace, token).is_ok() {
4551                return Ok(Some(Resolved::Note(note)));
4552            }
4553        }
4554
4555        // Event: storage get_event is ID-only — verify against visible set.
4556        if let Some(event) = self.events(token)?.get_event(id).await? {
4557            if Self::ensure_namespace_visible(&event.namespace, token).is_ok() {
4558                return Ok(Some(Resolved::Event(event)));
4559            }
4560        }
4561
4562        Ok(None)
4563    }
4564
4565    /// Resolve a UUID to its substrate kind with NO namespace filter, for edge
4566    /// endpoint validation.
4567    ///
4568    /// `link` and `create`'s `annotates` targets consume by-ID endpoints, so
4569    /// their existence check must follow the same by-ID contract as `get()`:
4570    /// by-ID ops are namespace-agnostic: the Gate, not storage-layer
4571    /// filtering, is the authz seam. Mirrors `resolve_by_id`
4572    /// (entity + note, unfiltered) and additionally resolves events,
4573    /// unfiltered, so edge endpoint validation resolves exactly what `get()`
4574    /// resolves regardless of the caller's namespace.
4575    pub async fn resolve_edge_endpoint(
4576        &self,
4577        token: &NamespaceToken,
4578        id: Uuid,
4579    ) -> RuntimeResult<Option<Resolved>> {
4580        if let Some(resolved) = self.resolve_by_id(token, id).await? {
4581            return Ok(Some(resolved));
4582        }
4583        if let Some(event) = self.events(token)?.get_event(id).await? {
4584            return Ok(Some(Resolved::Event(event)));
4585        }
4586        Ok(None)
4587    }
4588
4589    /// Resolve a UUID to its substrate kind using primary-namespace-only enforcement.
4590    ///
4591    /// Unlike `resolve`, never consults the visible set. Use from GTD dependency
4592    /// validation paths where strict primary ownership is required.
4593    pub async fn resolve_primary(
4594        &self,
4595        token: &NamespaceToken,
4596        id: Uuid,
4597    ) -> RuntimeResult<Option<Resolved>> {
4598        let ns = token.namespace().as_str();
4599
4600        // Entity: primary-only check (exclude entities in visible-only namespaces).
4601        if let Some(entity) = self.entities(token)?.get_entity(id).await? {
4602            if Self::ensure_namespace(&entity.namespace, ns).is_ok() {
4603                return Ok(Some(Resolved::Entity(entity)));
4604            }
4605        }
4606
4607        // Note: primary-only check.
4608        if let Some(note) = self.notes(token)?.get_note(id).await? {
4609            if Self::ensure_namespace(&note.namespace, ns).is_ok() {
4610                return Ok(Some(Resolved::Note(note)));
4611            }
4612        }
4613
4614        // Event: primary-only check.
4615        if let Some(event) = self.events(token)?.get_event(id).await? {
4616            if Self::ensure_namespace(&event.namespace, ns).is_ok() {
4617                return Ok(Some(Resolved::Event(event)));
4618            }
4619        }
4620
4621        Ok(None)
4622    }
4623
4624    /// Resolve a UUID to its substrate kind, including soft-deleted rows.
4625    ///
4626    /// Used exclusively by the hard-delete path to locate records that have
4627    /// already been soft-deleted. Namespace isolation is still enforced.
4628    pub async fn resolve_including_deleted(
4629        &self,
4630        token: &NamespaceToken,
4631        id: Uuid,
4632    ) -> RuntimeResult<Option<Resolved>> {
4633        let ns = token.namespace().as_str();
4634
4635        if let Some(entity) = self
4636            .entities(token)?
4637            .get_entity_including_deleted(id)
4638            .await?
4639        {
4640            if Self::ensure_namespace(&entity.namespace, ns).is_ok() {
4641                return Ok(Some(Resolved::Entity(entity)));
4642            }
4643        }
4644
4645        if let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? {
4646            if Self::ensure_namespace(&note.namespace, ns).is_ok() {
4647                return Ok(Some(Resolved::Note(note)));
4648            }
4649        }
4650
4651        if let Some(event) = self.events(token)?.get_event(id).await? {
4652            if Self::ensure_namespace(&event.namespace, ns).is_ok() {
4653                return Ok(Some(Resolved::Event(event)));
4654            }
4655        }
4656
4657        Ok(None)
4658    }
4659
4660    /// Hard-delete a single graph node (entity, note, or edge-as-node row) AND purge its
4661    /// incident edges in ONE write transaction — closes a race where a concurrent guarded
4662    /// write could insert a fresh edge against the endpoint between two separately
4663    /// committed calls; see docs/operations.md#atomic_hard_delete_with_edge_purge.
4664    ///
4665    /// `row_statement` is the exact hard-delete `DELETE` for the target row
4666    /// (entity, note, or edge). Before the incident-edge purge, the same plan
4667    /// appends any ADR-002 lineage-loss warnings from the still-present edge
4668    /// rows, so the warning payload and cascade commit or roll back together.
4669    /// Returns `Ok(true)` if the row was deleted, `Ok(false)` if it no longer
4670    /// existed (lost a race with a concurrent delete of the same row).
4671    async fn atomic_hard_delete_with_edge_purge(
4672        &self,
4673        row_statement: SqlStatement,
4674        node_id: Uuid,
4675        namespace: &str,
4676        actor: &str,
4677        substrate: SubstrateKind,
4678    ) -> RuntimeResult<bool> {
4679        let mut statements = vec![PlanStatement {
4680            statement: row_statement,
4681            guard: Some(AffectedRowGuard::exactly(1)),
4682        }];
4683        statements.extend(
4684            hard_delete_lineage_warning_statements(namespace, actor, node_id, substrate)
4685                .into_iter()
4686                .map(|statement| PlanStatement {
4687                    statement,
4688                    guard: None,
4689                }),
4690        );
4691        statements.push(PlanStatement {
4692            statement: purge_incident_edges_statement(node_id),
4693            guard: None,
4694        });
4695        let plan = AtomicOpPlan::Delete(DeletePlan {
4696            target_id: node_id,
4697            statements,
4698            post_commit: PostCommitEffect::None,
4699        });
4700        match run_atomic_unit(self.sql().as_ref(), vec![plan]).await {
4701            Ok(AtomicRunOutcome::Committed { .. }) => Ok(true),
4702            Ok(AtomicRunOutcome::RolledBack {
4703                failure: AtomicOpFailure::GuardFailed { .. },
4704                ..
4705            }) => Ok(false),
4706            Ok(AtomicRunOutcome::RolledBack {
4707                failure: AtomicOpFailure::SqlError { message, .. },
4708                ..
4709            }) => Err(RuntimeError::Internal(format!(
4710                "hard delete + edge purge for {node_id} failed: {message}"
4711            ))),
4712            Err(e) => Err(RuntimeError::Internal(format!(
4713                "hard delete + edge purge for {node_id}: atomic unit seam failure: {}",
4714                e.0
4715            ))),
4716        }
4717    }
4718
4719    /// Soft-delete or hard-delete a note by ID.
4720    ///
4721    /// On hard delete, cascades to remove all incident edges (both inbound and
4722    /// outbound) and cleans up FTS and vector indexes, preventing dangling
4723    /// references for `annotates` edges that target this note.
4724    /// Soft delete also cleans FTS and vector indexes; edges are left in place.
4725    ///
4726    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
4727    /// Cascade and index cleanup target the RECORD's stored namespace, not the caller token's.
4728    /// Returns `Ok(false)` if the note does not exist.
4729    pub async fn delete_note(
4730        &self,
4731        token: &NamespaceToken,
4732        id: Uuid,
4733        hard: bool,
4734    ) -> RuntimeResult<bool> {
4735        let note_store = self.notes(token)?;
4736        let note = if hard {
4737            match note_store.get_note_including_deleted(id).await? {
4738                Some(n) => n,
4739                None => return Ok(false),
4740            }
4741        } else {
4742            match note_store.get_note(id).await? {
4743                Some(n) => n,
4744                None => return Ok(false),
4745            }
4746        };
4747        let mode = if hard {
4748            DeleteMode::Hard
4749        } else {
4750            DeleteMode::Soft
4751        };
4752
4753        // Route index cleanup through the RECORD's namespace, not the caller's.
4754        let record_tok = NamespaceToken::for_namespace(
4755            khive_types::Namespace::parse(&note.namespace)
4756                .map_err(|e| RuntimeError::Internal(format!("note namespace invalid: {e}")))?,
4757        );
4758        let record_ns = note.namespace.clone();
4759        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
4760
4761        // On hard delete, the row delete and the incident-edge cascade (including
4762        // already-soft-deleted edges) run as ONE write transaction: see
4763        // `atomic_hard_delete_with_edge_purge`. Index cleanup follows the
4764        // commit; it is best-effort and idempotent, unlike the row/edge pair.
4765        let deleted = if hard {
4766            let deleted = self
4767                .atomic_hard_delete_with_edge_purge(
4768                    note_hard_delete_statement(id),
4769                    id,
4770                    &record_ns,
4771                    &actor,
4772                    SubstrateKind::Note,
4773                )
4774                .await?;
4775            self.text_for_notes(&record_tok)?
4776                .delete_document(&record_ns, id)
4777                .await?;
4778            // Scoped delete: iterate over EVERY registered embedding model's
4779            // vector store so non-default vectors don't orphan when the note is deleted.
4780            for model_name in self.registered_embedding_model_names() {
4781                self.vectors_for_model(&record_tok, &model_name)?
4782                    .delete(id)
4783                    .await?;
4784            }
4785            deleted
4786        } else {
4787            let deleted = note_store.delete_note(id, mode).await?;
4788            if deleted {
4789                self.text_for_notes(&record_tok)?
4790                    .delete_document(&record_ns, id)
4791                    .await?;
4792                for model_name in self.registered_embedding_model_names() {
4793                    self.vectors_for_model(&record_tok, &model_name)?
4794                        .delete(id)
4795                        .await?;
4796                }
4797            }
4798            deleted
4799        };
4800        if deleted {
4801            let event_store = self.events(token)?;
4802            let event = khive_storage::event::Event::new(
4803                record_ns.clone(),
4804                "delete",
4805                EventKind::NoteDeleted,
4806                SubstrateKind::Note,
4807                "",
4808            )
4809            .with_target(id)
4810            .with_payload(serde_json::json!({"id": id, "namespace": record_ns, "hard": hard}));
4811            event_store.append_event(event).await.map_err(|e| {
4812                RuntimeError::Internal(format!("delete_note: event store write failed: {e}"))
4813            })?;
4814            // A soft OR hard delete removes the note's vectors/FTS document
4815            // above: any pack-owned vector-derived cache (e.g.
4816            // khive-pack-memory's warm ANN index) needs to know the corpus
4817            // changed, reached via this generic hook so khive-runtime never
4818            // takes a dependency on khive-pack-memory. No-op when no pack has
4819            // installed a hook.
4820            self.fire_note_mutation_hook(&note.kind, id).await;
4821        }
4822        Ok(deleted)
4823    }
4824
4825    /// Row-first compensating delete for rolling back a partially-written note
4826    /// (e.g. `dual_write_message` rollback after a later delivery step fails).
4827    /// Unlike [`KhiveRuntime::delete_note`], which cleans up graph/FTS/
4828    /// vector indexes *before* removing the row, this removes the row first so
4829    /// that a cleanup failure afterward cannot leave the compensated note live.
4830    ///
4831    /// Returns `Ok(())` once the row is gone (whether or not cleanup fully
4832    /// succeeded). Returns `Err(RuntimeError::Internal)` naming the failed
4833    /// cleanup legs when row removal succeeded but cleanup did not — the
4834    /// message is gone, but stale index entries may remain and should be
4835    /// surfaced to the caller rather than silently discarded.
4836    ///
4837    /// Returns `Ok(())` immediately, with no cleanup attempted, if the note
4838    /// does not exist (nothing to compensate).
4839    ///
4840    /// Not a general-purpose replacement for `delete_note(..., hard=true)`:
4841    /// normal hard delete still needs cleanup-first semantics (no dangling
4842    /// references) since a caller-visible error there should not remove the row.
4843    pub async fn delete_note_row_first_for_compensation(
4844        &self,
4845        token: &NamespaceToken,
4846        id: Uuid,
4847    ) -> RuntimeResult<()> {
4848        let note_store = self.notes(token)?;
4849        let Some(note) = note_store.get_note_including_deleted(id).await? else {
4850            return Ok(());
4851        };
4852        let record_tok = NamespaceToken::for_namespace(
4853            khive_types::Namespace::parse(&note.namespace)
4854                .map_err(|e| RuntimeError::Internal(format!("note namespace invalid: {e}")))?,
4855        );
4856        let record_ns = note.namespace.clone();
4857
4858        // Critical ordering: remove the row before any cleanup that can fail.
4859        note_store.delete_note(id, DeleteMode::Hard).await?;
4860
4861        #[cfg(any(test, feature = "fault-injection"))]
4862        {
4863            let armed = ROLLBACK_CLEANUP_FAIL_NS.lock().unwrap().take();
4864            if armed.as_deref() == Some(record_ns.as_str()) {
4865                return Err(RuntimeError::Internal(
4866                    "row removed but compensation cleanup failed: injected=true".to_string(),
4867                ));
4868            }
4869        }
4870
4871        let mut cleanup_errors = Vec::new();
4872        if let Err(e) = self.graph(&record_tok)?.purge_incident_edges(id).await {
4873            cleanup_errors.push(format!("graph={e}"));
4874        }
4875        if let Err(e) = self
4876            .text_for_notes(&record_tok)?
4877            .delete_document(&record_ns, id)
4878            .await
4879        {
4880            cleanup_errors.push(format!("fts={e}"));
4881        }
4882        for model_name in self.registered_embedding_model_names() {
4883            if let Err(e) = self
4884                .vectors_for_model(&record_tok, &model_name)?
4885                .delete(id)
4886                .await
4887            {
4888                cleanup_errors.push(format!("vector[{model_name}]={e}"));
4889            }
4890        }
4891        if cleanup_errors.is_empty() {
4892            Ok(())
4893        } else {
4894            Err(RuntimeError::Internal(format!(
4895                "row removed but compensation cleanup failed: {}",
4896                cleanup_errors.join("; ")
4897            )))
4898        }
4899    }
4900}
4901
4902/// Result of a GQL/SPARQL query with optional validation warnings.
4903#[derive(Clone, Debug, Serialize)]
4904pub struct QueryResult {
4905    pub rows: Vec<SqlRow>,
4906    #[serde(skip_serializing_if = "Vec::is_empty")]
4907    pub warnings: Vec<String>,
4908    /// Zero-based offset of this deterministic result page.
4909    pub offset: usize,
4910    /// Effective payload bound after composing query `LIMIT` and server page size.
4911    pub page_size: usize,
4912    /// `true` when at least one additional match exists after this page.
4913    pub has_more: bool,
4914    /// GQL continuation offset. Present exactly when GQL has another page.
4915    #[serde(skip_serializing_if = "Option::is_none")]
4916    pub next_offset: Option<usize>,
4917    /// Backward-compatible alias for `has_more` (#1168, #1247, #1601).
4918    pub truncated: bool,
4919}
4920
4921/// Outcome of [`KhiveRuntime::update_edge_symmetric_dml`]'s in-transaction DML.
4922#[derive(Debug)]
4923enum SymmetricEdgeUpdateOutcome {
4924    /// A canonical row already existed (ADR-039 DO NOTHING): the
4925    /// requested edge was deleted, the existing canonical row (this id)
4926    /// left untouched.
4927    Absorbed(String),
4928    /// No conflict; the requested edge was updated in place.
4929    Updated,
4930    /// No conflict, but the in-place `UPDATE` matched zero rows because
4931    /// the row's revision or deletion marker moved after it was fetched —
4932    /// a concurrent writer raced this update and must be refused, not
4933    /// silently overwritten by a stale full-row write.
4934    Stale,
4935}
4936
4937impl KhiveRuntime {
4938    // ---- Query operations ----
4939
4940    /// Execute a GQL or SPARQL query string, returning raw SQL rows.
4941    ///
4942    /// The query is compiled to SQL with the namespace scope applied.
4943    /// GQL syntax: `MATCH (a:concept)-[e:extends]->(b) RETURN a, b LIMIT 10`
4944    /// SPARQL syntax: `SELECT ?a WHERE { ?a :kind "concept" . }`
4945    pub async fn query(&self, token: &NamespaceToken, query: &str) -> RuntimeResult<Vec<SqlRow>> {
4946        Ok(self
4947            .query_with_metadata(token, query, khive_query::CompileOptions::default())
4948            .await?
4949            .rows)
4950    }
4951
4952    /// Execute a GQL/SPARQL query, returning rows and any validation warnings.
4953    pub async fn query_with_metadata(
4954        &self,
4955        token: &NamespaceToken,
4956        query: &str,
4957        mut opts: khive_query::CompileOptions,
4958    ) -> RuntimeResult<QueryResult> {
4959        use khive_query::QueryValue;
4960        use khive_storage::types::SqlValue;
4961
4962        let (language, ast) = khive_query::language::parse_auto_with_language(query)?;
4963        if opts.max_limit == 0 {
4964            return Err(RuntimeError::InvalidInput(
4965                "query page size must be at least 1".into(),
4966            ));
4967        }
4968        let offset = ast.offset;
4969        let page_size = ast.limit.unwrap_or(opts.max_limit).min(opts.max_limit);
4970        opts.scopes = token
4971            .visible_namespaces()
4972            .iter()
4973            .map(|ns| ns.as_str().to_string())
4974            .collect();
4975        let compiled = khive_query::compile(&ast, &opts)?;
4976        let mut warnings = compiled.warnings;
4977        let truncation_check = compiled.truncation_check;
4978
4979        warnings.extend(self.with_pack_edge_rules(|pack_rules| {
4980            static_impossible_edge_pattern_warnings(language, &ast.pattern, pack_rules)
4981        }));
4982
4983        // Convert QueryValue params (query-layer type) to SqlValue (storage-layer type)
4984        // at the query–storage boundary.
4985        let params: Vec<SqlValue> = compiled
4986            .params
4987            .into_iter()
4988            .map(|qv| match qv {
4989                QueryValue::Null => SqlValue::Null,
4990                QueryValue::Integer(n) => SqlValue::Integer(n),
4991                QueryValue::Float(f) => SqlValue::Float(f),
4992                QueryValue::Text(s) => SqlValue::Text(s),
4993                QueryValue::Blob(b) => SqlValue::Blob(b),
4994            })
4995            .collect();
4996
4997        let mut reader = self.sql().reader().await?;
4998        let stmt = SqlStatement {
4999            sql: compiled.sql,
5000            params,
5001            label: None,
5002        };
5003        let mut rows = reader.query_all(stmt).await?;
5004
5005        // When the effective page size was the binding constraint, the compiled
5006        // SQL asked for one extra (sentinel) row. Its presence in the actual
5007        // result set — not the requested LIMIT — is the continuation signal.
5008        let mut truncated = false;
5009        if let Some(check) = truncation_check {
5010            if rows.len() > check.max_limit {
5011                rows.truncate(check.max_limit);
5012                truncated = true;
5013            }
5014        }
5015
5016        let next_offset = if truncated && language == khive_query::QueryLanguage::Gql {
5017            let next = offset.checked_add(rows.len()).ok_or_else(|| {
5018                RuntimeError::InvalidInput("GQL next_offset exceeds usize::MAX".into())
5019            })?;
5020            if next == offset {
5021                return Err(RuntimeError::InvalidInput(
5022                    "query page did not advance; page size must be at least 1".into(),
5023                ));
5024            }
5025            i64::try_from(next).map_err(|_| {
5026                RuntimeError::InvalidInput("GQL next_offset exceeds i64::MAX".into())
5027            })?;
5028            Some(next)
5029        } else {
5030            None
5031        };
5032
5033        if truncated {
5034            let Some(check) = truncation_check else {
5035                return Err(RuntimeError::Internal(
5036                    "truncated query result is missing sentinel metadata".into(),
5037                ));
5038            };
5039            let bound = match check.requested_limit {
5040                Some(requested) => {
5041                    format!("requested query LIMIT {requested} exceeds the effective page size")
5042                }
5043                None => "the query has no explicit LIMIT".to_string(),
5044            };
5045            let warning = match language {
5046                khive_query::QueryLanguage::Gql => {
5047                    let Some(next) = next_offset else {
5048                        return Err(RuntimeError::Internal(
5049                            "truncated GQL result is missing its continuation offset".into(),
5050                        ));
5051                    };
5052                    format!(
5053                        "result page capped at {} rows because {bound}; more matches exist. \
5054                         Continue the same GQL query with `SKIP {next}` (the machine-readable \
5055                         `next_offset`) and keep the same page size.",
5056                        check.max_limit
5057                    )
5058                }
5059                khive_query::QueryLanguage::Sparql => format!(
5060                    "result page capped at {} rows because {bound}; more matches exist. \
5061                     SPARQL OFFSET paging is not part of the supported dialect.",
5062                    check.max_limit
5063                ),
5064            };
5065            warnings.push(warning);
5066        }
5067
5068        Ok(QueryResult {
5069            rows,
5070            warnings,
5071            offset,
5072            page_size,
5073            has_more: truncated,
5074            next_offset,
5075            truncated,
5076        })
5077    }
5078
5079    /// Soft-delete or hard-delete an entity by ID (soft delete by default).
5080    ///
5081    /// On hard delete, cascades to remove all incident edges (both inbound and
5082    /// outbound) to prevent dangling references. Soft delete also cleans FTS
5083    /// and vector indexes; edges are left in place.
5084    ///
5085    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
5086    pub async fn delete_entity(
5087        &self,
5088        token: &NamespaceToken,
5089        id: Uuid,
5090        hard: bool,
5091    ) -> RuntimeResult<bool> {
5092        let entity = if hard {
5093            match self
5094                .entities(token)?
5095                .get_entity_including_deleted(id)
5096                .await?
5097            {
5098                Some(e) => e,
5099                None => return Ok(false),
5100            }
5101        } else {
5102            match self.entities(token)?.get_entity(id).await? {
5103                Some(e) => e,
5104                None => return Ok(false),
5105            }
5106        };
5107        let mode = if hard {
5108            DeleteMode::Hard
5109        } else {
5110            DeleteMode::Soft
5111        };
5112
5113        // Route cascade and index cleanup through the RECORD's namespace, not the caller's.
5114        let record_tok = NamespaceToken::for_namespace(
5115            khive_types::Namespace::parse(&entity.namespace)
5116                .map_err(|e| RuntimeError::Internal(format!("entity namespace invalid: {e}")))?,
5117        );
5118        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
5119
5120        // On hard delete, the row delete and the incident-edge cascade (including
5121        // already-soft-deleted edges) run as ONE write transaction: see
5122        // `atomic_hard_delete_with_edge_purge`. Index cleanup follows the
5123        // commit; it is best-effort and idempotent, unlike the row/edge pair.
5124        let deleted = if hard {
5125            let deleted = self
5126                .atomic_hard_delete_with_edge_purge(
5127                    entity_hard_delete_statement(id),
5128                    id,
5129                    &entity.namespace,
5130                    &actor,
5131                    SubstrateKind::Entity,
5132                )
5133                .await?;
5134            self.remove_from_indexes(&record_tok, id).await?;
5135            deleted
5136        } else {
5137            let deleted = self.entities(token)?.delete_entity(id, mode).await?;
5138            if deleted {
5139                self.remove_from_indexes(&record_tok, id).await?;
5140            }
5141            deleted
5142        };
5143        if deleted {
5144            let event_store = self.events(token)?;
5145            let ns = entity.namespace.clone();
5146            let event = khive_storage::event::Event::new(
5147                ns.clone(),
5148                "delete",
5149                EventKind::EntityDeleted,
5150                SubstrateKind::Entity,
5151                "",
5152            )
5153            .with_target(id)
5154            .with_payload(serde_json::json!({"id": id, "namespace": ns, "hard": hard}));
5155            event_store.append_event(event).await.map_err(|e| {
5156                RuntimeError::Internal(format!("delete_entity: event store write failed: {e}"))
5157            })?;
5158        }
5159        Ok(deleted)
5160    }
5161
5162    /// Count entities in a namespace, optionally filtered.
5163    pub async fn count_entities(
5164        &self,
5165        token: &NamespaceToken,
5166        kind: Option<&str>,
5167    ) -> RuntimeResult<u64> {
5168        let ns_strs: Vec<String> = token
5169            .visible_namespaces()
5170            .iter()
5171            .map(|ns| ns.as_str().to_owned())
5172            .collect();
5173        let filter = EntityFilter {
5174            kinds: match kind {
5175                Some(k) => vec![k.to_string()],
5176                None => vec![],
5177            },
5178            namespaces: ns_strs,
5179            ..Default::default()
5180        };
5181        Ok(self
5182            .entities(token)?
5183            .count_entities(token.namespace().as_str(), filter)
5184            .await?)
5185    }
5186
5187    // ---- Edge CRUD operations ----
5188
5189    /// Fetch a single edge by id.
5190    ///
5191    /// UUID v4 is globally unique: returns the edge regardless of which
5192    /// namespace the token carries. `Ok(None)` means the edge does not exist at all.
5193    pub async fn get_edge(
5194        &self,
5195        _token: &NamespaceToken,
5196        edge_id: Uuid,
5197    ) -> RuntimeResult<Option<Edge>> {
5198        let mut reader = self.sql().reader().await?;
5199        let record_ns = reader
5200            .query_scalar(SqlStatement {
5201                sql: "SELECT namespace FROM graph_edges \
5202                      WHERE id = ?1 AND deleted_at IS NULL LIMIT 1"
5203                    .into(),
5204                params: vec![SqlValue::Text(edge_id.to_string())],
5205                label: Some("get_edge_namespace".into()),
5206            })
5207            .await?;
5208
5209        let Some(SqlValue::Text(record_ns)) = record_ns else {
5210            return Ok(None);
5211        };
5212        // Route the storage fetch through the record's own namespace — the token is
5213        // just the caller context; by-ID ops cross namespace boundaries.
5214        let record_tok = NamespaceToken::for_namespace(
5215            khive_types::Namespace::parse(&record_ns)
5216                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5217        );
5218        Ok(self
5219            .graph(&record_tok)?
5220            .get_edge(LinkId::from(edge_id))
5221            .await?)
5222    }
5223
5224    /// Fetch a single edge by id.
5225    ///
5226    /// Delegates to `get_edge`: no visible-set check.  By-ID ops are
5227    /// namespace-agnostic; UUID v4 is globally unique.
5228    pub async fn get_edge_visible(
5229        &self,
5230        token: &NamespaceToken,
5231        edge_id: Uuid,
5232    ) -> RuntimeResult<Option<Edge>> {
5233        self.get_edge(token, edge_id).await
5234    }
5235
5236    /// Fetch an edge by UUID including soft-deleted rows.
5237    ///
5238    /// Returns the edge regardless of which namespace the token carries:
5239    /// UUID v4 is globally unique. Used by the hard-delete path so that a
5240    /// soft-deleted edge can still be purged via its edge ID.
5241    pub async fn get_edge_including_deleted(
5242        &self,
5243        _token: &NamespaceToken,
5244        edge_id: Uuid,
5245    ) -> RuntimeResult<Option<Edge>> {
5246        let mut reader = self.sql().reader().await?;
5247        let record_ns = reader
5248            .query_scalar(SqlStatement {
5249                sql: "SELECT namespace FROM graph_edges WHERE id = ?1 LIMIT 1".into(),
5250                params: vec![SqlValue::Text(edge_id.to_string())],
5251                label: Some("get_edge_including_deleted_namespace".into()),
5252            })
5253            .await?;
5254
5255        let Some(SqlValue::Text(record_ns)) = record_ns else {
5256            return Ok(None);
5257        };
5258        // Route through the record's own namespace store (no namespace equality check).
5259        let record_tok = NamespaceToken::for_namespace(
5260            khive_types::Namespace::parse(&record_ns)
5261                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5262        );
5263        Ok(self
5264            .graph(&record_tok)?
5265            .get_edge_including_deleted(LinkId::from(edge_id))
5266            .await?)
5267    }
5268
5269    /// Fetch an edge by natural key (namespace, canonical source/target, relation)
5270    /// including soft-deleted rows. Unlike [`Self::list_edges`]/[`Self::list_edges_after`],
5271    /// which always filter `deleted_at IS NULL`, this can render a tombstoned symmetric-edge
5272    /// survivor (ADR-039 DO NOTHING conflict absorption) — used by the atomic-apply
5273    /// post-commit result renderer, which otherwise reports "not found" for a committed
5274    /// update whose surviving row happens to be soft-deleted.
5275    ///
5276    /// `token` selects the store instance; `namespace` is the natural key's own
5277    /// namespace and is bound into the query explicitly. These can legitimately differ:
5278    /// the record namespace is fixed at prepare time (`EdgeNaturalKey::namespace`) and by-ID
5279    /// edge updates are namespace-agnostic (ADR-007 Rev 6), so the caller's ambient `token`
5280    /// namespace is never a safe substitute for the record's own — the prior implicit
5281    /// `self.namespace` scoping is exactly the bug this parameter closes (khive#1213/#1214).
5282    pub async fn get_edge_by_natural_key_including_deleted(
5283        &self,
5284        token: &NamespaceToken,
5285        namespace: &str,
5286        source_id: Uuid,
5287        target_id: Uuid,
5288        relation: EdgeRelation,
5289    ) -> RuntimeResult<Option<Edge>> {
5290        Ok(self
5291            .graph(token)?
5292            .get_edge_by_natural_key_including_deleted(namespace, source_id, target_id, relation)
5293            .await?)
5294    }
5295
5296    /// Maximum rows returned by a single [`Self::list_edges`] /
5297    /// [`Self::list_edges_after`] page. A lower bound the docs promise callers
5298    /// can rely on; kept as a named constant so tests can exercise pagination
5299    /// (page tiling, out-of-range offsets) without needing >1000 real rows.
5300    pub const EDGE_LIST_MAX_LIMIT: u32 = 1000;
5301
5302    /// List edges matching `filter`, paging by `offset`. `limit` is capped at
5303    /// [`Self::EDGE_LIST_MAX_LIMIT`]; defaults to 100. For O(1)-at-depth walks
5304    /// over large edge populations, prefer [`Self::list_edges_after`] instead
5305    /// of paging offset deep.
5306    pub async fn list_edges(
5307        &self,
5308        token: &NamespaceToken,
5309        filter: crate::curation::EdgeListFilter,
5310        limit: u32,
5311        offset: u32,
5312    ) -> RuntimeResult<Vec<Edge>> {
5313        let limit = limit.min(Self::EDGE_LIST_MAX_LIMIT);
5314        let visible = token.visible_namespaces();
5315
5316        // Common case: a single visible namespace — page directly against the
5317        // store so `offset`/`limit` reach SQL unmodified.
5318        if let [ns] = visible {
5319            let temp = NamespaceToken::for_namespace(ns.clone());
5320            let page = self
5321                .graph(&temp)?
5322                .query_edges(
5323                    filter.into(),
5324                    vec![SortOrder {
5325                        field: EdgeSortField::CreatedAt,
5326                        direction: khive_storage::types::SortDirection::Asc,
5327                    }],
5328                    PageRequest {
5329                        offset: offset.into(),
5330                        limit,
5331                    },
5332                )
5333                .await?;
5334            return Ok(page.items);
5335        }
5336
5337        // Multi-namespace visibility: one deterministic query with
5338        // `namespace IN (...)` and real SQL paging, mirroring
5339        // `list_entities`. Fetching per-namespace prefixes and slicing a
5340        // client-side merge re-sorted by UUID floats the offset window
5341        // between calls — pages silently duplicate and skip rows, so
5342        // enumeration never covers the set (#2088).
5343        let ns_strs: Vec<String> = visible.iter().map(|ns| ns.as_str().to_owned()).collect();
5344        let sort = vec![SortOrder {
5345            field: EdgeSortField::CreatedAt,
5346            direction: khive_storage::types::SortDirection::Asc,
5347        }];
5348        let graph = self.graph(token)?;
5349        match graph
5350            .query_edges_in_namespaces(
5351                &ns_strs,
5352                filter.clone().into(),
5353                sort.clone(),
5354                PageRequest {
5355                    offset: offset.into(),
5356                    limit,
5357                },
5358            )
5359            .await
5360        {
5361            Ok(page) => Ok(page.items),
5362            Err(khive_storage::StorageError::Unsupported { operation, .. })
5363                if operation == "query_edges_in_namespaces" =>
5364            {
5365                // Backend exercises the trait default (no batched
5366                // namespace query support): fall back to one `query_edges`
5367                // call per namespace. Unlike the pre-image fix for #2088,
5368                // this fetches an `offset + limit` prefix from every
5369                // namespace and merges by the *same* `(created_at, id)` key
5370                // each per-namespace fetch already orders by — the
5371                // pre-image bug sorted the merged set by UUID alone, a key
5372                // unrelated to the order each per-namespace prefix was cut
5373                // at, which floated the offset window and silently
5374                // duplicated/skipped rows across pages. Sorting by the
5375                // fetch's own order key keeps the top `offset + limit` of
5376                // the merge exactly equal to the true global prefix.
5377                let fetch_limit = offset.saturating_add(limit);
5378                let mut namespace_prefixes = Vec::new();
5379                for ns in visible {
5380                    let temp = NamespaceToken::for_namespace(ns.clone());
5381                    let page = self
5382                        .graph(&temp)?
5383                        .query_edges(
5384                            filter.clone().into(),
5385                            sort.clone(),
5386                            PageRequest {
5387                                offset: 0,
5388                                limit: fetch_limit,
5389                            },
5390                        )
5391                        .await?;
5392                    namespace_prefixes.push(page.items);
5393                }
5394                Ok(Self::merge_paged_namespace_edges(
5395                    namespace_prefixes,
5396                    offset,
5397                    limit,
5398                ))
5399            }
5400            Err(error) => Err(error.into()),
5401        }
5402    }
5403
5404    /// Merge per-namespace `(created_at, id)`-ordered edge prefixes (each
5405    /// already fetched up to `offset + limit` from its own namespace, as
5406    /// [`Self::list_edges`]'s trait-default fallback does) into one global
5407    /// `[offset, offset + limit)` page.
5408    ///
5409    /// Sorting by the *same key each prefix was already cut at* is what
5410    /// keeps this exact: the top `offset + limit` of the merged set is then
5411    /// provably equal to the true global prefix (a standard k-way merge
5412    /// argument — no element beyond position `offset + limit` in any single
5413    /// namespace can appear before that position in the global order). The
5414    /// pre-image #2088 bug instead re-sorted the merged set by UUID alone —
5415    /// a key unrelated to the order each namespace's prefix was fetched in —
5416    /// which floated the offset window and silently duplicated/skipped rows
5417    /// across pages.
5418    fn merge_paged_namespace_edges(
5419        namespace_prefixes: Vec<Vec<Edge>>,
5420        offset: u32,
5421        limit: u32,
5422    ) -> Vec<Edge> {
5423        let mut results: Vec<Edge> = namespace_prefixes.into_iter().flatten().collect();
5424        results.sort_by_key(|e| (e.created_at, Uuid::from(e.id)));
5425        let start = (offset as usize).min(results.len());
5426        let end = (start + limit as usize).min(results.len());
5427        results[start..end].to_vec()
5428    }
5429
5430    /// Keyset (seek) page of edges matching `filter`, ordered by immutable
5431    /// database-assigned insertion sequence. `after` is the last edge id from the
5432    /// previous page (exclusive); omit to start from the beginning. Returns
5433    /// `(items, next_after)` — `next_after` is `Some` when more rows remain
5434    /// past this page.
5435    ///
5436    /// Unlike [`Self::list_edges`], this is O(log n + limit) at any depth and
5437    /// genuinely new inserts are appended after already-issued boundaries. The
5438    /// cursor row is resolved including tombstones; a hard-deleted or
5439    /// out-of-scope cursor fails explicitly rather than hiding an incomplete
5440    /// traversal.
5441    pub async fn list_edges_after(
5442        &self,
5443        token: &NamespaceToken,
5444        filter: crate::curation::EdgeListFilter,
5445        after: Option<Uuid>,
5446        limit: u32,
5447    ) -> RuntimeResult<(Vec<Edge>, Option<Uuid>)> {
5448        let limit = limit.clamp(1, Self::EDGE_LIST_MAX_LIMIT);
5449        let visible = token.visible_namespaces();
5450        let limit_usize = limit as usize;
5451        let cursor_store = self.graph(token)?;
5452        let after = match after {
5453            Some(id) => {
5454                let edge = self
5455                    .get_edge_including_deleted(token, id)
5456                    .await?
5457                    .ok_or_else(|| RuntimeError::NotFound(format!("edge cursor {id}")))?;
5458                Self::ensure_namespace_visible(&edge.namespace, token)?;
5459                let sequence = cursor_store.edge_sequence(id).await?.ok_or_else(|| {
5460                    RuntimeError::Internal(format!(
5461                        "edge cursor {id} has no insertion-sequence ledger row"
5462                    ))
5463                })?;
5464                Some(SeekCursor { sequence, id })
5465            }
5466            None => None,
5467        };
5468
5469        if let [ns] = visible {
5470            let temp = NamespaceToken::for_namespace(ns.clone());
5471            let page = self
5472                .graph(&temp)?
5473                .query_edges_sequence_after(filter.into(), after, limit)
5474                .await?;
5475            return Ok((page.items, page.next_after.map(|cursor| cursor.id)));
5476        }
5477
5478        // Multi-namespace visibility: seek each namespace from the same
5479        // immutable boundary, merge in global insertion order, then take the head of
5480        // the merged set as this page.
5481        let probe_limit = limit.saturating_add(1);
5482        let mut results = Vec::new();
5483        for ns in visible {
5484            let temp = NamespaceToken::for_namespace(ns.clone());
5485            let page = self
5486                .graph(&temp)?
5487                .query_edges_sequence_after(filter.clone().into(), after, probe_limit)
5488                .await?;
5489            results.extend(page.items);
5490        }
5491        let ids = results
5492            .iter()
5493            .map(|edge| Uuid::from(edge.id))
5494            .collect::<Vec<_>>();
5495        let sequences = cursor_store
5496            .edge_sequences(&ids)
5497            .await?
5498            .into_iter()
5499            .collect::<HashMap<_, _>>();
5500        if let Some(missing) = ids.iter().find(|id| !sequences.contains_key(id)) {
5501            return Err(RuntimeError::Internal(format!(
5502                "edge {missing} has no insertion-sequence ledger row"
5503            )));
5504        }
5505        results.sort_by_key(|edge| {
5506            let id = Uuid::from(edge.id);
5507            (sequences[&id], id)
5508        });
5509        results.dedup_by_key(|e| Uuid::from(e.id));
5510        let has_more = results.len() > limit_usize;
5511        if has_more {
5512            results.truncate(limit_usize);
5513        }
5514        let next_after = if has_more {
5515            results.last().map(|e| Uuid::from(e.id))
5516        } else {
5517            None
5518        };
5519        Ok((results, next_after))
5520    }
5521
5522    /// Count edges by relation, ignoring soft-deleted rows. Used by
5523    /// `stats()` to report the true per-relation population so full-graph
5524    /// audits know what they're sampling from before they walk it.
5525    pub async fn count_edges_by_relation(
5526        &self,
5527        token: &NamespaceToken,
5528    ) -> RuntimeResult<std::collections::HashMap<String, u64>> {
5529        let namespaces: Vec<String> = token
5530            .visible_namespaces()
5531            .iter()
5532            .map(|namespace| namespace.as_str().to_owned())
5533            .collect();
5534        let graph = self.graph(token)?;
5535        let counts = match graph
5536            .count_edges_by_relation_in_namespaces(&namespaces)
5537            .await
5538        {
5539            Ok(counts) => counts,
5540            Err(khive_storage::StorageError::Unsupported { operation, .. })
5541                if operation == "count_edges_by_relation_in_namespaces" =>
5542            {
5543                let mut totals = HashMap::new();
5544                for namespace in token.visible_namespaces() {
5545                    let scoped = NamespaceToken::for_namespace(namespace.clone());
5546                    for (relation, count) in self.graph(&scoped)?.count_edges_by_relation().await? {
5547                        *totals.entry(relation).or_insert(0) += count;
5548                    }
5549                }
5550                return Ok(totals
5551                    .into_iter()
5552                    .map(|(relation, count)| (relation.to_string(), count))
5553                    .collect());
5554            }
5555            Err(error) => return Err(error.into()),
5556        };
5557        Ok(counts
5558            .into_iter()
5559            .map(|(relation, count)| (relation.to_string(), count))
5560            .collect())
5561    }
5562
5563    /// DML-only body of the symmetric-relation conflict-resolution path in
5564    /// [`Self::update_edge`]. Runs the conflict-check SELECT, then either the
5565    /// DELETE+UPDATE (case b, a canonical row already exists) or the
5566    /// in-place UPDATE (case a, no conflict). Callers own the surrounding transaction
5567    /// boundary — this function issues DML only, no `BEGIN`/`COMMIT`/`ROLLBACK`.
5568    ///
5569    /// The in-place update is guarded on the fetched snapshot's revision and
5570    /// deletion marker (mirrors the non-symmetric `replace_edge_if_unchanged`
5571    /// guard) and requires the replacement revision to strictly advance.
5572    /// Shares its DML text with the atomic `prepare_update_edge` symmetric
5573    /// branch — see docs/operations.md#update_edge_symmetric_dml.
5574    #[allow(clippy::too_many_arguments)]
5575    fn update_edge_symmetric_dml(
5576        conn: &rusqlite::Connection,
5577        ns: &str,
5578        edge_id_str: &str,
5579        canon_src_str: &str,
5580        canon_tgt_str: &str,
5581        relation_str: &str,
5582        weight: f64,
5583        metadata: Option<String>,
5584        expected_updated_at_micros: i64,
5585        expected_deleted_at_micros: Option<i64>,
5586    ) -> Result<SymmetricEdgeUpdateOutcome, SqliteError> {
5587        // `updated_at` is stored in MICROSECONDS on `graph_edges` (every other
5588        // write path — `edge_upsert_statement`, `edge_soft_delete_statement` —
5589        // uses `timestamp_micros()`; the column is read back via
5590        // `micros_to_datetime`). `timestamp()` (seconds) here was a
5591        // pre-existing bug in this raw-SQL path, found while unifying it with
5592        // the atomic builder (which already used `timestamp_micros()`
5593        // correctly).
5594        //
5595        // The replacement revision must strictly advance past the snapshot
5596        // even when two operations land inside one clock microsecond;
5597        // saturating to i64::MAX would let the CAS accept a write without
5598        // advancing its revision, so that is not a valid fallback (mirrors
5599        // the note path).
5600        let minimum_updated_at_micros =
5601            expected_updated_at_micros.checked_add(1).ok_or_else(|| {
5602                SqliteError::InvalidData(format!(
5603                    "update_edge: edge {edge_id_str} updated_at is already at i64::MAX \
5604                         and cannot advance"
5605                ))
5606            })?;
5607        let now_ts = chrono::Utc::now()
5608            .timestamp_micros()
5609            .max(minimum_updated_at_micros);
5610
5611        // Check for a conflicting canonical row (same namespace + natural key,
5612        // different id). This catches conflicts whether or not endpoints were flipped.
5613        let conflict_id: Option<String> = conn
5614            .query_row(
5615                khive_db::stores::graph::EDGE_SYMMETRIC_CONFLICT_PROBE_SQL,
5616                rusqlite::params![
5617                    &ns,
5618                    &canon_src_str,
5619                    &canon_tgt_str,
5620                    &relation_str,
5621                    &edge_id_str
5622                ],
5623                |row| row.get(0),
5624            )
5625            .optional()
5626            .map_err(SqliteError::Rusqlite)?;
5627
5628        if let Some(existing_id) = conflict_id {
5629            // Case (b): canonical row already exists — ADR-039's edge-conflict
5630            // contract is ON CONFLICT DO NOTHING: drop the non-canonical edge
5631            // and leave the existing canonical row untouched (live or
5632            // tombstoned). Refreshing it from the discarded edge's
5633            // weight/target_backend/metadata and forcing deleted_at = NULL
5634            // would silently overwrite the survivor and resurrect a
5635            // tombstone — the same defect already fixed on the merge-rewire
5636            // path (`merge_entity_sql`/`merge_note_sql`); this path binds the
5637            // same shared `EDGE_SYMMETRIC_*_SQL` text and must honor the same
5638            // contract. Return the surviving id unchanged so the caller
5639            // re-fetches its real (unmodified) attributes.
5640            //
5641            // Guarded on the fetched snapshot's revision and deletion marker:
5642            // a concurrent writer that changed this edge between fetch and
5643            // this write must be refused, not silently deleted just because
5644            // a canonical survivor happens to exist. Zero affected rows here
5645            // means stale, not "no conflict" — the probe above already
5646            // confirmed a conflicting canonical row exists.
5647            let affected = conn
5648                .execute(
5649                    khive_db::stores::graph::EDGE_SYMMETRIC_DELETE_NONCANONICAL_GUARDED_SQL,
5650                    rusqlite::params![
5651                        &ns,
5652                        &edge_id_str,
5653                        expected_updated_at_micros,
5654                        expected_deleted_at_micros,
5655                    ],
5656                )
5657                .map_err(SqliteError::Rusqlite)?;
5658            if affected == 0 {
5659                return Ok(SymmetricEdgeUpdateOutcome::Stale);
5660            }
5661            Ok(SymmetricEdgeUpdateOutcome::Absorbed(existing_id))
5662        } else {
5663            // Case (a): no conflict — update source_id/target_id in-place,
5664            // preserving the original edge UUID. Guarded on the fetched
5665            // snapshot's revision and deletion marker: a concurrent writer
5666            // that moved this edge between fetch and this write must be
5667            // refused, not silently overwritten by a stale full-row update.
5668            let affected = conn
5669                .execute(
5670                    khive_db::stores::graph::EDGE_SYMMETRIC_UPDATE_INPLACE_SQL,
5671                    rusqlite::params![
5672                        &canon_src_str,
5673                        &canon_tgt_str,
5674                        &relation_str,
5675                        weight,
5676                        now_ts,
5677                        metadata,
5678                        &ns,
5679                        &edge_id_str,
5680                        expected_updated_at_micros,
5681                        expected_deleted_at_micros,
5682                    ],
5683                )
5684                .map_err(SqliteError::Rusqlite)?;
5685            if affected == 0 {
5686                return Ok(SymmetricEdgeUpdateOutcome::Stale);
5687            }
5688            Ok(SymmetricEdgeUpdateOutcome::Updated)
5689        }
5690    }
5691
5692    /// Patch-style edge update. Only `Some(_)` fields are applied.
5693    ///
5694    /// When `relation` is `Some(new_rel)`, validates that the edge's existing endpoints
5695    /// are legal for `new_rel` before persisting. Weight-only updates (`relation = None`)
5696    /// skip validation. Returns `InvalidInput` if the new relation would violate the
5697    /// three-case endpoint contract; the edge is NOT mutated on error.
5698    ///
5699    /// For symmetric relations (`competes_with`, `composed_with`), endpoint order is
5700    /// canonicalised to `source_uuid < target_uuid` after validation. If a canonical
5701    /// row already exists at the target triple, the non-canonical edge is deleted and
5702    /// the existing canonical row is preserved unchanged (ADR-039 ON CONFLICT DO
5703    /// NOTHING, mirroring `merge_entity_sql`) — its attributes, including a soft-deleted
5704    /// `deleted_at`, are never overwritten by the discarded edge's patch.
5705    pub async fn update_edge(
5706        &self,
5707        token: &NamespaceToken,
5708        edge_id: Uuid,
5709        patch: crate::curation::EdgePatch,
5710    ) -> RuntimeResult<Edge> {
5711        // Fetch the edge by UUID: ID-only, no namespace check.
5712        // get_edge already uses the record's stored namespace internally.
5713        let graph_for_fetch = self.graph(token)?;
5714        let mut edge = graph_for_fetch
5715            .get_edge(LinkId::from(edge_id))
5716            .await?
5717            .ok_or_else(|| crate::RuntimeError::NotFound(format!("edge {edge_id}")))?;
5718        let expected_updated_at = edge.updated_at;
5719        let expected_deleted_at = edge.deleted_at;
5720        #[cfg(test)]
5721        crate::curation::race_seam::pause_after_read().await;
5722
5723        // After fetching, all mutations and validation must use the
5724        // RECORD's namespace, not the caller's.  Derive record_tok from the stored edge
5725        // namespace so that endpoint validation, raw-SQL predicates, and graph routing
5726        // all address the correct backend partition.
5727        let record_ns: String = edge.namespace.clone();
5728        let record_tok = NamespaceToken::for_namespace(
5729            khive_types::Namespace::parse(&record_ns)
5730                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5731        );
5732        let graph = self.graph(&record_tok)?;
5733
5734        let mut changed_fields: Vec<&'static str> = Vec::new();
5735        if let Some(r) = patch.relation {
5736            // Validate before mutating — use the existing endpoints with the new relation.
5737            // Use record_tok so that endpoint existence checks look in the edge's own namespace.
5738            self.validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, r)
5739                .await?;
5740            edge.relation = r;
5741            changed_fields.push("relation");
5742        }
5743        if let Some(w) = patch.weight {
5744            // Reject non-finite or out-of-range weight explicitly; do not silently
5745            // clamp invalid caller input (coding-standards §608-622).
5746            if !w.is_finite() || !(0.0..=1.0).contains(&w) {
5747                return Err(RuntimeError::InvalidInput(format!(
5748                    "edge weight must be a finite value in [0.0, 1.0]; got {w}"
5749                )));
5750            }
5751            edge.weight = w;
5752            changed_fields.push("weight");
5753        }
5754        if let Some(props) = patch.properties {
5755            crate::secret_gate::reject_reserved_secret_gate_property(Some(&props))?;
5756            edge.metadata = Some(props);
5757        }
5758
5759        // For symmetric relations, canonicalise endpoint order and check
5760        // for natural-key conflicts regardless of whether endpoints were flipped.
5761        //
5762        // The raw-SQL path is used for ALL symmetric relations because `upsert_edge`
5763        // resolves ON CONFLICT(namespace,id) first and cannot detect a duplicate at
5764        // the natural key (namespace, source_id, target_id, relation) with a different
5765        // id. Bug-fix: this path must also run when endpoints are already canonical
5766        // (endpoints_flipped=false) to catch conflicts arising from a relation change
5767        // that collides with an existing canonical row.
5768        let (canon_src, canon_tgt) =
5769            canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
5770
5771        if edge.relation.is_symmetric() {
5772            // Raw-SQL path (mirrors merge_entity_sql).
5773            // Use record_ns (the stored edge namespace) — NOT token.namespace() — so that
5774            // WHERE namespace = ?N predicates match the actual row.
5775            let ns = record_ns.clone();
5776            let edge_id_str = edge_id.to_string();
5777            let relation_str = edge.relation.to_string();
5778            let canon_src_str = canon_src.to_string();
5779            let canon_tgt_str = canon_tgt.to_string();
5780            let weight = edge.weight;
5781            let metadata = edge
5782                .metadata
5783                .as_ref()
5784                .map(|v| serde_json::to_string(v).unwrap_or_default());
5785
5786            let expected_updated_at_micros = expected_updated_at.timestamp_micros();
5787            let expected_deleted_at_micros = expected_deleted_at.map(|v| v.timestamp_micros());
5788
5789            let pool = self.backend().pool_arc();
5790            // Route through the single-writer task when the write queue is
5791            // enabled; best-effort lookup degrades to the legacy pool-mutex
5792            // path (mirrors merge_entity/merge_note above).
5793            let writer_task = pool.writer_task_handle().ok().flatten();
5794
5795            let outcome: SymmetricEdgeUpdateOutcome = if let Some(writer_task) = writer_task {
5796                writer_task
5797                    .send(move |conn| {
5798                        Self::update_edge_symmetric_dml(
5799                            conn,
5800                            &ns,
5801                            &edge_id_str,
5802                            &canon_src_str,
5803                            &canon_tgt_str,
5804                            &relation_str,
5805                            weight,
5806                            metadata,
5807                            expected_updated_at_micros,
5808                            expected_deleted_at_micros,
5809                        )
5810                        .map_err(|e| {
5811                            khive_storage::StorageError::driver(
5812                                khive_storage::StorageCapability::Graph,
5813                                "update_edge",
5814                                e,
5815                            )
5816                        })
5817                    })
5818                    .await
5819                    .map_err(RuntimeError::Storage)?
5820            } else {
5821                tokio::task::spawn_blocking(move || {
5822                    let guard = pool.writer()?;
5823                    guard.transaction(|conn| {
5824                        Self::update_edge_symmetric_dml(
5825                            conn,
5826                            &ns,
5827                            &edge_id_str,
5828                            &canon_src_str,
5829                            &canon_tgt_str,
5830                            &relation_str,
5831                            weight,
5832                            metadata,
5833                            expected_updated_at_micros,
5834                            expected_deleted_at_micros,
5835                        )
5836                    })
5837                })
5838                .await
5839                .map_err(|e| {
5840                    RuntimeError::Internal(format!("update_edge: spawn_blocking join: {e}"))
5841                })?
5842                .map_err(RuntimeError::Sqlite)?
5843            };
5844
5845            match outcome {
5846                SymmetricEdgeUpdateOutcome::Absorbed(sid) => {
5847                    // A conflict was absorbed (ADR-039 DO NOTHING): re-fetch the surviving
5848                    // canonical row so the caller receives its real, UNMODIFIED attributes —
5849                    // including soft-deleted rows, since the survivor's tombstone state (if
5850                    // any) must not be resurrected by the absorbed update either. Use
5851                    // record_tok — the surviving row lives in the same namespace as the
5852                    // original.
5853                    let surviving_uuid = Uuid::parse_str(&sid).map_err(|e| {
5854                        RuntimeError::Internal(format!(
5855                            "update_edge: surviving id parse failed: {e}"
5856                        ))
5857                    })?;
5858                    edge = self
5859                        .get_edge_including_deleted(&record_tok, surviving_uuid)
5860                        .await?
5861                        .ok_or_else(|| {
5862                            RuntimeError::Internal(format!(
5863                                "update_edge: surviving canonical row {surviving_uuid} vanished after update"
5864                            ))
5865                        })?;
5866                }
5867                SymmetricEdgeUpdateOutcome::Updated => {
5868                    // Reflect canonical endpoints in the returned edge (no conflict absorbed).
5869                    edge.source_id = canon_src;
5870                    edge.target_id = canon_tgt;
5871                }
5872                SymmetricEdgeUpdateOutcome::Stale => {
5873                    return Err(crate::curation::stale_edge_snapshot_error(edge_id));
5874                }
5875            }
5876        } else {
5877            // Non-symmetric: replace_edge_if_unchanged takes namespace from edge.namespace
5878            // (not from the graph store's routing namespace), so this is already
5879            // record-namespace correct. `graph` is already self.graph(&record_tok)?.
5880            // Guarded on the fetched snapshot's revision — a concurrent writer that moved
5881            // this edge between the fetch above and this write must be refused, not
5882            // silently overwritten by a full-row replacement derived from stale state.
5883            // `updated_at` must advance past the snapshot: the guard requires the
5884            // replacement revision to be strictly greater than the persisted one.
5885            // Make it strictly advance even when two operations land inside one
5886            // clock microsecond; saturating to i64::MAX would let the CAS accept
5887            // a write without advancing its revision, so that is not a valid
5888            // fallback (mirrors the note path).
5889            let minimum_updated_at_micros = expected_updated_at
5890                .timestamp_micros()
5891                .checked_add(1)
5892                .ok_or_else(|| {
5893                RuntimeError::Internal(format!(
5894                    "edge {edge_id} updated_at is already at i64::MAX and cannot advance"
5895                ))
5896            })?;
5897            let now_micros = chrono::Utc::now()
5898                .timestamp_micros()
5899                .max(minimum_updated_at_micros);
5900            edge.updated_at =
5901                chrono::DateTime::from_timestamp_micros(now_micros).ok_or_else(|| {
5902                    RuntimeError::Internal(format!(
5903                        "edge {edge_id}: computed updated_at {now_micros} is not a valid timestamp"
5904                    ))
5905                })?;
5906            let persisted = graph
5907                .replace_edge_if_unchanged(edge.clone(), expected_updated_at, expected_deleted_at)
5908                .await?;
5909            if !persisted {
5910                return Err(crate::curation::stale_edge_snapshot_error(edge_id));
5911            }
5912        }
5913
5914        // Audit event: use the record's namespace (record_ns) for the event payload.
5915        let event_store = self.events(&record_tok)?;
5916        let event = khive_storage::event::Event::new(
5917            record_ns.clone(),
5918            "update",
5919            EventKind::EdgeUpdated,
5920            SubstrateKind::Entity,
5921            "",
5922        )
5923        .with_target(edge_id)
5924        .with_payload(
5925            serde_json::json!({"id": edge_id, "namespace": record_ns, "changed_fields": changed_fields}),
5926        );
5927        event_store.append_event(event).await.map_err(|e| {
5928            RuntimeError::Internal(format!("update_edge: event store write failed: {e}"))
5929        })?;
5930
5931        Ok(edge)
5932    }
5933
5934    /// Hard-delete an edge by id.
5935    ///
5936    /// Cascades to remove any `annotates` edges whose target is the deleted edge
5937    /// (`annotates` is note → anything; deleting an edge target leaves annotation
5938    /// edges dangling if not cleaned up). Returns `true` if the primary
5939    /// edge was removed.
5940    ///
5941    /// If `edge_id` does not refer to an edge (e.g. the caller passes an entity or
5942    /// note UUID by mistake), this method returns `Ok(false)` immediately with no
5943    /// side effects — it does **not** cascade inbound edges of the non-edge record.
5944    pub async fn delete_edge(
5945        &self,
5946        token: &NamespaceToken,
5947        edge_id: Uuid,
5948        hard: bool,
5949    ) -> RuntimeResult<bool> {
5950        let mode = if hard {
5951            DeleteMode::Hard
5952        } else {
5953            DeleteMode::Soft
5954        };
5955
5956        // Fetch the edge first to obtain the record's own namespace.
5957        // By-ID ops cross namespace boundaries; all graph routing and audit
5958        // events must use the record namespace, not the caller's (mirrors update_edge).
5959        // For hard delete we also check soft-deleted rows so a soft-deleted edge
5960        // can still be purged via its edge ID.
5961        let edge = if hard {
5962            self.get_edge_including_deleted(token, edge_id).await?
5963        } else {
5964            self.get_edge(token, edge_id).await?
5965        };
5966        let Some(edge) = edge else {
5967            return Ok(false);
5968        };
5969
5970        // Derive record_ns / record_tok from the fetched edge (mirrors update_edge).
5971        let record_ns: String = edge.namespace.clone();
5972        let record_tok = NamespaceToken::for_namespace(
5973            khive_types::Namespace::parse(&record_ns)
5974                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5975        );
5976        let graph = self.graph(&record_tok)?;
5977        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
5978
5979        // Cascade: on hard delete, remove ALL annotates edges targeting this edge — including
5980        // already-soft-deleted ones: to prevent dangling graph_edges rows. The row
5981        // delete and the cascade purge run as ONE write transaction: see
5982        // `atomic_hard_delete_with_edge_purge`.
5983        // On soft delete the cascade is skipped (data-vs-view principle: soft-deleting the base
5984        // edge does not cascade to annotation edges; only a hard purge cleans up incident rows).
5985        let deleted = if hard {
5986            self.atomic_hard_delete_with_edge_purge(
5987                edge_hard_delete_statement(edge_id),
5988                edge_id,
5989                &record_ns,
5990                &actor,
5991                SubstrateKind::Entity,
5992            )
5993            .await?
5994        } else {
5995            graph.delete_edge(LinkId::from(edge_id), mode).await?
5996        };
5997        if deleted {
5998            // Audit event: use the record's namespace (record_ns), not the caller's namespace.
5999            let event_store = self.events(&record_tok)?;
6000            let event = khive_storage::event::Event::new(
6001                record_ns.clone(),
6002                "delete",
6003                EventKind::EdgeDeleted,
6004                SubstrateKind::Entity,
6005                "",
6006            )
6007            .with_target(edge_id)
6008            .with_payload(serde_json::json!({"id": edge_id, "namespace": record_ns, "hard": hard}));
6009            event_store.append_event(event).await.map_err(|e| {
6010                RuntimeError::Internal(format!("delete_edge: event store write failed: {e}"))
6011            })?;
6012        }
6013        Ok(deleted)
6014    }
6015
6016    /// Count edges matching `filter` across the caller's visible namespaces.
6017    pub async fn count_edges(
6018        &self,
6019        token: &NamespaceToken,
6020        filter: crate::curation::EdgeListFilter,
6021    ) -> RuntimeResult<u64> {
6022        let namespaces: Vec<String> = token
6023            .visible_namespaces()
6024            .iter()
6025            .map(|namespace| namespace.as_str().to_owned())
6026            .collect();
6027        let graph = self.graph(token)?;
6028        match graph
6029            .count_edges_in_namespaces(&namespaces, filter.clone().into())
6030            .await
6031        {
6032            Ok(count) => Ok(count),
6033            Err(khive_storage::StorageError::Unsupported { operation, .. })
6034                if operation == "count_edges_in_namespaces" =>
6035            {
6036                let mut total = 0;
6037                for namespace in token.visible_namespaces() {
6038                    let scoped = NamespaceToken::for_namespace(namespace.clone());
6039                    total += self
6040                        .graph(&scoped)?
6041                        .count_edges(filter.clone().into())
6042                        .await?;
6043                }
6044                Ok(total)
6045            }
6046            Err(error) => Err(error.into()),
6047        }
6048    }
6049
6050    /// Validate and construct an edge from a [`LinkSpec`] without writing to storage.
6051    ///
6052    /// Applies the full edge contract (endpoint validation, symmetric
6053    /// canonicalization, `dependency_kind` inference and metadata validation).
6054    /// Returns the constructed `Edge` on success; the caller is responsible for
6055    /// persisting it (e.g. via `upsert_edge` or `link_many`).
6056    ///
6057    /// The `token` must be a pre-authorized namespace token from the dispatch
6058    /// layer. If `spec.namespace` is set it must match `token.namespace()`;
6059    /// a mismatch returns `RuntimeError::InvalidInput`.
6060    pub async fn build_edge(&self, token: &NamespaceToken, spec: &LinkSpec) -> RuntimeResult<Edge> {
6061        let ns_str = match &spec.namespace {
6062            Some(s) => {
6063                let spec_ns = crate::Namespace::parse(s)
6064                    .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}")))?;
6065                if &spec_ns != token.namespace() {
6066                    return Err(RuntimeError::InvalidInput(
6067                        "LinkSpec namespace does not match token namespace".into(),
6068                    ));
6069                }
6070                s.as_str()
6071            }
6072            None => token.namespace().as_str(),
6073        };
6074        self.validate_edge_relation_endpoints(token, spec.source_id, spec.target_id, spec.relation)
6075            .await?;
6076        let (source_id, target_id) =
6077            canonical_edge_endpoints(spec.relation, spec.source_id, spec.target_id);
6078        let metadata = if spec.relation == EdgeRelation::DependsOn {
6079            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
6080            // above. The visible-set-scoped `resolve` would silently drop the
6081            // dependency_kind inference for endpoints validation now allows outside
6082            // the caller's visible set.
6083            match (
6084                self.resolve_edge_endpoint(token, source_id).await?,
6085                self.resolve_edge_endpoint(token, target_id).await?,
6086            ) {
6087                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
6088                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, spec.metadata.clone())
6089                }
6090                _ => spec.metadata.clone(),
6091            }
6092        } else {
6093            spec.metadata.clone()
6094        };
6095        validate_edge_metadata(spec.relation, metadata.as_ref())?;
6096        let now = chrono::Utc::now();
6097        Ok(Edge {
6098            id: LinkId::from(Uuid::new_v4()),
6099            namespace: ns_str.to_string(),
6100            source_id,
6101            target_id,
6102            relation: spec.relation,
6103            weight: spec.weight,
6104            created_at: now,
6105            updated_at: now,
6106            deleted_at: None,
6107            metadata,
6108            target_backend: None,
6109        })
6110    }
6111
6112    /// Validate and atomically upsert a batch of edges.
6113    ///
6114    /// All edges are validated and constructed with `build_edge` before any
6115    /// write. If validation fails for any entry the entire batch is rejected
6116    /// (no writes occur). On success, all edges are persisted in a single
6117    /// atomic transaction via `upsert_edges`.
6118    ///
6119    /// After the bulk upsert, each edge is read back by its natural key
6120    /// (namespace, source_id, target_id, relation) so that the returned IDs
6121    /// are always the persisted row IDs, not the locally-generated UUIDs that
6122    /// may have been displaced by an ON CONFLICT DO UPDATE. This mirrors the
6123    /// same read-back applied to singleton `link()` and prevents phantom-ID
6124    /// exposure when callers upsert overlapping triples with `verbose=true`.
6125    ///
6126    /// All specs must share the same namespace; the namespace is taken from
6127    /// `token` (or validated against it if `spec.namespace` is set).
6128    pub async fn link_many(
6129        &self,
6130        token: &NamespaceToken,
6131        specs: Vec<LinkSpec>,
6132    ) -> RuntimeResult<Vec<Edge>> {
6133        if specs.is_empty() {
6134            return Ok(vec![]);
6135        }
6136        let mut edges = Vec::with_capacity(specs.len());
6137        for spec in &specs {
6138            edges.push(self.build_edge(token, spec).await?);
6139        }
6140        // `upsert_edges_guarded` re-checks every edge's endpoints as part of the
6141        // same write, not the separate per-spec `build_edge` validation reads
6142        // above. A concurrent hard-delete of any endpoint landing between those
6143        // reads and this write aborts the whole batch (all-or-nothing, no
6144        // partial write) instead of persisting a dangling edge. The failing
6145        // entry's index and its missing endpoint(s) come from the guard's own
6146        // in-transaction pre-check (`GuardedBatchOutcome::refused`), not a
6147        // post-hoc re-read of the batch after the write already failed.
6148        let outcome = self
6149            .graph(token)?
6150            .upsert_edges_guarded(edges.clone())
6151            .await?;
6152        if let Some(refusal) = outcome.refused {
6153            return Err(RuntimeError::GuardedWriteFailed(GuardedWriteFailure {
6154                entry_index: Some(refusal.entry_index),
6155                missing_source: refusal
6156                    .missing
6157                    .source
6158                    .then_some(edges[refusal.entry_index].source_id),
6159                missing_target: refusal
6160                    .missing
6161                    .target
6162                    .then_some(edges[refusal.entry_index].target_id),
6163            }));
6164        }
6165        if outcome.summary.affected != edges.len() as u64 {
6166            return Err(RuntimeError::NotFound(format!(
6167                "link_many: one or more edge endpoints no longer exist at write time: {}",
6168                outcome.summary.first_error
6169            )));
6170        }
6171
6172        // Read back each persisted edge by natural key so callers always
6173        // receive the stored row ID, not the pre-upsert generated UUID.
6174        let mut persisted = Vec::with_capacity(edges.len());
6175        for edge in &edges {
6176            let row = self
6177                .list_edges(
6178                    token,
6179                    crate::curation::EdgeListFilter {
6180                        source_id: Some(edge.source_id),
6181                        target_id: Some(edge.target_id),
6182                        relations: vec![edge.relation],
6183                        ..Default::default()
6184                    },
6185                    1,
6186                    0,
6187                )
6188                .await?
6189                .into_iter()
6190                .next()
6191                .ok_or_else(|| {
6192                    crate::RuntimeError::Internal(format!(
6193                        "upsert_edges succeeded but natural-key lookup for ({}, {}, {}) returned nothing",
6194                        edge.source_id, edge.target_id, edge.relation.as_str()
6195                    ))
6196                })?;
6197            persisted.push(row);
6198        }
6199        Ok(persisted)
6200    }
6201
6202    /// Create a batch of entities atomically.
6203    ///
6204    /// All specs are validated before any write. If ANY spec fails validation
6205    /// (unknown kind, empty name, secret-gate violation), the method returns
6206    /// that error and no entities are written.
6207    ///
6208    /// Entity rows and their FTS documents are written in one SQLite transaction.
6209    /// Any statement failure rolls back the entire batch across both surfaces.
6210    /// Embedding is intentionally skipped: bulk structural ingest is the expected
6211    /// use-case, and dense vectors are backfilled later via a `reindex` call.
6212    pub async fn create_many(
6213        &self,
6214        token: &NamespaceToken,
6215        specs: Vec<EntityCreateSpec>,
6216    ) -> RuntimeResult<Vec<Entity>> {
6217        if specs.is_empty() {
6218            return Ok(vec![]);
6219        }
6220        let ns = token.namespace().as_str();
6221
6222        // Phase 1: validate ALL specs before any write.
6223        // Includes entity-type validation via the pack-installed validator when available.
6224        // Any validation failure here guarantees zero rows are written.
6225        let mut entities = Vec::with_capacity(specs.len());
6226        for spec in &specs {
6227            self.validate_entity_kind(&spec.kind)?;
6228            // Validate entity_type at the runtime layer via pack-installed callback.
6229            // When no validator is installed (bare runtime, unit tests without packs),
6230            // the type passes through unchanged — same skip-when-absent pattern as
6231            // validate_entity_kind. The handler layer remains the primary enforcement point.
6232            let validated_type =
6233                self.validate_entity_type_for_kind(&spec.kind, spec.entity_type.as_deref())?;
6234            if spec.name.trim().is_empty() {
6235                return Err(RuntimeError::InvalidInput("name must not be empty".into()));
6236            }
6237            crate::secret_gate::reject_reserved_secret_gate_property(spec.properties.as_ref())?;
6238            crate::secret_gate::check(&spec.name)?;
6239            if let Some(d) = &spec.description {
6240                crate::secret_gate::check(d)?;
6241            }
6242            if let Some(ref p) = spec.properties {
6243                crate::secret_gate::check_json(p)?;
6244            }
6245            crate::secret_gate::check_tags(&spec.tags)?;
6246
6247            let mut entity =
6248                Entity::new(ns, &spec.kind, &spec.name).with_entity_type(validated_type.as_deref());
6249            if let Some(d) = &spec.description {
6250                entity = entity.with_description(d);
6251            }
6252            if let Some(p) = spec.properties.clone() {
6253                entity = entity.with_properties(p);
6254            }
6255            if !spec.tags.is_empty() {
6256                entity = entity.with_tags(spec.tags.clone());
6257            }
6258            entities.push(entity);
6259        }
6260
6261        #[cfg(any(test, feature = "fault-injection"))]
6262        let fts_many_inject = consume_fault(&FTS_FAIL_MANY_NS, ns);
6263        #[cfg(not(any(test, feature = "fault-injection")))]
6264        let fts_many_inject = false;
6265
6266        #[cfg(any(test, feature = "fault-injection"))]
6267        let fts_many_inject_partial = consume_fault(&FTS_FAIL_MANY_PARTIAL_NS, ns);
6268        #[cfg(not(any(test, feature = "fault-injection")))]
6269        let fts_many_inject_partial = false;
6270
6271        let injected_failure_index = if fts_many_inject {
6272            Some(0)
6273        } else if fts_many_inject_partial {
6274            Some(usize::from(entities.len() > 1))
6275        } else {
6276            None
6277        };
6278
6279        let _ = self.entities(token)?;
6280        let _ = self.text(token)?;
6281
6282        let plans = entities
6283            .iter()
6284            .enumerate()
6285            .map(|(index, entity)| {
6286                let mut fts_statement =
6287                    insert_document_statement("fts_entities", &entity_fts_document(entity));
6288                if injected_failure_index == Some(index) {
6289                    fts_statement = SqlStatement {
6290                        sql: "INSERT INTO __khive_create_many_injected_failure__ DEFAULT VALUES"
6291                            .to_string(),
6292                        params: vec![],
6293                        label: Some("fts-insert-injected-failure".to_string()),
6294                    };
6295                }
6296                AtomicOpPlan::AddEntity(AddEntityPlan {
6297                    entity_id: entity.id,
6298                    statements: vec![
6299                        PlanStatement {
6300                            statement: entity_upsert_statement(entity),
6301                            guard: Some(AffectedRowGuard::exactly(1)),
6302                        },
6303                        PlanStatement {
6304                            statement: fts_statement,
6305                            guard: None,
6306                        },
6307                    ],
6308                    post_commit: PostCommitEffect::None,
6309                })
6310            })
6311            .collect();
6312
6313        match run_atomic_unit(self.sql().as_ref(), plans).await {
6314            Ok(AtomicRunOutcome::Committed { .. }) => Ok(entities),
6315            Ok(AtomicRunOutcome::RolledBack {
6316                failed_op_index,
6317                failure,
6318            }) => Err(RuntimeError::Internal(format!(
6319                "create_many: atomic batch rolled back at entity index {failed_op_index}: \
6320                 {failure:?}"
6321            ))),
6322            Err(e) => Err(RuntimeError::Internal(format!(
6323                "create_many: atomic batch failed: {}",
6324                e.0
6325            ))),
6326        }
6327    }
6328}
6329
6330/// Fully specified edge creation request — input to [`KhiveRuntime::build_edge`]
6331/// and [`KhiveRuntime::link_many`].
6332#[derive(Clone, Debug)]
6333pub struct LinkSpec {
6334    pub namespace: Option<String>,
6335    pub source_id: Uuid,
6336    pub target_id: Uuid,
6337    pub relation: EdgeRelation,
6338    pub weight: f64,
6339    pub metadata: Option<serde_json::Value>,
6340}
6341
6342/// Fully specified entity creation request — input to [`KhiveRuntime::create_many`].
6343///
6344/// `entity_type` is validated at the runtime layer by the pack-installed
6345/// entity-type validator. When a validator
6346/// is installed (e.g. by `KgPack`), unknown types are rejected with the valid
6347/// set listed. When no validator is installed (bare runtime without packs),
6348/// the value passes through — the handler layer is the primary enforcement point.
6349#[derive(Clone, Debug)]
6350pub struct EntityCreateSpec {
6351    pub kind: String,
6352    pub entity_type: Option<String>,
6353    pub name: String,
6354    pub description: Option<String>,
6355    pub properties: Option<serde_json::Value>,
6356    pub tags: Vec<String>,
6357}
6358
6359// INLINE TEST JUSTIFICATION: tests here exercise private helpers (canonical_edge_endpoints,
6360// validate_edge_metadata, merge_dependency_kind, link-fail injection) and runtime methods
6361// that require pub(crate) KhiveRuntime construction. Moving them to tests/ would require
6362// pub-exporting those private helpers, which would widen the crate's public API surface
6363// undesirably. Broad behavioral tests live in tests/integration.rs.
6364#[cfg(test)]
6365mod tests {
6366    use super::*;
6367    use crate::curation::EdgeListFilter;
6368    use crate::embedder_registry::{BlockingEmbeddingService, EmbedderProvider};
6369    use crate::error::RuntimeError;
6370    use crate::runtime::{KhiveRuntime, NamespaceToken};
6371    use crate::{ActorRef, Namespace};
6372    use async_trait::async_trait;
6373    use khive_storage::types::{PathNode, SqlValue};
6374    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_BYTES};
6375    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6376    use std::sync::Arc;
6377
6378    fn rt() -> KhiveRuntime {
6379        KhiveRuntime::memory().unwrap()
6380    }
6381
6382    #[tokio::test]
6383    async fn resolve_prefix_query_plan_uses_primary_key_range_seeks() {
6384        let rt = rt();
6385        let mut reader = rt.sql().reader().await.expect("prefix plan reader");
6386        let mut plans = Vec::new();
6387        let (lower, upper) =
6388            super::uuid_prefix_bounds("0b6cf134").expect("valid compact UUID prefix");
6389
6390        for (table, has_deleted_at) in [
6391            ("entities", true),
6392            ("notes", true),
6393            ("events", false),
6394            ("graph_edges", false),
6395        ] {
6396            let rows = reader
6397                .explain(super::resolve_prefix_statement(
6398                    table,
6399                    has_deleted_at,
6400                    false,
6401                    None,
6402                    &lower,
6403                    &upper,
6404                ))
6405                .await
6406                .expect("explain prefix query");
6407            let details: Vec<String> = rows
6408                .iter()
6409                .filter_map(|row| match row.get("detail") {
6410                    Some(SqlValue::Text(detail)) => Some(detail.clone()),
6411                    _ => None,
6412                })
6413                .collect();
6414            plans.push((table, details));
6415        }
6416
6417        assert!(
6418            plans.iter().all(|(table, details)| {
6419                details.iter().any(|detail| {
6420                    detail.contains(&format!("SEARCH {table}"))
6421                        && detail.contains("id>?")
6422                        && detail.contains("id<?")
6423                }) && !details
6424                    .iter()
6425                    .any(|detail| detail.contains(&format!("SCAN {table}")))
6426            }),
6427            "every short-id table must use a primary-key range seek: {plans:?}"
6428        );
6429    }
6430
6431    #[test]
6432    fn fts_fault_arm_disarms_namespace_when_scope_panics() {
6433        let ns = format!("fault-arm-drop-{}", uuid::Uuid::new_v4().as_simple());
6434
6435        let panic_result = std::panic::catch_unwind(|| {
6436            let _arm = arm_fts_fail_scoped(&ns);
6437            panic!("leave the armed scope before consumption");
6438        });
6439
6440        assert!(panic_result.is_err());
6441        assert!(
6442            !consume_fault(&FTS_FAIL_NS, &ns),
6443            "unwinding an armed scope must remove its namespace"
6444        );
6445    }
6446
6447    #[test]
6448    fn fault_arm_set_rejects_entries_over_capacity() {
6449        static BOUNDED_ARMS: std::sync::LazyLock<FaultArmSet> =
6450            std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
6451        let first_ns = format!("fault-arm-bound-a-{}", uuid::Uuid::new_v4().as_simple());
6452        let overflow_ns = format!("fault-arm-bound-b-{}", uuid::Uuid::new_v4().as_simple());
6453        let arm = arm_fault(&BOUNDED_ARMS, &first_ns, 1);
6454
6455        let overflow = std::panic::catch_unwind(|| arm_fault(&BOUNDED_ARMS, &overflow_ns, 1));
6456
6457        assert!(
6458            overflow.is_err(),
6459            "an arm set must reject entries over its bound"
6460        );
6461        drop(arm);
6462        assert!(BOUNDED_ARMS.lock().unwrap().is_empty());
6463    }
6464
6465    // ── Custom embedder fan-out regression ──────────────────────────────────
6466    // A runtime with no `config.embedding_model` but a custom registered
6467    // embedder must fan out create_note through that embedder and store a
6468    // vector so recall can find the note.
6469
6470    /// Trivial constant-vector embedding service.  The model argument is ignored;
6471    /// the service always returns a synthetic `dims × 1.0f32` vector.
6472    struct ConstVecService {
6473        dims: usize,
6474    }
6475
6476    #[async_trait]
6477    impl EmbeddingService for ConstVecService {
6478        async fn embed(
6479            &self,
6480            texts: &[String],
6481            _model: EmbeddingModel,
6482        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6483            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6484        }
6485
6486        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6487            true
6488        }
6489
6490        fn name(&self) -> &'static str {
6491            "const-vec"
6492        }
6493    }
6494
6495    struct ConstVecProvider {
6496        provider_name: String,
6497        dims: usize,
6498        pub build_count: Arc<AtomicUsize>,
6499    }
6500
6501    impl ConstVecProvider {
6502        fn new(name: &str, dims: usize) -> (Self, Arc<AtomicUsize>) {
6503            let counter = Arc::new(AtomicUsize::new(0));
6504            let provider = Self {
6505                provider_name: name.to_owned(),
6506                dims,
6507                build_count: Arc::clone(&counter),
6508            };
6509            (provider, counter)
6510        }
6511    }
6512
6513    #[async_trait]
6514    impl EmbedderProvider for ConstVecProvider {
6515        fn name(&self) -> &str {
6516            &self.provider_name
6517        }
6518
6519        fn dimensions(&self) -> usize {
6520            self.dims
6521        }
6522
6523        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6524            self.build_count.fetch_add(1, Ordering::SeqCst);
6525            Ok(Arc::new(ConstVecService { dims: self.dims }))
6526        }
6527    }
6528
6529    /// Embedding service that sleeps briefly before returning, so its spawned
6530    /// embed task is still in flight when a sibling model's task resolves
6531    /// first — used to exercise the drain-before-return invariant on the
6532    /// multi-model embed fan-out.
6533    struct SlowVecService {
6534        dims: usize,
6535    }
6536
6537    #[async_trait]
6538    impl EmbeddingService for SlowVecService {
6539        async fn embed(
6540            &self,
6541            texts: &[String],
6542            _model: EmbeddingModel,
6543        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6544            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
6545            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6546        }
6547
6548        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6549            true
6550        }
6551
6552        fn name(&self) -> &'static str {
6553            "slow-vec"
6554        }
6555    }
6556
6557    struct SlowVecProvider {
6558        provider_name: String,
6559        dims: usize,
6560    }
6561
6562    impl SlowVecProvider {
6563        fn new(name: &str, dims: usize) -> Self {
6564            Self {
6565                provider_name: name.to_owned(),
6566                dims,
6567            }
6568        }
6569    }
6570
6571    #[async_trait]
6572    impl EmbedderProvider for SlowVecProvider {
6573        fn name(&self) -> &str {
6574            &self.provider_name
6575        }
6576
6577        fn dimensions(&self) -> usize {
6578            self.dims
6579        }
6580
6581        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6582            Ok(Arc::new(SlowVecService { dims: self.dims }))
6583        }
6584    }
6585
6586    /// Embedder that fails inference immediately unless configured to wait for
6587    /// a sibling's entry signal first.
6588    struct FailFastProvider {
6589        provider_name: String,
6590        wait_for: Option<Arc<AtomicBool>>,
6591    }
6592
6593    impl FailFastProvider {
6594        fn new(name: &str) -> Self {
6595            Self {
6596                provider_name: name.to_owned(),
6597                wait_for: None,
6598            }
6599        }
6600
6601        fn after_signal(name: &str, wait_for: Arc<AtomicBool>) -> Self {
6602            Self {
6603                provider_name: name.to_owned(),
6604                wait_for: Some(wait_for),
6605            }
6606        }
6607    }
6608
6609    #[async_trait]
6610    impl EmbedderProvider for FailFastProvider {
6611        fn name(&self) -> &str {
6612            &self.provider_name
6613        }
6614
6615        fn dimensions(&self) -> usize {
6616            4
6617        }
6618
6619        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6620            Ok(Arc::new(FailFastService {
6621                wait_for: self.wait_for.clone(),
6622            }))
6623        }
6624    }
6625
6626    struct FailFastService {
6627        wait_for: Option<Arc<AtomicBool>>,
6628    }
6629
6630    #[async_trait]
6631    impl EmbeddingService for FailFastService {
6632        async fn embed(
6633            &self,
6634            _texts: &[String],
6635            _model: EmbeddingModel,
6636        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6637            if let Some(wait_for) = &self.wait_for {
6638                while !wait_for.load(Ordering::Acquire) {
6639                    tokio::task::yield_now().await;
6640                }
6641            }
6642            Err(EmbedError::InferenceFailed(
6643                "injected embed failure".to_string(),
6644            ))
6645        }
6646
6647        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6648            true
6649        }
6650
6651        fn name(&self) -> &'static str {
6652            "fail-fast"
6653        }
6654    }
6655
6656    /// Embedder whose synchronous inference section is controlled by a
6657    /// condition variable, matching native inference that cannot observe task
6658    /// cancellation until the encode call returns.
6659    struct BlockingVecProvider {
6660        provider_name: String,
6661        dims: usize,
6662        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6663        entered: Arc<AtomicBool>,
6664    }
6665
6666    struct BlockingVecControls {
6667        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6668        entered: Arc<AtomicBool>,
6669    }
6670
6671    impl BlockingVecProvider {
6672        fn new(name: &str, dims: usize) -> (Self, BlockingVecControls) {
6673            let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
6674            let entered = Arc::new(AtomicBool::new(false));
6675            (
6676                Self {
6677                    provider_name: name.to_owned(),
6678                    dims,
6679                    release: Arc::clone(&release),
6680                    entered: Arc::clone(&entered),
6681                },
6682                BlockingVecControls { release, entered },
6683            )
6684        }
6685    }
6686
6687    #[async_trait]
6688    impl EmbedderProvider for BlockingVecProvider {
6689        fn name(&self) -> &str {
6690            &self.provider_name
6691        }
6692
6693        fn dimensions(&self) -> usize {
6694            self.dims
6695        }
6696
6697        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6698            let service = Arc::new(BlockingVecService {
6699                dims: self.dims,
6700                release: Arc::clone(&self.release),
6701                entered: Arc::clone(&self.entered),
6702            });
6703            Ok(Arc::new(BlockingEmbeddingService::new(service)))
6704        }
6705    }
6706
6707    struct BlockingVecService {
6708        dims: usize,
6709        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6710        entered: Arc<AtomicBool>,
6711    }
6712
6713    #[async_trait]
6714    impl EmbeddingService for BlockingVecService {
6715        async fn embed(
6716            &self,
6717            texts: &[String],
6718            _model: EmbeddingModel,
6719        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6720            self.entered.store(true, Ordering::Release);
6721            let (released, wake) = &*self.release;
6722            let guard = released.lock().expect("release lock must not be poisoned");
6723            let _guard = wake
6724                .wait_while(guard, |released| !*released)
6725                .expect("release lock must not be poisoned");
6726            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6727        }
6728
6729        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6730            true
6731        }
6732
6733        fn name(&self) -> &'static str {
6734            "blocking-vec"
6735        }
6736    }
6737
6738    /// Embedder whose `embed` parks until a release that never comes — models
6739    /// a hung provider. Only task abort can end its embed future. `entered`
6740    /// receives a permit when `embed` is reached, so a test can wait until the
6741    /// parked task is provably past the dispatch point before acting on it.
6742    struct ParkedVecProvider {
6743        provider_name: String,
6744        dims: usize,
6745        release: Arc<tokio::sync::Notify>,
6746        entered: Arc<tokio::sync::Notify>,
6747    }
6748
6749    impl ParkedVecProvider {
6750        fn new(
6751            name: &str,
6752            dims: usize,
6753        ) -> (Self, Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
6754            let release = Arc::new(tokio::sync::Notify::new());
6755            let entered = Arc::new(tokio::sync::Notify::new());
6756            (
6757                Self {
6758                    provider_name: name.to_owned(),
6759                    dims,
6760                    release: Arc::clone(&release),
6761                    entered: Arc::clone(&entered),
6762                },
6763                release,
6764                entered,
6765            )
6766        }
6767    }
6768
6769    #[async_trait]
6770    impl EmbedderProvider for ParkedVecProvider {
6771        fn name(&self) -> &str {
6772            &self.provider_name
6773        }
6774
6775        fn dimensions(&self) -> usize {
6776            self.dims
6777        }
6778
6779        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6780            Ok(Arc::new(ParkedVecService {
6781                dims: self.dims,
6782                release: Arc::clone(&self.release),
6783                entered: Arc::clone(&self.entered),
6784            }))
6785        }
6786    }
6787
6788    struct ParkedVecService {
6789        dims: usize,
6790        release: Arc<tokio::sync::Notify>,
6791        entered: Arc<tokio::sync::Notify>,
6792    }
6793
6794    #[async_trait]
6795    impl EmbeddingService for ParkedVecService {
6796        async fn embed(
6797            &self,
6798            texts: &[String],
6799            _model: EmbeddingModel,
6800        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6801            // notify_one stores a permit when no waiter is registered yet, so
6802            // the entered signal cannot be lost to a start-order race.
6803            self.entered.notify_one();
6804            self.release.notified().await;
6805            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6806        }
6807
6808        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6809            true
6810        }
6811
6812        fn name(&self) -> &'static str {
6813            "parked-vec"
6814        }
6815    }
6816
6817    /// Custom embedder with no lattice model in config must participate in
6818    /// fan-out: the gate must check `registered_embedding_model_names()`, not
6819    /// `config().embedding_model.is_some()`: the latter falls through to
6820    /// `vec![]` when only a custom provider is registered.
6821    #[tokio::test]
6822    async fn custom_embedder_only_runtime_fanout_stores_vector() {
6823        const MODEL_NAME: &str = "test-custom-encoder";
6824        const DIMS: usize = 8;
6825
6826        // Build a runtime with no lattice embedding_model.
6827        let rt = KhiveRuntime::memory().unwrap();
6828
6829        // Register the custom provider — this is the only embedder configured.
6830        let (provider, _counter) = ConstVecProvider::new(MODEL_NAME, DIMS);
6831        rt.register_embedder(provider);
6832
6833        // Sanity: config.embedding_model is None, but the registry has one entry.
6834        assert!(rt.config().embedding_model.is_none());
6835        assert_eq!(rt.registered_embedding_model_names(), vec![MODEL_NAME]);
6836
6837        let tok = NamespaceToken::local();
6838
6839        // create_note should fan out to the custom embedder and store a vector.
6840        let note = rt
6841            .create_note(
6842                &tok,
6843                "memory",
6844                None,
6845                "custom embedder integration test content",
6846                Some(0.7),
6847                None,
6848                vec![],
6849            )
6850            .await
6851            .expect("create_note with custom-only embedder must succeed");
6852
6853        // Verify: a vector was written in the custom model's store.
6854        use khive_storage::types::VectorSearchRequest;
6855        let query_vec = vec![1.0_f32; DIMS];
6856        let hits = rt
6857            .vectors_for_model(&tok, MODEL_NAME)
6858            .expect("vector store for custom model must be accessible")
6859            .search(VectorSearchRequest {
6860                query_vectors: vec![query_vec],
6861                top_k: 5,
6862                namespace: Some(tok.namespace().as_str().to_string()),
6863                kind: Some(khive_types::SubstrateKind::Note),
6864                embedding_model: Some(MODEL_NAME.to_string()),
6865                filter: None,
6866                backend_hints: None,
6867            })
6868            .await
6869            .expect("vector search succeeds");
6870
6871        assert!(
6872            hits.iter().any(|h| h.subject_id == note.id),
6873            "custom embedder must have written a vector for note {}: hits={hits:?}",
6874            note.id
6875        );
6876    }
6877
6878    /// Custom-only embedder participates in `embed_with_model` so recall
6879    /// fan-out also works: the lattice alias parse must be optional, with
6880    /// the embedder registry consulted directly, since requiring a lattice
6881    /// alias would reject valid custom provider names with `UnknownModel`.
6882    #[tokio::test]
6883    async fn embed_with_model_accepts_custom_provider_name() {
6884        const MODEL_NAME: &str = "my-custom-enc";
6885        const DIMS: usize = 4;
6886
6887        let rt = KhiveRuntime::memory().unwrap();
6888        let (provider, _counter) = ConstVecProvider::new(MODEL_NAME, DIMS);
6889        rt.register_embedder(provider);
6890
6891        let result = rt
6892            .embed_with_model(MODEL_NAME, "hello world")
6893            .await
6894            .expect("embed_with_model must accept custom provider names");
6895
6896        assert_eq!(
6897            result.len(),
6898            DIMS,
6899            "embedding dimension must match provider"
6900        );
6901        assert!(
6902            result.iter().all(|&v| (v - 1.0_f32).abs() < 1e-6),
6903            "ConstVecService must produce all-ones vector; got: {result:?}"
6904        );
6905    }
6906
6907    /// `embed_with_model` must still reject names that are not in the
6908    /// registry (neither lattice aliases nor custom providers).
6909    #[tokio::test]
6910    async fn embed_with_model_rejects_unregistered_name() {
6911        let rt = KhiveRuntime::memory().unwrap();
6912        let result = rt.embed_with_model("nonexistent-model", "hello").await;
6913        assert!(
6914            matches!(result.unwrap_err(), RuntimeError::UnknownModel(ref n) if n == "nonexistent-model"),
6915            "unregistered model name must return UnknownModel"
6916        );
6917    }
6918
6919    // ── No-embeddings config regression ─────────────────────────────────────
6920    // `RuntimeConfig::no_embeddings()` must register zero embedders, so
6921    // `create_note` never attempts to lazily build a lattice embedding model —
6922    // this is what lets `memory.remember` succeed on a machine with no local
6923    // model files present.
6924
6925    #[tokio::test]
6926    async fn no_embeddings_config_registers_zero_embedders() {
6927        let config = crate::config::RuntimeConfig {
6928            db_path: None,
6929            packs: vec!["kg".to_string()],
6930            ..crate::config::RuntimeConfig::no_embeddings()
6931        };
6932        let rt = KhiveRuntime::new(config).expect("runtime construction must succeed");
6933
6934        assert!(rt.config().embedding_model.is_none());
6935        assert!(
6936            rt.registered_embedding_model_names().is_empty(),
6937            "no_embeddings() runtime must register zero embedders"
6938        );
6939    }
6940
6941    #[tokio::test]
6942    async fn no_embeddings_runtime_create_note_succeeds_without_model_fanout() {
6943        let config = crate::config::RuntimeConfig {
6944            db_path: None,
6945            packs: vec!["kg".to_string()],
6946            ..crate::config::RuntimeConfig::no_embeddings()
6947        };
6948        let rt = KhiveRuntime::new(config).expect("runtime construction must succeed");
6949        let tok = NamespaceToken::local();
6950
6951        // With zero registered embedders, create_note's embed fan-out list is
6952        // empty and no lattice model build is ever attempted -- the write must
6953        // succeed, degrading to FTS-only.
6954        let note = rt
6955            .create_note(
6956                &tok,
6957                "memory",
6958                None,
6959                "issue-396 regression: model-less remember must succeed",
6960                Some(0.7),
6961                None,
6962                vec![],
6963            )
6964            .await
6965            .expect("create_note must succeed with zero registered embedders");
6966
6967        assert_eq!(
6968            note.content,
6969            "issue-396 regression: model-less remember must succeed"
6970        );
6971    }
6972
6973    #[tokio::test]
6974    async fn update_edge_changes_weight() {
6975        let rt = rt();
6976        let tok = NamespaceToken::local();
6977        let a = rt
6978            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6979            .await
6980            .unwrap();
6981        let b = rt
6982            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6983            .await
6984            .unwrap();
6985        let edge = rt
6986            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6987            .await
6988            .unwrap();
6989        let edge_id: Uuid = edge.id.into();
6990
6991        let updated = rt
6992            .update_edge(
6993                &tok,
6994                edge_id,
6995                crate::curation::EdgePatch {
6996                    weight: Some(0.5),
6997                    ..Default::default()
6998                },
6999            )
7000            .await
7001            .unwrap();
7002        assert!((updated.weight - 0.5).abs() < 0.001);
7003    }
7004
7005    /// Regression for the non-symmetric edge lost-update race (khive #1753).
7006    /// Two readers fetch the SAME edge revision (nothing else writes between
7007    /// these two `get_edge` calls, so this is a deterministic "two reads from
7008    /// one revision", not a timing assumption), each derives an independent
7009    /// patch (weight vs. metadata), and the two writes commit in a fixed
7010    /// order. Before the guarded `replace_edge_if_unchanged` primitive,
7011    /// `update_edge`'s non-symmetric branch called the unconditional
7012    /// `graph.upsert_edge`, so both commits "succeeded" and B's write
7013    /// silently discarded A's weight change. This reddens if the
7014    /// `updated_at = ?11 AND deleted_at IS ?12 AND ?6 > updated_at` predicate
7015    /// is dropped from `edge_replace_if_unchanged_statement`: B's write would
7016    /// then also return `true` and A's weight update would be lost.
7017    ///
7018    /// SCOPE: this exercises the STORE PRIMITIVE directly and never invokes
7019    /// `update_edge`, so it stays green if the production caller is reverted
7020    /// to an unconditional write. The wiring is covered separately by
7021    /// `production_update_edge_non_symmetric_refuses_concurrent_stale_writer`;
7022    /// both are required, neither substitutes for the other.
7023    #[tokio::test]
7024    async fn concurrent_edge_patches_from_one_revision_only_one_survives() {
7025        let rt = rt();
7026        let tok = NamespaceToken::local();
7027        let a = rt
7028            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7029            .await
7030            .unwrap();
7031        let b = rt
7032            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7033            .await
7034            .unwrap();
7035        let edge = rt
7036            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.5, None)
7037            .await
7038            .unwrap();
7039        let edge_id: Uuid = edge.id.into();
7040
7041        let graph = rt.graph(&tok).expect("graph store");
7042        let snapshot_for_a = graph
7043            .get_edge(LinkId::from(edge_id))
7044            .await
7045            .unwrap()
7046            .expect("edge exists");
7047        let snapshot_for_b = graph
7048            .get_edge(LinkId::from(edge_id))
7049            .await
7050            .unwrap()
7051            .expect("edge exists");
7052        assert_eq!(
7053            snapshot_for_a.updated_at, snapshot_for_b.updated_at,
7054            "both readers must observe the same pre-write revision for this to be a real race"
7055        );
7056        let expected_updated_at = snapshot_for_a.updated_at;
7057        let expected_deleted_at = snapshot_for_a.deleted_at;
7058
7059        let mut edge_a = snapshot_for_a;
7060        edge_a.weight = 0.9;
7061        edge_a.updated_at = expected_updated_at + chrono::Duration::microseconds(1);
7062
7063        let mut edge_b = snapshot_for_b;
7064        edge_b.metadata = Some(serde_json::json!({"note": "from B"}));
7065        edge_b.updated_at = expected_updated_at + chrono::Duration::microseconds(1);
7066
7067        assert!(
7068            graph
7069                .replace_edge_if_unchanged(edge_a, expected_updated_at, expected_deleted_at)
7070                .await
7071                .expect("writer A CAS query"),
7072            "the first committer from a shared revision must win"
7073        );
7074        assert!(
7075            !graph
7076                .replace_edge_if_unchanged(edge_b, expected_updated_at, expected_deleted_at)
7077                .await
7078                .expect("writer B CAS query"),
7079            "the second committer from the SAME stale revision must be refused, not merged"
7080        );
7081
7082        let final_edge = graph
7083            .get_edge(LinkId::from(edge_id))
7084            .await
7085            .unwrap()
7086            .expect("edge still exists");
7087        assert!(
7088            (final_edge.weight - 0.9).abs() < 0.001,
7089            "writer A's weight change must survive: {final_edge:?}"
7090        );
7091        assert!(
7092            final_edge.metadata.is_none(),
7093            "writer B's metadata must not be silently merged into the persisted row: {final_edge:?}"
7094        );
7095    }
7096
7097    /// Same race as `concurrent_edge_patches_from_one_revision_only_one_survives`,
7098    /// but driven entirely through the PRODUCTION entry point (`update_edge`,
7099    /// non-symmetric branch) rather than `replace_edge_if_unchanged` directly.
7100    /// This closes a gap the primitive-level test cannot: it would still pass
7101    /// unchanged if `update_edge` were reverted to an unconditional write,
7102    /// since it never invokes `update_edge` at all. Uses
7103    /// `crate::curation::race_seam::pause_after_read` (test-only, compiled
7104    /// out of non-test builds) to force both concurrent callers to observe
7105    /// the identical pre-write revision deterministically — no sleeps, no
7106    /// reliance on scheduler ordering.
7107    #[tokio::test]
7108    async fn production_update_edge_non_symmetric_refuses_concurrent_stale_writer() {
7109        let rt = std::sync::Arc::new(rt());
7110        let tok = NamespaceToken::local();
7111        let a = rt
7112            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7113            .await
7114            .unwrap();
7115        let b = rt
7116            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7117            .await
7118            .unwrap();
7119        let edge = rt
7120            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.5, None)
7121            .await
7122            .unwrap();
7123        let edge_id: Uuid = edge.id.into();
7124
7125        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
7126
7127        let writer_a = {
7128            let rt = std::sync::Arc::clone(&rt);
7129            let tok = tok.clone();
7130            let barrier = std::sync::Arc::clone(&barrier);
7131            tokio::spawn(crate::curation::race_seam::AFTER_READ_BARRIER.scope(
7132                barrier,
7133                async move {
7134                    rt.update_edge(
7135                        &tok,
7136                        edge_id,
7137                        crate::curation::EdgePatch {
7138                            weight: Some(0.9),
7139                            ..Default::default()
7140                        },
7141                    )
7142                    .await
7143                },
7144            ))
7145        };
7146        let writer_b = {
7147            let rt = std::sync::Arc::clone(&rt);
7148            let tok = tok.clone();
7149            let barrier = std::sync::Arc::clone(&barrier);
7150            tokio::spawn(crate::curation::race_seam::AFTER_READ_BARRIER.scope(
7151                barrier,
7152                async move {
7153                    rt.update_edge(
7154                        &tok,
7155                        edge_id,
7156                        crate::curation::EdgePatch {
7157                            properties: Some(serde_json::json!({"note": "from B"})),
7158                            ..Default::default()
7159                        },
7160                    )
7161                    .await
7162                },
7163            ))
7164        };
7165
7166        let result_a = writer_a.await.expect("writer A task");
7167        let result_b = writer_b.await.expect("writer B task");
7168        let successes = [result_a.is_ok(), result_b.is_ok()]
7169            .into_iter()
7170            .filter(|ok| *ok)
7171            .count();
7172        assert_eq!(
7173            successes, 1,
7174            "exactly one production caller must win the race; the other must be refused: \
7175             a={result_a:?} b={result_b:?}"
7176        );
7177        let refused = if result_a.is_err() {
7178            result_a
7179        } else {
7180            result_b
7181        };
7182        match &refused {
7183            Err(RuntimeError::Khive(khive_error)) => {
7184                assert_eq!(
7185                    khive_error.kind(),
7186                    khive_types::ErrorKind::Conflict,
7187                    "the losing production caller must surface a typed conflict, not \
7188                     silently overwrite: {refused:?}"
7189                );
7190            }
7191            other => panic!("expected a typed conflict error, got {other:?}"),
7192        }
7193
7194        let final_edge = rt
7195            .graph(&tok)
7196            .expect("graph store")
7197            .get_edge(LinkId::from(edge_id))
7198            .await
7199            .unwrap()
7200            .expect("edge still exists");
7201        assert!(
7202            !((final_edge.weight - 0.9).abs() < 0.001 && final_edge.metadata.is_some()),
7203            "both racers' changes must never both land: that would mean the loser's stale \
7204             write silently succeeded: {final_edge:?}"
7205        );
7206    }
7207
7208    /// Symmetric-relation counterpart of
7209    /// `production_update_edge_non_symmetric_refuses_concurrent_stale_writer`:
7210    /// two production `update_edge` callers race a `competes_with` edge from
7211    /// the same pre-write revision. Before the symmetric CAS guard, the
7212    /// in-place `UPDATE` carried no expected-revision predicate, so both
7213    /// commits would "succeed" and the second would silently discard the
7214    /// first's weight change — this reddens if that guard (or its wiring
7215    /// into `update_edge_symmetric_dml`) regresses.
7216    #[tokio::test]
7217    async fn production_update_edge_symmetric_refuses_concurrent_stale_writer() {
7218        let rt = std::sync::Arc::new(rt());
7219        let tok = NamespaceToken::local();
7220        let a = rt
7221            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7222            .await
7223            .unwrap();
7224        let b = rt
7225            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7226            .await
7227            .unwrap();
7228        let edge = rt
7229            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.5, None)
7230            .await
7231            .unwrap();
7232        let edge_id: Uuid = edge.id.into();
7233
7234        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
7235
7236        let writer_a = {
7237            let rt = std::sync::Arc::clone(&rt);
7238            let tok = tok.clone();
7239            let barrier = std::sync::Arc::clone(&barrier);
7240            tokio::spawn(crate::curation::race_seam::AFTER_READ_BARRIER.scope(
7241                barrier,
7242                async move {
7243                    rt.update_edge(
7244                        &tok,
7245                        edge_id,
7246                        crate::curation::EdgePatch {
7247                            weight: Some(0.9),
7248                            ..Default::default()
7249                        },
7250                    )
7251                    .await
7252                },
7253            ))
7254        };
7255        let writer_b = {
7256            let rt = std::sync::Arc::clone(&rt);
7257            let tok = tok.clone();
7258            let barrier = std::sync::Arc::clone(&barrier);
7259            tokio::spawn(crate::curation::race_seam::AFTER_READ_BARRIER.scope(
7260                barrier,
7261                async move {
7262                    rt.update_edge(
7263                        &tok,
7264                        edge_id,
7265                        crate::curation::EdgePatch {
7266                            weight: Some(0.1),
7267                            ..Default::default()
7268                        },
7269                    )
7270                    .await
7271                },
7272            ))
7273        };
7274
7275        let result_a = writer_a.await.expect("writer A task");
7276        let result_b = writer_b.await.expect("writer B task");
7277        let successes = [result_a.is_ok(), result_b.is_ok()]
7278            .into_iter()
7279            .filter(|ok| *ok)
7280            .count();
7281        assert_eq!(
7282            successes, 1,
7283            "exactly one production caller must win the symmetric-edge race; the other must \
7284             be refused: a={result_a:?} b={result_b:?}"
7285        );
7286        let refused = if result_a.is_err() {
7287            result_a
7288        } else {
7289            result_b
7290        };
7291        match &refused {
7292            Err(RuntimeError::Khive(khive_error)) => {
7293                assert_eq!(
7294                    khive_error.kind(),
7295                    khive_types::ErrorKind::Conflict,
7296                    "the losing production caller must surface a typed conflict, not \
7297                     silently overwrite: {refused:?}"
7298                );
7299            }
7300            other => panic!("expected a typed conflict error, got {other:?}"),
7301        }
7302    }
7303
7304    /// The symmetric absorption delete (case (b): a canonical survivor `S`
7305    /// already exists at the target natural key) must refuse a stale writer
7306    /// the same way the in-place update arm (case (a)) already does. `E`'s
7307    /// own revision advances after a would-be stale writer's snapshot read;
7308    /// that snapshot is then fed straight into the exact DML `update_edge`
7309    /// runs, reproducing the race deterministically (no scheduler-dependent
7310    /// concurrency needed: the outcome depends only on which snapshot the
7311    /// delete is guarded against, not on wall-clock interleaving).
7312    #[tokio::test]
7313    async fn update_edge_symmetric_absorption_refuses_stale_snapshot_when_survivor_exists() {
7314        let rt = rt();
7315        let tok = NamespaceToken::local();
7316        let a = rt
7317            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7318            .await
7319            .unwrap();
7320        let b = rt
7321            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7322            .await
7323            .unwrap();
7324
7325        // Survivor S already owns the canonical natural key before the
7326        // stale writer's snapshot is even read.
7327        let survivor = rt
7328            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.6, None)
7329            .await
7330            .unwrap();
7331        let survivor_id: Uuid = survivor.id.into();
7332
7333        // E: the edge a stale writer will try to move onto that same
7334        // natural key.
7335        let e = rt
7336            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.2, None)
7337            .await
7338            .unwrap();
7339        let e_id: Uuid = e.id.into();
7340        let stale_updated_at_micros = e.updated_at.timestamp_micros();
7341        let stale_deleted_at_micros = e.deleted_at.map(|t| t.timestamp_micros());
7342
7343        // A concurrent writer advances E's own revision after that snapshot
7344        // was captured.
7345        let advanced = rt
7346            .update_edge(
7347                &tok,
7348                e_id,
7349                crate::curation::EdgePatch {
7350                    weight: Some(0.77),
7351                    ..Default::default()
7352                },
7353            )
7354            .await
7355            .expect("concurrent writer update");
7356        assert_ne!(
7357            advanced.updated_at.timestamp_micros(),
7358            stale_updated_at_micros,
7359            "test setup: the concurrent write must actually advance the revision"
7360        );
7361
7362        // Prove every non-target premise BEFORE the DML runs. Asserting them
7363        // afterwards cannot distinguish "the survivor already held the canonical
7364        // key and the conflict predicate refused" from "the survivor appeared
7365        // later", and it cannot show which conjunct did the refusing.
7366        assert_eq!(
7367            stale_deleted_at_micros, None,
7368            "fixture premise: the stale snapshot must be of a LIVE edge, otherwise \
7369             `deleted_at IS ?14` would refuse and this stops being an isolating fixture"
7370        );
7371        let survivor_before = rt.get_edge(&tok, survivor_id).await.unwrap().expect(
7372            "fixture premise: the survivor must already own the canonical natural key \
7373                 before the stale DML runs",
7374        );
7375        assert_eq!(
7376            survivor_before.relation,
7377            EdgeRelation::CompetesWith,
7378            "fixture premise: the survivor must occupy the canonical natural key this stale \
7379             writer is about to target, otherwise there is no conflict to absorb and the \
7380             refusal would be attributable to something else: {survivor_before:?}"
7381        );
7382        assert_ne!(
7383            survivor_id, e_id,
7384            "fixture premise: the survivor and the stale writer's edge must be distinct rows"
7385        );
7386
7387        // Reproduce the exact DML `update_edge` runs for the stale writer,
7388        // using the snapshot it captured BEFORE the concurrent write above.
7389        let pool = rt.backend().pool_arc();
7390        let guard = pool.writer().expect("writer guard");
7391        let (canon_src, canon_tgt) =
7392            canonical_edge_endpoints(EdgeRelation::CompetesWith, a.id, b.id);
7393        let outcome = guard
7394            .transaction(|conn| {
7395                KhiveRuntime::update_edge_symmetric_dml(
7396                    conn,
7397                    "local",
7398                    &e_id.to_string(),
7399                    &canon_src.to_string(),
7400                    &canon_tgt.to_string(),
7401                    "competes_with",
7402                    0.9,
7403                    None,
7404                    stale_updated_at_micros,
7405                    stale_deleted_at_micros,
7406                )
7407            })
7408            .expect("dml call must not error");
7409        drop(guard);
7410        assert!(
7411            matches!(outcome, SymmetricEdgeUpdateOutcome::Stale),
7412            "a stale writer must be refused, not silently absorbed into the survivor: {outcome:?}"
7413        );
7414
7415        let e_after = rt
7416            .get_edge(&tok, e_id)
7417            .await
7418            .unwrap()
7419            .expect("E must still exist after the refused absorption");
7420        assert_eq!(
7421            e_after.relation,
7422            EdgeRelation::Extends,
7423            "E must be untouched by the refused absorption: {e_after:?}"
7424        );
7425        assert!(
7426            (e_after.weight - 0.77).abs() < 1e-9,
7427            "the concurrent writer's weight must survive the refused absorption: {e_after:?}"
7428        );
7429
7430        let s_after = rt
7431            .get_edge(&tok, survivor_id)
7432            .await
7433            .unwrap()
7434            .expect("S must still exist after the refused absorption");
7435        assert_eq!(
7436            s_after.weight, 0.6,
7437            "the survivor must be untouched by the refused absorption: {s_after:?}"
7438        );
7439    }
7440
7441    /// `updated_at` on this path must use `timestamp_micros()`, matching every other
7442    /// `graph_edges` write path (`edge_upsert_statement`, `edge_soft_delete_statement`);
7443    /// a seconds value misread as microseconds round-trips to a date a few minutes
7444    /// after the Unix epoch, not "now".
7445    #[tokio::test]
7446    async fn update_edge_symmetric_relation_stores_microsecond_updated_at() {
7447        let rt = rt();
7448        let tok = NamespaceToken::local();
7449        let a = rt
7450            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7451            .await
7452            .unwrap();
7453        let b = rt
7454            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7455            .await
7456            .unwrap();
7457        let edge = rt
7458            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
7459            .await
7460            .unwrap();
7461        let edge_id: Uuid = edge.id.into();
7462
7463        let before = chrono::Utc::now();
7464        let updated = rt
7465            .update_edge(
7466                &tok,
7467                edge_id,
7468                crate::curation::EdgePatch {
7469                    weight: Some(0.5),
7470                    ..Default::default()
7471                },
7472            )
7473            .await
7474            .unwrap();
7475
7476        let drift = (updated.updated_at - before).num_seconds().abs();
7477        assert!(
7478            drift < 60,
7479            "updated_at must round-trip as a recent timestamp (micros, not \
7480             seconds); got {:?}, expected within 60s of {:?}",
7481            updated.updated_at,
7482            before
7483        );
7484    }
7485
7486    #[tokio::test]
7487    async fn update_edge_changes_relation() {
7488        let rt = rt();
7489        let tok = NamespaceToken::local();
7490        let a = rt
7491            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7492            .await
7493            .unwrap();
7494        let b = rt
7495            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7496            .await
7497            .unwrap();
7498        let edge = rt
7499            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7500            .await
7501            .unwrap();
7502        let edge_id: Uuid = edge.id.into();
7503
7504        let updated = rt
7505            .update_edge(
7506                &tok,
7507                edge_id,
7508                crate::curation::EdgePatch {
7509                    relation: Some(EdgeRelation::VariantOf),
7510                    ..Default::default()
7511                },
7512            )
7513            .await
7514            .unwrap();
7515        assert_eq!(updated.relation, EdgeRelation::VariantOf);
7516    }
7517
7518    /// A symmetric-relation update whose canonical natural key collides
7519    /// with an existing edge must delete the requested (non-canonical)
7520    /// row and leave the surviving canonical row's attributes untouched
7521    /// (ADR-039 ON CONFLICT DO NOTHING) — the discarded edge's patched
7522    /// weight must never overwrite the survivor (khive#1213).
7523    #[tokio::test]
7524    async fn update_edge_symmetric_conflict_keeps_survivor_attributes() {
7525        let rt = rt();
7526        let tok = NamespaceToken::local();
7527        let a = rt
7528            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7529            .await
7530            .unwrap();
7531        let b = rt
7532            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7533            .await
7534            .unwrap();
7535
7536        let requested = rt
7537            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.2, None)
7538            .await
7539            .unwrap();
7540        let requested_id: Uuid = requested.id.into();
7541
7542        let canonical = rt
7543            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.6, None)
7544            .await
7545            .unwrap();
7546        let canonical_id: Uuid = canonical.id.into();
7547
7548        let updated = rt
7549            .update_edge(
7550                &tok,
7551                requested_id,
7552                crate::curation::EdgePatch {
7553                    relation: Some(EdgeRelation::CompetesWith),
7554                    weight: Some(0.9),
7555                    ..Default::default()
7556                },
7557            )
7558            .await
7559            .unwrap();
7560
7561        // The requested (non-canonical) row was absorbed into the survivor.
7562        assert_eq!(Uuid::from(updated.id), canonical_id);
7563        assert_eq!(
7564            updated.weight, 0.6,
7565            "survivor weight must not be overwritten by the discarded edge's patch"
7566        );
7567
7568        let requested_after = rt
7569            .get_edge_including_deleted(&tok, requested_id)
7570            .await
7571            .unwrap();
7572        assert!(
7573            requested_after.is_none(),
7574            "the non-canonical requested row must be deleted, not just tombstoned"
7575        );
7576    }
7577
7578    /// A soft-deleted surviving canonical row must not be resurrected by a
7579    /// conflicting symmetric-relation update (khive#1213).
7580    #[tokio::test]
7581    async fn update_edge_symmetric_conflict_does_not_resurrect_tombstoned_survivor() {
7582        let rt = rt();
7583        let tok = NamespaceToken::local();
7584        let a = rt
7585            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7586            .await
7587            .unwrap();
7588        let b = rt
7589            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7590            .await
7591            .unwrap();
7592
7593        let requested = rt
7594            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.2, None)
7595            .await
7596            .unwrap();
7597        let requested_id: Uuid = requested.id.into();
7598
7599        let canonical = rt
7600            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.6, None)
7601            .await
7602            .unwrap();
7603        let canonical_id: Uuid = canonical.id.into();
7604        rt.delete_edge(&tok, canonical_id, false).await.unwrap();
7605
7606        rt.update_edge(
7607            &tok,
7608            requested_id,
7609            crate::curation::EdgePatch {
7610                relation: Some(EdgeRelation::CompetesWith),
7611                weight: Some(0.9),
7612                ..Default::default()
7613            },
7614        )
7615        .await
7616        .unwrap();
7617
7618        let requested_after = rt
7619            .get_edge_including_deleted(&tok, requested_id)
7620            .await
7621            .unwrap();
7622        assert!(
7623            requested_after.is_none(),
7624            "the non-canonical requested row must be deleted, not just tombstoned"
7625        );
7626
7627        let canonical_after = rt.get_edge(&tok, canonical_id).await.unwrap();
7628        assert!(
7629            canonical_after.is_none(),
7630            "a tombstoned survivor must not be resurrected by a conflicting update"
7631        );
7632    }
7633
7634    // ---- update_edge endpoint validation ----
7635
7636    // update_edge: note→entity annotates → set relation=Supersedes → InvalidInput (crossing).
7637    // Edge must NOT be mutated in the store.
7638    #[tokio::test]
7639    async fn update_edge_annotates_note_to_entity_set_supersedes_returns_invalid_input() {
7640        let rt = rt();
7641        let tok = NamespaceToken::local();
7642        let note = rt
7643            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
7644            .await
7645            .unwrap();
7646        let entity = rt
7647            .create_entity(&tok, "concept", None, "E", None, None, vec![])
7648            .await
7649            .unwrap();
7650        // Create a valid note→entity annotates edge.
7651        let edge = rt
7652            .link(&tok, note.id, entity.id, EdgeRelation::Annotates, 1.0, None)
7653            .await
7654            .unwrap();
7655        let edge_id: Uuid = edge.id.into();
7656
7657        // Attempt to change relation to Supersedes (crossing substrates → invalid).
7658        let result = rt
7659            .update_edge(
7660                &tok,
7661                edge_id,
7662                crate::curation::EdgePatch {
7663                    relation: Some(EdgeRelation::Supersedes),
7664                    ..Default::default()
7665                },
7666            )
7667            .await;
7668        assert!(
7669            matches!(result, Err(RuntimeError::InvalidInput(_))),
7670            "update to Supersedes on note→entity edge must return InvalidInput, got {result:?}"
7671        );
7672
7673        // Edge must NOT be mutated — re-fetch and verify relation unchanged.
7674        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
7675        assert_eq!(
7676            fetched.relation,
7677            EdgeRelation::Annotates,
7678            "edge relation must be unchanged after failed update"
7679        );
7680    }
7681
7682    // update_edge: entity→entity extends → set relation=Annotates → InvalidInput
7683    // (annotates source must be a note).
7684    #[tokio::test]
7685    async fn update_edge_entity_to_entity_set_annotates_returns_invalid_input() {
7686        let rt = rt();
7687        let tok = NamespaceToken::local();
7688        let a = rt
7689            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7690            .await
7691            .unwrap();
7692        let b = rt
7693            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7694            .await
7695            .unwrap();
7696        let edge = rt
7697            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7698            .await
7699            .unwrap();
7700        let edge_id: Uuid = edge.id.into();
7701
7702        let result = rt
7703            .update_edge(
7704                &tok,
7705                edge_id,
7706                crate::curation::EdgePatch {
7707                    relation: Some(EdgeRelation::Annotates),
7708                    ..Default::default()
7709                },
7710            )
7711            .await;
7712        assert!(
7713            matches!(result, Err(RuntimeError::InvalidInput(_))),
7714            "update to Annotates on entity→entity edge must return InvalidInput, got {result:?}"
7715        );
7716    }
7717
7718    // update_edge: entity→entity extends → set relation=Supersedes → Ok
7719    // (entity→entity is valid for supersedes).
7720    #[tokio::test]
7721    async fn update_edge_entity_to_entity_set_supersedes_succeeds() {
7722        let rt = rt();
7723        let tok = NamespaceToken::local();
7724        let a = rt
7725            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7726            .await
7727            .unwrap();
7728        let b = rt
7729            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7730            .await
7731            .unwrap();
7732        let edge = rt
7733            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7734            .await
7735            .unwrap();
7736        let edge_id: Uuid = edge.id.into();
7737
7738        let updated = rt
7739            .update_edge(
7740                &tok,
7741                edge_id,
7742                crate::curation::EdgePatch {
7743                    relation: Some(EdgeRelation::Supersedes),
7744                    ..Default::default()
7745                },
7746            )
7747            .await
7748            .unwrap();
7749        assert_eq!(updated.relation, EdgeRelation::Supersedes);
7750
7751        // Verify persisted.
7752        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
7753        assert_eq!(fetched.relation, EdgeRelation::Supersedes);
7754    }
7755
7756    // update_edge: weight-only (relation = None) → Ok, no validation, unchanged relation.
7757    #[tokio::test]
7758    async fn update_edge_weight_only_skips_validation() {
7759        let rt = rt();
7760        let tok = NamespaceToken::local();
7761        let a = rt
7762            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7763            .await
7764            .unwrap();
7765        let b = rt
7766            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7767            .await
7768            .unwrap();
7769        let edge = rt
7770            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7771            .await
7772            .unwrap();
7773        let edge_id: Uuid = edge.id.into();
7774
7775        let updated = rt
7776            .update_edge(
7777                &tok,
7778                edge_id,
7779                crate::curation::EdgePatch {
7780                    weight: Some(0.3),
7781                    ..Default::default()
7782                },
7783            )
7784            .await
7785            .unwrap();
7786        assert_eq!(updated.relation, EdgeRelation::Extends);
7787        assert!((updated.weight - 0.3).abs() < 0.001);
7788    }
7789
7790    // update_edge: entity→entity extends → set relation=VariantOf (same class) → Ok.
7791    #[tokio::test]
7792    async fn update_edge_same_class_relation_change_succeeds() {
7793        let rt = rt();
7794        let tok = NamespaceToken::local();
7795        let a = rt
7796            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7797            .await
7798            .unwrap();
7799        let b = rt
7800            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7801            .await
7802            .unwrap();
7803        let edge = rt
7804            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7805            .await
7806            .unwrap();
7807        let edge_id: Uuid = edge.id.into();
7808
7809        let updated = rt
7810            .update_edge(
7811                &tok,
7812                edge_id,
7813                crate::curation::EdgePatch {
7814                    relation: Some(EdgeRelation::VariantOf),
7815                    ..Default::default()
7816                },
7817            )
7818            .await
7819            .unwrap();
7820        assert_eq!(updated.relation, EdgeRelation::VariantOf);
7821    }
7822
7823    /// #2088 regression at the runtime seam; this fixture was rebuilt
7824    /// deterministically for #2089 because the previous fixture created edges
7825    /// through the normal `link()` path (random UUIDs, wall-clock
7826    /// timestamps), so whether it exposed the pre-image bug — sorting the
7827    /// per-namespace merge by UUID alone, a key unrelated to the
7828    /// `created_at` order each per-namespace fetch was actually cut at —
7829    /// depended on the RNG; it could pass against pre-image code by pure
7830    /// luck.
7831    ///
7832    /// This fixture pins both: every `ns-a` edge gets a UUID numerically
7833    /// greater than every `ns-b` edge, while `created_at` strictly
7834    /// interleaves the two namespaces (a, b, a, b, a, b). A UUID-only sort
7835    /// therefore reliably produces "every ns-b edge, then every ns-a edge"
7836    /// — provably different from the true `created_at` interleaving — so
7837    /// asserting this exact expected sequence (not just the resulting set)
7838    /// is what a reverted pre-image implementation would fail to
7839    /// reproduce.
7840    #[tokio::test]
7841    async fn list_edges_multi_namespace_offset_paging_enumerates_exactly() {
7842        let rt = rt();
7843        let ns_a = Namespace::parse("ns-a").unwrap();
7844        let ns_b = Namespace::parse("ns-b").unwrap();
7845        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
7846        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
7847
7848        let source = rt
7849            .create_entity(&tok_a, "concept", None, "Source", None, None, vec![])
7850            .await
7851            .unwrap();
7852        let mut targets = Vec::new();
7853        for index in 0..6 {
7854            targets.push(
7855                rt.create_entity(
7856                    &tok_a,
7857                    "concept",
7858                    None,
7859                    &format!("Target{index}"),
7860                    None,
7861                    None,
7862                    vec![],
7863                )
7864                .await
7865                .unwrap(),
7866            );
7867        }
7868
7869        // Every `a_uuids` entry is numerically greater than every
7870        // `b_uuids` entry (leading nibble `f` vs `0`).
7871        let a_uuids = [
7872            Uuid::parse_str("ffffffff-ffff-4fff-8fff-ffffffffff01").unwrap(),
7873            Uuid::parse_str("ffffffff-ffff-4fff-8fff-ffffffffff02").unwrap(),
7874            Uuid::parse_str("ffffffff-ffff-4fff-8fff-ffffffffff03").unwrap(),
7875        ];
7876        let b_uuids = [
7877            Uuid::parse_str("00000000-0000-4000-8000-000000000001").unwrap(),
7878            Uuid::parse_str("00000000-0000-4000-8000-000000000002").unwrap(),
7879            Uuid::parse_str("00000000-0000-4000-8000-000000000003").unwrap(),
7880        ];
7881
7882        let graph_a = rt.graph(&tok_a).unwrap();
7883        let graph_b = rt.graph(&tok_b).unwrap();
7884        let mut expected_order: Vec<Uuid> = Vec::new();
7885        for i in 0..3usize {
7886            let a_created_at = chrono::DateTime::<chrono::Utc>::from_timestamp_micros(
7887                1_000_000 + (2 * i as i64) * 1_000_000,
7888            )
7889            .unwrap();
7890            graph_a
7891                .upsert_edge(Edge {
7892                    id: a_uuids[i].into(),
7893                    namespace: "ns-a".into(),
7894                    source_id: source.id,
7895                    target_id: targets[2 * i].id,
7896                    relation: EdgeRelation::Extends,
7897                    weight: 0.5,
7898                    created_at: a_created_at,
7899                    updated_at: a_created_at,
7900                    deleted_at: None,
7901                    metadata: None,
7902                    target_backend: None,
7903                })
7904                .await
7905                .unwrap();
7906            expected_order.push(a_uuids[i]);
7907
7908            let b_created_at = chrono::DateTime::<chrono::Utc>::from_timestamp_micros(
7909                2_000_000 + (2 * i as i64) * 1_000_000,
7910            )
7911            .unwrap();
7912            graph_b
7913                .upsert_edge(Edge {
7914                    id: b_uuids[i].into(),
7915                    namespace: "ns-b".into(),
7916                    source_id: source.id,
7917                    target_id: targets[2 * i + 1].id,
7918                    relation: EdgeRelation::Extends,
7919                    weight: 0.5,
7920                    created_at: b_created_at,
7921                    updated_at: b_created_at,
7922                    deleted_at: None,
7923                    metadata: None,
7924                    target_backend: None,
7925                })
7926                .await
7927                .unwrap();
7928            expected_order.push(b_uuids[i]);
7929        }
7930
7931        let multi = NamespaceToken::mint_with_visibility(ns_a, vec![ns_b], ActorRef::anonymous());
7932        let mut seen: Vec<Uuid> = Vec::new();
7933        let mut offset = 0u32;
7934        loop {
7935            let page = rt
7936                .list_edges(&multi, EdgeListFilter::default(), 2, offset)
7937                .await
7938                .unwrap();
7939            if page.is_empty() {
7940                break;
7941            }
7942            seen.extend(page.iter().map(|e| Uuid::from(e.id)));
7943            offset += 2;
7944        }
7945
7946        assert_eq!(
7947            seen, expected_order,
7948            "must enumerate in exact created_at order, not UUID order"
7949        );
7950        let distinct: std::collections::HashSet<Uuid> = seen.iter().copied().collect();
7951        assert_eq!(distinct.len(), 6, "no duplicates across pages");
7952        let expected_set: std::collections::HashSet<Uuid> =
7953            expected_order.iter().copied().collect();
7954        assert_eq!(
7955            distinct, expected_set,
7956            "enumerated set must equal the seeded set"
7957        );
7958    }
7959
7960    /// #2089: `list_edges`'s trait-default fallback
7961    /// (taken when a `GraphStore` backend returns `Unsupported` from
7962    /// `query_edges_in_namespaces` — i.e. it does not override the batched
7963    /// namespace query, per [`khive_storage::GraphStore`]'s default) merges
7964    /// independently-fetched per-namespace prefixes through
7965    /// [`KhiveRuntime::merge_paged_namespace_edges`]. This exercises that
7966    /// merge directly: `ns_a`'s edges all carry numerically-greater UUIDs
7967    /// than every `ns_b` edge, while `created_at` interleaves the two
7968    /// namespaces. Sorting the merge by UUID alone (the pre-image #2088 bug)
7969    /// would put every `ns_b` edge before every `ns_a` edge regardless of
7970    /// `created_at` — provably different from this fixture's expected
7971    /// order — so an exact-sequence assertion here is sufficient to catch a
7972    /// regression back to that bug.
7973    #[test]
7974    fn merge_paged_namespace_edges_orders_by_created_at_not_uuid() {
7975        fn edge(id_hex_suffix: &str, created_at_micros: i64) -> Edge {
7976            let created_at =
7977                chrono::DateTime::<chrono::Utc>::from_timestamp_micros(created_at_micros).unwrap();
7978            Edge {
7979                id: Uuid::parse_str(&format!("00000000-0000-4000-8000-{id_hex_suffix}"))
7980                    .unwrap()
7981                    .into(),
7982                namespace: "irrelevant".into(),
7983                source_id: Uuid::nil(),
7984                target_id: Uuid::nil(),
7985                relation: EdgeRelation::Extends,
7986                weight: 0.5,
7987                created_at,
7988                updated_at: created_at,
7989                deleted_at: None,
7990                metadata: None,
7991                target_backend: None,
7992            }
7993        }
7994
7995        // Every `a*` UUID (leading nibble `f`) is numerically greater than
7996        // every `b*` UUID (leading nibble `0`), but `created_at` interleaves
7997        // them: a0 < b0 < a1 < b1.
7998        let a0 = edge("ffffffffffff", 1_000_000);
7999        let b0 = edge("000000000001", 2_000_000);
8000        let a1 = edge("fffffffffffe", 3_000_000);
8001        let b1 = edge("000000000002", 4_000_000);
8002
8003        let namespace_prefixes = vec![vec![a0.clone(), a1.clone()], vec![b0.clone(), b1.clone()]];
8004
8005        let full_page = KhiveRuntime::merge_paged_namespace_edges(namespace_prefixes.clone(), 0, 4);
8006        let ids: Vec<Uuid> = full_page.iter().map(|e| Uuid::from(e.id)).collect();
8007        assert_eq!(
8008            ids,
8009            vec![
8010                Uuid::from(a0.id),
8011                Uuid::from(b0.id),
8012                Uuid::from(a1.id),
8013                Uuid::from(b1.id)
8014            ],
8015            "must order the merge by created_at, not by UUID magnitude"
8016        );
8017
8018        // Mid-window offset must slice the same globally-ordered sequence,
8019        // not re-derive order per page.
8020        let middle_page = KhiveRuntime::merge_paged_namespace_edges(namespace_prefixes, 1, 2);
8021        let middle_ids: Vec<Uuid> = middle_page.iter().map(|e| Uuid::from(e.id)).collect();
8022        assert_eq!(middle_ids, vec![Uuid::from(b0.id), Uuid::from(a1.id)]);
8023    }
8024
8025    #[tokio::test]
8026    async fn list_edges_filters_by_relation() {
8027        let rt = rt();
8028        let tok = NamespaceToken::local();
8029        let a = rt
8030            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8031            .await
8032            .unwrap();
8033        let b = rt
8034            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8035            .await
8036            .unwrap();
8037        let c = rt
8038            .create_entity(&tok, "concept", None, "C", None, None, vec![])
8039            .await
8040            .unwrap();
8041
8042        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
8043            .await
8044            .unwrap();
8045        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
8046            .await
8047            .unwrap();
8048
8049        let filter = EdgeListFilter {
8050            relations: vec![EdgeRelation::Extends],
8051            ..Default::default()
8052        };
8053        let edges = rt.list_edges(&tok, filter, 100, 0).await.unwrap();
8054        assert_eq!(edges.len(), 1);
8055        assert_eq!(edges[0].relation, EdgeRelation::Extends);
8056    }
8057
8058    #[tokio::test]
8059    async fn list_edges_filters_by_source() {
8060        let rt = rt();
8061        let tok = NamespaceToken::local();
8062        let a = rt
8063            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8064            .await
8065            .unwrap();
8066        let b = rt
8067            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8068            .await
8069            .unwrap();
8070        let c = rt
8071            .create_entity(&tok, "concept", None, "C", None, None, vec![])
8072            .await
8073            .unwrap();
8074        let d = rt
8075            .create_entity(&tok, "concept", None, "D", None, None, vec![])
8076            .await
8077            .unwrap();
8078
8079        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
8080            .await
8081            .unwrap();
8082        rt.link(&tok, c.id, d.id, EdgeRelation::Extends, 1.0, None)
8083            .await
8084            .unwrap();
8085
8086        let filter = EdgeListFilter {
8087            source_id: Some(a.id),
8088            ..Default::default()
8089        };
8090        let edges = rt.list_edges(&tok, filter, 100, 0).await.unwrap();
8091        assert_eq!(edges.len(), 1);
8092        let src: Uuid = edges[0].source_id;
8093        assert_eq!(src, a.id);
8094    }
8095
8096    /// Regression: `offset` was hard-coded to 0 in `list_edges`, so every
8097    /// page returned the identical first rows. Pages must now tile the full
8098    /// matching set with no gaps or duplicates, and an out-of-range offset
8099    /// must return empty rather than page 1.
8100    #[tokio::test]
8101    async fn list_edges_offset_pages_through_full_set() {
8102        let rt = rt();
8103        let tok = NamespaceToken::local();
8104        let a = rt
8105            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8106            .await
8107            .unwrap();
8108        for i in 0..5 {
8109            let t = rt
8110                .create_entity(&tok, "concept", None, &format!("T{i}"), None, None, vec![])
8111                .await
8112                .unwrap();
8113            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
8114                .await
8115                .unwrap();
8116        }
8117
8118        let filter = EdgeListFilter {
8119            source_id: Some(a.id),
8120            relations: vec![EdgeRelation::Extends],
8121            ..Default::default()
8122        };
8123
8124        let page0 = rt.list_edges(&tok, filter.clone(), 2, 0).await.unwrap();
8125        let page1 = rt.list_edges(&tok, filter.clone(), 2, 2).await.unwrap();
8126        let page2 = rt.list_edges(&tok, filter.clone(), 2, 4).await.unwrap();
8127        assert_eq!(page0.len(), 2);
8128        assert_eq!(page1.len(), 2);
8129        assert_eq!(page2.len(), 1);
8130
8131        let ids = |p: &[Edge]| p.iter().map(|e| Uuid::from(e.id)).collect::<Vec<_>>();
8132        assert_ne!(ids(&page0), ids(&page1), "page 2 must differ from page 1");
8133
8134        let mut all_ids: Vec<Uuid> = ids(&page0)
8135            .into_iter()
8136            .chain(ids(&page1))
8137            .chain(ids(&page2))
8138            .collect();
8139        all_ids.sort();
8140        all_ids.dedup();
8141        assert_eq!(all_ids.len(), 5, "pages must tile the full edge set");
8142
8143        let empty = rt.list_edges(&tok, filter.clone(), 2, 100).await.unwrap();
8144        assert!(
8145            empty.is_empty(),
8146            "offset past the end must return empty, not page 1"
8147        );
8148    }
8149
8150    /// `list_edges_after` seeks via a durable insertion sequence instead of
8151    /// paging through OFFSET, so cost does not grow with walk depth.
8152    #[tokio::test]
8153    async fn list_edges_after_keyset_tiles_full_set() {
8154        let rt = rt();
8155        let tok = NamespaceToken::local();
8156        let a = rt
8157            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8158            .await
8159            .unwrap();
8160        for i in 0..5 {
8161            let t = rt
8162                .create_entity(&tok, "concept", None, &format!("K{i}"), None, None, vec![])
8163                .await
8164                .unwrap();
8165            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
8166                .await
8167                .unwrap();
8168        }
8169
8170        let filter = EdgeListFilter {
8171            source_id: Some(a.id),
8172            relations: vec![EdgeRelation::Extends],
8173            ..Default::default()
8174        };
8175
8176        let mut seen = Vec::new();
8177        let mut cursor: Option<Uuid> = None;
8178        for _ in 0..20 {
8179            let (page, next) = rt
8180                .list_edges_after(&tok, filter.clone(), cursor, 2)
8181                .await
8182                .unwrap();
8183            if page.is_empty() {
8184                break;
8185            }
8186            seen.extend(page.iter().map(|e| Uuid::from(e.id)));
8187            if next.is_none() {
8188                break;
8189            }
8190            cursor = next;
8191        }
8192        seen.sort();
8193        seen.dedup();
8194        assert_eq!(seen.len(), 5, "keyset walk must tile the full edge set");
8195
8196        // With no intervening writes, repeating the same cursor returns the
8197        // same insertion-sequence page.
8198        let (first_a, next_a) = rt
8199            .list_edges_after(&tok, filter.clone(), None, 2)
8200            .await
8201            .unwrap();
8202        let (first_b, next_b) = rt
8203            .list_edges_after(&tok, filter.clone(), None, 2)
8204            .await
8205            .unwrap();
8206        assert_eq!(
8207            first_a.iter().map(|e| e.id.0).collect::<Vec<_>>(),
8208            first_b.iter().map(|e| e.id.0).collect::<Vec<_>>(),
8209        );
8210        assert_eq!(next_a, next_b);
8211    }
8212
8213    #[tokio::test]
8214    async fn list_entities_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
8215        let rt = rt();
8216        let tok = NamespaceToken::local();
8217        let ids = [
8218            Uuid::parse_str("f0000000-0000-4000-8000-000000000011").unwrap(),
8219            Uuid::parse_str("f0000000-0000-4000-8000-000000000012").unwrap(),
8220            Uuid::parse_str("f0000000-0000-4000-8000-000000000013").unwrap(),
8221        ];
8222        let store = rt.entities(&tok).unwrap();
8223        for (index, id) in ids.into_iter().enumerate() {
8224            let mut entity = Entity::new("local", "concept", format!("Entity{index}"));
8225            entity.id = id;
8226            entity.created_at = 1_000_000;
8227            entity.updated_at = 1_000_000;
8228            store.upsert_entity(entity).await.unwrap();
8229        }
8230
8231        let (first, next) = rt
8232            .list_entities_after(&tok, None, None, &[], None, 2)
8233            .await
8234            .unwrap();
8235        assert_eq!(
8236            first.iter().map(|entity| entity.id).collect::<Vec<_>>(),
8237            ids[..2]
8238        );
8239        let cursor = next.expect("one original entity remains after page one");
8240
8241        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000011").unwrap();
8242        assert!(low_id < cursor);
8243        let mut inserted = Entity::new("local", "concept", "InsertedEntity");
8244        inserted.id = low_id;
8245        inserted.created_at = 1_000_000;
8246        inserted.updated_at = 1_000_000;
8247        store.upsert_entity(inserted).await.unwrap();
8248
8249        let (second, final_cursor) = rt
8250            .list_entities_after(&tok, None, None, &[], Some(cursor), 2)
8251            .await
8252            .unwrap();
8253        assert_eq!(
8254            second.iter().map(|entity| entity.id).collect::<Vec<_>>(),
8255            vec![ids[2], low_id]
8256        );
8257        assert_eq!(final_cursor, None);
8258    }
8259
8260    #[tokio::test]
8261    async fn list_notes_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
8262        let rt = rt();
8263        let tok = NamespaceToken::local();
8264        let ids = [
8265            Uuid::parse_str("f0000000-0000-4000-8000-000000000021").unwrap(),
8266            Uuid::parse_str("f0000000-0000-4000-8000-000000000022").unwrap(),
8267            Uuid::parse_str("f0000000-0000-4000-8000-000000000023").unwrap(),
8268        ];
8269        let store = rt.notes(&tok).unwrap();
8270        for (index, id) in ids.into_iter().enumerate() {
8271            let mut note = Note::new("local", "observation", format!("Note {index}"));
8272            note.id = id;
8273            note.created_at = 1_000_000;
8274            note.updated_at = 1_000_000;
8275            store.upsert_note(note).await.unwrap();
8276        }
8277
8278        let (first, next) = rt.list_notes_after(&tok, None, None, 2).await.unwrap();
8279        assert_eq!(
8280            first.iter().map(|note| note.id).collect::<Vec<_>>(),
8281            ids[..2]
8282        );
8283        let cursor = next.expect("one original note remains after page one");
8284
8285        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000021").unwrap();
8286        assert!(low_id < cursor);
8287        let mut inserted = Note::new("local", "observation", "Inserted note");
8288        inserted.id = low_id;
8289        inserted.created_at = 1_000_000;
8290        inserted.updated_at = 1_000_000;
8291        store.upsert_note(inserted).await.unwrap();
8292
8293        let (second, final_cursor) = rt
8294            .list_notes_after(&tok, None, Some(cursor), 2)
8295            .await
8296            .unwrap();
8297        assert_eq!(
8298            second.iter().map(|note| note.id).collect::<Vec<_>>(),
8299            vec![ids[2], low_id]
8300        );
8301        assert_eq!(final_cursor, None);
8302    }
8303
8304    #[tokio::test]
8305    async fn list_edges_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
8306        let rt = rt();
8307        let tok = NamespaceToken::local();
8308        let source = rt
8309            .create_entity(&tok, "concept", None, "CursorSource", None, None, vec![])
8310            .await
8311            .unwrap();
8312        let mut targets = Vec::new();
8313        for index in 0..4 {
8314            targets.push(
8315                rt.create_entity(
8316                    &tok,
8317                    "concept",
8318                    None,
8319                    &format!("CursorTarget{index}"),
8320                    None,
8321                    None,
8322                    vec![],
8323                )
8324                .await
8325                .unwrap(),
8326            );
8327        }
8328
8329        let ids = [
8330            Uuid::parse_str("f0000000-0000-4000-8000-000000000001").unwrap(),
8331            Uuid::parse_str("f0000000-0000-4000-8000-000000000002").unwrap(),
8332            Uuid::parse_str("f0000000-0000-4000-8000-000000000003").unwrap(),
8333        ];
8334        let graph = rt.graph(&tok).unwrap();
8335        let created_at = chrono::DateTime::<chrono::Utc>::from_timestamp_micros(1_000_000).unwrap();
8336        for (index, id) in ids.into_iter().enumerate() {
8337            graph
8338                .upsert_edge(Edge {
8339                    id: id.into(),
8340                    namespace: "local".into(),
8341                    source_id: source.id,
8342                    target_id: targets[index].id,
8343                    relation: EdgeRelation::Extends,
8344                    weight: 1.0,
8345                    created_at,
8346                    updated_at: created_at,
8347                    deleted_at: None,
8348                    metadata: None,
8349                    target_backend: None,
8350                })
8351                .await
8352                .unwrap();
8353        }
8354
8355        let filter = EdgeListFilter {
8356            source_id: Some(source.id),
8357            relations: vec![EdgeRelation::Extends],
8358            ..Default::default()
8359        };
8360        let (first, next) = rt
8361            .list_edges_after(&tok, filter.clone(), None, 2)
8362            .await
8363            .unwrap();
8364        assert_eq!(
8365            first.iter().map(|edge| edge.id.0).collect::<Vec<_>>(),
8366            ids[..2]
8367        );
8368        let cursor = next.expect("one original edge remains after page one");
8369
8370        // The later insert has the same wall-clock microsecond and sorts before
8371        // the cursor UUID. Its database-assigned sequence still places it after
8372        // the issued boundary.
8373        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000001").unwrap();
8374        assert!(low_id < cursor);
8375        graph
8376            .upsert_edge(Edge {
8377                id: low_id.into(),
8378                namespace: "local".into(),
8379                source_id: source.id,
8380                target_id: targets[3].id,
8381                relation: EdgeRelation::Extends,
8382                weight: 1.0,
8383                created_at,
8384                updated_at: created_at,
8385                deleted_at: None,
8386                metadata: None,
8387                target_backend: None,
8388            })
8389            .await
8390            .unwrap();
8391
8392        let (second, final_cursor) = rt
8393            .list_edges_after(&tok, filter, Some(cursor), 2)
8394            .await
8395            .unwrap();
8396        assert_eq!(
8397            second.iter().map(|edge| edge.id.0).collect::<Vec<_>>(),
8398            vec![ids[2], low_id]
8399        );
8400        assert_eq!(final_cursor, None);
8401    }
8402
8403    #[tokio::test]
8404    async fn list_entity_cursor_survives_soft_delete_and_rejects_hard_delete_or_hidden_scope() {
8405        let rt = rt();
8406        let local = NamespaceToken::local();
8407        for index in 0..3 {
8408            rt.create_entity(
8409                &local,
8410                "concept",
8411                None,
8412                &format!("CursorLifecycle{index}"),
8413                None,
8414                None,
8415                vec![],
8416            )
8417            .await
8418            .unwrap();
8419        }
8420
8421        let (_, next) = rt
8422            .list_entities_after(&local, None, None, &[], None, 2)
8423            .await
8424            .unwrap();
8425        let cursor = next.expect("three entities require a second page");
8426        let store = rt.entities(&local).unwrap();
8427        assert!(store.delete_entity(cursor, DeleteMode::Soft).await.unwrap());
8428
8429        let (remaining, next) = rt
8430            .list_entities_after(&local, None, None, &[], Some(cursor), 2)
8431            .await
8432            .expect("a soft-deleted cursor must retain its sequence boundary");
8433        assert_eq!(remaining.len(), 1);
8434        assert_eq!(next, None);
8435
8436        assert!(store.delete_entity(cursor, DeleteMode::Hard).await.unwrap());
8437        let hard_deleted = rt
8438            .list_entities_after(&local, None, None, &[], Some(cursor), 2)
8439            .await;
8440        assert!(
8441            matches!(hard_deleted, Err(RuntimeError::NotFound(_))),
8442            "a hard-deleted cursor must fail explicitly: {hard_deleted:?}"
8443        );
8444
8445        let hidden_ns = Namespace::parse("cursor-hidden").unwrap();
8446        let hidden_token = NamespaceToken::for_namespace(hidden_ns);
8447        let hidden = rt
8448            .create_entity(
8449                &hidden_token,
8450                "concept",
8451                None,
8452                "HiddenCursor",
8453                None,
8454                None,
8455                vec![],
8456            )
8457            .await
8458            .unwrap();
8459        let out_of_scope = rt
8460            .list_entities_after(&local, None, None, &[], Some(hidden.id), 2)
8461            .await;
8462        assert!(
8463            matches!(out_of_scope, Err(RuntimeError::NotFound(_))),
8464            "an out-of-scope cursor must not reveal or resume from the hidden row: {out_of_scope:?}"
8465        );
8466    }
8467
8468    #[tokio::test]
8469    async fn list_edges_after_single_namespace_exact_final_page_has_no_next_after() {
8470        let rt = rt();
8471        let tok = NamespaceToken::local();
8472        let a = rt
8473            .create_entity(&tok, "concept", None, "SingleCursorA", None, None, vec![])
8474            .await
8475            .unwrap();
8476        for i in 0..4 {
8477            let t = rt
8478                .create_entity(
8479                    &tok,
8480                    "concept",
8481                    None,
8482                    &format!("SingleCursorT{i}"),
8483                    None,
8484                    None,
8485                    vec![],
8486                )
8487                .await
8488                .unwrap();
8489            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
8490                .await
8491                .unwrap();
8492        }
8493
8494        let filter = EdgeListFilter {
8495            source_id: Some(a.id),
8496            relations: vec![EdgeRelation::Extends],
8497            ..Default::default()
8498        };
8499
8500        let (page1, next1) = rt
8501            .list_edges_after(&tok, filter.clone(), None, 2)
8502            .await
8503            .unwrap();
8504        assert_eq!(page1.len(), 2);
8505        let cursor = next1.expect("first page must report a cursor when two rows remain");
8506
8507        let (page2, next2) = rt
8508            .list_edges_after(&tok, filter, Some(cursor), 2)
8509            .await
8510            .unwrap();
8511        assert_eq!(page2.len(), 2);
8512        assert_eq!(
8513            next2, None,
8514            "an exact-size final single-namespace page must not report a cursor"
8515        );
8516    }
8517
8518    #[tokio::test]
8519    async fn list_edges_after_multi_namespace_exact_final_page_has_no_next_after() {
8520        let rt = rt();
8521        let ns_a = Namespace::parse("cursor-ns-a").unwrap();
8522        let ns_b = Namespace::parse("cursor-ns-b").unwrap();
8523        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
8524        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
8525        let visible = NamespaceToken::mint_with_visibility(ns_a, vec![ns_b], ActorRef::anonymous());
8526
8527        for (tok, prefix) in [(&tok_a, "A"), (&tok_b, "B")] {
8528            let source = rt
8529                .create_entity(
8530                    tok,
8531                    "concept",
8532                    None,
8533                    &format!("MultiCursor{prefix}Source"),
8534                    None,
8535                    None,
8536                    vec![],
8537                )
8538                .await
8539                .unwrap();
8540            for i in 0..2 {
8541                let target = rt
8542                    .create_entity(
8543                        tok,
8544                        "concept",
8545                        None,
8546                        &format!("MultiCursor{prefix}Target{i}"),
8547                        None,
8548                        None,
8549                        vec![],
8550                    )
8551                    .await
8552                    .unwrap();
8553                rt.link(tok, source.id, target.id, EdgeRelation::Extends, 1.0, None)
8554                    .await
8555                    .unwrap();
8556            }
8557        }
8558
8559        let filter = EdgeListFilter {
8560            relations: vec![EdgeRelation::Extends],
8561            ..Default::default()
8562        };
8563        let (page1, next1) = rt
8564            .list_edges_after(&visible, filter.clone(), None, 2)
8565            .await
8566            .unwrap();
8567        assert_eq!(page1.len(), 2);
8568        let cursor = next1.expect("first merged page must report a cursor when rows remain");
8569
8570        let (page2, next2) = rt
8571            .list_edges_after(&visible, filter, Some(cursor), 2)
8572            .await
8573            .unwrap();
8574        assert_eq!(page2.len(), 2);
8575        assert_eq!(
8576            next2, None,
8577            "an exact-size final multi-namespace page must not report a cursor"
8578        );
8579    }
8580
8581    /// `stats()` should be able to report a per-relation breakdown so
8582    /// auditors know the true population per relation before sampling.
8583    #[tokio::test]
8584    async fn count_edges_by_relation_matches_fixtures() {
8585        let rt = rt();
8586        let tok = NamespaceToken::local();
8587        let a = rt
8588            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8589            .await
8590            .unwrap();
8591        let b = rt
8592            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8593            .await
8594            .unwrap();
8595        let c = rt
8596            .create_entity(&tok, "concept", None, "C", None, None, vec![])
8597            .await
8598            .unwrap();
8599
8600        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
8601            .await
8602            .unwrap();
8603        rt.link(&tok, a.id, c.id, EdgeRelation::Extends, 1.0, None)
8604            .await
8605            .unwrap();
8606        rt.link(&tok, b.id, c.id, EdgeRelation::Enables, 1.0, None)
8607            .await
8608            .unwrap();
8609
8610        let counts = rt.count_edges_by_relation(&tok).await.unwrap();
8611        assert_eq!(counts.get("extends").copied(), Some(2));
8612        assert_eq!(counts.get("enables").copied(), Some(1));
8613    }
8614
8615    #[tokio::test]
8616    async fn delete_edge_removes_from_storage() {
8617        let rt = rt();
8618        let tok = NamespaceToken::local();
8619        let a = rt
8620            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8621            .await
8622            .unwrap();
8623        let b = rt
8624            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8625            .await
8626            .unwrap();
8627        let edge = rt
8628            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
8629            .await
8630            .unwrap();
8631        let edge_id: Uuid = edge.id.into();
8632
8633        let deleted = rt.delete_edge(&tok, edge_id, true).await.unwrap();
8634        assert!(deleted);
8635
8636        let fetched = rt.get_edge(&tok, edge_id).await.unwrap();
8637        assert!(fetched.is_none(), "edge should be gone after delete");
8638    }
8639
8640    #[tokio::test]
8641    async fn count_edges_matches_filter() {
8642        let rt = rt();
8643        let tok = NamespaceToken::local();
8644        let a = rt
8645            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8646            .await
8647            .unwrap();
8648        let b = rt
8649            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8650            .await
8651            .unwrap();
8652        let c = rt
8653            .create_entity(&tok, "concept", None, "C", None, None, vec![])
8654            .await
8655            .unwrap();
8656
8657        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
8658            .await
8659            .unwrap();
8660        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
8661            .await
8662            .unwrap();
8663
8664        let all = rt
8665            .count_edges(&tok, EdgeListFilter::default())
8666            .await
8667            .unwrap();
8668        assert_eq!(all, 2);
8669
8670        let just_extends = rt
8671            .count_edges(
8672                &tok,
8673                EdgeListFilter {
8674                    relations: vec![EdgeRelation::Extends],
8675                    ..Default::default()
8676                },
8677            )
8678            .await
8679            .unwrap();
8680        assert_eq!(just_extends, 1);
8681    }
8682
8683    // ---- substrate_exists_in_ns must use get_edge_visible ----
8684
8685    /// An edge owned by a visible (non-primary) namespace must be found by
8686    /// `substrate_exists_in_ns` and therefore usable as a graph root in
8687    /// `neighbors` and `traverse`.
8688    #[tokio::test]
8689    async fn edge_in_visible_namespace_reachable_as_graph_root() {
8690        let rt = rt();
8691        let ns_a = Namespace::parse("vis-edge-a").unwrap();
8692        let ns_b = Namespace::parse("vis-edge-b").unwrap();
8693
8694        // Create two entities and an edge in namespace B.
8695        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
8696        let src = rt
8697            .create_entity(&tok_b, "concept", None, "SrcB", None, None, vec![])
8698            .await
8699            .unwrap();
8700        let tgt = rt
8701            .create_entity(&tok_b, "concept", None, "TgtB", None, None, vec![])
8702            .await
8703            .unwrap();
8704        let edge = rt
8705            .link(&tok_b, src.id, tgt.id, EdgeRelation::Extends, 1.0, None)
8706            .await
8707            .unwrap();
8708
8709        // Namespace A with B in its visible set should be able to get the
8710        // edge and use it as a traverse root.
8711        let tok_a_vis = rt
8712            .authorize_with_visibility(ns_a.clone(), vec![ns_b.clone()])
8713            .unwrap();
8714
8715        // Direct get of the edge must succeed (visible namespace).
8716        let got = rt.get_edge_visible(&tok_a_vis, edge.id.0).await.unwrap();
8717        assert!(
8718            got.is_some(),
8719            "edge in visible namespace must be retrievable via get_edge_visible"
8720        );
8721
8722        // neighbors/traverse use substrate_exists_in_ns which now calls
8723        // get_edge_visible — they must not return empty for a visible-ns edge root.
8724        let neighbors = rt
8725            .neighbors(&tok_a_vis, src.id, Direction::Out, Some(16), None)
8726            .await
8727            .unwrap();
8728        assert!(
8729            neighbors.iter().any(|h| h.node_id == tgt.id),
8730            "neighbors of visible-ns node must include its visible-ns neighbor; got: {neighbors:?}"
8731        );
8732    }
8733
8734    // By-ID ops do not enforce namespace isolation. Shared-brain OSS model:
8735    // UUID is globally unique; get/update/delete find the record regardless
8736    // of caller's token namespace.
8737    #[tokio::test]
8738    async fn get_entity_cross_namespace_no_longer_denied() {
8739        let rt = rt();
8740        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8741        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8742        let entity = rt
8743            .create_entity(&ns_a, "concept", None, "Alpha", None, None, vec![])
8744            .await
8745            .unwrap();
8746
8747        // Same namespace: still works.
8748        let found = rt.get_entity(&ns_a, entity.id).await;
8749        assert!(found.is_ok(), "same-namespace get must succeed");
8750
8751        // Different namespace: now also returns the entity (shared brain).
8752        let cross = rt.get_entity(&ns_b, entity.id).await;
8753        assert!(
8754            cross.is_ok(),
8755            "cross-namespace get must succeed in shared-brain OSS (ADR-007 rule 2)"
8756        );
8757        assert_eq!(cross.unwrap().id, entity.id);
8758    }
8759
8760    #[tokio::test]
8761    async fn delete_entity_cross_namespace_no_longer_denied() {
8762        let rt = rt();
8763        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8764        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8765        let entity = rt
8766            .create_entity(&ns_a, "concept", None, "Beta", None, None, vec![])
8767            .await
8768            .unwrap();
8769
8770        // Cross-namespace delete now succeeds (shared brain).
8771        let cross_ns_result = rt.delete_entity(&ns_b, entity.id, true).await;
8772        assert!(
8773            cross_ns_result.is_ok(),
8774            "cross-namespace delete must succeed in shared-brain OSS; got {:?}",
8775            cross_ns_result
8776        );
8777        assert!(cross_ns_result.unwrap(), "delete must return true");
8778
8779        // Entity is gone — even from the original namespace.
8780        let gone = rt.get_entity(&ns_a, entity.id).await;
8781        assert!(gone.is_err(), "entity must be gone after delete");
8782    }
8783
8784    // ---- Note annotation tests ----
8785
8786    #[tokio::test]
8787    async fn create_note_indexes_into_fts5() {
8788        let rt = rt();
8789        let tok = NamespaceToken::local();
8790        let note = rt
8791            .create_note(
8792                &tok,
8793                "observation",
8794                None,
8795                "FlashAttention reduces memory by using tiling",
8796                Some(0.8),
8797                None,
8798                vec![],
8799            )
8800            .await
8801            .unwrap();
8802
8803        // FTS5 should have indexed the note content.
8804        let ns = tok.namespace().as_str().to_string();
8805        let hits = rt
8806            .text_for_notes(&tok)
8807            .unwrap()
8808            .search(khive_storage::types::TextSearchRequest {
8809                query: "FlashAttention".to_string(),
8810                mode: khive_storage::types::TextQueryMode::Plain,
8811                filter: Some(khive_storage::types::TextFilter {
8812                    namespaces: vec![ns],
8813                    ..Default::default()
8814                }),
8815                top_k: 10,
8816                snippet_chars: 100,
8817            })
8818            .await
8819            .unwrap();
8820
8821        assert!(
8822            hits.iter().any(|h| h.subject_id == note.id),
8823            "note should be indexed in FTS5 after create"
8824        );
8825    }
8826
8827    /// #916: `@` used to reach SQLite FTS5's bareword parser raw and error
8828    /// (`sanitize_fts5_query` did not strip it), surfacing as
8829    /// `RuntimeError::InvalidInput` per #569's fail-loud policy.
8830    /// `sanitize_fts5_token_group`'s bareword-safety gate now routes it
8831    /// through the quoted-phrase alternative instead, so `search_notes`
8832    /// succeeds and finds the seeded content.
8833    #[tokio::test]
8834    async fn search_notes_with_residual_fts5_char_now_sanitized() {
8835        let rt = rt();
8836        let tok = NamespaceToken::local();
8837        rt.create_note(
8838            &tok,
8839            "observation",
8840            None,
8841            "use foo@bar to chain calls",
8842            Some(0.5),
8843            None,
8844            vec![],
8845        )
8846        .await
8847        .unwrap();
8848
8849        let result = rt
8850            .search_notes(&tok, "foo@bar", None, 10, None, false, &[], None)
8851            .await;
8852
8853        let hits = result.unwrap_or_else(|e| {
8854            panic!("#916 search_notes must not fail on an '@'-bearing query, got: {e:?}")
8855        });
8856        assert!(
8857            !hits.is_empty(),
8858            "#916 '@'-bearing query must still find the seeded 'foo@bar' content via the \
8859             quoted-phrase alternative"
8860        );
8861    }
8862
8863    /// The `search_notes` FTS fail-open arm must only degrade genuine FTS5
8864    /// parser syntax errors. A non-parser `StorageError`: e.g. a pool
8865    /// exhaustion or connection timeout on the text-search backend — is not a
8866    /// bad query and must propagate as `Err`, not be silently swallowed into
8867    /// an empty (falsely "successful") result set. `search_notes`,
8868    /// `hybrid_search`, `hybrid_search_with_strategy`, and
8869    /// `collect_recall_text_hits` all share the same `is_fts5_syntax_error()`
8870    /// gate on `StorageError`, so this case generalizes to all four call sites.
8871    #[tokio::test]
8872    async fn search_notes_propagates_non_parser_fts_error() {
8873        let rt = rt();
8874        let tok = NamespaceToken::local();
8875        rt.create_note(
8876            &tok,
8877            "observation",
8878            None,
8879            "FlashAttention reduces memory by using tiling",
8880            Some(0.8),
8881            None,
8882            vec![],
8883        )
8884        .await
8885        .unwrap();
8886
8887        let ns = tok.namespace().as_str().to_string();
8888        arm_fts_search_fail(&ns);
8889
8890        let result = rt
8891            .search_notes(&tok, "FlashAttention", None, 10, None, false, &[], None)
8892            .await;
8893
8894        assert!(
8895            result.is_err(),
8896            "search_notes must propagate a non-parser FTS StorageError (Timeout) \
8897             as Err, not silently degrade it to an empty result, got: {:?}",
8898            result.ok()
8899        );
8900        assert!(
8901            matches!(
8902                result.unwrap_err(),
8903                RuntimeError::Storage(khive_storage::StorageError::Timeout { .. })
8904            ),
8905            "propagated error must be the injected StorageError::Timeout, unwrapped \
8906             through RuntimeError::Storage"
8907        );
8908    }
8909
8910    #[tokio::test]
8911    async fn create_note_with_properties() {
8912        let rt = rt();
8913        let tok = NamespaceToken::local();
8914        let props = serde_json::json!({"source": "arxiv:2205.14135"});
8915        let note = rt
8916            .create_note(
8917                &tok,
8918                "insight",
8919                None,
8920                "FlashAttention is IO-aware",
8921                Some(0.9),
8922                Some(props.clone()),
8923                vec![],
8924            )
8925            .await
8926            .unwrap();
8927
8928        assert_eq!(note.properties.as_ref().unwrap(), &props);
8929    }
8930
8931    #[tokio::test]
8932    async fn create_note_creates_annotates_edges() {
8933        let rt = rt();
8934        let tok = NamespaceToken::local();
8935        let entity = rt
8936            .create_entity(&tok, "concept", None, "FlashAttention", None, None, vec![])
8937            .await
8938            .unwrap();
8939
8940        let note = rt
8941            .create_note(
8942                &tok,
8943                "observation",
8944                None,
8945                "FlashAttention uses SRAM tiling for memory efficiency",
8946                Some(0.9),
8947                None,
8948                vec![entity.id],
8949            )
8950            .await
8951            .unwrap();
8952
8953        // The note should have an outbound `annotates` edge to the entity.
8954        let out_neighbors = rt
8955            .neighbors(
8956                &tok,
8957                note.id,
8958                Direction::Out,
8959                None,
8960                Some(vec![EdgeRelation::Annotates]),
8961            )
8962            .await
8963            .unwrap();
8964        assert_eq!(out_neighbors.len(), 1);
8965        assert_eq!(out_neighbors[0].node_id, entity.id);
8966        assert_eq!(out_neighbors[0].relation, EdgeRelation::Annotates);
8967
8968        // The entity should have an inbound `annotates` edge from the note.
8969        let in_neighbors = rt
8970            .neighbors(
8971                &tok,
8972                entity.id,
8973                Direction::In,
8974                None,
8975                Some(vec![EdgeRelation::Annotates]),
8976            )
8977            .await
8978            .unwrap();
8979        assert_eq!(in_neighbors.len(), 1);
8980        assert_eq!(in_neighbors[0].node_id, note.id);
8981    }
8982
8983    #[tokio::test]
8984    async fn neighbors_without_relation_filter_returns_all() {
8985        let rt = rt();
8986        let tok = NamespaceToken::local();
8987        let a = rt
8988            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8989            .await
8990            .unwrap();
8991        let b = rt
8992            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8993            .await
8994            .unwrap();
8995        let c = rt
8996            .create_entity(&tok, "concept", None, "C", None, None, vec![])
8997            .await
8998            .unwrap();
8999
9000        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9001            .await
9002            .unwrap();
9003        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
9004            .await
9005            .unwrap();
9006
9007        let all = rt
9008            .neighbors(&tok, a.id, Direction::Out, None, None)
9009            .await
9010            .unwrap();
9011        assert_eq!(all.len(), 2);
9012    }
9013
9014    #[tokio::test]
9015    async fn neighbors_with_relation_filter_returns_subset() {
9016        let rt = rt();
9017        let tok = NamespaceToken::local();
9018        let a = rt
9019            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9020            .await
9021            .unwrap();
9022        let b = rt
9023            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9024            .await
9025            .unwrap();
9026        let c = rt
9027            .create_entity(&tok, "concept", None, "C", None, None, vec![])
9028            .await
9029            .unwrap();
9030
9031        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9032            .await
9033            .unwrap();
9034        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
9035            .await
9036            .unwrap();
9037
9038        let filtered = rt
9039            .neighbors(
9040                &tok,
9041                a.id,
9042                Direction::Out,
9043                None,
9044                Some(vec![EdgeRelation::Extends]),
9045            )
9046            .await
9047            .unwrap();
9048        assert_eq!(filtered.len(), 1);
9049        assert_eq!(filtered[0].node_id, b.id);
9050        assert_eq!(filtered[0].relation, EdgeRelation::Extends);
9051    }
9052
9053    /// Self-loop direction parity:
9054    /// `neighbors_with_query_directed`'s post-merge dedup must not collapse a
9055    /// self-loop edge's Out row and In row into one — they share `(node_id,
9056    /// edge_id)` but are opposite directions, matching what a separate `Out`
9057    /// call plus a separate `In` call would return for the same edge. The
9058    /// self-loop edge is inserted directly through the graph store (`link()`
9059    /// rejects source_id == target_id) to exercise the merge/dedup path.
9060    #[tokio::test]
9061    async fn neighbors_with_query_directed_preserves_self_loop_direction_parity() {
9062        let rt = rt();
9063        let tok = NamespaceToken::local();
9064        let centre = rt
9065            .create_entity(&tok, "concept", None, "Centre", None, None, vec![])
9066            .await
9067            .unwrap();
9068
9069        let now = chrono::Utc::now();
9070        rt.graph(&tok)
9071            .unwrap()
9072            .upsert_edge(Edge {
9073                id: LinkId::from(Uuid::new_v4()),
9074                namespace: "local".to_string(),
9075                source_id: centre.id,
9076                target_id: centre.id,
9077                relation: EdgeRelation::Extends,
9078                weight: 0.7,
9079                created_at: now,
9080                updated_at: now,
9081                deleted_at: None,
9082                metadata: None,
9083                target_backend: None,
9084            })
9085            .await
9086            .unwrap();
9087
9088        let directed = rt
9089            .neighbors_with_query_directed(
9090                &tok,
9091                centre.id,
9092                NeighborQuery {
9093                    direction: Direction::Both,
9094                    relations: None,
9095                    limit: None,
9096                    min_weight: None,
9097                },
9098            )
9099            .await
9100            .unwrap();
9101
9102        assert_eq!(
9103            directed.len(),
9104            2,
9105            "a self-loop edge must produce both an Out hit and an In hit, not one collapsed hit"
9106        );
9107        let directions: Vec<Direction> = directed.iter().map(|(_, d)| d.clone()).collect();
9108        assert!(
9109            directions.contains(&Direction::Out),
9110            "self-loop must retain its Out-tagged hit"
9111        );
9112        assert!(
9113            directions.contains(&Direction::In),
9114            "self-loop must retain its In-tagged hit"
9115        );
9116    }
9117
9118    #[tokio::test]
9119    async fn search_notes_returns_relevant_note() {
9120        let rt = rt();
9121        let tok = NamespaceToken::local();
9122        rt.create_note(
9123            &tok,
9124            "observation",
9125            None,
9126            "GQA reduces KV cache memory for large models",
9127            Some(0.8),
9128            None,
9129            vec![],
9130        )
9131        .await
9132        .unwrap();
9133
9134        let results = rt
9135            .search_notes(&tok, "GQA KV cache", None, 10, None, false, &[], None)
9136            .await
9137            .unwrap();
9138
9139        assert!(!results.is_empty(), "search should return the indexed note");
9140        let hit = &results[0];
9141        assert!(
9142            hit.title.is_some(),
9143            "note hit title should be populated (falls back to content)"
9144        );
9145        assert!(
9146            hit.snippet.is_some(),
9147            "note hit snippet should be populated"
9148        );
9149    }
9150
9151    #[tokio::test]
9152    async fn search_notes_excludes_soft_deleted() {
9153        let rt = rt();
9154        let tok = NamespaceToken::local();
9155        let note = rt
9156            .create_note(
9157                &tok,
9158                "observation",
9159                None,
9160                "RoPE positional encoding rotary embeddings",
9161                Some(0.7),
9162                None,
9163                vec![],
9164            )
9165            .await
9166            .unwrap();
9167
9168        // Soft-delete the note.
9169        rt.notes(&tok)
9170            .unwrap()
9171            .delete_note(note.id, DeleteMode::Soft)
9172            .await
9173            .unwrap();
9174
9175        let results = rt
9176            .search_notes(
9177                &tok,
9178                "RoPE rotary positional",
9179                None,
9180                10,
9181                None,
9182                false,
9183                &[],
9184                None,
9185            )
9186            .await
9187            .unwrap();
9188
9189        assert!(
9190            results.iter().all(|h| h.note_id != note.id),
9191            "soft-deleted note should be excluded from search"
9192        );
9193    }
9194
9195    // ---- predicate pushdown before truncation (note branch) ----
9196
9197    /// Regression: notes store tags inside `properties["tags"]`: there is no
9198    /// separate tags column. Without pushdown, the tag filter is applied after
9199    /// `hits.truncate(limit)`, so a tag-matching note ranked beyond `limit` in
9200    /// the raw RRF fusion is silently dropped.
9201    ///
9202    /// Scenario: `limit=1`, tags_any=["note-target-tag"]. Two notes are inserted:
9203    ///   - decoy: high FTS rank (repeats query terms), NO target tag.
9204    ///   - target: lower FTS rank, HAS "note-target-tag" in `properties["tags"]`.
9205    ///
9206    /// Without pushdown: decoy occupies the slot, target is dropped.
9207    /// With pushdown: decoy is excluded in the alive-note loop, target survives, returned.
9208    #[tokio::test]
9209    async fn search_notes_tag_filter_pushed_before_truncation() {
9210        let rt = rt();
9211        let tok = NamespaceToken::local();
9212
9213        // Decoy note: repeats query tokens → higher FTS rank. No target tag.
9214        rt.create_note(
9215            &tok,
9216            "observation",
9217            None,
9218            "kappa lambda mu note decoy kappa lambda mu note decoy kappa lambda mu",
9219            Some(0.5),
9220            Some(serde_json::json!({"tags": ["other-note-tag"]})),
9221            vec![],
9222        )
9223        .await
9224        .unwrap();
9225
9226        // Target note: fewer query tokens → lower FTS rank. Has the target tag.
9227        let target = rt
9228            .create_note(
9229                &tok,
9230                "observation",
9231                None,
9232                "kappa lambda mu note target",
9233                Some(0.5),
9234                Some(serde_json::json!({"tags": ["note-target-tag"]})),
9235                vec![],
9236            )
9237            .await
9238            .unwrap();
9239
9240        // With limit=1 and tags_any, the fix must return the target note despite the
9241        // decoy ranking higher in raw FTS.
9242        let hits = rt
9243            .search_notes(
9244                &tok,
9245                "kappa lambda mu note",
9246                None,
9247                1,
9248                None,
9249                false,
9250                &["note-target-tag".to_string()],
9251                None,
9252            )
9253            .await
9254            .unwrap();
9255
9256        assert_eq!(
9257            hits.len(),
9258            1,
9259            "exactly one hit expected (tag-matching note)"
9260        );
9261        assert_eq!(
9262            hits[0].note_id, target.id,
9263            "tag-filtered note must be returned even when ranked below limit in raw fusion"
9264        );
9265    }
9266
9267    /// Regression: without pushdown, the properties filter is applied after truncation; a matching
9268    /// note ranked beyond `limit` is silently dropped.
9269    ///
9270    /// Scenario: `limit=1`, properties_filter={{"source": "target"}}. Two notes:
9271    ///   - decoy: high FTS rank, properties {{"source": "other"}}.
9272    ///   - target: lower FTS rank, properties {{"source": "target"}}.
9273    #[tokio::test]
9274    async fn search_notes_props_filter_pushed_before_truncation() {
9275        let rt = rt();
9276        let tok = NamespaceToken::local();
9277
9278        rt.create_note(
9279            &tok,
9280            "observation",
9281            None,
9282            "nu xi omicron note decoy nu xi omicron note decoy nu xi omicron",
9283            Some(0.5),
9284            Some(serde_json::json!({"source": "other"})),
9285            vec![],
9286        )
9287        .await
9288        .unwrap();
9289
9290        let target = rt
9291            .create_note(
9292                &tok,
9293                "observation",
9294                None,
9295                "nu xi omicron note target",
9296                Some(0.5),
9297                Some(serde_json::json!({"source": "target"})),
9298                vec![],
9299            )
9300            .await
9301            .unwrap();
9302
9303        let filter = serde_json::json!({"source": "target"});
9304        let hits = rt
9305            .search_notes(
9306                &tok,
9307                "nu xi omicron note",
9308                None,
9309                1,
9310                None,
9311                false,
9312                &[],
9313                Some(&filter),
9314            )
9315            .await
9316            .unwrap();
9317
9318        assert_eq!(
9319            hits.len(),
9320            1,
9321            "exactly one hit expected (properties-matching note)"
9322        );
9323        assert_eq!(
9324            hits[0].note_id, target.id,
9325            "properties-filtered note must be returned even when ranked below limit"
9326        );
9327    }
9328
9329    #[tokio::test]
9330    async fn resolve_returns_entity() {
9331        let rt = rt();
9332        let tok = NamespaceToken::local();
9333        let entity = rt
9334            .create_entity(&tok, "concept", None, "LoRA", None, None, vec![])
9335            .await
9336            .unwrap();
9337
9338        let resolved = rt.resolve(&tok, entity.id).await.unwrap();
9339        match resolved {
9340            Some(Resolved::Entity(e)) => assert_eq!(e.id, entity.id),
9341            other => panic!("expected Resolved::Entity, got {:?}", other),
9342        }
9343    }
9344
9345    #[tokio::test]
9346    async fn resolve_returns_note() {
9347        let rt = rt();
9348        let tok = NamespaceToken::local();
9349        let note = rt
9350            .create_note(
9351                &tok,
9352                "observation",
9353                None,
9354                "LoRA fine-tunes LLMs with low-rank adapters",
9355                Some(0.85),
9356                None,
9357                vec![],
9358            )
9359            .await
9360            .unwrap();
9361
9362        let resolved = rt.resolve(&tok, note.id).await.unwrap();
9363        match resolved {
9364            Some(Resolved::Note(n)) => assert_eq!(n.id, note.id),
9365            other => panic!("expected Resolved::Note, got {:?}", other),
9366        }
9367    }
9368
9369    #[tokio::test]
9370    async fn resolve_returns_none_for_unknown_uuid() {
9371        let rt = rt();
9372        let tok = NamespaceToken::local();
9373        let unknown = Uuid::new_v4();
9374        let resolved = rt.resolve(&tok, unknown).await.unwrap();
9375        assert!(resolved.is_none(), "unknown UUID should resolve to None");
9376    }
9377
9378    #[tokio::test]
9379    async fn resolve_prefix_finds_entity_in_own_namespace() {
9380        let rt = rt();
9381        let tok = NamespaceToken::local();
9382        let entity = rt
9383            .create_entity(&tok, "concept", None, "PrefixTest", None, None, vec![])
9384            .await
9385            .unwrap();
9386        let prefix = &entity.id.to_string()[..8];
9387
9388        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
9389        assert_eq!(resolved, Some(entity.id));
9390    }
9391
9392    #[test]
9393    fn hex_prefix_to_uuid_pattern_inserts_hyphens_at_canonical_boundaries() {
9394        let full = "aabbccdd112240008000000000000ab1";
9395        let cases: &[(usize, &str)] = &[
9396            (1, "a"),
9397            (7, "aabbccd"),
9398            (8, "aabbccdd"),
9399            (9, "aabbccdd-1"),
9400            (12, "aabbccdd-1122"),
9401            (13, "aabbccdd-1122-4"),
9402            (16, "aabbccdd-1122-4000"),
9403            (18, "aabbccdd-1122-4000-80"),
9404            (20, "aabbccdd-1122-4000-8000"),
9405            (23, "aabbccdd-1122-4000-8000-000"),
9406            (24, "aabbccdd-1122-4000-8000-0000"),
9407            (28, "aabbccdd-1122-4000-8000-00000000"),
9408            (31, "aabbccdd-1122-4000-8000-000000000ab"),
9409        ];
9410        for (len, expected) in cases {
9411            let input = &full[..*len];
9412            assert_eq!(
9413                hex_prefix_to_uuid_pattern(input),
9414                *expected,
9415                "len={len} input={input:?}"
9416            );
9417        }
9418    }
9419
9420    #[test]
9421    fn hex_prefix_to_uuid_pattern_full_32_char_matches_canonical_uuid() {
9422        let compact = "aabbccdd112240008000000000000ab1";
9423        let compact32 = &compact[..32];
9424        assert_eq!(
9425            hex_prefix_to_uuid_pattern(compact32),
9426            "aabbccdd-1122-4000-8000-000000000ab1"
9427        );
9428    }
9429
9430    /// Input longer than 32 hex chars is NOT truncated: the extra chars land
9431    /// past the canonical 12-char final
9432    /// segment with no further hyphen, so the pattern can never match a real
9433    /// (36-char) stored `id`, instead of silently truncating down to a
9434    /// pattern that matches the valid 32-char UUID.
9435    #[test]
9436    fn hex_prefix_to_uuid_pattern_overlong_input_is_not_truncated() {
9437        let compact32 = "aabbccdd112240008000000000000ab1";
9438        let overlong = format!("{compact32}extrahex");
9439        let pattern = hex_prefix_to_uuid_pattern(&overlong);
9440        assert_eq!(
9441            pattern, "aabbccdd-1122-4000-8000-000000000ab1extrahex",
9442            "overlong input must keep its extra chars, not truncate to the valid UUID"
9443        );
9444        assert_ne!(
9445            pattern, "aabbccdd-1122-4000-8000-000000000ab1",
9446            "overlong pattern must not collapse to the canonical 36-char UUID form"
9447        );
9448    }
9449
9450    #[test]
9451    fn hex_prefix_to_uuid_pattern_passes_through_hyphenated_input() {
9452        let hyphenated = "aabbccdd-1122-4000-8000-000000000ab1";
9453        assert_eq!(hex_prefix_to_uuid_pattern(hyphenated), hyphenated);
9454
9455        let partial = "aabbccdd-11";
9456        assert_eq!(hex_prefix_to_uuid_pattern(partial), partial);
9457    }
9458
9459    #[test]
9460    fn uuid_prefix_bounds_are_canonical_lowercase_half_open_ranges() {
9461        assert_eq!(
9462            super::uuid_prefix_bounds("0ABCDEFF"),
9463            Some(("0abcdeff".into(), "0abcdf".into()))
9464        );
9465        assert_eq!(
9466            super::uuid_prefix_bounds("aabbccdd1"),
9467            Some(("aabbccdd-1".into(), "aabbccdd-2".into()))
9468        );
9469        assert_eq!(
9470            super::uuid_prefix_bounds("AABBCCDD-19FF"),
9471            Some(("aabbccdd-19ff".into(), "aabbccdd-1a".into()))
9472        );
9473        assert_eq!(
9474            super::uuid_prefix_bounds("ffffffff"),
9475            Some(("ffffffff".into(), "g".into()))
9476        );
9477    }
9478
9479    #[test]
9480    fn uuid_prefix_bounds_reject_malformed_or_overlong_input() {
9481        for invalid in [
9482            "",
9483            "aabbccdd_",
9484            "aabbccdd1-",
9485            "aabbccdd-11111",
9486            "aabbccdd--",
9487            "aabbccdd112240008000000000000ab1f",
9488        ] {
9489            assert_eq!(
9490                super::uuid_prefix_bounds(invalid),
9491                None,
9492                "invalid prefix {invalid:?} must fail closed"
9493            );
9494        }
9495    }
9496
9497    #[tokio::test]
9498    async fn resolve_prefix_compact_9_to_31_char_matches() {
9499        let rt = rt();
9500        let tok = NamespaceToken::local();
9501        let entity = rt
9502            .create_entity(
9503                &tok,
9504                "concept",
9505                None,
9506                "CompactPrefixTest",
9507                None,
9508                None,
9509                vec![],
9510            )
9511            .await
9512            .unwrap();
9513        let compact = entity.id.simple().to_string();
9514
9515        for len in [9, 12, 16, 20, 24, 28, 31] {
9516            let prefix = &compact[..len];
9517            let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
9518            assert_eq!(
9519                resolved,
9520                Some(entity.id),
9521                "compact prefix of len {len} should resolve"
9522            );
9523        }
9524    }
9525
9526    #[tokio::test]
9527    async fn resolve_prefix_compact_full_32_char_matches() {
9528        let rt = rt();
9529        let tok = NamespaceToken::local();
9530        let entity = rt
9531            .create_entity(&tok, "concept", None, "Full32Test", None, None, vec![])
9532            .await
9533            .unwrap();
9534        let compact = entity.id.simple().to_string();
9535        assert_eq!(compact.len(), 32);
9536
9537        let resolved = rt.resolve_prefix(&tok, &compact).await.unwrap();
9538        assert_eq!(resolved, Some(entity.id));
9539    }
9540
9541    /// A valid 32-char compact id with extra trailing hex chars appended must
9542    /// fail to resolve, not silently resolve to the valid entity via truncation.
9543    #[tokio::test]
9544    async fn resolve_prefix_rejects_overlong_all_hex_input() {
9545        let rt = rt();
9546        let tok = NamespaceToken::local();
9547        let entity = rt
9548            .create_entity(&tok, "concept", None, "OverlongTest", None, None, vec![])
9549            .await
9550            .unwrap();
9551        let compact = entity.id.simple().to_string();
9552        assert_eq!(compact.len(), 32);
9553
9554        let overlong = format!("{compact}ab");
9555        let resolved = rt.resolve_prefix(&tok, &overlong).await.unwrap();
9556        assert_eq!(
9557            resolved, None,
9558            "a 32-char id plus extra hex chars must not resolve to the valid entity"
9559        );
9560    }
9561
9562    /// The `resolve_prefix*` boundary rejects
9563    /// non-hex/non-hyphen input (e.g. LIKE wildcards `%`/`_`) instead of
9564    /// letting it reach the bound `LIKE` pattern unfiltered — covers callers
9565    /// (like khive-pack-git/src/ingest.rs) that resolve raw input without
9566    /// their own all-hex gate.
9567    #[tokio::test]
9568    async fn resolve_prefix_rejects_like_wildcard_input() {
9569        let rt = rt();
9570        let tok = NamespaceToken::local();
9571        let entity = rt
9572            .create_entity(&tok, "concept", None, "WildcardTest", None, None, vec![])
9573            .await
9574            .unwrap();
9575        let compact = entity.id.simple().to_string();
9576        // A caller that forgot to hex-gate might pass a `%`-bearing string
9577        // straight through, hoping to broaden a scan; the resolver boundary
9578        // must reject it instead of running it as a wildcard LIKE.
9579        let wildcard_prefix = format!("{}%", &compact[..8]);
9580
9581        let resolved = rt.resolve_prefix(&tok, &wildcard_prefix).await.unwrap();
9582        assert_eq!(
9583            resolved, None,
9584            "prefix containing a LIKE wildcard must be rejected, not resolved"
9585        );
9586    }
9587
9588    #[tokio::test]
9589    async fn resolve_prefix_boundary_at_hyphen_positions() {
9590        let rt = rt();
9591        let tok = NamespaceToken::local();
9592        let entity = rt
9593            .create_entity(&tok, "concept", None, "BoundaryTest", None, None, vec![])
9594            .await
9595            .unwrap();
9596        let compact = entity.id.simple().to_string();
9597
9598        for len in [8, 12, 16, 20, 24] {
9599            let prefix = &compact[..len];
9600            let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
9601            assert_eq!(
9602                resolved,
9603                Some(entity.id),
9604                "boundary prefix of len {len} should resolve"
9605            );
9606        }
9607    }
9608
9609    #[tokio::test]
9610    async fn resolve_prefix_range_preserves_boundaries_ambiguity_and_not_found() {
9611        use khive_storage::entity::Entity;
9612
9613        let rt = rt();
9614        let tok = NamespaceToken::local();
9615        let ids = [
9616            "0abcdefe-ffff-4fff-8fff-ffffffffffff",
9617            "0abcdeff-0000-4000-8000-000000000001",
9618            "0abcdeff-1000-4000-8000-000000000002",
9619            "0abcdf00-0000-4000-8000-000000000003",
9620        ];
9621        let store = rt.entities(&tok).unwrap();
9622        for (index, id) in ids.into_iter().enumerate() {
9623            let mut entity = Entity::new("local", "concept", format!("RangeControl{index}"));
9624            entity.id = Uuid::parse_str(id).unwrap();
9625            store.upsert_entity(entity).await.unwrap();
9626        }
9627
9628        let unique = rt.resolve_prefix(&tok, "0abcdeff0").await.unwrap();
9629        assert_eq!(unique, Some(Uuid::parse_str(ids[1]).unwrap()));
9630
9631        let ambiguous = rt.resolve_prefix(&tok, "0abcdeff").await.unwrap_err();
9632        assert!(
9633            matches!(
9634                ambiguous,
9635                RuntimeError::AmbiguousPrefix { ref matches, .. } if matches.len() == 2
9636            ),
9637            "the two in-range UUIDs must remain ambiguous: {ambiguous:?}"
9638        );
9639
9640        let missing = rt.resolve_prefix(&tok, "0abcdeff2").await.unwrap();
9641        assert_eq!(missing, None, "adjacent UUIDs must not become prefix hits");
9642    }
9643
9644    #[tokio::test]
9645    async fn resolve_prefix_ambiguous_still_detected_after_normalization() {
9646        use khive_storage::entity::Entity;
9647
9648        let rt = rt();
9649        let tok = NamespaceToken::local();
9650        let id_a = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000001").unwrap();
9651        let id_b = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000002").unwrap();
9652
9653        let mut entity_a = Entity::new("local", "concept", "AmbigCompactA");
9654        entity_a.id = id_a;
9655        let mut entity_b = Entity::new("local", "concept", "AmbigCompactB");
9656        entity_b.id = id_b;
9657
9658        let store = rt.entities(&tok).unwrap();
9659        store.upsert_entity(entity_a).await.unwrap();
9660        store.upsert_entity(entity_b).await.unwrap();
9661
9662        // Shared 20-char compact prefix (past the first hyphen boundary).
9663        let shared_compact = &id_a.simple().to_string()[..20];
9664        let err = rt.resolve_prefix(&tok, shared_compact).await.unwrap_err();
9665        assert!(
9666            matches!(
9667                err,
9668                RuntimeError::AmbiguousPrefix { ref matches, .. } if matches.len() == 2
9669            ),
9670            "shared compact prefix must still return AmbiguousPrefix; got {err:?}"
9671        );
9672    }
9673
9674    #[tokio::test]
9675    async fn resolve_prefix_invisible_across_namespaces() {
9676        let rt = rt();
9677        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
9678        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
9679        let entity = rt
9680            .create_entity(&ns_a, "concept", None, "Invisible", None, None, vec![])
9681            .await
9682            .unwrap();
9683        let prefix = &entity.id.to_string()[..8];
9684
9685        // From ns_b, the entity in ns_a should not be visible.
9686        let resolved = rt.resolve_prefix(&ns_b, prefix).await.unwrap();
9687        assert_eq!(resolved, None);
9688    }
9689
9690    #[tokio::test]
9691    async fn resolve_prefix_ambiguous_same_namespace() {
9692        use khive_storage::entity::Entity;
9693
9694        let rt = rt();
9695        let tok = NamespaceToken::local();
9696        // Two entities with UUIDs sharing the same 8-char prefix "aabbccdd".
9697        let id_a = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000001").unwrap();
9698        let id_b = Uuid::parse_str("aabbccdd-2222-4000-8000-000000000002").unwrap();
9699
9700        let mut entity_a = Entity::new("local", "concept", "AmbigA");
9701        entity_a.id = id_a;
9702        let mut entity_b = Entity::new("local", "concept", "AmbigB");
9703        entity_b.id = id_b;
9704
9705        let store = rt.entities(&tok).unwrap();
9706        store.upsert_entity(entity_a).await.unwrap();
9707        store.upsert_entity(entity_b).await.unwrap();
9708
9709        let err = rt.resolve_prefix(&tok, "aabbccdd").await.unwrap_err();
9710        assert!(
9711            matches!(
9712                err,
9713                RuntimeError::AmbiguousPrefix { ref prefix, ref matches }
9714                    if prefix == "aabbccdd" && matches.len() == 2
9715            ),
9716            "shared 8-char prefix must return AmbiguousPrefix; got {err:?}"
9717        );
9718    }
9719
9720    /// A single UUID legitimately present in TWO scanned tables (entities and
9721    /// notes here) must resolve cleanly to that one UUID, not a false
9722    /// `AmbiguousPrefix` naming the same UUID twice: without cross-table
9723    /// dedup, `matches.len()` becomes 2 for a single record.
9724    #[tokio::test]
9725    async fn resolve_prefix_cross_table_duplicate_uuid_resolves_cleanly() {
9726        use khive_storage::entity::Entity;
9727
9728        let rt = rt();
9729        let tok = NamespaceToken::local();
9730        let shared_id = Uuid::parse_str("ccddeeff-1111-4000-8000-000000000001").unwrap();
9731
9732        let mut entity = Entity::new("local", "concept", "Nvk749Entity");
9733        entity.id = shared_id;
9734        rt.entities(&tok)
9735            .unwrap()
9736            .upsert_entity(entity)
9737            .await
9738            .unwrap();
9739
9740        let mut note = Note::new("local", "observation", "nvk749 note with the same id");
9741        note.id = shared_id;
9742        rt.notes(&tok).unwrap().upsert_note(note).await.unwrap();
9743
9744        let resolved = rt
9745            .resolve_prefix(&tok, "ccddeeff")
9746            .await
9747            .expect("#749: a UUID present in two tables must not be reported as ambiguous");
9748        assert_eq!(
9749            resolved,
9750            Some(shared_id),
9751            "#749: cross-table duplicate must resolve to the single shared UUID"
9752        );
9753    }
9754
9755    /// The early-exit inside the per-table scan loop (`if matches.len()
9756    /// > 1 { break }`) must also operate on DEDUPED state — otherwise a
9757    /// cross-table duplicate could still short-circuit the scan before a
9758    /// later table contributes the SAME UUID again, which would have masked
9759    /// the bug rather than exercising it. This drives the duplicate through
9760    /// the earliest two tables scanned (entities, notes) so the early-exit
9761    /// path is the one under test, not a post-loop dedup applied too late.
9762    #[tokio::test]
9763    async fn resolve_prefix_early_exit_uses_deduped_match_count() {
9764        use khive_storage::entity::Entity;
9765
9766        let rt = rt();
9767        let tok = NamespaceToken::local();
9768        let shared_id = Uuid::parse_str("ddeeff11-2222-4000-8000-000000000002").unwrap();
9769
9770        // entities and notes are the first two tables scanned inside
9771        // resolve_prefix_inner — the same UUID in both must not trip the
9772        // mid-scan `matches.len() > 1` break as if two distinct UUIDs had
9773        // been found.
9774        let mut entity = Entity::new("local", "concept", "Nvk749bEntity");
9775        entity.id = shared_id;
9776        rt.entities(&tok)
9777            .unwrap()
9778            .upsert_entity(entity)
9779            .await
9780            .unwrap();
9781
9782        let mut note = Note::new("local", "observation", "nvk749b note with the same id");
9783        note.id = shared_id;
9784        rt.notes(&tok).unwrap().upsert_note(note).await.unwrap();
9785
9786        let resolved = rt
9787            .resolve_prefix(&tok, "ddeeff11")
9788            .await
9789            .expect("#749: deduped early-exit must not falsely report ambiguity");
9790        assert_eq!(resolved, Some(shared_id));
9791    }
9792
9793    // ---- Event resolution tests ----
9794    //
9795    // resolve_prefix and handle_get already include events; these tests are
9796    // regression coverage confirming event UUIDs are resolvable and that get()
9797    // returns kind="event".
9798
9799    #[tokio::test]
9800    async fn resolve_finds_event_by_full_uuid() {
9801        use khive_storage::Event;
9802        use khive_types::{EventKind, SubstrateKind};
9803
9804        let rt = rt();
9805        let tok = NamespaceToken::local();
9806        let ns = tok.namespace().as_str();
9807        let event = Event::new(
9808            ns,
9809            "test_verb",
9810            EventKind::Audit,
9811            SubstrateKind::Entity,
9812            "actor",
9813        );
9814        let event_id = event.id;
9815        rt.events(&tok).unwrap().append_event(event).await.unwrap();
9816
9817        let resolved = rt.resolve(&tok, event_id).await.unwrap();
9818        assert!(
9819            matches!(resolved, Some(Resolved::Event(_))),
9820            "event UUID must resolve to Resolved::Event, got {resolved:?}"
9821        );
9822    }
9823
9824    #[tokio::test]
9825    async fn resolve_prefix_finds_event() {
9826        use khive_storage::Event;
9827        use khive_types::{EventKind, SubstrateKind};
9828
9829        let rt = rt();
9830        let tok = NamespaceToken::local();
9831        let ns = tok.namespace().as_str();
9832        let event = Event::new(
9833            ns,
9834            "test_verb",
9835            EventKind::Audit,
9836            SubstrateKind::Entity,
9837            "actor",
9838        );
9839        let event_id = event.id;
9840        rt.events(&tok).unwrap().append_event(event).await.unwrap();
9841
9842        let prefix = &event_id.to_string()[..8];
9843        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
9844        assert_eq!(
9845            resolved,
9846            Some(event_id),
9847            "resolve_prefix must return event UUID for 8-char prefix"
9848        );
9849    }
9850
9851    // ---- Referential integrity tests ----
9852
9853    #[tokio::test]
9854    async fn link_phantom_source_returns_not_found() {
9855        let rt = rt();
9856        let tok = NamespaceToken::local();
9857        let b = rt
9858            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9859            .await
9860            .unwrap();
9861        let phantom = Uuid::new_v4();
9862
9863        let result = rt
9864            .link(&tok, phantom, b.id, EdgeRelation::Extends, 1.0, None)
9865            .await;
9866        match result {
9867            Err(RuntimeError::NotFound(msg)) => {
9868                assert!(
9869                    msg.contains("source"),
9870                    "error message must name 'source': {msg}"
9871                );
9872            }
9873            other => panic!("expected NotFound for phantom source, got {other:?}"),
9874        }
9875    }
9876
9877    #[tokio::test]
9878    async fn link_phantom_target_returns_not_found() {
9879        let rt = rt();
9880        let tok = NamespaceToken::local();
9881        let a = rt
9882            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9883            .await
9884            .unwrap();
9885        let phantom = Uuid::new_v4();
9886
9887        let result = rt
9888            .link(&tok, a.id, phantom, EdgeRelation::Extends, 1.0, None)
9889            .await;
9890        match result {
9891            Err(RuntimeError::NotFound(msg)) => {
9892                assert!(
9893                    msg.contains("target"),
9894                    "error message must name 'target': {msg}"
9895                );
9896            }
9897            other => panic!("expected NotFound for phantom target, got {other:?}"),
9898        }
9899    }
9900
9901    #[tokio::test]
9902    async fn link_real_entities_succeeds() {
9903        let rt = rt();
9904        let tok = NamespaceToken::local();
9905        let a = rt
9906            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9907            .await
9908            .unwrap();
9909        let b = rt
9910            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9911            .await
9912            .unwrap();
9913
9914        let edge = rt
9915            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
9916            .await
9917            .unwrap();
9918        assert_eq!(edge.source_id, a.id);
9919        assert_eq!(edge.target_id, b.id);
9920        assert_eq!(edge.relation, EdgeRelation::Extends);
9921    }
9922
9923    // ---- commit-time endpoint guard vs concurrent hard-delete ----
9924
9925    /// Deterministic form of the regression, exercised directly at the
9926    /// write step `link` performs after prepare-time validation: build the
9927    /// exact `Edge` `link` would build, delete the target the way a
9928    /// concurrent racer would, and confirm the guarded write refuses it.
9929    #[tokio::test]
9930    async fn link_write_time_guard_blocks_dangling_edge_after_target_vanishes() {
9931        let rt = rt();
9932        let tok = NamespaceToken::local();
9933        let a = rt
9934            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9935            .await
9936            .unwrap();
9937        let x = rt
9938            .create_entity(&tok, "concept", None, "X", None, None, vec![])
9939            .await
9940            .unwrap();
9941
9942        rt.validate_edge_relation_endpoints(&tok, a.id, x.id, EdgeRelation::Extends)
9943            .await
9944            .expect("prepare-time validation must pass while X is live");
9945
9946        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
9947
9948        let now = chrono::Utc::now();
9949        let edge = Edge {
9950            id: LinkId::from(Uuid::new_v4()),
9951            namespace: tok.namespace().as_str().to_string(),
9952            source_id: a.id,
9953            target_id: x.id,
9954            relation: EdgeRelation::Extends,
9955            weight: 1.0,
9956            created_at: now,
9957            updated_at: now,
9958            deleted_at: None,
9959            metadata: None,
9960            target_backend: None,
9961        };
9962        let outcome = rt
9963            .graph(&tok)
9964            .unwrap()
9965            .upsert_edge_guarded(edge)
9966            .await
9967            .unwrap();
9968        match outcome {
9969            khive_storage::GuardedWriteOutcome::Refused(missing) => {
9970                assert!(missing.target, "target must be reported missing");
9971            }
9972            other => panic!(
9973                "guarded write must refuse an edge whose target vanished before commit, got {other:?}"
9974            ),
9975        }
9976
9977        let edges = rt
9978            .list_edges(
9979                &tok,
9980                crate::curation::EdgeListFilter {
9981                    source_id: Some(a.id),
9982                    target_id: Some(x.id),
9983                    relations: vec![EdgeRelation::Extends],
9984                    ..Default::default()
9985                },
9986                10,
9987                0,
9988            )
9989            .await
9990            .unwrap();
9991        assert!(
9992            edges.is_empty(),
9993            "no dangling edge may be persisted after the guarded write refused it"
9994        );
9995    }
9996
9997    #[tokio::test]
9998    async fn link_many_writes_nothing_when_one_target_vanishes_before_write() {
9999        let rt = rt();
10000        let tok = NamespaceToken::local();
10001        let a = rt
10002            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10003            .await
10004            .unwrap();
10005        let b = rt
10006            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10007            .await
10008            .unwrap();
10009        let x = rt
10010            .create_entity(&tok, "concept", None, "X", None, None, vec![])
10011            .await
10012            .unwrap();
10013
10014        let specs = vec![
10015            LinkSpec {
10016                namespace: None,
10017                source_id: a.id,
10018                target_id: x.id,
10019                relation: EdgeRelation::Extends,
10020                weight: 1.0,
10021                metadata: None,
10022            },
10023            LinkSpec {
10024                namespace: None,
10025                source_id: a.id,
10026                target_id: b.id,
10027                relation: EdgeRelation::Extends,
10028                weight: 1.0,
10029                metadata: None,
10030            },
10031        ];
10032
10033        // Both specs validate fine at build_edge time (X and B both live).
10034        let mut edges = Vec::with_capacity(specs.len());
10035        for spec in &specs {
10036            edges.push(rt.build_edge(&tok, spec).await.unwrap());
10037        }
10038
10039        // X vanishes before the batched write — mirrors a concurrent
10040        // hard-delete landing between per-spec validation and link_many's
10041        // single guarded batch write.
10042        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
10043
10044        let outcome = rt
10045            .graph(&tok)
10046            .unwrap()
10047            .upsert_edges_guarded(edges)
10048            .await
10049            .unwrap();
10050        assert_eq!(
10051            outcome.summary.affected, 0,
10052            "no edge from the batch may be persisted when any endpoint vanished"
10053        );
10054        assert!(
10055            outcome.refused.is_some(),
10056            "refused batch entry must be reported"
10057        );
10058
10059        let edges = rt
10060            .list_edges(
10061                &tok,
10062                crate::curation::EdgeListFilter {
10063                    source_id: Some(a.id),
10064                    relations: vec![EdgeRelation::Extends],
10065                    ..Default::default()
10066                },
10067                10,
10068                0,
10069            )
10070            .await
10071            .unwrap();
10072        assert!(
10073            edges.is_empty(),
10074            "link_many's guarded batch must be all-or-nothing: the live A-B edge \
10075             must not have been persisted alongside the doomed A-X edge"
10076        );
10077    }
10078
10079    // ---- hard-delete row + incident-edge purge is ONE transaction ----
10080    //
10081    // Six tests below cover both orderings (write-then-delete, and a
10082    // concurrent write raced against delete via `tokio::join!`) across all
10083    // three hard-delete paths that cascade-purge incident edges: entity,
10084    // note, and edge-as-node. No sleeps — the "concurrent" tests assert an
10085    // invariant that must hold for EITHER interleaving the async scheduler
10086    // picks, rather than forcing one specific interleaving, so they are
10087    // deterministic (never flaky) without a barrier.
10088
10089    fn raw_edge(source_id: Uuid, target_id: Uuid, ns: &str) -> Edge {
10090        let now = chrono::Utc::now();
10091        Edge {
10092            id: LinkId::from(Uuid::new_v4()),
10093            namespace: ns.to_string(),
10094            source_id,
10095            target_id,
10096            relation: EdgeRelation::Extends,
10097            weight: 1.0,
10098            created_at: now,
10099            updated_at: now,
10100            deleted_at: None,
10101            metadata: None,
10102            target_backend: None,
10103        }
10104    }
10105
10106    async fn assert_no_edges_touch(rt: &KhiveRuntime, tok: &NamespaceToken, node_id: Uuid) {
10107        let as_source = rt
10108            .list_edges(
10109                tok,
10110                crate::curation::EdgeListFilter {
10111                    source_id: Some(node_id),
10112                    ..Default::default()
10113                },
10114                10,
10115                0,
10116            )
10117            .await
10118            .unwrap();
10119        let as_target = rt
10120            .list_edges(
10121                tok,
10122                crate::curation::EdgeListFilter {
10123                    target_id: Some(node_id),
10124                    ..Default::default()
10125                },
10126                10,
10127                0,
10128            )
10129            .await
10130            .unwrap();
10131        assert!(
10132            as_source.is_empty() && as_target.is_empty(),
10133            "no edge may reference hard-deleted node {node_id}: source-side={as_source:?} \
10134             target-side={as_target:?}"
10135        );
10136    }
10137
10138    #[tokio::test]
10139    async fn hard_delete_entity_purges_edge_written_before_delete() {
10140        let rt = rt();
10141        let tok = NamespaceToken::local();
10142        let a = rt
10143            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10144            .await
10145            .unwrap();
10146        let x = rt
10147            .create_entity(&tok, "concept", None, "X", None, None, vec![])
10148            .await
10149            .unwrap();
10150
10151        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
10152        assert_eq!(
10153            rt.graph(&tok)
10154                .unwrap()
10155                .upsert_edge_guarded(edge)
10156                .await
10157                .unwrap(),
10158            khive_storage::GuardedWriteOutcome::Written
10159        );
10160
10161        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
10162        assert_no_edges_touch(&rt, &tok, x.id).await;
10163    }
10164
10165    #[tokio::test]
10166    async fn hard_delete_entity_concurrent_with_guarded_write_never_leaves_dangling_edge() {
10167        let rt = std::sync::Arc::new(rt());
10168        let tok = NamespaceToken::local();
10169        let a = rt
10170            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10171            .await
10172            .unwrap();
10173        let x = rt
10174            .create_entity(&tok, "concept", None, "X", None, None, vec![])
10175            .await
10176            .unwrap();
10177
10178        let delete_rt = std::sync::Arc::clone(&rt);
10179        let delete_tok = tok.clone();
10180        let delete_task =
10181            tokio::spawn(async move { delete_rt.delete_entity(&delete_tok, x.id, true).await });
10182
10183        let write_rt = std::sync::Arc::clone(&rt);
10184        let write_tok = tok.clone();
10185        let ns = tok.namespace().as_str().to_string();
10186        let write_task = tokio::spawn(async move {
10187            let edge = raw_edge(a.id, x.id, &ns);
10188            write_rt
10189                .graph(&write_tok)
10190                .unwrap()
10191                .upsert_edge_guarded(edge)
10192                .await
10193        });
10194
10195        let (deleted, _written) = tokio::join!(delete_task, write_task);
10196        deleted.unwrap().unwrap();
10197        assert_no_edges_touch(&rt, &tok, x.id).await;
10198    }
10199
10200    #[tokio::test]
10201    async fn hard_delete_note_purges_edge_written_before_delete() {
10202        let rt = rt();
10203        let tok = NamespaceToken::local();
10204        let a = rt
10205            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10206            .await
10207            .unwrap();
10208        let n = rt
10209            .create_note(
10210                &tok,
10211                "observation",
10212                None,
10213                "note content",
10214                None,
10215                None,
10216                vec![],
10217            )
10218            .await
10219            .unwrap();
10220
10221        let edge = raw_edge(a.id, n.id, tok.namespace().as_str());
10222        assert_eq!(
10223            rt.graph(&tok)
10224                .unwrap()
10225                .upsert_edge_guarded(edge)
10226                .await
10227                .unwrap(),
10228            khive_storage::GuardedWriteOutcome::Written
10229        );
10230
10231        assert!(rt.delete_note(&tok, n.id, true).await.unwrap());
10232        assert_no_edges_touch(&rt, &tok, n.id).await;
10233    }
10234
10235    #[tokio::test]
10236    async fn hard_delete_note_concurrent_with_guarded_write_never_leaves_dangling_edge() {
10237        let rt = std::sync::Arc::new(rt());
10238        let tok = NamespaceToken::local();
10239        let a = rt
10240            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10241            .await
10242            .unwrap();
10243        let n = rt
10244            .create_note(
10245                &tok,
10246                "observation",
10247                None,
10248                "note content",
10249                None,
10250                None,
10251                vec![],
10252            )
10253            .await
10254            .unwrap();
10255
10256        let delete_rt = std::sync::Arc::clone(&rt);
10257        let delete_tok = tok.clone();
10258        let note_id = n.id;
10259        let delete_task =
10260            tokio::spawn(async move { delete_rt.delete_note(&delete_tok, note_id, true).await });
10261
10262        let write_rt = std::sync::Arc::clone(&rt);
10263        let write_tok = tok.clone();
10264        let ns = tok.namespace().as_str().to_string();
10265        let write_task = tokio::spawn(async move {
10266            let edge = raw_edge(a.id, note_id, &ns);
10267            write_rt
10268                .graph(&write_tok)
10269                .unwrap()
10270                .upsert_edge_guarded(edge)
10271                .await
10272        });
10273
10274        let (deleted, _written) = tokio::join!(delete_task, write_task);
10275        deleted.unwrap().unwrap();
10276        assert_no_edges_touch(&rt, &tok, note_id).await;
10277    }
10278
10279    #[tokio::test]
10280    async fn hard_delete_edge_endpoint_purges_annotating_edge_written_before_delete() {
10281        let rt = rt();
10282        let tok = NamespaceToken::local();
10283        let a = rt
10284            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10285            .await
10286            .unwrap();
10287        let b = rt
10288            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10289            .await
10290            .unwrap();
10291        let n = rt
10292            .create_note(
10293                &tok,
10294                "observation",
10295                None,
10296                "note content",
10297                None,
10298                None,
10299                vec![],
10300            )
10301            .await
10302            .unwrap();
10303        let base_edge = rt
10304            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
10305            .await
10306            .unwrap();
10307        let base_edge_id = Uuid::from(base_edge.id);
10308
10309        // An edge whose TARGET is another edge — the "edge-as-node" case
10310        // `delete_edge`'s cascade must sweep.
10311        let annotating = raw_edge(n.id, base_edge_id, tok.namespace().as_str());
10312        assert_eq!(
10313            rt.graph(&tok)
10314                .unwrap()
10315                .upsert_edge_guarded(annotating)
10316                .await
10317                .unwrap(),
10318            khive_storage::GuardedWriteOutcome::Written
10319        );
10320
10321        assert!(rt.delete_edge(&tok, base_edge_id, true).await.unwrap());
10322        assert_no_edges_touch(&rt, &tok, base_edge_id).await;
10323    }
10324
10325    #[tokio::test]
10326    async fn hard_delete_edge_endpoint_concurrent_with_guarded_write_never_leaves_dangling_edge() {
10327        let rt = std::sync::Arc::new(rt());
10328        let tok = NamespaceToken::local();
10329        let a = rt
10330            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10331            .await
10332            .unwrap();
10333        let b = rt
10334            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10335            .await
10336            .unwrap();
10337        let n = rt
10338            .create_note(
10339                &tok,
10340                "observation",
10341                None,
10342                "note content",
10343                None,
10344                None,
10345                vec![],
10346            )
10347            .await
10348            .unwrap();
10349        let base_edge = rt
10350            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
10351            .await
10352            .unwrap();
10353        let base_edge_id = Uuid::from(base_edge.id);
10354
10355        let delete_rt = std::sync::Arc::clone(&rt);
10356        let delete_tok = tok.clone();
10357        let delete_task =
10358            tokio::spawn(
10359                async move { delete_rt.delete_edge(&delete_tok, base_edge_id, true).await },
10360            );
10361
10362        let write_rt = std::sync::Arc::clone(&rt);
10363        let write_tok = tok.clone();
10364        let ns = tok.namespace().as_str().to_string();
10365        let write_task = tokio::spawn(async move {
10366            let edge = raw_edge(n.id, base_edge_id, &ns);
10367            write_rt
10368                .graph(&write_tok)
10369                .unwrap()
10370                .upsert_edge_guarded(edge)
10371                .await
10372        });
10373
10374        let (deleted, _written) = tokio::join!(delete_task, write_task);
10375        deleted.unwrap().unwrap();
10376        assert_no_edges_touch(&rt, &tok, base_edge_id).await;
10377    }
10378
10379    // ---- file-backed, both write-queue configs ----
10380    // The six tests above race delete against the guarded write via `tokio::join!` with
10381    // no ordering control, so the scheduler could run them fully sequentially without
10382    // exercising real interleaving, and neither the file-backed storage path nor
10383    // `write_queue_enabled: Some(true)` (`KHIVE_WRITE_QUEUE=1`) is covered. The four
10384    // tests below force the guarded write to land on one specific side of the delete via
10385    // plain `.await` sequencing instead of an uncontrolled race.
10386
10387    fn file_backed_runtime(
10388        dir: &tempfile::TempDir,
10389        name: &str,
10390        write_queue_enabled: bool,
10391    ) -> KhiveRuntime {
10392        let path = dir.path().join(name);
10393        if write_queue_enabled {
10394            std::env::set_var("KHIVE_WRITE_QUEUE", "1");
10395        } else {
10396            std::env::remove_var("KHIVE_WRITE_QUEUE");
10397        }
10398        let rt = KhiveRuntime::new(crate::config::RuntimeConfig {
10399            db_path: Some(path),
10400            packs: vec!["kg".to_string()],
10401            brain_profile: None,
10402            actor_id: None,
10403            ..crate::config::RuntimeConfig::no_embeddings()
10404        })
10405        .unwrap();
10406        std::env::remove_var("KHIVE_WRITE_QUEUE");
10407        rt
10408    }
10409
10410    async fn assert_guarded_write_committed_before_delete_is_swept(rt: &KhiveRuntime) {
10411        let tok = NamespaceToken::local();
10412        let a = rt
10413            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10414            .await
10415            .unwrap();
10416        let x = rt
10417            .create_entity(&tok, "concept", None, "X", None, None, vec![])
10418            .await
10419            .unwrap();
10420
10421        // Write lands fully committed while X is still live — squarely
10422        // inside the window before the delete's cascade runs.
10423        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
10424        assert_eq!(
10425            rt.graph(&tok)
10426                .unwrap()
10427                .upsert_edge_guarded(edge)
10428                .await
10429                .unwrap(),
10430            khive_storage::GuardedWriteOutcome::Written,
10431            "write must succeed while both endpoints are still live"
10432        );
10433
10434        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
10435        assert_no_edges_touch(rt, &tok, x.id).await;
10436    }
10437
10438    async fn assert_guarded_write_attempted_after_delete_is_refused(rt: &KhiveRuntime) {
10439        let tok = NamespaceToken::local();
10440        let a = rt
10441            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10442            .await
10443            .unwrap();
10444        let x = rt
10445            .create_entity(&tok, "concept", None, "X", None, None, vec![])
10446            .await
10447            .unwrap();
10448
10449        // The delete's transaction has fully committed before the guarded
10450        // write is even attempted — squarely after the window has closed.
10451        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
10452
10453        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
10454        let outcome = rt
10455            .graph(&tok)
10456            .unwrap()
10457            .upsert_edge_guarded(edge)
10458            .await
10459            .unwrap();
10460        match outcome {
10461            khive_storage::GuardedWriteOutcome::Refused(missing) => {
10462                assert!(
10463                    missing.target,
10464                    "target must be reported missing once the delete has committed"
10465                );
10466                assert!(!missing.source, "source was never deleted");
10467            }
10468            other => panic!(
10469                "guarded write attempted after the delete committed must be refused, got {other:?}"
10470            ),
10471        }
10472        assert_no_edges_touch(rt, &tok, x.id).await;
10473    }
10474
10475    #[tokio::test]
10476    #[serial_test::serial(khive_write_queue_env)]
10477    async fn guarded_write_before_delete_swept_file_backed_write_queue_off() {
10478        let dir = tempfile::tempdir().unwrap();
10479        let rt = file_backed_runtime(&dir, "guard_before_off.db", false);
10480        assert_guarded_write_committed_before_delete_is_swept(&rt).await;
10481    }
10482
10483    #[tokio::test]
10484    #[serial_test::serial(khive_write_queue_env)]
10485    async fn guarded_write_after_delete_refused_file_backed_write_queue_off() {
10486        let dir = tempfile::tempdir().unwrap();
10487        let rt = file_backed_runtime(&dir, "guard_after_off.db", false);
10488        assert_guarded_write_attempted_after_delete_is_refused(&rt).await;
10489    }
10490
10491    #[tokio::test]
10492    #[serial_test::serial(khive_write_queue_env)]
10493    async fn guarded_write_before_delete_swept_file_backed_write_queue_on() {
10494        let dir = tempfile::tempdir().unwrap();
10495        let rt = file_backed_runtime(&dir, "guard_before_on.db", true);
10496        assert_guarded_write_committed_before_delete_is_swept(&rt).await;
10497    }
10498
10499    #[tokio::test]
10500    #[serial_test::serial(khive_write_queue_env)]
10501    async fn guarded_write_after_delete_refused_file_backed_write_queue_on() {
10502        let dir = tempfile::tempdir().unwrap();
10503        let rt = file_backed_runtime(&dir, "guard_after_on.db", true);
10504        assert_guarded_write_attempted_after_delete_is_refused(&rt).await;
10505    }
10506
10507    #[tokio::test]
10508    async fn create_note_annotates_phantom_returns_not_found() {
10509        let rt = rt();
10510        let tok = NamespaceToken::local();
10511        let phantom = Uuid::new_v4();
10512
10513        let result = rt
10514            .create_note(
10515                &tok,
10516                "observation",
10517                None,
10518                "some content",
10519                Some(0.5),
10520                None,
10521                vec![phantom],
10522            )
10523            .await;
10524        assert!(
10525            matches!(result, Err(RuntimeError::NotFound(_))),
10526            "annotates with phantom uuid must return NotFound, got {result:?}"
10527        );
10528    }
10529
10530    #[tokio::test]
10531    async fn create_note_annotates_real_entity_succeeds() {
10532        let rt = rt();
10533        let tok = NamespaceToken::local();
10534        let entity = rt
10535            .create_entity(&tok, "concept", None, "RealTarget", None, None, vec![])
10536            .await
10537            .unwrap();
10538
10539        let note = rt
10540            .create_note(
10541                &tok,
10542                "observation",
10543                None,
10544                "content",
10545                Some(0.5),
10546                None,
10547                vec![entity.id],
10548            )
10549            .await
10550            .unwrap();
10551
10552        let neighbors = rt
10553            .neighbors(
10554                &tok,
10555                note.id,
10556                Direction::Out,
10557                None,
10558                Some(vec![EdgeRelation::Annotates]),
10559            )
10560            .await
10561            .unwrap();
10562        assert_eq!(neighbors.len(), 1);
10563        assert_eq!(neighbors[0].node_id, entity.id);
10564    }
10565
10566    // Atomicity: multi-target annotates golden path — all edges created, note present.
10567    #[tokio::test]
10568    async fn create_note_multi_annotates_creates_all_edges() {
10569        let rt = rt();
10570        let tok = NamespaceToken::local();
10571        let t1 = rt
10572            .create_entity(&tok, "concept", None, "Target1", None, None, vec![])
10573            .await
10574            .unwrap();
10575        let t2 = rt
10576            .create_entity(&tok, "concept", None, "Target2", None, None, vec![])
10577            .await
10578            .unwrap();
10579
10580        let note = rt
10581            .create_note(
10582                &tok,
10583                "observation",
10584                None,
10585                "content",
10586                Some(0.5),
10587                None,
10588                vec![t1.id, t2.id],
10589            )
10590            .await
10591            .unwrap();
10592
10593        let neighbors = rt
10594            .neighbors(
10595                &tok,
10596                note.id,
10597                Direction::Out,
10598                None,
10599                Some(vec![EdgeRelation::Annotates]),
10600            )
10601            .await
10602            .unwrap();
10603        assert_eq!(
10604            neighbors.len(),
10605            2,
10606            "multi-annotates note must have exactly 2 outbound annotates edges"
10607        );
10608        let target_ids: Vec<Uuid> = neighbors.iter().map(|n| n.node_id).collect();
10609        assert!(target_ids.contains(&t1.id));
10610        assert!(target_ids.contains(&t2.id));
10611    }
10612
10613    /// The atomic-apply post-commit renderer for a
10614    /// symmetric-edge update resolves the surviving row's store by the CALLER's
10615    /// token but must filter by the record's OWN namespace, passed explicitly —
10616    /// never by re-deriving it from whichever token happened to select the store
10617    /// (`self.graph(token)` scopes by `token.namespace()`, and by-ID edge updates
10618    /// are namespace-agnostic, so a caller in one namespace can legitimately
10619    /// commit an update against an edge recorded in another). This proves the
10620    /// `namespace` parameter — not the `token` argument — decides which row the
10621    /// natural-key lookup finds, at the level that is otherwise an
10622    /// acceptable substitute for a full cross-namespace atomic-apply test.
10623    #[tokio::test]
10624    async fn get_edge_by_natural_key_including_deleted_honors_explicit_namespace_not_token() {
10625        let rt = rt();
10626        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
10627        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
10628
10629        let a = rt
10630            .create_entity(&ns_b, "concept", None, "A", None, None, vec![])
10631            .await
10632            .unwrap();
10633        let b = rt
10634            .create_entity(&ns_b, "concept", None, "B", None, None, vec![])
10635            .await
10636            .unwrap();
10637        let edge = rt
10638            .link(&ns_b, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
10639            .await
10640            .unwrap();
10641        let (canon_src, canon_tgt) =
10642            canonical_edge_endpoints(EdgeRelation::CompetesWith, a.id, b.id);
10643
10644        // Caller token is ns-a (an unrelated namespace); passing "ns-b" explicitly
10645        // must still find the edge recorded there.
10646        let found = rt
10647            .get_edge_by_natural_key_including_deleted(
10648                &ns_a,
10649                "ns-b",
10650                canon_src,
10651                canon_tgt,
10652                EdgeRelation::CompetesWith,
10653            )
10654            .await
10655            .unwrap();
10656        assert_eq!(
10657            found.map(|e| Uuid::from(e.id)),
10658            Some(Uuid::from(edge.id)),
10659            "must find the edge by its own namespace regardless of the caller's token"
10660        );
10661
10662        // Passing the caller token's OWN namespace ("ns-a") as the explicit filter
10663        // must NOT find it — proves the lookup is keyed on the `namespace` argument,
10664        // not silently re-scoped to whatever namespace the token carries.
10665        let not_found = rt
10666            .get_edge_by_natural_key_including_deleted(
10667                &ns_a,
10668                "ns-a",
10669                canon_src,
10670                canon_tgt,
10671                EdgeRelation::CompetesWith,
10672            )
10673            .await
10674            .unwrap();
10675        assert!(
10676            not_found.is_none(),
10677            "must not find an edge recorded in a different namespace than the one queried"
10678        );
10679    }
10680
10681    /// `link` endpoint existence is a by-ID check and therefore namespace-agnostic:
10682    /// a target living in a different namespace than the caller must still
10683    /// resolve, exactly as `get()` would.
10684    #[tokio::test]
10685    async fn link_target_in_different_namespace_succeeds() {
10686        let rt = rt();
10687        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
10688        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
10689        let a = rt
10690            .create_entity(&ns_a, "concept", None, "A", None, None, vec![])
10691            .await
10692            .unwrap();
10693        let b = rt
10694            .create_entity(&ns_b, "concept", None, "B", None, None, vec![])
10695            .await
10696            .unwrap();
10697
10698        // Linking from ns-a: target b lives in ns-b — by-ID resolution finds it anyway.
10699        let result = rt
10700            .link(&ns_a, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10701            .await;
10702        assert!(
10703            result.is_ok(),
10704            "target in a different namespace than the caller must resolve (#631), got {result:?}"
10705        );
10706    }
10707
10708    #[tokio::test]
10709    async fn link_phantom_self_loop_returns_invalid_input() {
10710        let rt = rt();
10711        let tok = NamespaceToken::local();
10712        let phantom = Uuid::new_v4();
10713
10714        let result = rt
10715            .link(&tok, phantom, phantom, EdgeRelation::Extends, 1.0, None)
10716            .await;
10717        match result {
10718            Err(RuntimeError::InvalidInput(msg)) => {
10719                assert!(
10720                    msg.contains("self-loop"),
10721                    "self-loop must be rejected with self-loop message: {msg}"
10722                );
10723            }
10724            other => panic!("expected InvalidInput for self-loop, got {other:?}"),
10725        }
10726    }
10727
10728    // ---- edge target coverage + atomicity ----
10729
10730    #[tokio::test]
10731    async fn link_note_to_edge_annotates_succeeds() {
10732        let rt = rt();
10733        let tok = NamespaceToken::local();
10734        let a = rt
10735            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10736            .await
10737            .unwrap();
10738        let b = rt
10739            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10740            .await
10741            .unwrap();
10742        // Create a real edge between a and b, capture its UUID.
10743        let edge = rt
10744            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10745            .await
10746            .unwrap();
10747        let edge_uuid: Uuid = edge.id.into();
10748
10749        // Create a note and annotate the edge itself (edge is a valid substrate target for annotates).
10750        let note = rt
10751            .create_note(
10752                &tok,
10753                "observation",
10754                None,
10755                "edge note",
10756                Some(0.5),
10757                None,
10758                vec![],
10759            )
10760            .await
10761            .unwrap();
10762
10763        let result = rt
10764            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
10765            .await;
10766        assert!(
10767            result.is_ok(),
10768            "note→edge Annotates must succeed, got {result:?}"
10769        );
10770    }
10771    /// #803: `neighbors(edge_id, direction=In, relations=[Annotates])` must
10772    /// find the annotating note — the storage-layer `graph_edges` query
10773    /// filters on `target_id = node_id` with no substrate-type check, so an
10774    /// edge id works as a neighbor-query node the same as an entity or note
10775    /// id. This is the runtime capability `get(edge_id)`'s new `annotations`
10776    /// field (khive-pack-kg) builds on.
10777    #[tokio::test]
10778    async fn neighbors_edge_id_finds_annotating_note() {
10779        let rt = rt();
10780        let tok = NamespaceToken::local();
10781        let a = rt
10782            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10783            .await
10784            .unwrap();
10785        let b = rt
10786            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10787            .await
10788            .unwrap();
10789        let edge = rt
10790            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10791            .await
10792            .unwrap();
10793        let edge_uuid: Uuid = edge.id.into();
10794
10795        let note = rt
10796            .create_note(
10797                &tok,
10798                "observation",
10799                None,
10800                "edge note",
10801                Some(0.5),
10802                None,
10803                vec![edge_uuid],
10804            )
10805            .await
10806            .unwrap();
10807
10808        let neighbors = rt
10809            .neighbors(
10810                &tok,
10811                edge_uuid,
10812                Direction::In,
10813                None,
10814                Some(vec![EdgeRelation::Annotates]),
10815            )
10816            .await
10817            .unwrap();
10818        assert_eq!(neighbors.len(), 1, "expected annotating note to show up");
10819        assert_eq!(neighbors[0].node_id, note.id);
10820    }
10821
10822    #[tokio::test]
10823    async fn create_note_annotates_real_edge_succeeds() {
10824        let rt = rt();
10825        let tok = NamespaceToken::local();
10826        let a = rt
10827            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10828            .await
10829            .unwrap();
10830        let b = rt
10831            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10832            .await
10833            .unwrap();
10834        let edge = rt
10835            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10836            .await
10837            .unwrap();
10838        let edge_uuid: Uuid = edge.id.into();
10839
10840        let note = rt
10841            .create_note(
10842                &tok,
10843                "observation",
10844                None,
10845                "annotating an edge",
10846                Some(0.5),
10847                None,
10848                vec![edge_uuid],
10849            )
10850            .await
10851            .unwrap();
10852
10853        let neighbors = rt
10854            .neighbors(
10855                &tok,
10856                note.id,
10857                Direction::Out,
10858                None,
10859                Some(vec![EdgeRelation::Annotates]),
10860            )
10861            .await
10862            .unwrap();
10863        assert_eq!(neighbors.len(), 1);
10864        assert_eq!(neighbors[0].node_id, edge_uuid);
10865    }
10866
10867    #[tokio::test]
10868    async fn create_note_annotates_phantom_is_atomic_no_note_persisted() {
10869        let rt = rt();
10870        let tok = NamespaceToken::local();
10871        let phantom = Uuid::new_v4();
10872
10873        let before_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();
10874
10875        let result = rt
10876            .create_note(
10877                &tok,
10878                "observation",
10879                None,
10880                "should not persist",
10881                Some(0.5),
10882                None,
10883                vec![phantom],
10884            )
10885            .await;
10886        assert!(
10887            matches!(result, Err(RuntimeError::NotFound(_))),
10888            "phantom annotates target must return NotFound, got {result:?}"
10889        );
10890
10891        // Atomicity: the note row must NOT have been written.
10892        let after_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();
10893        assert_eq!(
10894            before_count, after_count,
10895            "failed create_note must not persist any note row (atomicity)"
10896        );
10897
10898        // FTS must not contain the content either.
10899        let search_hits = rt
10900            .search_notes(&tok, "should not persist", None, 10, None, false, &[], None)
10901            .await
10902            .unwrap();
10903        assert!(
10904            search_hits.is_empty(),
10905            "failed create_note must not index into FTS (atomicity)"
10906        );
10907        // Vector-store row: only written when an embedding model is configured; the rt()
10908        // harness has none, so no vector assertion is needed here.
10909    }
10910
10911    // ---- relation-aware endpoint contract ----
10912
10913    // Test #2: entity→entity with non-annotates rejects an edge UUID as target.
10914    #[tokio::test]
10915    async fn link_entity_to_edge_uuid_non_annotates_returns_invalid_input() {
10916        let rt = rt();
10917        let tok = NamespaceToken::local();
10918        let a = rt
10919            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10920            .await
10921            .unwrap();
10922        let b = rt
10923            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10924            .await
10925            .unwrap();
10926        // Create a real edge; capture its UUID as the bad target.
10927        let edge = rt
10928            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10929            .await
10930            .unwrap();
10931        let edge_uuid: Uuid = edge.id.into();
10932
10933        let result = rt
10934            .link(&tok, a.id, edge_uuid, EdgeRelation::Extends, 1.0, None)
10935            .await;
10936        match result {
10937            Err(RuntimeError::InvalidInput(msg)) => {
10938                assert!(
10939                    msg.contains("target"),
10940                    "error message must name 'target': {msg}"
10941                );
10942            }
10943            other => {
10944                panic!("expected InvalidInput for edge-uuid target with Extends, got {other:?}")
10945            }
10946        }
10947    }
10948
10949    // Test #3: non-annotates rejects a note UUID as source.
10950    #[tokio::test]
10951    async fn link_note_as_source_non_annotates_returns_invalid_input() {
10952        let rt = rt();
10953        let tok = NamespaceToken::local();
10954        let note = rt
10955            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
10956            .await
10957            .unwrap();
10958        let entity = rt
10959            .create_entity(&tok, "concept", None, "E", None, None, vec![])
10960            .await
10961            .unwrap();
10962
10963        let result = rt
10964            .link(&tok, note.id, entity.id, EdgeRelation::DependsOn, 1.0, None)
10965            .await;
10966        match result {
10967            Err(RuntimeError::InvalidInput(msg)) => {
10968                assert!(
10969                    msg.contains("source"),
10970                    "error message must name 'source': {msg}"
10971                );
10972            }
10973            other => panic!("expected InvalidInput for note source with DependsOn, got {other:?}"),
10974        }
10975    }
10976
10977    // Test #4: annotates rejects entity as source (source must be a note).
10978    #[tokio::test]
10979    async fn link_entity_as_annotates_source_returns_invalid_input() {
10980        let rt = rt();
10981        let tok = NamespaceToken::local();
10982        let a = rt
10983            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10984            .await
10985            .unwrap();
10986        let b = rt
10987            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10988            .await
10989            .unwrap();
10990
10991        let result = rt
10992            .link(&tok, a.id, b.id, EdgeRelation::Annotates, 1.0, None)
10993            .await;
10994        match result {
10995            Err(RuntimeError::InvalidInput(msg)) => {
10996                assert!(
10997                    msg.contains("source") && msg.contains("note"),
10998                    "error must say source must be a note: {msg}"
10999                );
11000            }
11001            other => {
11002                panic!("expected InvalidInput for entity source with Annotates, got {other:?}")
11003            }
11004        }
11005    }
11006
11007    #[tokio::test]
11008    async fn link_edge_as_annotates_source_returns_invalid_input() {
11009        let rt = rt();
11010        let tok = NamespaceToken::local();
11011        let a = rt
11012            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11013            .await
11014            .unwrap();
11015        let b = rt
11016            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11017            .await
11018            .unwrap();
11019        let edge = rt
11020            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11021            .await
11022            .unwrap();
11023        let edge_uuid: Uuid = edge.id.into();
11024
11025        // An existing edge used as an annotates source: wrong kind, not absent.
11026        let result = rt
11027            .link(&tok, edge_uuid, a.id, EdgeRelation::Annotates, 1.0, None)
11028            .await;
11029        match result {
11030            Err(RuntimeError::InvalidInput(msg)) => {
11031                assert!(
11032                    msg.contains("source") && msg.contains("note"),
11033                    "edge-as-annotates-source must report wrong kind, not NotFound: {msg}"
11034                );
11035            }
11036            other => panic!("expected InvalidInput for edge source with Annotates, got {other:?}"),
11037        }
11038    }
11039
11040    // Test #5: note→event with annotates succeeds (event is a valid annotates target).
11041    #[tokio::test]
11042    async fn link_note_to_event_annotates_succeeds() {
11043        use khive_storage::Event;
11044        use khive_types::{EventKind, SubstrateKind};
11045
11046        let rt = rt();
11047        let tok = NamespaceToken::local();
11048        let note = rt
11049            .create_note(
11050                &tok,
11051                "observation",
11052                None,
11053                "observing an event",
11054                Some(0.6),
11055                None,
11056                vec![],
11057            )
11058            .await
11059            .unwrap();
11060
11061        // Build an event directly via the store (no runtime create_event exists).
11062        let ns = tok.namespace().as_str();
11063        let event = Event::new(
11064            ns,
11065            "test_verb",
11066            EventKind::Audit,
11067            SubstrateKind::Entity,
11068            "test_actor",
11069        );
11070        let event_id = event.id;
11071        rt.events(&tok).unwrap().append_event(event).await.unwrap();
11072
11073        let result = rt
11074            .link(&tok, note.id, event_id, EdgeRelation::Annotates, 1.0, None)
11075            .await;
11076        assert!(
11077            result.is_ok(),
11078            "note→event Annotates must succeed, got {result:?}"
11079        );
11080    }
11081
11082    // Test #6: create_note with event as annotates target succeeds.
11083    #[tokio::test]
11084    async fn create_note_annotates_event_succeeds() {
11085        use khive_storage::Event;
11086        use khive_types::{EventKind, SubstrateKind};
11087
11088        let rt = rt();
11089        let tok = NamespaceToken::local();
11090        let ns = tok.namespace().as_str();
11091        let event = Event::new(
11092            ns,
11093            "test_verb",
11094            EventKind::Audit,
11095            SubstrateKind::Entity,
11096            "test_actor",
11097        );
11098        let event_id = event.id;
11099        rt.events(&tok).unwrap().append_event(event).await.unwrap();
11100
11101        let result = rt
11102            .create_note(
11103                &tok,
11104                "observation",
11105                None,
11106                "note annotating an event",
11107                Some(0.5),
11108                None,
11109                vec![event_id],
11110            )
11111            .await;
11112        assert!(
11113            result.is_ok(),
11114            "create_note with event annotates target must succeed, got {result:?}"
11115        );
11116        // Verify the annotates edge was created.
11117        let note = result.unwrap();
11118        let neighbors = rt
11119            .neighbors(
11120                &tok,
11121                note.id,
11122                Direction::Out,
11123                None,
11124                Some(vec![EdgeRelation::Annotates]),
11125            )
11126            .await
11127            .unwrap();
11128        assert_eq!(neighbors.len(), 1);
11129        assert_eq!(neighbors[0].node_id, event_id);
11130    }
11131
11132    // ---- supersedes same-substrate contract ----
11133
11134    #[tokio::test]
11135    async fn link_supersedes_note_to_note_succeeds() {
11136        let rt = rt();
11137        let tok = NamespaceToken::local();
11138        let old_note = rt
11139            .create_note(
11140                &tok,
11141                "observation",
11142                None,
11143                "old observation",
11144                Some(0.7),
11145                None,
11146                vec![],
11147            )
11148            .await
11149            .unwrap();
11150        let new_note = rt
11151            .create_note(
11152                &tok,
11153                "observation",
11154                None,
11155                "revised observation superseding the old one",
11156                Some(0.9),
11157                None,
11158                vec![],
11159            )
11160            .await
11161            .unwrap();
11162
11163        let result = rt
11164            .link(
11165                &tok,
11166                new_note.id,
11167                old_note.id,
11168                EdgeRelation::Supersedes,
11169                1.0,
11170                None,
11171            )
11172            .await;
11173        assert!(
11174            result.is_ok(),
11175            "note→note Supersedes must succeed (note supersession), got {result:?}"
11176        );
11177    }
11178
11179    #[tokio::test]
11180    async fn link_supersedes_entity_to_entity_succeeds() {
11181        let rt = rt();
11182        let tok = NamespaceToken::local();
11183        let old_entity = rt
11184            .create_entity(&tok, "concept", None, "OldConcept", None, None, vec![])
11185            .await
11186            .unwrap();
11187        let new_entity = rt
11188            .create_entity(&tok, "concept", None, "NewConcept", None, None, vec![])
11189            .await
11190            .unwrap();
11191
11192        let result = rt
11193            .link(
11194                &tok,
11195                new_entity.id,
11196                old_entity.id,
11197                EdgeRelation::Supersedes,
11198                1.0,
11199                None,
11200            )
11201            .await;
11202        assert!(
11203            result.is_ok(),
11204            "entity→entity Supersedes must succeed, got {result:?}"
11205        );
11206    }
11207
11208    #[tokio::test]
11209    async fn link_supersedes_note_to_entity_returns_invalid_input() {
11210        let rt = rt();
11211        let tok = NamespaceToken::local();
11212        let note = rt
11213            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
11214            .await
11215            .unwrap();
11216        let entity = rt
11217            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
11218            .await
11219            .unwrap();
11220
11221        let result = rt
11222            .link(
11223                &tok,
11224                note.id,
11225                entity.id,
11226                EdgeRelation::Supersedes,
11227                1.0,
11228                None,
11229            )
11230            .await;
11231        match result {
11232            Err(RuntimeError::InvalidInput(msg)) => {
11233                assert!(
11234                    msg.contains("same substrate") || msg.contains("same-substrate"),
11235                    "error must name the same-substrate rule: {msg}"
11236                );
11237            }
11238            other => panic!(
11239                "expected InvalidInput for note→entity Supersedes (cross-substrate), got {other:?}"
11240            ),
11241        }
11242    }
11243
11244    #[tokio::test]
11245    async fn link_supersedes_entity_to_note_returns_invalid_input() {
11246        let rt = rt();
11247        let tok = NamespaceToken::local();
11248        let entity = rt
11249            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
11250            .await
11251            .unwrap();
11252        let note = rt
11253            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
11254            .await
11255            .unwrap();
11256
11257        let result = rt
11258            .link(
11259                &tok,
11260                entity.id,
11261                note.id,
11262                EdgeRelation::Supersedes,
11263                1.0,
11264                None,
11265            )
11266            .await;
11267        match result {
11268            Err(RuntimeError::InvalidInput(msg)) => {
11269                assert!(
11270                    msg.contains("same substrate") || msg.contains("same-substrate"),
11271                    "error must name the same-substrate rule: {msg}"
11272                );
11273            }
11274            other => panic!(
11275                "expected InvalidInput for entity→note Supersedes (cross-substrate), got {other:?}"
11276            ),
11277        }
11278    }
11279
11280    #[tokio::test]
11281    async fn link_supersedes_event_source_returns_invalid_input() {
11282        use khive_storage::Event;
11283        use khive_types::{EventKind, SubstrateKind};
11284
11285        let rt = rt();
11286        let tok = NamespaceToken::local();
11287        let ns = tok.namespace().as_str();
11288        let event = Event::new(
11289            ns,
11290            "test_verb",
11291            EventKind::Audit,
11292            SubstrateKind::Entity,
11293            "test_actor",
11294        );
11295        let event_id = event.id;
11296        rt.events(&tok).unwrap().append_event(event).await.unwrap();
11297
11298        let entity = rt
11299            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
11300            .await
11301            .unwrap();
11302
11303        let result = rt
11304            .link(
11305                &tok,
11306                event_id,
11307                entity.id,
11308                EdgeRelation::Supersedes,
11309                1.0,
11310                None,
11311            )
11312            .await;
11313        match result {
11314            Err(RuntimeError::InvalidInput(msg)) => {
11315                assert!(msg.contains("event"), "error must mention 'event': {msg}");
11316            }
11317            other => {
11318                panic!("expected InvalidInput for event source with Supersedes, got {other:?}")
11319            }
11320        }
11321    }
11322
11323    #[tokio::test]
11324    async fn link_supersedes_event_target_returns_invalid_input() {
11325        use khive_storage::Event;
11326        use khive_types::{EventKind, SubstrateKind};
11327
11328        let rt = rt();
11329        let tok = NamespaceToken::local();
11330        let ns = tok.namespace().as_str();
11331        let event = Event::new(
11332            ns,
11333            "test_verb",
11334            EventKind::Audit,
11335            SubstrateKind::Entity,
11336            "test_actor",
11337        );
11338        let event_id = event.id;
11339        rt.events(&tok).unwrap().append_event(event).await.unwrap();
11340
11341        let entity = rt
11342            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
11343            .await
11344            .unwrap();
11345
11346        let result = rt
11347            .link(
11348                &tok,
11349                entity.id,
11350                event_id,
11351                EdgeRelation::Supersedes,
11352                1.0,
11353                None,
11354            )
11355            .await;
11356        match result {
11357            Err(RuntimeError::InvalidInput(msg)) => {
11358                assert!(msg.contains("event"), "error must mention 'event': {msg}");
11359            }
11360            other => {
11361                panic!("expected InvalidInput for event target with Supersedes, got {other:?}")
11362            }
11363        }
11364    }
11365
11366    #[tokio::test]
11367    async fn link_supersedes_edge_source_returns_invalid_input() {
11368        let rt = rt();
11369        let tok = NamespaceToken::local();
11370        let a = rt
11371            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11372            .await
11373            .unwrap();
11374        let b = rt
11375            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11376            .await
11377            .unwrap();
11378        let edge = rt
11379            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11380            .await
11381            .unwrap();
11382        let edge_uuid: Uuid = edge.id.into();
11383
11384        let result = rt
11385            .link(&tok, edge_uuid, a.id, EdgeRelation::Supersedes, 1.0, None)
11386            .await;
11387        match result {
11388            Err(RuntimeError::InvalidInput(msg)) => {
11389                assert!(msg.contains("source"), "error must name 'source': {msg}");
11390            }
11391            other => {
11392                panic!("expected InvalidInput for edge-uuid source with Supersedes, got {other:?}")
11393            }
11394        }
11395    }
11396
11397    #[tokio::test]
11398    async fn link_supersedes_edge_target_returns_invalid_input() {
11399        let rt = rt();
11400        let tok = NamespaceToken::local();
11401        let a = rt
11402            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11403            .await
11404            .unwrap();
11405        let b = rt
11406            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11407            .await
11408            .unwrap();
11409        let edge = rt
11410            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11411            .await
11412            .unwrap();
11413        let edge_uuid: Uuid = edge.id.into();
11414
11415        let result = rt
11416            .link(&tok, a.id, edge_uuid, EdgeRelation::Supersedes, 1.0, None)
11417            .await;
11418        match result {
11419            Err(RuntimeError::InvalidInput(msg)) => {
11420                assert!(msg.contains("target"), "error must name 'target': {msg}");
11421            }
11422            other => {
11423                panic!("expected InvalidInput for edge-uuid target with Supersedes, got {other:?}")
11424            }
11425        }
11426    }
11427
11428    #[tokio::test]
11429    async fn link_supersedes_phantom_source_returns_not_found() {
11430        let rt = rt();
11431        let tok = NamespaceToken::local();
11432        let note = rt
11433            .create_note(
11434                &tok,
11435                "observation",
11436                None,
11437                "existing note",
11438                Some(0.5),
11439                None,
11440                vec![],
11441            )
11442            .await
11443            .unwrap();
11444        let phantom = Uuid::new_v4();
11445
11446        let result = rt
11447            .link(&tok, phantom, note.id, EdgeRelation::Supersedes, 1.0, None)
11448            .await;
11449        match result {
11450            Err(RuntimeError::NotFound(msg)) => {
11451                assert!(msg.contains("source"), "error must name 'source': {msg}");
11452            }
11453            other => panic!("expected NotFound for phantom source with Supersedes, got {other:?}"),
11454        }
11455    }
11456
11457    #[tokio::test]
11458    async fn link_supersedes_phantom_target_returns_not_found() {
11459        let rt = rt();
11460        let tok = NamespaceToken::local();
11461        let note = rt
11462            .create_note(
11463                &tok,
11464                "observation",
11465                None,
11466                "existing note",
11467                Some(0.5),
11468                None,
11469                vec![],
11470            )
11471            .await
11472            .unwrap();
11473        let phantom = Uuid::new_v4();
11474
11475        let result = rt
11476            .link(&tok, note.id, phantom, EdgeRelation::Supersedes, 1.0, None)
11477            .await;
11478        match result {
11479            Err(RuntimeError::NotFound(msg)) => {
11480                assert!(msg.contains("target"), "error must name 'target': {msg}");
11481            }
11482            other => panic!("expected NotFound for phantom target with Supersedes, got {other:?}"),
11483        }
11484    }
11485
11486    /// The canonical `remember | supersedes` chain: a `supersedes` source note living
11487    /// in a different namespace than the caller must still resolve as a by-ID endpoint.
11488    #[tokio::test]
11489    async fn link_supersedes_cross_namespace_source_succeeds() {
11490        let rt = rt();
11491        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
11492        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
11493        let note_a = rt
11494            .create_note(
11495                &ns_a,
11496                "observation",
11497                None,
11498                "note in ns-a",
11499                Some(0.5),
11500                None,
11501                vec![],
11502            )
11503            .await
11504            .unwrap();
11505        let note_b = rt
11506            .create_note(
11507                &ns_b,
11508                "observation",
11509                None,
11510                "note in ns-b",
11511                Some(0.5),
11512                None,
11513                vec![],
11514            )
11515            .await
11516            .unwrap();
11517
11518        // From ns-a perspective, note_b is in a different namespace — by-ID resolution
11519        // finds it anyway.
11520        let result = rt
11521            .link(
11522                &ns_a,
11523                note_b.id,
11524                note_a.id,
11525                EdgeRelation::Supersedes,
11526                1.0,
11527                None,
11528            )
11529            .await;
11530        assert!(
11531            result.is_ok(),
11532            "cross-namespace supersedes source must resolve (#631), got {result:?}"
11533        );
11534    }
11535
11536    // Sanity: extends (non-annotates, non-supersedes) still requires entity→entity.
11537    #[tokio::test]
11538    async fn link_extends_note_source_still_returns_invalid_input() {
11539        let rt = rt();
11540        let tok = NamespaceToken::local();
11541        let note = rt
11542            .create_note(
11543                &tok,
11544                "observation",
11545                None,
11546                "a note that cannot be an extends source",
11547                Some(0.5),
11548                None,
11549                vec![],
11550            )
11551            .await
11552            .unwrap();
11553        let entity = rt
11554            .create_entity(&tok, "concept", None, "E", None, None, vec![])
11555            .await
11556            .unwrap();
11557
11558        let result = rt
11559            .link(&tok, note.id, entity.id, EdgeRelation::Extends, 1.0, None)
11560            .await;
11561        assert!(
11562            matches!(result, Err(RuntimeError::InvalidInput(_))),
11563            "note source with Extends must still return InvalidInput after this fix, got {result:?}"
11564        );
11565    }
11566
11567    #[tokio::test]
11568    async fn link_annotates_note_to_edge_still_succeeds_after_fix() {
11569        let rt = rt();
11570        let tok = NamespaceToken::local();
11571        let a = rt
11572            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11573            .await
11574            .unwrap();
11575        let b = rt
11576            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11577            .await
11578            .unwrap();
11579        let edge = rt
11580            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11581            .await
11582            .unwrap();
11583        let edge_uuid: Uuid = edge.id.into();
11584
11585        let note = rt
11586            .create_note(
11587                &tok,
11588                "observation",
11589                None,
11590                "annotating an edge",
11591                Some(0.5),
11592                None,
11593                vec![],
11594            )
11595            .await
11596            .unwrap();
11597
11598        let result = rt
11599            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
11600            .await;
11601        assert!(
11602            result.is_ok(),
11603            "note→edge Annotates must still succeed after supersedes fix, got {result:?}"
11604        );
11605    }
11606
11607    // ---- Compensation-path rollback (fix/annotates) ----
11608
11609    // The compensation branch in `create_note_inner` (operations.rs) rolls back
11610    // a partial write — note row + first edge + FTS + vector — when a subsequent
11611    // link call fails. The failure trigger is a storage error (e.g. I/O failure)
11612    // that cannot occur in the in-memory runtime; this test instead exercises the
11613    // exact cleanup operations that the compensation branch performs, starting from
11614    // a manually-constructed partial state, and verifies the post-cleanup invariants.
11615    //
11616    // What this covers: the cleanup sequence (delete_edge, delete_note hard, FTS
11617    // index clean) is correct and leaves the DB in a pristine state. What it does
11618    // not cover: the trigger condition (second link failure). Storage-error injection
11619    // would require a mock GraphStore, which is beyond the current test infrastructure.
11620    #[tokio::test]
11621    async fn create_note_multi_annotates_compensation_cleanup_restores_pristine_state() {
11622        let rt = rt();
11623        let tok = NamespaceToken::local();
11624        let t1 = rt
11625            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
11626            .await
11627            .unwrap();
11628
11629        // Construct the partial state that the compensation branch would encounter:
11630        // note persisted + first annotates edge created.
11631        let note = rt
11632            .create_note(
11633                &tok,
11634                "observation",
11635                None,
11636                "partial note",
11637                Some(0.5),
11638                None,
11639                vec![t1.id],
11640            )
11641            .await
11642            .unwrap();
11643
11644        // Confirm the partial state exists before compensation.
11645        let before_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11646        assert_eq!(before_notes.len(), 1, "note must be present before cleanup");
11647        let before_edges = rt
11648            .neighbors(
11649                &tok,
11650                note.id,
11651                Direction::Out,
11652                None,
11653                Some(vec![EdgeRelation::Annotates]),
11654            )
11655            .await
11656            .unwrap();
11657        assert_eq!(
11658            before_edges.len(),
11659            1,
11660            "one annotates edge must exist before cleanup"
11661        );
11662        let edge_id: Uuid = before_edges[0].edge_id;
11663
11664        // Execute the same cleanup sequence that `create_note_inner`'s Err branch runs.
11665        rt.delete_edge(&tok, edge_id, true).await.unwrap();
11666        rt.delete_note(&tok, note.id, true /* hard */)
11667            .await
11668            .unwrap();
11669
11670        // Post-compensation invariants:
11671        let after_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11672        assert!(
11673            after_notes.is_empty(),
11674            "compensation must remove the note row; got {after_notes:?}"
11675        );
11676        let search_hits = rt
11677            .search_notes(&tok, "partial note", None, 10, None, false, &[], None)
11678            .await
11679            .unwrap();
11680        assert!(
11681            search_hits.is_empty(),
11682            "compensation must clean the FTS index; got {search_hits:?}"
11683        );
11684        let after_edges = rt
11685            .neighbors(&tok, note.id, Direction::Out, None, None)
11686            .await
11687            .unwrap();
11688        assert!(
11689            after_edges.is_empty(),
11690            "compensation must remove all partial edges; got {after_edges:?}"
11691        );
11692    }
11693
11694    // ---- Hard-delete cascade for note and edge annotation targets (fix/annotates) ----
11695
11696    // annotates is note → ANYTHING (entity, note, edge, event);
11697    // targets may be entity, edge, event, or note.
11698    // Hard-deleting any of those targets must cascade incident annotates edges.
11699    // Soft deletes leave edges (data-vs-view rule).
11700
11701    #[tokio::test]
11702    async fn annotated_entity_hard_delete_cascades_annotate_edge() {
11703        let rt = rt();
11704        let tok = NamespaceToken::local();
11705        let entity = rt
11706            .create_entity(&tok, "concept", None, "E", None, None, vec![])
11707            .await
11708            .unwrap();
11709        let note = rt
11710            .create_note(
11711                &tok,
11712                "observation",
11713                None,
11714                "note about entity",
11715                Some(0.5),
11716                None,
11717                vec![entity.id],
11718            )
11719            .await
11720            .unwrap();
11721
11722        // Confirm edge exists before delete.
11723        let before = rt
11724            .neighbors(
11725                &tok,
11726                note.id,
11727                Direction::Out,
11728                None,
11729                Some(vec![EdgeRelation::Annotates]),
11730            )
11731            .await
11732            .unwrap();
11733        assert_eq!(
11734            before.len(),
11735            1,
11736            "annotates edge must exist before entity delete"
11737        );
11738
11739        // Hard delete the entity.
11740        let deleted = rt.delete_entity(&tok, entity.id, true).await.unwrap();
11741        assert!(deleted, "entity hard delete must return true");
11742
11743        // Annotates edge must be gone.
11744        let after = rt
11745            .neighbors(
11746                &tok,
11747                note.id,
11748                Direction::Out,
11749                None,
11750                Some(vec![EdgeRelation::Annotates]),
11751            )
11752            .await
11753            .unwrap();
11754        assert!(
11755            after.is_empty(),
11756            "annotates edge must be cascaded on entity hard delete; got {after:?}"
11757        );
11758    }
11759
11760    #[tokio::test]
11761    async fn annotated_note_hard_delete_cascades_annotate_edge() {
11762        let rt = rt();
11763        let tok = NamespaceToken::local();
11764        // note_target is the thing being annotated (a note itself).
11765        let note_target = rt
11766            .create_note(
11767                &tok,
11768                "observation",
11769                None,
11770                "target note",
11771                Some(0.5),
11772                None,
11773                vec![],
11774            )
11775            .await
11776            .unwrap();
11777        // note_source annotates note_target.
11778        let note_source = rt
11779            .create_note(
11780                &tok,
11781                "insight",
11782                None,
11783                "annotation",
11784                Some(0.5),
11785                None,
11786                vec![note_target.id],
11787            )
11788            .await
11789            .unwrap();
11790
11791        let before = rt
11792            .neighbors(
11793                &tok,
11794                note_source.id,
11795                Direction::Out,
11796                None,
11797                Some(vec![EdgeRelation::Annotates]),
11798            )
11799            .await
11800            .unwrap();
11801        assert_eq!(
11802            before.len(),
11803            1,
11804            "annotates edge must exist before note delete"
11805        );
11806
11807        // Hard delete the annotation TARGET note.
11808        let deleted = rt.delete_note(&tok, note_target.id, true).await.unwrap();
11809        assert!(deleted, "note hard delete must return true");
11810
11811        // The annotates edge targeting note_target must be gone.
11812        let after = rt
11813            .neighbors(
11814                &tok,
11815                note_source.id,
11816                Direction::Out,
11817                None,
11818                Some(vec![EdgeRelation::Annotates]),
11819            )
11820            .await
11821            .unwrap();
11822        assert!(
11823            after.is_empty(),
11824            "annotates edge must be cascaded on note-target hard delete; got {after:?}"
11825        );
11826    }
11827
11828    #[tokio::test]
11829    async fn annotated_edge_delete_cascades_annotate_edge() {
11830        let rt = rt();
11831        let tok = NamespaceToken::local();
11832        let a = rt
11833            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11834            .await
11835            .unwrap();
11836        let b = rt
11837            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11838            .await
11839            .unwrap();
11840        // Create an edge to annotate.
11841        let base_edge = rt
11842            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11843            .await
11844            .unwrap();
11845        let base_edge_uuid: Uuid = base_edge.id.into();
11846
11847        // Create a note that annotates the edge.
11848        let note = rt
11849            .create_note(
11850                &tok,
11851                "observation",
11852                None,
11853                "note about edge",
11854                Some(0.5),
11855                None,
11856                vec![base_edge_uuid],
11857            )
11858            .await
11859            .unwrap();
11860
11861        let before = rt
11862            .neighbors(
11863                &tok,
11864                note.id,
11865                Direction::Out,
11866                None,
11867                Some(vec![EdgeRelation::Annotates]),
11868            )
11869            .await
11870            .unwrap();
11871        assert_eq!(
11872            before.len(),
11873            1,
11874            "annotates edge must exist before base edge delete"
11875        );
11876
11877        // Delete the base edge.
11878        let deleted = rt.delete_edge(&tok, base_edge_uuid, true).await.unwrap();
11879        assert!(deleted, "edge delete must return true");
11880
11881        // The annotates edge targeting base_edge must be gone.
11882        let after = rt
11883            .neighbors(
11884                &tok,
11885                note.id,
11886                Direction::Out,
11887                None,
11888                Some(vec![EdgeRelation::Annotates]),
11889            )
11890            .await
11891            .unwrap();
11892        assert!(
11893            after.is_empty(),
11894            "annotates edge must be cascaded on base edge delete; got {after:?}"
11895        );
11896    }
11897
11898    #[tokio::test]
11899    async fn mixed_multi_annotates_partial_target_hard_delete_leaves_remaining_edges() {
11900        let rt = rt();
11901        let tok = NamespaceToken::local();
11902        let t1 = rt
11903            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
11904            .await
11905            .unwrap();
11906        let t2 = rt
11907            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
11908            .await
11909            .unwrap();
11910
11911        // Note annotates both t1 and t2.
11912        let note = rt
11913            .create_note(
11914                &tok,
11915                "observation",
11916                None,
11917                "multi-target note",
11918                Some(0.5),
11919                None,
11920                vec![t1.id, t2.id],
11921            )
11922            .await
11923            .unwrap();
11924
11925        let before = rt
11926            .neighbors(
11927                &tok,
11928                note.id,
11929                Direction::Out,
11930                None,
11931                Some(vec![EdgeRelation::Annotates]),
11932            )
11933            .await
11934            .unwrap();
11935        assert_eq!(
11936            before.len(),
11937            2,
11938            "must have 2 annotates edges before any delete"
11939        );
11940
11941        // Hard delete only t1.
11942        rt.delete_entity(&tok, t1.id, true).await.unwrap();
11943
11944        // Edge to t1 must be gone, edge to t2 must remain.
11945        let after = rt
11946            .neighbors(
11947                &tok,
11948                note.id,
11949                Direction::Out,
11950                None,
11951                Some(vec![EdgeRelation::Annotates]),
11952            )
11953            .await
11954            .unwrap();
11955        assert_eq!(
11956            after.len(),
11957            1,
11958            "only the edge to t1 must be cascaded; t2 edge must remain"
11959        );
11960        assert_eq!(
11961            after[0].node_id, t2.id,
11962            "remaining annotates edge must point to t2"
11963        );
11964    }
11965
11966    #[tokio::test]
11967    async fn annotated_note_soft_delete_preserves_annotate_edge() {
11968        let rt = rt();
11969        let tok = NamespaceToken::local();
11970        let note_target = rt
11971            .create_note(&tok, "observation", None, "target", Some(0.5), None, vec![])
11972            .await
11973            .unwrap();
11974        let note_source = rt
11975            .create_note(
11976                &tok,
11977                "insight",
11978                None,
11979                "annotation",
11980                Some(0.5),
11981                None,
11982                vec![note_target.id],
11983            )
11984            .await
11985            .unwrap();
11986
11987        let before = rt
11988            .neighbors(
11989                &tok,
11990                note_source.id,
11991                Direction::Out,
11992                None,
11993                Some(vec![EdgeRelation::Annotates]),
11994            )
11995            .await
11996            .unwrap();
11997        assert_eq!(before.len(), 1);
11998        let edge_id = before[0].edge_id;
11999
12000        // Soft delete must NOT cascade edges (data-vs-view principle).
12001        let deleted = rt.delete_note(&tok, note_target.id, false).await.unwrap();
12002        assert!(deleted, "soft delete must return true");
12003
12004        // The edge itself must survive the soft delete — checked at the
12005        // storage/edge layer directly (`get_edge`), not through `neighbors()`.
12006        // `neighbors()` is a VIEW query and correctly screens
12007        // out soft-deleted note targets — so it no longer surfaces this edge
12008        // once note_target is soft-deleted, even though the edge row itself
12009        // is untouched (data-vs-view principle: the edge is data, what
12010        // `neighbors()` shows is a view decision).
12011        let edge_after = rt.get_edge(&tok, edge_id).await.unwrap();
12012        assert!(
12013            edge_after.is_some(),
12014            "soft delete must NOT cascade edges; get_edge returned None"
12015        );
12016
12017        let after = rt
12018            .neighbors(
12019                &tok,
12020                note_source.id,
12021                Direction::Out,
12022                None,
12023                Some(vec![EdgeRelation::Annotates]),
12024            )
12025            .await
12026            .unwrap();
12027        assert_eq!(
12028            after.len(),
12029            0,
12030            "#748: neighbors() must screen out the soft-deleted note target; got {after:?}"
12031        );
12032    }
12033
12034    // ---- delete_edge public-API safety ----
12035
12036    // Passing an entity/note UUID to `delete_edge` must return Ok(false) with no
12037    // side effects — it must NOT delete inbound annotates edges targeting that record.
12038    // Without the get_edge guard, the old code would cascade inbound edges before
12039    // returning false.
12040    #[tokio::test]
12041    async fn delete_edge_non_edge_uuid_has_no_side_effects() {
12042        let rt = rt();
12043        let tok = NamespaceToken::local();
12044
12045        // Create an entity that has an inbound annotates edge.
12046        let entity = rt
12047            .create_entity(&tok, "concept", None, "Target", None, None, vec![])
12048            .await
12049            .unwrap();
12050        let note = rt
12051            .create_note(
12052                &tok,
12053                "observation",
12054                None,
12055                "annotates the entity",
12056                Some(0.5),
12057                None,
12058                vec![entity.id],
12059            )
12060            .await
12061            .unwrap();
12062
12063        // Confirm the annotates edge exists.
12064        let before = rt
12065            .neighbors(
12066                &tok,
12067                note.id,
12068                Direction::Out,
12069                None,
12070                Some(vec![EdgeRelation::Annotates]),
12071            )
12072            .await
12073            .unwrap();
12074        assert_eq!(before.len(), 1, "annotates edge must exist before test");
12075        let annotates_edge_id: Uuid = before[0].edge_id;
12076
12077        // Call delete_edge with the entity UUID (NOT an edge UUID).
12078        let result = rt.delete_edge(&tok, entity.id, true).await;
12079        assert!(
12080            result.is_ok(),
12081            "delete_edge must not error on a non-edge UUID"
12082        );
12083        assert!(
12084            !result.unwrap(),
12085            "delete_edge must return false for a non-edge UUID"
12086        );
12087
12088        // The inbound annotates edge to the entity must still exist — no side effects.
12089        let after = rt
12090            .neighbors(
12091                &tok,
12092                note.id,
12093                Direction::Out,
12094                None,
12095                Some(vec![EdgeRelation::Annotates]),
12096            )
12097            .await
12098            .unwrap();
12099        assert_eq!(
12100            after.len(),
12101            1,
12102            "delete_edge with a non-edge UUID must not touch inbound annotates edges"
12103        );
12104        assert_eq!(
12105            after[0].edge_id, annotates_edge_id,
12106            "the original annotates edge must be unchanged"
12107        );
12108    }
12109
12110    // ---- create_note compensation branch ----
12111
12112    // This test injects a deterministic failure on the second `link` call inside
12113    // `create_note_inner` (the one that would create the second annotates edge).
12114    // It verifies that the compensation branch is wired — i.e. this test would
12115    // fail if the `Err(e)` rollback arm at operations.rs were deleted.
12116    //
12117    // Injection mechanism: LINK_FAIL_AFTER thread-local (ops.rs, cfg(test) only).
12118    // Setting it to 2 forces the 2nd link call to return an error.  The counter is
12119    // reset to 0 once triggered, so no other test is affected.
12120    #[tokio::test]
12121    async fn create_note_multi_annotates_second_link_failure_rolls_back_partial_write() {
12122        let rt = rt();
12123        let tok = NamespaceToken::local();
12124        let t1 = rt
12125            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
12126            .await
12127            .unwrap();
12128        let t2 = rt
12129            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
12130            .await
12131            .unwrap();
12132
12133        // Arm the injection: fail on the 2nd link (link_idx+1 == 2).
12134        LINK_FAIL_AFTER.with(|cell| cell.set(2));
12135
12136        let result = rt
12137            .create_note(
12138                &tok,
12139                "observation",
12140                None,
12141                "rollback target",
12142                Some(0.5),
12143                None,
12144                vec![t1.id, t2.id],
12145            )
12146            .await;
12147
12148        // The call must fail with the injected error.
12149        assert!(
12150            result.is_err(),
12151            "create_note must propagate the injected link failure"
12152        );
12153        let err_msg = result.unwrap_err().to_string();
12154        assert!(
12155            err_msg.contains("injected link failure"),
12156            "error must carry injection message; got: {err_msg}"
12157        );
12158
12159        // Compensation must have removed the note row.
12160        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12161        assert!(
12162            notes.is_empty(),
12163            "compensation must remove the note row; got {notes:?}"
12164        );
12165
12166        // FTS must have no hit for the content.
12167        let hits = rt
12168            .search_notes(&tok, "rollback target", None, 10, None, false, &[], None)
12169            .await
12170            .unwrap();
12171        assert!(
12172            hits.is_empty(),
12173            "compensation must clean FTS index; got {hits:?}"
12174        );
12175
12176        // No partial annotates edges must remain (first edge must have been deleted).
12177        let edges_from_t1 = rt
12178            .neighbors(
12179                &tok,
12180                t1.id,
12181                Direction::In,
12182                None,
12183                Some(vec![EdgeRelation::Annotates]),
12184            )
12185            .await
12186            .unwrap();
12187        let edges_from_t2 = rt
12188            .neighbors(
12189                &tok,
12190                t2.id,
12191                Direction::In,
12192                None,
12193                Some(vec![EdgeRelation::Annotates]),
12194            )
12195            .await
12196            .unwrap();
12197        assert!(
12198            edges_from_t1.is_empty(),
12199            "compensation must delete the first annotates edge; got {edges_from_t1:?}"
12200        );
12201        assert!(
12202            edges_from_t2.is_empty(),
12203            "no second annotates edge must exist; got {edges_from_t2:?}"
12204        );
12205    }
12206
12207    // Inject an FTS failure after the note row is committed and assert the note
12208    // row is removed (no stranded row). arm_fts_fail_scoped() arms the flag before
12209    // the call and it resets automatically after one trigger.
12210    #[tokio::test]
12211    async fn create_note_fts_failure_rolls_back_note_row() {
12212        let rt = rt();
12213        // Unique namespace: FTS_FAIL_NS is a namespace-keyed set, so a
12214        // concurrently running test arming a different namespace never evicts
12215        // this test's arm. The namespace still guards against a same-test
12216        // mismatch between the armed value and the note actually being created.
12217        let ns = Namespace::parse("fault-fts-rollback").unwrap();
12218        let tok = NamespaceToken::for_namespace(ns.clone());
12219
12220        let _arm = arm_fts_fail_scoped(ns.as_str());
12221
12222        let result = rt
12223            .create_note(
12224                &tok,
12225                "observation",
12226                None,
12227                "fts-fail rollback target",
12228                None,
12229                None,
12230                vec![],
12231            )
12232            .await;
12233
12234        assert!(
12235            result.is_err(),
12236            "create_note must propagate the injected FTS failure"
12237        );
12238        let err_msg = result.unwrap_err().to_string();
12239        assert!(
12240            err_msg.contains("injected FTS failure"),
12241            "error must carry injection message; got: {err_msg}"
12242        );
12243
12244        // Compensation must have removed the note row.
12245        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12246        assert!(
12247            notes.is_empty(),
12248            "compensation must remove the note row after FTS failure; got {notes:?}"
12249        );
12250    }
12251
12252    // Arming FTS_FAIL_NS on one OS thread must still fire on a `create_note`
12253    // call that runs on a genuinely different OS thread. Arms here on the
12254    // test's own (tokio current-thread) task, then hands the triggering
12255    // `create_note` call to a `std::thread::spawn` worker running its own
12256    // single-threaded tokio runtime — a stronger guarantee of thread migration
12257    // than `tokio::spawn`, which may schedule the spawned task back onto the
12258    // same worker. Proves the process-wide, namespace-keyed `FTS_FAIL_NS` set
12259    // is thread-independent.
12260    #[tokio::test]
12261    async fn create_note_fts_failure_fires_across_os_threads() {
12262        let rt = std::sync::Arc::new(rt());
12263        let ns = Namespace::parse("fault-fts-rollback-cross-thread").unwrap();
12264        let tok = NamespaceToken::for_namespace(ns.clone());
12265
12266        let _arm = arm_fts_fail_scoped(ns.as_str());
12267
12268        let thread_rt = std::sync::Arc::clone(&rt);
12269        let thread_tok = tok.clone();
12270        let result = std::thread::spawn(move || {
12271            let worker = tokio::runtime::Builder::new_current_thread()
12272                .enable_all()
12273                .build()
12274                .expect("worker runtime must build");
12275            worker.block_on(thread_rt.create_note(
12276                &thread_tok,
12277                "observation",
12278                None,
12279                "fts-fail rollback target (cross-thread)",
12280                None,
12281                None,
12282                vec![],
12283            ))
12284        })
12285        .join()
12286        .expect("worker thread must not panic");
12287
12288        assert!(
12289            result.is_err(),
12290            "create_note on a different OS thread must still observe the injected FTS failure"
12291        );
12292        let err_msg = result.unwrap_err().to_string();
12293        assert!(
12294            err_msg.contains("injected FTS failure"),
12295            "error must carry injection message; got: {err_msg}"
12296        );
12297
12298        // Compensation must have removed the note row.
12299        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12300        assert!(
12301            notes.is_empty(),
12302            "compensation must remove the note row after FTS failure; got {notes:?}"
12303        );
12304    }
12305
12306    // Inject a vector insertion failure after note row + FTS commit and assert
12307    // both the note row and the FTS document are removed (no stranded rows).
12308    // Uses a unique namespace (see create_note_fts_failure_rolls_back_note_row)
12309    // so only this test consumes its VECTOR_FAIL_NS entry.
12310    // Since the single registered provider fires embed_document before the
12311    // injection check, the injection converts the successful embedding into an
12312    // error just before the VectorStore insert, then disarms.
12313    #[tokio::test]
12314    async fn create_note_vector_failure_rolls_back_note_row_and_fts() {
12315        const MODEL: &str = "test-vec-inject";
12316        const DIMS: usize = 4;
12317
12318        let rt = KhiveRuntime::memory().unwrap();
12319        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
12320        rt.register_embedder(provider);
12321
12322        let ns = Namespace::parse("fault-vec-rollback").unwrap();
12323        let tok = NamespaceToken::for_namespace(ns.clone());
12324
12325        let _arm = arm_vector_fail_scoped(ns.as_str());
12326
12327        let result = rt
12328            .create_note(
12329                &tok,
12330                "observation",
12331                None,
12332                "vec-fail rollback target",
12333                None,
12334                None,
12335                vec![],
12336            )
12337            .await;
12338
12339        assert!(
12340            result.is_err(),
12341            "create_note must propagate the injected vector failure"
12342        );
12343        let err_msg = result.unwrap_err().to_string();
12344        assert!(
12345            err_msg.contains("injected vector failure"),
12346            "error must carry injection message; got: {err_msg}"
12347        );
12348
12349        // Compensation must have removed the note row.
12350        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12351        assert!(
12352            notes.is_empty(),
12353            "compensation must remove note row after vector failure; got {notes:?}"
12354        );
12355    }
12356
12357    #[tokio::test]
12358    async fn vector_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other() {
12359        const MODEL: &str = "test-vec-inject-distinct-namespaces";
12360        const DIMS: usize = 4;
12361
12362        let rt_a = KhiveRuntime::memory().unwrap();
12363        let (provider_a, _counter_a) = ConstVecProvider::new(MODEL, DIMS);
12364        rt_a.register_embedder(provider_a);
12365        let ns_a = Namespace::parse("fault-vec-distinct-a").unwrap();
12366        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
12367
12368        let rt_b = KhiveRuntime::memory().unwrap();
12369        let (provider_b, _counter_b) = ConstVecProvider::new(MODEL, DIMS);
12370        rt_b.register_embedder(provider_b);
12371        let ns_b = Namespace::parse("fault-vec-distinct-b").unwrap();
12372        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
12373
12374        let _arm_a = arm_vector_fail_scoped(ns_a.as_str());
12375        let _arm_b = arm_vector_fail_scoped(ns_b.as_str());
12376
12377        let (result_a, result_b) = tokio::join!(
12378            rt_a.create_note(
12379                &tok_a,
12380                "observation",
12381                None,
12382                "vector failure target A",
12383                None,
12384                None,
12385                vec![],
12386            ),
12387            rt_b.create_note(
12388                &tok_b,
12389                "observation",
12390                None,
12391                "vector failure target B",
12392                None,
12393                None,
12394                vec![],
12395            ),
12396        );
12397
12398        assert!(
12399            result_a.is_err(),
12400            "namespace A must retain its pending vector failure injection"
12401        );
12402        assert!(
12403            result_b.is_err(),
12404            "namespace B must retain its pending vector failure injection"
12405        );
12406    }
12407
12408    // The `embedding_content` override must not bypass the same
12409    // FTS/vector compensation the plain `create_note` path already has —
12410    // both use `create_note_inner` underneath, but these tests exercise it
12411    // through `create_note_with_embedding_content` with a real Some(head)
12412    // override to prove the override path shares the identical rollback.
12413    #[tokio::test]
12414    async fn create_note_with_embedding_content_fts_failure_rolls_back_note_row() {
12415        let rt = rt();
12416        let ns = Namespace::parse("fault-fts-rollback-embedding-content").unwrap();
12417        let tok = NamespaceToken::for_namespace(ns.clone());
12418
12419        let _arm = arm_fts_fail_scoped(ns.as_str());
12420
12421        let full = "fts-fail rollback target with an embedding-content override";
12422        let head = &full[.."fts-fail rollback target".len()];
12423        let result = rt
12424            .create_note_with_embedding_content(
12425                &tok,
12426                "observation",
12427                None,
12428                full,
12429                Some(head),
12430                None,
12431                None,
12432                vec![],
12433            )
12434            .await;
12435
12436        assert!(
12437            result.is_err(),
12438            "create_note_with_embedding_content must propagate the injected FTS failure"
12439        );
12440        let err_msg = result.unwrap_err().to_string();
12441        assert!(
12442            err_msg.contains("injected FTS failure"),
12443            "error must carry injection message; got: {err_msg}"
12444        );
12445
12446        // Compensation must have removed the note row; a failed create must
12447        // never leave a stranded row behind just because it carried an
12448        // embedding_content override.
12449        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12450        assert!(
12451            notes.is_empty(),
12452            "compensation must remove the note row after FTS failure; got {notes:?}"
12453        );
12454    }
12455
12456    #[tokio::test]
12457    async fn create_note_with_embedding_content_vector_failure_rolls_back_note_row_and_fts() {
12458        const MODEL: &str = "test-vec-inject-embedding-content";
12459        const DIMS: usize = 4;
12460
12461        let rt = KhiveRuntime::memory().unwrap();
12462        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
12463        rt.register_embedder(provider);
12464
12465        let ns = Namespace::parse("fault-vec-rollback-embedding-content").unwrap();
12466        let tok = NamespaceToken::for_namespace(ns.clone());
12467
12468        let _arm = arm_vector_fail_scoped(ns.as_str());
12469
12470        let full = "vec-fail rollback target with an embedding-content override";
12471        let head = &full[.."vec-fail rollback target".len()];
12472        let result = rt
12473            .create_note_with_embedding_content(
12474                &tok,
12475                "observation",
12476                None,
12477                full,
12478                Some(head),
12479                None,
12480                None,
12481                vec![],
12482            )
12483            .await;
12484
12485        assert!(
12486            result.is_err(),
12487            "create_note_with_embedding_content must propagate the injected vector failure"
12488        );
12489        let err_msg = result.unwrap_err().to_string();
12490        assert!(
12491            err_msg.contains("injected vector failure"),
12492            "error must carry injection message; got: {err_msg}"
12493        );
12494
12495        // Compensation must have removed the note row: the ingest-layer
12496        // truncation counter only increments in the successful-create arm,
12497        // so a failed create — with or without an embedding_content override
12498        // — can never cause a spurious truncation count on the caller side.
12499        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
12500        assert!(
12501            notes.is_empty(),
12502            "compensation must remove note row after vector failure; got {notes:?}"
12503        );
12504    }
12505
12506    // ---- soft-delete index cleanup tests ----
12507
12508    #[tokio::test]
12509    async fn soft_delete_entity_removes_indexes() {
12510        let rt = rt();
12511        let tok = NamespaceToken::local();
12512        let entity = rt
12513            .create_entity(
12514                &tok,
12515                "concept",
12516                None,
12517                "QuantumEntanglement",
12518                Some("unique FTS term xzqjwv for soft delete test"),
12519                None,
12520                vec![],
12521            )
12522            .await
12523            .unwrap();
12524
12525        let ns = tok.namespace().as_str().to_string();
12526
12527        let before = rt
12528            .text(&tok)
12529            .unwrap()
12530            .search(TextSearchRequest {
12531                query: "xzqjwv".to_string(),
12532                mode: TextQueryMode::Plain,
12533                filter: Some(TextFilter {
12534                    namespaces: vec![ns.clone()],
12535                    ..Default::default()
12536                }),
12537                top_k: 10,
12538                snippet_chars: 100,
12539            })
12540            .await
12541            .unwrap();
12542        assert!(
12543            before.iter().any(|h| h.subject_id == entity.id),
12544            "entity must be in FTS before soft-delete"
12545        );
12546
12547        let deleted = rt.delete_entity(&tok, entity.id, false).await.unwrap();
12548        assert!(deleted, "soft delete must return true");
12549
12550        let after = rt
12551            .text(&tok)
12552            .unwrap()
12553            .search(TextSearchRequest {
12554                query: "xzqjwv".to_string(),
12555                mode: TextQueryMode::Plain,
12556                filter: Some(TextFilter {
12557                    namespaces: vec![ns],
12558                    ..Default::default()
12559                }),
12560                top_k: 10,
12561                snippet_chars: 100,
12562            })
12563            .await
12564            .unwrap();
12565        assert!(
12566            after.iter().all(|h| h.subject_id != entity.id),
12567            "soft-deleted entity must be removed from FTS index"
12568        );
12569    }
12570
12571    #[tokio::test]
12572    async fn soft_delete_note_removes_indexes() {
12573        let rt = rt();
12574        let tok = NamespaceToken::local();
12575        let note = rt
12576            .create_note(
12577                &tok,
12578                "observation",
12579                None,
12580                "SpectralDecomposition unique term yvwkqz for soft delete test",
12581                Some(0.7),
12582                None,
12583                vec![],
12584            )
12585            .await
12586            .unwrap();
12587
12588        let before = rt
12589            .search_notes(&tok, "yvwkqz", None, 10, None, false, &[], None)
12590            .await
12591            .unwrap();
12592        assert!(
12593            before.iter().any(|h| h.note_id == note.id),
12594            "note must be in FTS before soft-delete"
12595        );
12596
12597        let deleted = rt.delete_note(&tok, note.id, false).await.unwrap();
12598        assert!(deleted, "soft delete must return true");
12599
12600        let after = rt
12601            .search_notes(&tok, "yvwkqz", None, 10, None, false, &[], None)
12602            .await
12603            .unwrap();
12604        assert!(
12605            after.iter().all(|h| h.note_id != note.id),
12606            "soft-deleted note must be removed from FTS index"
12607        );
12608    }
12609
12610    // Base endpoint allowlist: unlisted triples must fail closed.
12611    // Document->Document Extends is not in the allowlist.
12612    #[tokio::test]
12613    async fn link_extends_document_to_document_returns_invalid_input() {
12614        let rt = rt();
12615        let tok = NamespaceToken::local();
12616        let d1 = rt
12617            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
12618            .await
12619            .unwrap();
12620        let d2 = rt
12621            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
12622            .await
12623            .unwrap();
12624        let result = rt
12625            .link(&tok, d1.id, d2.id, EdgeRelation::Extends, 1.0, None)
12626            .await;
12627        assert!(
12628            result.is_err(),
12629            "F010: document->document Extends must be rejected by the base allowlist; \
12630             current generic entity fallthrough incorrectly accepts it"
12631        );
12632    }
12633
12634    #[tokio::test]
12635    async fn link_illegal_entity_pair_names_loaded_legal_relations() {
12636        let rt = rt();
12637        let tok = NamespaceToken::local();
12638        rt.install_edge_rules(vec![EdgeEndpointRule {
12639            relation: EdgeRelation::DependsOn,
12640            source: EndpointKind::EntityOfKind("concept"),
12641            target: EndpointKind::EntityOfKind("project"),
12642        }]);
12643        let concept = rt
12644            .create_entity(&tok, "concept", None, "Concept", None, None, vec![])
12645            .await
12646            .unwrap();
12647        let project = rt
12648            .create_entity(&tok, "project", None, "Project", None, None, vec![])
12649            .await
12650            .unwrap();
12651
12652        let error = rt
12653            .link(
12654                &tok,
12655                concept.id,
12656                project.id,
12657                EdgeRelation::CompetesWith,
12658                1.0,
12659                None,
12660            )
12661            .await
12662            .expect_err("concept competes_with project must be rejected");
12663        let message = error.to_string();
12664        assert!(
12665            message.contains(
12666                "currently legal relations for concept -> project under the loaded endpoint rules: depends_on"
12667            ),
12668            "rejection must expose the exact loaded legal set; got: {message}"
12669        );
12670    }
12671
12672    #[test]
12673    fn cross_backend_legal_set_ignores_unenforced_annotates_pack_rule() {
12674        let rt = rt();
12675        rt.install_edge_rules(vec![EdgeEndpointRule {
12676            relation: EdgeRelation::Annotates,
12677            source: EndpointKind::EntityOfKind("concept"),
12678            target: EndpointKind::EntityOfKind("project"),
12679        }]);
12680        let source_id = Uuid::new_v4();
12681        let target_id = Uuid::new_v4();
12682        let source = Resolved::Entity(Entity::new("local", "concept", "Concept"));
12683        let target = Resolved::Entity(Entity::new("local", "project", "Project"));
12684
12685        rt.validate_link_endpoints_by_resolved(
12686            source_id,
12687            target_id,
12688            EdgeRelation::Annotates,
12689            Some(&source),
12690            Some(&target),
12691        )
12692        .expect_err(
12693            "an annotates pack rule cannot override the dedicated note-source validator branch",
12694        );
12695
12696        let error = rt
12697            .validate_link_endpoints_by_resolved(
12698                source_id,
12699                target_id,
12700                EdgeRelation::CompetesWith,
12701                Some(&source),
12702                Some(&target),
12703            )
12704            .expect_err("concept competes_with project must be rejected");
12705        let message = error.to_string();
12706        assert!(
12707            message.contains(
12708                "currently legal relations for concept -> project under the loaded endpoint rules: none"
12709            ),
12710            "an unenforced entity-source annotates pack rule must not be advertised; got: {message}"
12711        );
12712        assert!(
12713            !message.contains("endpoint rules: annotates"),
12714            "the rejection must not call annotates legal when the live validator rejects it; got: {message}"
12715        );
12716    }
12717
12718    // Happy path: Concept->Concept Extends is in the base allowlist and must succeed.
12719    #[tokio::test]
12720    async fn link_extends_concept_to_concept_succeeds() {
12721        let rt = rt();
12722        let tok = NamespaceToken::local();
12723        let a = rt
12724            .create_entity(&tok, "concept", None, "CA", None, None, vec![])
12725            .await
12726            .unwrap();
12727        let b = rt
12728            .create_entity(&tok, "concept", None, "CB", None, None, vec![])
12729            .await
12730            .unwrap();
12731        let result = rt
12732            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
12733            .await;
12734        assert!(
12735            result.is_ok(),
12736            "F010: concept->concept Extends must be allowed (base allowlist)"
12737        );
12738    }
12739
12740    // CompetesWith is symmetric; reversed pair must deduplicate to one canonical row.
12741    #[tokio::test]
12742    async fn link_symmetric_relation_canonicalizes_endpoint_order() {
12743        use khive_storage::EdgeFilter;
12744        let rt = rt();
12745        let tok = NamespaceToken::local();
12746        let a = rt
12747            .create_entity(&tok, "concept", None, "ConceptP", None, None, vec![])
12748            .await
12749            .unwrap();
12750        let b = rt
12751            .create_entity(&tok, "concept", None, "ConceptQ", None, None, vec![])
12752            .await
12753            .unwrap();
12754        // Link A->B then B->A with the same symmetric relation.
12755        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
12756            .await
12757            .unwrap();
12758        rt.link(&tok, b.id, a.id, EdgeRelation::CompetesWith, 1.0, None)
12759            .await
12760            .unwrap();
12761        let count = rt
12762            .graph(&tok)
12763            .unwrap()
12764            .count_edges(EdgeFilter::default())
12765            .await
12766            .unwrap();
12767        assert_eq!(
12768            count,
12769            1,
12770            "F012: CompetesWith is symmetric; A->B and B->A must deduplicate to one canonical row; \
12771             found {count} rows (canonicalization not yet implemented)"
12772        );
12773    }
12774
12775    // Supersedes: positive tests for all 5 allowed entity kinds.
12776    #[tokio::test]
12777    async fn f010_supersedes_document_to_document_allowed() {
12778        let rt = rt();
12779        let tok = NamespaceToken::local();
12780        let a = rt
12781            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
12782            .await
12783            .unwrap();
12784        let b = rt
12785            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
12786            .await
12787            .unwrap();
12788        let result = rt
12789            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12790            .await;
12791        assert!(
12792            result.is_ok(),
12793            "document->document Supersedes must be allowed (allowlist), got {result:?}"
12794        );
12795    }
12796
12797    #[tokio::test]
12798    async fn f010_supersedes_artifact_to_artifact_allowed() {
12799        let rt = rt();
12800        let tok = NamespaceToken::local();
12801        let a = rt
12802            .create_entity(&tok, "artifact", None, "ArtA", None, None, vec![])
12803            .await
12804            .unwrap();
12805        let b = rt
12806            .create_entity(&tok, "artifact", None, "ArtB", None, None, vec![])
12807            .await
12808            .unwrap();
12809        let result = rt
12810            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12811            .await;
12812        assert!(
12813            result.is_ok(),
12814            "artifact->artifact Supersedes must be allowed (allowlist), got {result:?}"
12815        );
12816    }
12817
12818    #[tokio::test]
12819    async fn f010_supersedes_service_to_service_allowed() {
12820        let rt = rt();
12821        let tok = NamespaceToken::local();
12822        let a = rt
12823            .create_entity(&tok, "service", None, "SvcA", None, None, vec![])
12824            .await
12825            .unwrap();
12826        let b = rt
12827            .create_entity(&tok, "service", None, "SvcB", None, None, vec![])
12828            .await
12829            .unwrap();
12830        let result = rt
12831            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12832            .await;
12833        assert!(
12834            result.is_ok(),
12835            "service->service Supersedes must be allowed (allowlist), got {result:?}"
12836        );
12837    }
12838
12839    #[tokio::test]
12840    async fn f010_supersedes_dataset_to_dataset_allowed() {
12841        let rt = rt();
12842        let tok = NamespaceToken::local();
12843        let a = rt
12844            .create_entity(&tok, "dataset", None, "DataA", None, None, vec![])
12845            .await
12846            .unwrap();
12847        let b = rt
12848            .create_entity(&tok, "dataset", None, "DataB", None, None, vec![])
12849            .await
12850            .unwrap();
12851        let result = rt
12852            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12853            .await;
12854        assert!(
12855            result.is_ok(),
12856            "dataset->dataset Supersedes must be allowed (allowlist), got {result:?}"
12857        );
12858    }
12859
12860    // Supersedes: negative tests for rejected entity kinds.
12861    #[tokio::test]
12862    async fn f010_supersedes_project_to_project_rejected() {
12863        let rt = rt();
12864        let tok = NamespaceToken::local();
12865        let a = rt
12866            .create_entity(&tok, "project", None, "ProjA", None, None, vec![])
12867            .await
12868            .unwrap();
12869        let b = rt
12870            .create_entity(&tok, "project", None, "ProjB", None, None, vec![])
12871            .await
12872            .unwrap();
12873        let result = rt
12874            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12875            .await;
12876        assert!(
12877            matches!(result, Err(RuntimeError::InvalidInput(_))),
12878            "project->project Supersedes must be rejected (not in allowlist), got {result:?}"
12879        );
12880    }
12881
12882    #[tokio::test]
12883    async fn f010_supersedes_person_to_person_rejected() {
12884        let rt = rt();
12885        let tok = NamespaceToken::local();
12886        let a = rt
12887            .create_entity(&tok, "person", None, "Alice", None, None, vec![])
12888            .await
12889            .unwrap();
12890        let b = rt
12891            .create_entity(&tok, "person", None, "Bob", None, None, vec![])
12892            .await
12893            .unwrap();
12894        let result = rt
12895            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12896            .await;
12897        assert!(
12898            matches!(result, Err(RuntimeError::InvalidInput(_))),
12899            "person->person Supersedes must be rejected (not in allowlist), got {result:?}"
12900        );
12901    }
12902
12903    #[tokio::test]
12904    async fn f010_supersedes_org_to_org_rejected() {
12905        let rt = rt();
12906        let tok = NamespaceToken::local();
12907        let a = rt
12908            .create_entity(&tok, "org", None, "OrgA", None, None, vec![])
12909            .await
12910            .unwrap();
12911        let b = rt
12912            .create_entity(&tok, "org", None, "OrgB", None, None, vec![])
12913            .await
12914            .unwrap();
12915        let result = rt
12916            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12917            .await;
12918        assert!(
12919            matches!(result, Err(RuntimeError::InvalidInput(_))),
12920            "org->org Supersedes must be rejected (not in allowlist), got {result:?}"
12921        );
12922    }
12923
12924    // Supersedes entity→entity: same kind (concept→concept) must be allowed.
12925    #[tokio::test]
12926    async fn f010_supersedes_same_kind_entity_allowed() {
12927        let rt = rt();
12928        let tok = NamespaceToken::local();
12929        let a = rt
12930            .create_entity(&tok, "concept", None, "OldV", None, None, vec![])
12931            .await
12932            .unwrap();
12933        let b = rt
12934            .create_entity(&tok, "concept", None, "NewV", None, None, vec![])
12935            .await
12936            .unwrap();
12937        let result = rt
12938            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
12939            .await;
12940        assert!(
12941            result.is_ok(),
12942            "concept->concept Supersedes must be allowed by the base allowlist, got {result:?}"
12943        );
12944    }
12945
12946    // target_backend invariant: all edges written through link() must have
12947    // target_backend = None because validate_edge_relation_endpoints already ensured the
12948    // target exists locally.
12949    #[tokio::test]
12950    async fn f161_link_always_writes_null_target_backend() {
12951        let rt = rt();
12952        let tok = NamespaceToken::local();
12953        let a = rt
12954            .create_entity(&tok, "concept", None, "A", None, None, vec![])
12955            .await
12956            .unwrap();
12957        let b = rt
12958            .create_entity(&tok, "concept", None, "B", None, None, vec![])
12959            .await
12960            .unwrap();
12961        let edge = rt
12962            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
12963            .await
12964            .unwrap();
12965        assert!(
12966            edge.target_backend.is_none(),
12967            "F161: target_backend must be None for locally-routed edges; got {:?}",
12968            edge.target_backend
12969        );
12970    }
12971
12972    // link_many must also write null target_backend for all local edges.
12973    #[tokio::test]
12974    async fn f161_link_many_always_writes_null_target_backend() {
12975        let rt = rt();
12976        let tok = NamespaceToken::local();
12977        let a = rt
12978            .create_entity(&tok, "concept", None, "A", None, None, vec![])
12979            .await
12980            .unwrap();
12981        let b = rt
12982            .create_entity(&tok, "concept", None, "B", None, None, vec![])
12983            .await
12984            .unwrap();
12985        let c = rt
12986            .create_entity(&tok, "concept", None, "C", None, None, vec![])
12987            .await
12988            .unwrap();
12989        let specs = vec![
12990            LinkSpec {
12991                namespace: None,
12992                source_id: a.id,
12993                target_id: b.id,
12994                relation: EdgeRelation::Extends,
12995                weight: 1.0,
12996                metadata: None,
12997            },
12998            LinkSpec {
12999                namespace: None,
13000                source_id: a.id,
13001                target_id: c.id,
13002                relation: EdgeRelation::Enables,
13003                weight: 1.0,
13004                metadata: None,
13005            },
13006        ];
13007        let edges = rt.link_many(&tok, specs).await.unwrap();
13008        for edge in &edges {
13009            assert!(
13010                edge.target_backend.is_none(),
13011                "F161: target_backend must be None for locally-routed edges in link_many; got {:?}",
13012                edge.target_backend
13013            );
13014        }
13015    }
13016
13017    // Symmetric relation neighbors: competes_with queried from the non-canonical
13018    // endpoint must still return results when direction=Out is requested.
13019    #[tokio::test]
13020    async fn f012_symmetric_neighbors_visible_from_both_endpoints() {
13021        let rt = rt();
13022        let tok = NamespaceToken::local();
13023        let a = rt
13024            .create_entity(&tok, "concept", None, "A", None, None, vec![])
13025            .await
13026            .unwrap();
13027        let b = rt
13028            .create_entity(&tok, "concept", None, "B", None, None, vec![])
13029            .await
13030            .unwrap();
13031        // Link A→B competes_with; if A.id > B.id the edge is stored as B→A (canonical).
13032        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
13033            .await
13034            .unwrap();
13035        // Both endpoints should see the edge regardless of direction=Out.
13036        let from_a = rt
13037            .neighbors(
13038                &tok,
13039                a.id,
13040                Direction::Out,
13041                None,
13042                Some(vec![EdgeRelation::CompetesWith]),
13043            )
13044            .await
13045            .unwrap();
13046        let from_b = rt
13047            .neighbors(
13048                &tok,
13049                b.id,
13050                Direction::Out,
13051                None,
13052                Some(vec![EdgeRelation::CompetesWith]),
13053            )
13054            .await
13055            .unwrap();
13056        assert_eq!(
13057            from_a.len(),
13058            1,
13059            "node A must see competes_with neighbor from Direction::Out (F012); got {from_a:?}"
13060        );
13061        assert_eq!(
13062            from_b.len(),
13063            1,
13064            "node B must see competes_with neighbor from Direction::Out (F012); got {from_b:?}"
13065        );
13066    }
13067
13068    // Fix 1: Supersedes entity→entity — cross-kind (concept→document) must be rejected.
13069    #[tokio::test]
13070    async fn f010_supersedes_cross_kind_entity_rejected() {
13071        let rt = rt();
13072        let tok = NamespaceToken::local();
13073        let concept = rt
13074            .create_entity(&tok, "concept", None, "MyConcept", None, None, vec![])
13075            .await
13076            .unwrap();
13077        let doc = rt
13078            .create_entity(&tok, "document", None, "MyDoc", None, None, vec![])
13079            .await
13080            .unwrap();
13081        let result = rt
13082            .link(
13083                &tok,
13084                concept.id,
13085                doc.id,
13086                EdgeRelation::Supersedes,
13087                1.0,
13088                None,
13089            )
13090            .await;
13091        assert!(
13092            matches!(result, Err(RuntimeError::InvalidInput(_))),
13093            "concept->document Supersedes must be rejected by the base allowlist, got {result:?}"
13094        );
13095    }
13096
13097    // Cross-namespace delete_note now succeeds (UUID v4 is globally unique,
13098    // no namespace isolation on by-ID ops).
13099    #[tokio::test]
13100    async fn delete_note_cross_namespace_succeeds() {
13101        let rt = rt();
13102        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
13103        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
13104        let note = rt
13105            .create_note(
13106                &ns_a,
13107                "observation",
13108                None,
13109                "note in ns-a",
13110                Some(0.8),
13111                None,
13112                vec![],
13113            )
13114            .await
13115            .unwrap();
13116
13117        // Delete from a different namespace must now SUCCEED.
13118        let result = rt.delete_note(&ns_b, note.id, false).await;
13119        assert!(
13120            result.unwrap(),
13121            "cross-namespace delete_note (soft) must return Ok(true)"
13122        );
13123
13124        // Note must be gone from ns-a storage after the cross-ns soft delete.
13125        let note_store = rt.notes(&ns_a).unwrap();
13126        let gone = note_store.get_note(note.id).await.unwrap();
13127        assert!(
13128            gone.is_none(),
13129            "note must be soft-deleted in its home namespace after cross-ns delete"
13130        );
13131
13132        // Hard-delete path: create a fresh note and hard-delete from foreign token.
13133        let note2 = rt
13134            .create_note(
13135                &ns_a,
13136                "observation",
13137                None,
13138                "note2 in ns-a",
13139                Some(0.5),
13140                None,
13141                vec![],
13142            )
13143            .await
13144            .unwrap();
13145        let hard_result = rt.delete_note(&ns_b, note2.id, true).await;
13146        assert!(
13147            hard_result.unwrap(),
13148            "cross-namespace hard delete_note must return Ok(true)"
13149        );
13150        let gone2 = rt
13151            .get_note_including_deleted(&ns_a, note2.id)
13152            .await
13153            .unwrap();
13154        assert!(
13155            gone2.is_none(),
13156            "hard-deleted note must not appear even in including_deleted query"
13157        );
13158    }
13159
13160    // Regression: parallel link_many calls with overlapping triples must
13161    // return the identical persisted edge ID, not locally-generated phantom IDs.
13162    //
13163    // Sequence:
13164    //   1. First link_many creates the A→B Extends edge (persisted with ID₁).
13165    //   2. Second link_many upserts the same triple (ON CONFLICT DO UPDATE keeps ID₁).
13166    //   3. Both callers must see ID₁ in their returned Vec<Edge>.
13167    #[tokio::test]
13168    async fn link_many_overlapping_triple_returns_persisted_ids() {
13169        let rt = rt();
13170        let tok = NamespaceToken::local();
13171        let a = rt
13172            .create_entity(&tok, "concept", None, "A", None, None, vec![])
13173            .await
13174            .unwrap();
13175        let b = rt
13176            .create_entity(&tok, "concept", None, "B", None, None, vec![])
13177            .await
13178            .unwrap();
13179
13180        let spec = || LinkSpec {
13181            namespace: None,
13182            source_id: a.id,
13183            target_id: b.id,
13184            relation: EdgeRelation::Extends,
13185            weight: 1.0,
13186            metadata: None,
13187        };
13188
13189        // First call — creates the edge.
13190        let first = rt.link_many(&tok, vec![spec()]).await.unwrap();
13191        assert_eq!(first.len(), 1);
13192        let persisted_id: Uuid = first[0].id.into();
13193
13194        // Second call — same natural-key triple; ON CONFLICT updates, preserving the
13195        // existing row ID. link_many must read back the row and return that same ID.
13196        let second = rt.link_many(&tok, vec![spec()]).await.unwrap();
13197        assert_eq!(second.len(), 1);
13198        let second_id: Uuid = second[0].id.into();
13199
13200        assert_eq!(
13201            persisted_id, second_id,
13202            "link_many with an existing triple must return the persisted row ID ({persisted_id}), \
13203             not a new phantom ID ({second_id})"
13204        );
13205
13206        // Confirm only one edge row exists in the graph store.
13207        let count = rt
13208            .count_edges(&tok, crate::curation::EdgeListFilter::default())
13209            .await
13210            .unwrap();
13211        assert_eq!(count, 1, "upsert must not duplicate the edge row");
13212    }
13213
13214    // ── create_many: batch entity creation ───────────────────────────────────
13215
13216    #[tokio::test]
13217    async fn create_many_persists_all_entities() {
13218        let rt = rt();
13219        let tok = NamespaceToken::local();
13220
13221        let specs: Vec<EntityCreateSpec> = (0..5)
13222            .map(|i| EntityCreateSpec {
13223                kind: "concept".into(),
13224                entity_type: None,
13225                name: format!("BulkConcept-{i}"),
13226                description: Some(format!("desc {i}")),
13227                properties: None,
13228                tags: vec!["bulk-test".into()],
13229            })
13230            .collect();
13231
13232        let entities = rt.create_many(&tok, specs).await.unwrap();
13233        assert_eq!(entities.len(), 5, "all 5 entities must be returned");
13234
13235        // Verify each one is retrievable from storage.
13236        for entity in &entities {
13237            let fetched = rt.get_entity(&tok, entity.id).await.unwrap();
13238            assert_eq!(fetched.id, entity.id);
13239        }
13240    }
13241
13242    #[tokio::test]
13243    async fn create_many_empty_name_rejects_atomically() {
13244        let rt = rt();
13245        let tok = NamespaceToken::local();
13246
13247        let specs = vec![
13248            EntityCreateSpec {
13249                kind: "concept".into(),
13250                entity_type: None,
13251                name: "ValidEntity".into(),
13252                description: None,
13253                properties: None,
13254                tags: vec![],
13255            },
13256            EntityCreateSpec {
13257                kind: "concept".into(),
13258                entity_type: None,
13259                name: "".into(), // invalid — triggers atomic rejection
13260                description: None,
13261                properties: None,
13262                tags: vec![],
13263            },
13264        ];
13265
13266        let result = rt.create_many(&tok, specs).await;
13267        assert!(
13268            matches!(result, Err(RuntimeError::InvalidInput(_))),
13269            "empty name must produce InvalidInput error"
13270        );
13271
13272        // Nothing must have been written — list_entities returns 0 items.
13273        let rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
13274        assert_eq!(
13275            rows.len(),
13276            0,
13277            "atomic rejection must leave storage unchanged"
13278        );
13279    }
13280
13281    // entity_type validated at runtime layer when validator is installed.
13282    #[tokio::test]
13283    async fn create_many_rejects_unknown_entity_type_when_validator_installed() {
13284        let rt = rt();
13285        let tok = NamespaceToken::local();
13286
13287        // Install a mock validator that only accepts "algorithm" for "concept".
13288        rt.install_entity_type_validator(Arc::new(|kind, entity_type| {
13289            let Some(raw) = entity_type else {
13290                return Ok(None);
13291            };
13292            if kind == "concept" && raw == "algorithm" {
13293                return Ok(Some("algorithm".to_string()));
13294            }
13295            Err(RuntimeError::InvalidInput(format!(
13296                "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
13297            )))
13298        }));
13299
13300        let bad_spec = vec![EntityCreateSpec {
13301            kind: "concept".into(),
13302            entity_type: Some("not_a_registered_type".into()),
13303            name: "ShouldNotLand".into(),
13304            description: None,
13305            properties: None,
13306            tags: vec![],
13307        }];
13308
13309        let result = rt.create_many(&tok, bad_spec).await;
13310        assert!(
13311            matches!(result, Err(RuntimeError::InvalidInput(_))),
13312            "unknown entity_type must be rejected by the runtime-layer validator; got {result:?}"
13313        );
13314
13315        // Zero rows written — validator fires before any storage call.
13316        let rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
13317        assert_eq!(
13318            rows.len(),
13319            0,
13320            "validator rejection must leave storage empty"
13321        );
13322    }
13323
13324    // Valid entity_type passes through and is normalised by the validator.
13325    #[tokio::test]
13326    async fn create_many_accepts_valid_entity_type_via_validator() {
13327        let rt = rt();
13328        let tok = NamespaceToken::local();
13329
13330        rt.install_entity_type_validator(Arc::new(|kind, entity_type| {
13331            let Some(raw) = entity_type else {
13332                return Ok(None);
13333            };
13334            if kind == "concept" && raw == "algorithm" {
13335                return Ok(Some("algorithm".to_string()));
13336            }
13337            Err(RuntimeError::InvalidInput(format!(
13338                "unknown entity_type {raw:?} for {kind:?}"
13339            )))
13340        }));
13341
13342        let specs = vec![EntityCreateSpec {
13343            kind: "concept".into(),
13344            entity_type: Some("algorithm".into()),
13345            name: "BubbleSort".into(),
13346            description: None,
13347            properties: None,
13348            tags: vec![],
13349        }];
13350
13351        let entities = rt.create_many(&tok, specs).await.unwrap();
13352        assert_eq!(entities.len(), 1, "valid entity_type must be accepted");
13353        assert_eq!(
13354            entities[0].entity_type.as_deref(),
13355            Some("algorithm"),
13356            "entity_type must be stored as returned by the validator"
13357        );
13358    }
13359
13360    // FTS failure in create_many rolls back both substrates.
13361    //
13362    // Arm `arm_fts_fail_many_scoped` before the call; the FTS phase returns an injected
13363    // error; the test asserts zero rows in both `entities` and `fts_entities`.
13364    #[tokio::test]
13365    async fn create_many_fts_failure_rolls_back_both_substrates() {
13366        // Use a unique namespace so only this test consumes its failure entry.
13367        let ns = format!("fts-fail-many-{}", uuid::Uuid::new_v4().as_simple());
13368        let rt = rt();
13369        let tok = NamespaceToken::for_namespace(Namespace::parse(&ns).unwrap());
13370
13371        let specs = vec![
13372            EntityCreateSpec {
13373                kind: "concept".into(),
13374                entity_type: None,
13375                name: "FtsRollbackA".into(),
13376                description: None,
13377                properties: None,
13378                tags: vec![],
13379            },
13380            EntityCreateSpec {
13381                kind: "concept".into(),
13382                entity_type: None,
13383                name: "FtsRollbackB".into(),
13384                description: None,
13385                properties: None,
13386                tags: vec![],
13387            },
13388        ];
13389
13390        let _arm = arm_fts_fail_many_scoped(&ns);
13391        let result = rt.create_many(&tok, specs).await;
13392
13393        assert!(
13394            result.is_err(),
13395            "create_many must return Err when FTS write fails"
13396        );
13397
13398        // Entity substrate must be empty — entity rows must have been rolled back.
13399        let entity_rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
13400        assert_eq!(
13401            entity_rows.len(),
13402            0,
13403            "entity rows must be rolled back on FTS failure; found {entity_rows:?}"
13404        );
13405
13406        // FTS substrate must be empty — no stale fts_entities rows.
13407        let fts = rt.text(&tok).unwrap();
13408        let fts_count = fts
13409            .count(TextFilter {
13410                ids: vec![],
13411                kinds: vec![],
13412                namespaces: vec![ns.clone()],
13413            })
13414            .await
13415            .unwrap();
13416        assert_eq!(
13417            fts_count, 0,
13418            "fts_entities must be empty after FTS-failure rollback; found {fts_count}"
13419        );
13420    }
13421
13422    #[tokio::test]
13423    async fn create_many_fts_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other(
13424    ) {
13425        let rt_a = rt();
13426        let ns_a = Namespace::parse("fts-fail-many-distinct-a").unwrap();
13427        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
13428        let rt_b = rt();
13429        let ns_b = Namespace::parse("fts-fail-many-distinct-b").unwrap();
13430        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
13431
13432        let _arm_a = arm_fts_fail_many_scoped(ns_a.as_str());
13433        let _arm_b = arm_fts_fail_many_scoped(ns_b.as_str());
13434
13435        let (result_a, result_b) = tokio::join!(
13436            rt_a.create_many(
13437                &tok_a,
13438                vec![EntityCreateSpec {
13439                    kind: "concept".into(),
13440                    entity_type: None,
13441                    name: "FtsFailureTargetA".into(),
13442                    description: None,
13443                    properties: None,
13444                    tags: vec![],
13445                }],
13446            ),
13447            rt_b.create_many(
13448                &tok_b,
13449                vec![EntityCreateSpec {
13450                    kind: "concept".into(),
13451                    entity_type: None,
13452                    name: "FtsFailureTargetB".into(),
13453                    description: None,
13454                    properties: None,
13455                    tags: vec![],
13456                }],
13457            ),
13458        );
13459
13460        assert!(
13461            result_a.is_err(),
13462            "namespace A must retain its pending create_many FTS failure injection"
13463        );
13464        assert!(
13465            result_b.is_err(),
13466            "namespace B must retain its pending create_many FTS failure injection"
13467        );
13468    }
13469
13470    // A failure after the first entity and FTS document have been written rolls
13471    // back both substrates for the entire batch. Injected via
13472    // `arm_fts_fail_many_partial_scoped`.
13473    #[tokio::test]
13474    async fn create_many_mid_batch_storage_failure_rolls_back_both_substrates() {
13475        let ns = format!("fts-fail-partial-{}", uuid::Uuid::new_v4().as_simple());
13476        let rt = rt();
13477        let tok = NamespaceToken::for_namespace(Namespace::parse(&ns).unwrap());
13478
13479        let specs = vec![
13480            EntityCreateSpec {
13481                kind: "concept".into(),
13482                entity_type: None,
13483                name: "PartialRollbackA".into(),
13484                description: None,
13485                properties: None,
13486                tags: vec![],
13487            },
13488            EntityCreateSpec {
13489                kind: "concept".into(),
13490                entity_type: None,
13491                name: "PartialRollbackB".into(),
13492                description: None,
13493                properties: None,
13494                tags: vec![],
13495            },
13496        ];
13497
13498        let _arm = arm_fts_fail_many_partial_scoped(&ns);
13499        let result = rt.create_many(&tok, specs).await;
13500
13501        assert!(
13502            result.is_err(),
13503            "create_many must return Err when an FTS write fails mid-batch"
13504        );
13505        let error = result.unwrap_err().to_string();
13506        assert!(
13507            error.contains("atomic batch rolled back at entity index 1"),
13508            "the failure must occur inside the atomic batch after one complete row; got: {error}"
13509        );
13510
13511        // Entity substrate must be empty — entity rows must have been rolled back.
13512        let entity_rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
13513        assert_eq!(
13514            entity_rows.len(),
13515            0,
13516            "entity rows must be empty after a mid-batch FTS failure; found {entity_rows:?}"
13517        );
13518
13519        // FTS substrate must be empty — no stale fts_entities rows.
13520        let fts = rt.text(&tok).unwrap();
13521        let fts_count = fts
13522            .count(TextFilter {
13523                ids: vec![],
13524                kinds: vec![],
13525                namespaces: vec![ns.clone()],
13526            })
13527            .await
13528            .unwrap();
13529        assert_eq!(
13530            fts_count, 0,
13531            "fts_entities must be empty after a mid-batch FTS failure; found {fts_count}"
13532        );
13533    }
13534
13535    #[tokio::test]
13536    async fn create_many_fts_partial_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other(
13537    ) {
13538        let rt_a = rt();
13539        let ns_a = Namespace::parse("fts-fail-many-partial-distinct-a").unwrap();
13540        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
13541        let rt_b = rt();
13542        let ns_b = Namespace::parse("fts-fail-many-partial-distinct-b").unwrap();
13543        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
13544
13545        let _arm_a = arm_fts_fail_many_partial_scoped(ns_a.as_str());
13546        let _arm_b = arm_fts_fail_many_partial_scoped(ns_b.as_str());
13547
13548        let (result_a, result_b) = tokio::join!(
13549            rt_a.create_many(
13550                &tok_a,
13551                vec![EntityCreateSpec {
13552                    kind: "concept".into(),
13553                    entity_type: None,
13554                    name: "FtsPartialFailureTargetA".into(),
13555                    description: None,
13556                    properties: None,
13557                    tags: vec![],
13558                }],
13559            ),
13560            rt_b.create_many(
13561                &tok_b,
13562                vec![EntityCreateSpec {
13563                    kind: "concept".into(),
13564                    entity_type: None,
13565                    name: "FtsPartialFailureTargetB".into(),
13566                    description: None,
13567                    properties: None,
13568                    tags: vec![],
13569                }],
13570            ),
13571        );
13572
13573        assert!(
13574            result_a.is_err(),
13575            "namespace A must retain its pending create_many partial FTS failure injection"
13576        );
13577        assert!(
13578            result_b.is_err(),
13579            "namespace B must retain its pending create_many partial FTS failure injection"
13580        );
13581    }
13582
13583    // ── Cross-namespace get_edge now succeeds (UUID v4 is globally unique) ──
13584
13585    #[tokio::test]
13586    async fn get_edge_cross_namespace_succeeds() {
13587        let rt = rt();
13588        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
13589        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
13590
13591        let src = rt
13592            .create_entity(&ns_a, "concept", None, "Src", None, None, vec![])
13593            .await
13594            .unwrap();
13595        let tgt = rt
13596            .create_entity(&ns_a, "concept", None, "Tgt", None, None, vec![])
13597            .await
13598            .unwrap();
13599        let edge = rt
13600            .link(&ns_a, src.id, tgt.id, EdgeRelation::Extends, 1.0, None)
13601            .await
13602            .unwrap();
13603
13604        // Visible from own namespace.
13605        let own_ns = rt.get_edge(&ns_a, Uuid::from(edge.id)).await;
13606        assert!(
13607            own_ns.is_ok() && own_ns.unwrap().is_some(),
13608            "edge must be visible in its own namespace"
13609        );
13610
13611        // Foreign namespace must now SUCCEED: by-ID get is namespace-agnostic.
13612        let cross_ns = rt.get_edge(&ns_b, Uuid::from(edge.id)).await;
13613        assert!(
13614            matches!(cross_ns, Ok(Some(_))),
13615            "cross-namespace get_edge must return Ok(Some(_)) after PR-A1, got {cross_ns:?}"
13616        );
13617
13618        // Absent edge UUID still returns None regardless of token namespace.
13619        let absent = rt.get_edge(&ns_b, Uuid::new_v4()).await;
13620        assert!(
13621            matches!(absent, Ok(None)),
13622            "absent edge must return Ok(None), got {absent:?}"
13623        );
13624    }
13625
13626    // get_entity finds any entity by UUID; traverse finds the root and returns paths
13627    // scoped to the graph store's namespace filter for ns_b, even when the token's
13628    // namespace differs from the root's.
13629    #[tokio::test]
13630    async fn traverse_cross_namespace_root_is_accepted() {
13631        use khive_storage::types::TraversalOptions;
13632
13633        let rt = rt();
13634        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
13635        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
13636
13637        let a = rt
13638            .create_entity(&ns_a, "concept", None, "A", None, None, vec![])
13639            .await
13640            .unwrap();
13641        rt.create_entity(&ns_a, "concept", None, "B", None, None, vec![])
13642            .await
13643            .unwrap();
13644        rt.link(&ns_a, a.id, a.id, EdgeRelation::Extends, 1.0, None)
13645            .await
13646            .ok(); // may conflict with self-loop check; we just need an entity
13647
13648        // substrate_exists_in_ns finds the ns_a root via get_entity
13649        // (UUID-global lookup). The traverse proceeds; no panic.
13650        let result = rt
13651            .traverse(
13652                &ns_b,
13653                TraversalRequest {
13654                    roots: vec![a.id],
13655                    options: TraversalOptions {
13656                        max_depth: 1,
13657                        direction: Direction::Out,
13658                        ..Default::default()
13659                    },
13660                    include_roots: true,
13661                    include_properties: false,
13662                    execution_budget: Default::default(),
13663                },
13664            )
13665            .await;
13666        assert!(result.is_ok(), "traverse must not error; got {:?}", result);
13667    }
13668
13669    // ── Single root visible in multiple namespaces must yield exactly one
13670    //    traversal object (see merge_traversal_paths_by_root) ─────────────
13671    #[tokio::test]
13672    async fn traverse_single_root_across_visible_namespaces_yields_one_path() {
13673        use khive_storage::types::TraversalOptions;
13674
13675        let rt = rt();
13676        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns").unwrap());
13677        let a = rt
13678            .create_entity(&owner, "concept", None, "A", None, None, vec![])
13679            .await
13680            .unwrap();
13681        let b = rt
13682            .create_entity(&owner, "concept", None, "B", None, None, vec![])
13683            .await
13684            .unwrap();
13685        rt.link(&owner, a.id, b.id, EdgeRelation::Extends, 1.0, None)
13686            .await
13687            .unwrap();
13688
13689        // Token whose primary namespace ("caller-ns") does not own the root,
13690        // but whose visible set also includes "owner-ns" (where the root and
13691        // its edge actually live) — the shape produced by pack.rs always
13692        // widening visibility to include `local`.
13693        let caller = NamespaceToken::mint_with_visibility(
13694            Namespace::parse("caller-ns").unwrap(),
13695            vec![Namespace::parse("owner-ns").unwrap()],
13696            ActorRef::anonymous(),
13697        );
13698        assert_eq!(caller.visible_namespaces().len(), 2);
13699
13700        let result = rt
13701            .traverse(
13702                &caller,
13703                TraversalRequest {
13704                    roots: vec![a.id],
13705                    options: TraversalOptions {
13706                        max_depth: 1,
13707                        direction: Direction::Out,
13708                        ..Default::default()
13709                    },
13710                    include_roots: true,
13711                    include_properties: false,
13712                    execution_budget: Default::default(),
13713                },
13714            )
13715            .await
13716            .unwrap();
13717
13718        assert_eq!(
13719            result.len(),
13720            1,
13721            "one root visible across 2 namespaces must yield exactly one \
13722             GraphPath, got {result:#?}"
13723        );
13724        assert_eq!(result[0].root_id, a.id);
13725        let node_ids: std::collections::HashSet<Uuid> =
13726            result[0].nodes.iter().map(|n| n.node_id).collect();
13727        assert!(node_ids.contains(&a.id));
13728        assert!(
13729            node_ids.contains(&b.id),
13730            "merged path must retain the neighbor discovered in the owning \
13731             namespace, got {result:#?}"
13732        );
13733    }
13734
13735    /// Namespace fan-out clones one request but must not clone a fresh work
13736    /// allowance. With one adjacency row in each visible namespace, a one-row
13737    /// shared budget admits the first and makes the later namespace fail the
13738    /// whole operation instead of returning a partial merged path.
13739    #[tokio::test]
13740    async fn traverse_visible_namespaces_share_one_work_budget() {
13741        use khive_storage::types::{TraversalExecutionBudget, TraversalOptions};
13742
13743        let rt = rt();
13744        let ns_a = Namespace::parse("traverse-budget-a").unwrap();
13745        let ns_b = Namespace::parse("traverse-budget-b").unwrap();
13746        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
13747        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
13748        let visible = NamespaceToken::mint_with_visibility(ns_a, vec![ns_b], ActorRef::anonymous());
13749
13750        let root = rt
13751            .create_entity(&tok_a, "concept", None, "BudgetRoot", None, None, vec![])
13752            .await
13753            .unwrap();
13754        let child_a = rt
13755            .create_entity(&tok_a, "concept", None, "BudgetChildA", None, None, vec![])
13756            .await
13757            .unwrap();
13758        let child_b = rt
13759            .create_entity(&tok_b, "concept", None, "BudgetChildB", None, None, vec![])
13760            .await
13761            .unwrap();
13762        rt.link(
13763            &tok_a,
13764            root.id,
13765            child_a.id,
13766            EdgeRelation::Extends,
13767            1.0,
13768            None,
13769        )
13770        .await
13771        .unwrap();
13772        rt.link(
13773            &tok_b,
13774            root.id,
13775            child_b.id,
13776            EdgeRelation::Extends,
13777            1.0,
13778            None,
13779        )
13780        .await
13781        .unwrap();
13782
13783        let result = rt
13784            .traverse(
13785                &visible,
13786                TraversalRequest {
13787                    roots: vec![root.id],
13788                    options: TraversalOptions {
13789                        max_depth: 1,
13790                        direction: Direction::Out,
13791                        relations: None,
13792                        min_weight: None,
13793                        limit: Some(2),
13794                    },
13795                    include_roots: false,
13796                    include_properties: false,
13797                    execution_budget: TraversalExecutionBudget::new(
13798                        1,
13799                        std::time::Duration::from_secs(5),
13800                    ),
13801                },
13802            )
13803            .await;
13804
13805        assert!(matches!(
13806            result,
13807            Err(RuntimeError::Storage(khive_storage::StorageError::InvalidInput {
13808                message,
13809                ..
13810            })) if message.contains("work budget exceeded after 1 adjacency rows")
13811        ));
13812    }
13813
13814    // ── Multi-root traverse: one object per distinct root, including a
13815    //    root supplied both as itself and as a duplicate re-resolution ────
13816    #[tokio::test]
13817    async fn traverse_multi_root_one_path_per_distinct_root() {
13818        use khive_storage::types::TraversalOptions;
13819
13820        let rt = rt();
13821        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns2").unwrap());
13822        let a = rt
13823            .create_entity(&owner, "concept", None, "A", None, None, vec![])
13824            .await
13825            .unwrap();
13826        let c = rt
13827            .create_entity(&owner, "concept", None, "C", None, None, vec![])
13828            .await
13829            .unwrap();
13830
13831        // `a` appears twice in the roots list — this is what the pack
13832        // handler produces when a caller passes the same root once as a
13833        // short prefix and once as the full UUID: both resolve to the same
13834        // `Uuid` value by the time the request reaches the runtime.
13835        let result = rt
13836            .traverse(
13837                &owner,
13838                TraversalRequest {
13839                    roots: vec![a.id, a.id, c.id],
13840                    options: TraversalOptions {
13841                        max_depth: 1,
13842                        direction: Direction::Out,
13843                        ..Default::default()
13844                    },
13845                    include_roots: true,
13846                    include_properties: false,
13847                    execution_budget: Default::default(),
13848                },
13849            )
13850            .await
13851            .unwrap();
13852
13853        let root_ids: Vec<Uuid> = result.iter().map(|p| p.root_id).collect();
13854        assert_eq!(
13855            root_ids.len(),
13856            2,
13857            "duplicate root value must not produce a duplicate GraphPath, got {result:#?}"
13858        );
13859        assert!(root_ids.contains(&a.id));
13860        assert!(root_ids.contains(&c.id));
13861    }
13862
13863    // ── Note-kind nodes reached via traversal must use the same enrichment
13864    //    shape as neighbors, without restoring per-namespace phantom paths ──
13865    #[tokio::test]
13866    async fn traverse_note_node_matches_neighbors_in_one_path() {
13867        use khive_storage::types::TraversalOptions;
13868
13869        let rt = rt();
13870        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns3").unwrap());
13871        let a = rt
13872            .create_entity(&owner, "concept", None, "A", None, None, vec![])
13873            .await
13874            .unwrap();
13875        let note = rt
13876            .create_note(
13877                &owner,
13878                "observation",
13879                Some("TraversalNote"),
13880                "note body",
13881                None,
13882                None,
13883                vec![a.id],
13884            )
13885            .await
13886            .unwrap();
13887
13888        let caller = NamespaceToken::mint_with_visibility(
13889            Namespace::parse("caller-ns3").unwrap(),
13890            vec![Namespace::parse("owner-ns3").unwrap()],
13891            ActorRef::anonymous(),
13892        );
13893        let neighbors = rt
13894            .neighbors(
13895                &caller,
13896                a.id,
13897                Direction::In,
13898                None,
13899                Some(vec![EdgeRelation::Annotates]),
13900            )
13901            .await
13902            .unwrap();
13903        let note_hit = neighbors
13904            .iter()
13905            .find(|hit| hit.node_id == note.id)
13906            .unwrap_or_else(|| panic!("note must be present in neighbors, got {neighbors:#?}"));
13907
13908        let result = rt
13909            .traverse(
13910                &caller,
13911                TraversalRequest {
13912                    roots: vec![a.id],
13913                    options: TraversalOptions {
13914                        max_depth: 1,
13915                        direction: Direction::In,
13916                        relations: Some(vec![EdgeRelation::Annotates]),
13917                        ..Default::default()
13918                    },
13919                    include_roots: false,
13920                    include_properties: false,
13921                    execution_budget: Default::default(),
13922                },
13923            )
13924            .await
13925            .unwrap();
13926
13927        assert_eq!(
13928            result.len(),
13929            1,
13930            "one requested root must yield one path across the caller and owner namespaces"
13931        );
13932        let note_node = result[0]
13933            .nodes
13934            .iter()
13935            .find(|n| n.node_id == note.id)
13936            .unwrap_or_else(|| panic!("note must be present in traversal nodes, got {result:#?}"));
13937        assert_eq!(note_node.name.as_deref(), note_hit.name.as_deref());
13938        assert_eq!(note_node.kind.as_deref(), note_hit.kind.as_deref());
13939        assert_eq!(note_node.name.as_deref(), Some("TraversalNote"));
13940        assert_eq!(note_node.kind.as_deref(), Some("observation"));
13941    }
13942
13943    // ── A nameless annotation note reached via traversal must fall back to
13944    //    the same `[kind]` placeholder that `neighbors` produces ──
13945    #[tokio::test]
13946    async fn traverse_nameless_note_falls_back_to_bracketed_kind() {
13947        use khive_storage::types::TraversalOptions;
13948
13949        let rt = rt();
13950        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns4").unwrap());
13951        let a = rt
13952            .create_entity(&owner, "concept", None, "A", None, None, vec![])
13953            .await
13954            .unwrap();
13955        let note = rt
13956            .create_note(
13957                &owner,
13958                "observation",
13959                None,
13960                "note body",
13961                None,
13962                None,
13963                vec![a.id],
13964            )
13965            .await
13966            .unwrap();
13967
13968        let caller = NamespaceToken::mint_with_visibility(
13969            Namespace::parse("caller-ns4").unwrap(),
13970            vec![Namespace::parse("owner-ns4").unwrap()],
13971            ActorRef::anonymous(),
13972        );
13973        let neighbors = rt
13974            .neighbors(
13975                &caller,
13976                a.id,
13977                Direction::In,
13978                None,
13979                Some(vec![EdgeRelation::Annotates]),
13980            )
13981            .await
13982            .unwrap();
13983        let note_hit = neighbors
13984            .iter()
13985            .find(|hit| hit.node_id == note.id)
13986            .unwrap_or_else(|| panic!("note must be present in neighbors, got {neighbors:#?}"));
13987
13988        let result = rt
13989            .traverse(
13990                &caller,
13991                TraversalRequest {
13992                    roots: vec![a.id],
13993                    options: TraversalOptions {
13994                        max_depth: 1,
13995                        direction: Direction::In,
13996                        relations: Some(vec![EdgeRelation::Annotates]),
13997                        ..Default::default()
13998                    },
13999                    include_roots: false,
14000                    include_properties: false,
14001                    execution_budget: Default::default(),
14002                },
14003            )
14004            .await
14005            .unwrap();
14006
14007        let note_node = result[0]
14008            .nodes
14009            .iter()
14010            .find(|n| n.node_id == note.id)
14011            .unwrap_or_else(|| panic!("note must be present in traversal nodes, got {result:#?}"));
14012        assert_eq!(note_node.name.as_deref(), note_hit.name.as_deref());
14013        assert_eq!(note_node.kind.as_deref(), note_hit.kind.as_deref());
14014        assert_eq!(note_node.name.as_deref(), Some("[observation]"));
14015        assert_eq!(note_node.kind.as_deref(), Some("observation"));
14016    }
14017
14018    // ---- purge cascade must include already-soft-deleted edges ----
14019    //
14020    // Hard delete must cascade ALL incident edges synchronously. A cascade driven
14021    // through `neighbors()`, which filters `deleted_at IS NULL`, would let incident
14022    // edges that were already soft-deleted survive endpoint purge as dangling rows.
14023    // `purge_incident_edges` issues a single DELETE without a `deleted_at` guard.
14024
14025    /// Count ALL `graph_edges` rows for a given UUID (source OR target), including soft-deleted.
14026    async fn count_all_incident_edges(rt: &KhiveRuntime, node_id: Uuid, ns: &str) -> u64 {
14027        let mut reader = rt.sql().reader().await.expect("sql reader must open");
14028        let row = reader
14029            .query_scalar(SqlStatement {
14030                sql: "SELECT COUNT(*) FROM graph_edges \
14031                      WHERE namespace = ?1 AND (source_id = ?2 OR target_id = ?2)"
14032                    .into(),
14033                params: vec![
14034                    SqlValue::Text(ns.to_string()),
14035                    SqlValue::Text(node_id.to_string()),
14036                ],
14037                label: Some("count_all_incident_edges".into()),
14038            })
14039            .await
14040            .expect("count query must succeed");
14041        match row {
14042            Some(SqlValue::Integer(n)) => n as u64,
14043            _ => panic!("count must return an integer"),
14044        }
14045    }
14046
14047    async fn lineage_warning_events(
14048        rt: &KhiveRuntime,
14049        tok: &NamespaceToken,
14050        target_id: Uuid,
14051    ) -> Vec<Event> {
14052        rt.events(tok)
14053            .expect("event store")
14054            .query_events(
14055                EventFilter {
14056                    kinds: vec![EventKind::Audit],
14057                    ..Default::default()
14058                },
14059                PageRequest::default(),
14060            )
14061            .await
14062            .expect("query warning events")
14063            .items
14064            .into_iter()
14065            .filter(|event| event.target_id == Some(target_id))
14066            .collect()
14067    }
14068
14069    #[tokio::test]
14070    async fn hard_delete_emits_relation_specific_lineage_warnings_only() {
14071        let rt = rt();
14072        let tok = NamespaceToken::local();
14073        let doomed = rt
14074            .create_entity(&tok, "document", None, "doomed", None, None, vec![])
14075            .await
14076            .unwrap();
14077
14078        let provenance_source = rt
14079            .create_entity(&tok, "artifact", None, "source", None, None, vec![])
14080            .await
14081            .unwrap();
14082        rt.link(
14083            &tok,
14084            provenance_source.id,
14085            doomed.id,
14086            EdgeRelation::DerivedFrom,
14087            1.0,
14088            None,
14089        )
14090        .await
14091        .unwrap();
14092
14093        for (kind, name, relation) in [
14094            ("document", "old", EdgeRelation::Supersedes),
14095            ("document", "next", EdgeRelation::Precedes),
14096            ("concept", "supported", EdgeRelation::Supports),
14097            ("concept", "refuted", EdgeRelation::Refutes),
14098        ] {
14099            let target = rt
14100                .create_entity(&tok, kind, None, name, None, None, vec![])
14101                .await
14102                .unwrap();
14103            rt.link(&tok, doomed.id, target.id, relation, 1.0, None)
14104                .await
14105                .unwrap();
14106        }
14107        let unrelated = rt
14108            .create_entity(&tok, "concept", None, "unrelated", None, None, vec![])
14109            .await
14110            .unwrap();
14111        rt.link(
14112            &tok,
14113            unrelated.id,
14114            doomed.id,
14115            EdgeRelation::IntroducedBy,
14116            1.0,
14117            None,
14118        )
14119        .await
14120        .unwrap();
14121
14122        assert!(rt.delete_entity(&tok, doomed.id, false).await.unwrap());
14123        assert!(
14124            lineage_warning_events(&rt, &tok, doomed.id)
14125                .await
14126                .is_empty(),
14127            "soft delete must not emit cascade-loss warnings"
14128        );
14129
14130        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
14131        let warnings = lineage_warning_events(&rt, &tok, doomed.id).await;
14132        assert_eq!(warnings.len(), 5);
14133
14134        let mut actual = warnings
14135            .iter()
14136            .map(|event| {
14137                assert_eq!(event.substrate, SubstrateKind::Entity);
14138                assert_eq!(event.payload["severity"], "warning");
14139                assert_eq!(event.payload["deleted_id"], doomed.id.to_string());
14140                assert_eq!(event.payload["edge_count"], 1);
14141                assert_eq!(event.payload["edges"].as_array().unwrap().len(), 1);
14142                (
14143                    event.payload["relation"].as_str().unwrap().to_string(),
14144                    event.payload["warning"].as_str().unwrap().to_string(),
14145                )
14146            })
14147            .collect::<Vec<_>>();
14148        actual.sort();
14149        assert_eq!(
14150            actual,
14151            vec![
14152                ("derived_from".into(), "provenance_loss".into()),
14153                ("precedes".into(), "temporal_sequence_loss".into()),
14154                ("refutes".into(), "evidential_link_loss".into()),
14155                ("supersedes".into(), "replacement_lineage_loss".into()),
14156                ("supports".into(), "evidential_link_loss".into()),
14157            ]
14158        );
14159        assert!(warnings
14160            .iter()
14161            .all(|event| event.payload["relation"] != "introduced_by"));
14162    }
14163
14164    #[tokio::test]
14165    async fn hard_delete_lineage_warning_is_filterable_by_caller_actor() {
14166        let rt = rt();
14167        let tok = NamespaceToken::mint_authorized(
14168            Namespace::local(),
14169            ActorRef::new("agent", "lineage-deleter"),
14170        );
14171        let expected_actor = "agent:lineage-deleter";
14172        let doomed = rt
14173            .create_entity(&tok, "document", None, "actor-doomed", None, None, vec![])
14174            .await
14175            .unwrap();
14176        let source = rt
14177            .create_entity(&tok, "artifact", None, "actor-source", None, None, vec![])
14178            .await
14179            .unwrap();
14180        rt.link(
14181            &tok,
14182            source.id,
14183            doomed.id,
14184            EdgeRelation::DerivedFrom,
14185            1.0,
14186            None,
14187        )
14188        .await
14189        .unwrap();
14190
14191        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
14192
14193        let warnings = rt
14194            .events(&tok)
14195            .expect("event store")
14196            .query_events(
14197                EventFilter {
14198                    kinds: vec![EventKind::Audit],
14199                    actors: vec![expected_actor.to_string()],
14200                    ..Default::default()
14201                },
14202                PageRequest::default(),
14203            )
14204            .await
14205            .expect("query actor-filtered warning events")
14206            .items
14207            .into_iter()
14208            .filter(|event| event.target_id == Some(doomed.id))
14209            .collect::<Vec<_>>();
14210        assert_eq!(warnings.len(), 1);
14211        assert_eq!(warnings[0].actor, expected_actor);
14212        assert_eq!(warnings[0].payload["relation"], "derived_from");
14213    }
14214
14215    #[tokio::test]
14216    async fn hard_delete_warns_for_tombstoned_protected_incident_edge() {
14217        let rt = rt();
14218        let tok = NamespaceToken::local();
14219        let doomed = rt
14220            .create_entity(
14221                &tok,
14222                "document",
14223                None,
14224                "tombstoned-edge-doomed",
14225                None,
14226                None,
14227                vec![],
14228            )
14229            .await
14230            .unwrap();
14231        let source = rt
14232            .create_entity(
14233                &tok,
14234                "artifact",
14235                None,
14236                "tombstoned-edge-source",
14237                None,
14238                None,
14239                vec![],
14240            )
14241            .await
14242            .unwrap();
14243        let edge = rt
14244            .link(
14245                &tok,
14246                source.id,
14247                doomed.id,
14248                EdgeRelation::DerivedFrom,
14249                1.0,
14250                None,
14251            )
14252            .await
14253            .unwrap();
14254        let edge_id = Uuid::from(edge.id);
14255        assert!(rt.delete_edge(&tok, edge_id, false).await.unwrap());
14256
14257        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
14258
14259        let warnings = lineage_warning_events(&rt, &tok, doomed.id).await;
14260        assert_eq!(warnings.len(), 1);
14261        assert_eq!(warnings[0].payload["edge_count"], 1);
14262        let warned_edge = &warnings[0].payload["edges"].as_array().unwrap()[0];
14263        assert_eq!(warned_edge["id"], edge_id.to_string());
14264        assert!(
14265            warned_edge["deleted_at"].is_number(),
14266            "warning must preserve the edge's prior tombstone timestamp"
14267        );
14268        assert!(
14269            rt.get_edge_including_deleted(&tok, edge_id)
14270                .await
14271                .unwrap()
14272                .is_none(),
14273            "the warned tombstoned edge must still be physically cascaded"
14274        );
14275    }
14276
14277    #[tokio::test]
14278    async fn hard_delete_note_emits_evidential_lineage_warning() {
14279        let rt = rt();
14280        let tok = NamespaceToken::local();
14281        let evidence = rt
14282            .create_note(&tok, "observation", None, "evidence", None, None, vec![])
14283            .await
14284            .unwrap();
14285        let claim = rt
14286            .create_note(&tok, "insight", None, "claim", None, None, vec![])
14287            .await
14288            .unwrap();
14289        rt.link(
14290            &tok,
14291            evidence.id,
14292            claim.id,
14293            EdgeRelation::Supports,
14294            1.0,
14295            None,
14296        )
14297        .await
14298        .unwrap();
14299
14300        assert!(rt.delete_note(&tok, evidence.id, true).await.unwrap());
14301        let warnings = lineage_warning_events(&rt, &tok, evidence.id).await;
14302        assert_eq!(warnings.len(), 1);
14303        assert_eq!(warnings[0].substrate, SubstrateKind::Note);
14304        assert_eq!(warnings[0].payload["relation"], "supports");
14305        assert_eq!(warnings[0].payload["warning"], "evidential_link_loss");
14306    }
14307
14308    #[tokio::test]
14309    async fn lineage_warning_insert_failure_rolls_back_hard_delete_and_cascade() {
14310        let rt = rt();
14311        let tok = NamespaceToken::local();
14312        let doomed = rt
14313            .create_entity(&tok, "document", None, "doomed", None, None, vec![])
14314            .await
14315            .unwrap();
14316        let source = rt
14317            .create_entity(&tok, "artifact", None, "source", None, None, vec![])
14318            .await
14319            .unwrap();
14320        let edge = rt
14321            .link(
14322                &tok,
14323                source.id,
14324                doomed.id,
14325                EdgeRelation::DerivedFrom,
14326                1.0,
14327                None,
14328            )
14329            .await
14330            .unwrap();
14331
14332        let mut writer = rt.sql().writer().await.expect("sql writer");
14333        writer
14334            .execute_script(
14335                "CREATE TRIGGER reject_lineage_warning \
14336                 BEFORE INSERT ON events \
14337                 WHEN NEW.kind = 'audit' \
14338                   AND json_extract(NEW.payload, '$.severity') = 'warning' \
14339                 BEGIN \
14340                   SELECT RAISE(ABORT, 'injected lineage warning failure'); \
14341                 END;"
14342                    .into(),
14343            )
14344            .await
14345            .expect("install warning failure trigger");
14346        drop(writer);
14347
14348        let error = rt.delete_entity(&tok, doomed.id, true).await.unwrap_err();
14349        assert!(error
14350            .to_string()
14351            .contains("injected lineage warning failure"));
14352        assert!(
14353            rt.entities(&tok)
14354                .unwrap()
14355                .get_entity(doomed.id)
14356                .await
14357                .unwrap()
14358                .is_some(),
14359            "the endpoint row must roll back with the failed warning insert"
14360        );
14361        assert!(
14362            rt.get_edge(&tok, Uuid::from(edge.id))
14363                .await
14364                .unwrap()
14365                .is_some(),
14366            "the incident edge must roll back with the failed warning insert"
14367        );
14368    }
14369
14370    #[tokio::test]
14371    async fn hard_delete_entity_purges_already_soft_deleted_incident_edge() {
14372        let rt = rt();
14373        let tok = NamespaceToken::local();
14374        let ns = tok.namespace().to_string();
14375
14376        let a = rt
14377            .create_entity(&tok, "concept", None, "SrcA", None, None, vec![])
14378            .await
14379            .unwrap();
14380        let b = rt
14381            .create_entity(&tok, "concept", None, "TgtB", None, None, vec![])
14382            .await
14383            .unwrap();
14384
14385        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
14386            .await
14387            .unwrap();
14388
14389        // Soft-delete the edge — it is now invisible to `neighbors` but still in storage.
14390        let edge_hit = rt
14391            .neighbors(&tok, a.id, Direction::Out, None, None)
14392            .await
14393            .unwrap();
14394        assert_eq!(edge_hit.len(), 1, "edge must exist before soft-delete");
14395        let edge_uuid = edge_hit[0].edge_id;
14396        rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
14397
14398        // Confirm the edge is invisible to normal read paths but present in raw storage.
14399        let visible = rt
14400            .neighbors(&tok, a.id, Direction::Out, None, None)
14401            .await
14402            .unwrap();
14403        assert!(visible.is_empty(), "soft-deleted edge must be invisible");
14404        let raw_before = count_all_incident_edges(&rt, a.id, &ns).await;
14405        assert_eq!(
14406            raw_before, 1,
14407            "soft-deleted edge must still be a physical row"
14408        );
14409
14410        // Hard-delete (purge) the source entity — cascade must also remove the soft-deleted edge.
14411        rt.delete_entity(&tok, a.id, true).await.unwrap();
14412
14413        let raw_after = count_all_incident_edges(&rt, a.id, &ns).await;
14414        assert_eq!(
14415            raw_after, 0,
14416            "purge_incident_edges must physically remove soft-deleted edge rows (ADR-002)"
14417        );
14418    }
14419
14420    #[tokio::test]
14421    async fn hard_delete_note_purges_already_soft_deleted_incident_edge() {
14422        let rt = rt();
14423        let tok = NamespaceToken::local();
14424        let ns = tok.namespace().to_string();
14425
14426        let target = rt
14427            .create_note(
14428                &tok,
14429                "observation",
14430                None,
14431                "purge-cascade target note",
14432                Some(0.5),
14433                None,
14434                vec![],
14435            )
14436            .await
14437            .unwrap();
14438        let annotating = rt
14439            .create_note(
14440                &tok,
14441                "insight",
14442                None,
14443                "annotator note",
14444                Some(0.5),
14445                None,
14446                vec![target.id],
14447            )
14448            .await
14449            .unwrap();
14450
14451        // Soft-delete the annotates edge.
14452        let edge_hit = rt
14453            .neighbors(
14454                &tok,
14455                annotating.id,
14456                Direction::Out,
14457                None,
14458                Some(vec![EdgeRelation::Annotates]),
14459            )
14460            .await
14461            .unwrap();
14462        assert_eq!(edge_hit.len(), 1, "annotates edge must exist");
14463        let edge_uuid = edge_hit[0].edge_id;
14464        rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
14465
14466        let raw_before = count_all_incident_edges(&rt, target.id, &ns).await;
14467        assert_eq!(
14468            raw_before, 1,
14469            "soft-deleted edge must still be a physical row before note purge"
14470        );
14471
14472        // Hard-delete the target note — cascade must remove the soft-deleted edge row.
14473        rt.delete_note(&tok, target.id, true).await.unwrap();
14474
14475        let raw_after = count_all_incident_edges(&rt, target.id, &ns).await;
14476        assert_eq!(
14477            raw_after, 0,
14478            "purge_incident_edges must physically remove soft-deleted edge rows on note purge (ADR-002)"
14479        );
14480    }
14481
14482    // ---- cross-namespace entity hard-delete purges ALL incident edges ----
14483    //
14484    // `purge_incident_edges` must not scope its DELETE by `WHERE namespace = caller_ns`,
14485    // or a foreign-namespace entity's incident edges in ITS namespace would survive
14486    // the cascade as dangling rows.
14487
14488    /// Count ALL `graph_edges` rows for a given node UUID, across every namespace.
14489    async fn count_all_incident_edges_global(rt: &KhiveRuntime, node_id: Uuid) -> u64 {
14490        let mut reader = rt.sql().reader().await.expect("sql reader must open");
14491        let row = reader
14492            .query_scalar(SqlStatement {
14493                sql: "SELECT COUNT(*) FROM graph_edges WHERE source_id = ?1 OR target_id = ?1"
14494                    .into(),
14495                params: vec![SqlValue::Text(node_id.to_string())],
14496                label: Some("count_all_incident_edges_global".into()),
14497            })
14498            .await
14499            .expect("count query must succeed");
14500        match row {
14501            Some(SqlValue::Integer(n)) => n as u64,
14502            _ => panic!("count must return an integer"),
14503        }
14504    }
14505
14506    #[tokio::test]
14507    async fn cross_namespace_hard_delete_entity_purges_all_incident_edges() {
14508        // Entity lives in ns-owner. Edges live in ns-owner.
14509        // Delete is driven from ns-caller (a different namespace).
14510        // Assertion: after hard delete, no incident edges remain in ANY namespace.
14511        let rt = rt();
14512        let ns_owner = NamespaceToken::for_namespace(Namespace::parse("ns-owner").unwrap());
14513        let ns_caller = NamespaceToken::for_namespace(Namespace::parse("ns-caller").unwrap());
14514
14515        let entity = rt
14516            .create_entity(
14517                &ns_owner,
14518                "concept",
14519                None,
14520                "ForeignEntity",
14521                None,
14522                None,
14523                vec![],
14524            )
14525            .await
14526            .unwrap();
14527        let peer = rt
14528            .create_entity(&ns_owner, "concept", None, "Peer", None, None, vec![])
14529            .await
14530            .unwrap();
14531        // Create two incident edges in ns_owner. concept->Extends->concept is in the allowlist.
14532        rt.link(
14533            &ns_owner,
14534            entity.id,
14535            peer.id,
14536            EdgeRelation::Extends,
14537            1.0,
14538            None,
14539        )
14540        .await
14541        .unwrap();
14542        rt.link(
14543            &ns_owner,
14544            peer.id,
14545            entity.id,
14546            EdgeRelation::Extends,
14547            1.0,
14548            None,
14549        )
14550        .await
14551        .unwrap();
14552
14553        let before = count_all_incident_edges_global(&rt, entity.id).await;
14554        assert_eq!(before, 2, "two incident edges must exist before delete");
14555
14556        // Hard-delete entity from a DIFFERENT namespace token.
14557        let deleted = rt.delete_entity(&ns_caller, entity.id, true).await.unwrap();
14558        assert!(deleted, "cross-ns hard delete must return true");
14559
14560        // All incident edges must be gone regardless of namespace.
14561        let after = count_all_incident_edges_global(&rt, entity.id).await;
14562        assert_eq!(
14563            after, 0,
14564            "purge_incident_edges must remove all incident edges across namespaces (ADR-002, ADR-007)"
14565        );
14566    }
14567
14568    // ---- edge-ID hard-delete path ----
14569    //
14570    // Bug class: delete_edge drove the primary-edge guard through get_edge()
14571    // (live-only) and the cascade through neighbors() (live-only). Two reachable holes:
14572    // (a) soft-deleted primary edge cannot be hard-purged via its own ID;
14573    // (b) an already-soft-deleted annotates edge targeting a base edge survives that
14574    //     edge's hard delete as a dangling row with target_id = physically-gone edge id.
14575
14576    /// Count graph_edges rows matching the given edge ID, including soft-deleted rows.
14577    async fn count_edge_rows_by_id(rt: &KhiveRuntime, edge_id: Uuid, ns: &str) -> u64 {
14578        let mut reader = rt.sql().reader().await.expect("sql reader must open");
14579        let row = reader
14580            .query_scalar(SqlStatement {
14581                sql: "SELECT COUNT(*) FROM graph_edges WHERE namespace = ?1 AND id = ?2".into(),
14582                params: vec![
14583                    SqlValue::Text(ns.to_string()),
14584                    SqlValue::Text(edge_id.to_string()),
14585                ],
14586                label: Some("count_edge_rows_by_id".into()),
14587            })
14588            .await
14589            .expect("count query must succeed");
14590        match row {
14591            Some(SqlValue::Integer(n)) => n as u64,
14592            _ => panic!("count must return an integer"),
14593        }
14594    }
14595
14596    #[tokio::test]
14597    async fn hard_delete_edge_purges_already_soft_deleted_primary_edge() {
14598        let rt = rt();
14599        let tok = NamespaceToken::local();
14600        let ns = tok.namespace().to_string();
14601
14602        let a = rt
14603            .create_entity(&tok, "concept", None, "EA", None, None, vec![])
14604            .await
14605            .unwrap();
14606        let b = rt
14607            .create_entity(&tok, "concept", None, "EB", None, None, vec![])
14608            .await
14609            .unwrap();
14610
14611        let edge = rt
14612            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
14613            .await
14614            .unwrap();
14615        let edge_uuid: Uuid = edge.id.into();
14616
14617        // Soft-delete the edge first.
14618        let soft = rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
14619        assert!(soft, "soft delete must succeed");
14620
14621        // Edge is now invisible to normal reads but still a physical row.
14622        assert!(
14623            rt.get_edge(&tok, edge_uuid).await.unwrap().is_none(),
14624            "soft-deleted edge must be invisible to get_edge"
14625        );
14626        assert_eq!(
14627            count_edge_rows_by_id(&rt, edge_uuid, &ns).await,
14628            1,
14629            "soft-deleted edge must still be a physical row"
14630        );
14631
14632        // Hard-delete (purge) via the edge ID — must succeed and remove the row.
14633        let purged = rt.delete_edge(&tok, edge_uuid, true).await.unwrap();
14634        assert!(
14635            purged,
14636            "hard delete of a soft-deleted edge must return true"
14637        );
14638
14639        assert_eq!(
14640            count_edge_rows_by_id(&rt, edge_uuid, &ns).await,
14641            0,
14642            "hard-delete must physically remove the soft-deleted edge row (ADR-002)"
14643        );
14644    }
14645
14646    #[tokio::test]
14647    async fn hard_delete_base_edge_purges_already_soft_deleted_annotates_edge() {
14648        let rt = rt();
14649        let tok = NamespaceToken::local();
14650        let ns = tok.namespace().to_string();
14651
14652        let a = rt
14653            .create_entity(&tok, "concept", None, "CA", None, None, vec![])
14654            .await
14655            .unwrap();
14656        let b = rt
14657            .create_entity(&tok, "concept", None, "CB", None, None, vec![])
14658            .await
14659            .unwrap();
14660
14661        // Create the base edge to be annotated.
14662        let base_edge = rt
14663            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
14664            .await
14665            .unwrap();
14666        let base_edge_uuid: Uuid = base_edge.id.into();
14667
14668        // Create a note that annotates the base edge.
14669        let note = rt
14670            .create_note(
14671                &tok,
14672                "observation",
14673                None,
14674                "note about base edge",
14675                Some(0.5),
14676                None,
14677                vec![base_edge_uuid],
14678            )
14679            .await
14680            .unwrap();
14681
14682        // Find the annotates edge.
14683        let ann_hits = rt
14684            .neighbors(
14685                &tok,
14686                note.id,
14687                Direction::Out,
14688                None,
14689                Some(vec![EdgeRelation::Annotates]),
14690            )
14691            .await
14692            .unwrap();
14693        assert_eq!(ann_hits.len(), 1, "annotates edge must exist");
14694        let ann_edge_uuid = ann_hits[0].edge_id;
14695
14696        // Soft-delete the annotates edge — now invisible but still a physical row.
14697        rt.delete_edge(&tok, ann_edge_uuid, false).await.unwrap();
14698        assert_eq!(
14699            count_edge_rows_by_id(&rt, ann_edge_uuid, &ns).await,
14700            1,
14701            "soft-deleted annotates edge must still be a physical row"
14702        );
14703
14704        // Hard-delete the base edge — cascade must also remove the soft-deleted annotates row.
14705        let purged = rt.delete_edge(&tok, base_edge_uuid, true).await.unwrap();
14706        assert!(purged, "hard delete of base edge must return true");
14707
14708        assert_eq!(
14709            count_edge_rows_by_id(&rt, ann_edge_uuid, &ns).await,
14710            0,
14711            "hard-delete of base edge must purge already-soft-deleted annotates edge row (ADR-002)"
14712        );
14713        assert_eq!(
14714            count_edge_rows_by_id(&rt, base_edge_uuid, &ns).await,
14715            0,
14716            "hard-delete must physically remove the base edge row"
14717        );
14718    }
14719
14720    // ---- entity create/update multi-model embed fan-out tests ----
14721
14722    // FTS failure after entity row commit rolls back the entity row.
14723    // Mirrors create_note_fts_failure_rolls_back_note_row but for entities.
14724    // Uses a unique namespace so this test's arm never fires for the wrong
14725    // write path, even under full-suite parallelism.
14726    #[tokio::test]
14727    async fn create_entity_fts_failure_rolls_back_entity_row() {
14728        let rt = KhiveRuntime::memory().unwrap();
14729        let ns = Namespace::parse("fault-entity-fts").unwrap();
14730        let tok = NamespaceToken::for_namespace(ns.clone());
14731
14732        let _arm = arm_fts_fail_scoped(ns.as_str());
14733
14734        let result = rt
14735            .create_entity(
14736                &tok,
14737                "concept",
14738                None,
14739                "fts-fail rollback target",
14740                None,
14741                None,
14742                vec![],
14743            )
14744            .await;
14745
14746        assert!(
14747            result.is_err(),
14748            "create_entity must propagate the injected FTS failure"
14749        );
14750        let err_msg = result.unwrap_err().to_string();
14751        assert!(
14752            err_msg.contains("injected FTS failure"),
14753            "error must carry injection message; got: {err_msg}"
14754        );
14755
14756        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
14757        assert!(
14758            entities.is_empty(),
14759            "compensation must remove the entity row after FTS failure; got {entities:?}"
14760        );
14761    }
14762
14763    #[tokio::test]
14764    async fn create_entity_fts_and_compensation_failures_report_partial_persistence() {
14765        let rt = KhiveRuntime::memory().unwrap();
14766        let ns = Namespace::parse("partial-persistence-fts").unwrap();
14767        let tok = NamespaceToken::for_namespace(ns.clone());
14768        let _fts_arm = arm_fts_fail_scoped(ns.as_str());
14769        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
14770
14771        let error = rt
14772            .create_entity(
14773                &tok,
14774                "concept",
14775                None,
14776                "FTS partial persistence",
14777                None,
14778                None,
14779                vec![],
14780            )
14781            .await
14782            .expect_err("FTS and compensation failures must fail create_entity");
14783        assert!(
14784            matches!(&error, RuntimeError::Khive(_)),
14785            "combined failures must use the structured wire error path"
14786        );
14787        let error_message = error.to_string();
14788        assert!(error_message.contains("injected FTS failure"));
14789        assert!(error_message.contains("injected compensation failure"));
14790        assert!(error_message.contains("partial persistence is possible"));
14791
14792        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
14793        assert_eq!(
14794            entities.len(),
14795            1,
14796            "the failed row cleanup must leave residue"
14797        );
14798        let record_id = entities[0].id;
14799        assert!(
14800            error_message.contains(&record_id.to_string()),
14801            "the error must identify the durable row that needs reconciliation"
14802        );
14803        assert!(
14804            rt.text(&tok)
14805                .unwrap()
14806                .get_document(ns.as_str(), record_id)
14807                .await
14808                .unwrap()
14809                .is_none(),
14810            "FTS cleanup must run even when the FTS upsert reports failure"
14811        );
14812    }
14813
14814    // Vector insert failure after entity row + FTS commit rolls back both.
14815    // Uses a unique namespace so only this test consumes its VECTOR_FAIL_NS entry.
14816    #[tokio::test]
14817    async fn create_entity_vector_failure_rolls_back_entity_row_and_fts() {
14818        const MODEL: &str = "test-entity-vec-inject";
14819        const DIMS: usize = 4;
14820
14821        let rt = KhiveRuntime::memory().unwrap();
14822        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
14823        rt.register_embedder(provider);
14824
14825        let ns = Namespace::parse("fault-entity-vec").unwrap();
14826        let tok = NamespaceToken::for_namespace(ns.clone());
14827
14828        let _arm = arm_vector_fail_scoped(ns.as_str());
14829
14830        let result = rt
14831            .create_entity(
14832                &tok,
14833                "concept",
14834                None,
14835                "vec-fail rollback target",
14836                Some("description so embed body is non-empty"),
14837                None,
14838                vec![],
14839            )
14840            .await;
14841
14842        assert!(
14843            result.is_err(),
14844            "create_entity must propagate the injected vector failure"
14845        );
14846        let err_msg = result.unwrap_err().to_string();
14847        assert!(
14848            err_msg.contains("injected vector failure"),
14849            "error must carry injection message; got: {err_msg}"
14850        );
14851
14852        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
14853        assert!(
14854            entities.is_empty(),
14855            "compensation must remove entity row after vector failure; got {entities:?}"
14856        );
14857
14858        // FTS document must also be removed.
14859        use khive_storage::types::{TextFilter, TextQueryMode, TextSearchRequest};
14860        let fts_hits = rt
14861            .text(&tok)
14862            .unwrap()
14863            .search(TextSearchRequest {
14864                query: "vec-fail rollback target".to_string(),
14865                mode: TextQueryMode::Plain,
14866                filter: Some(TextFilter {
14867                    namespaces: vec![ns.as_str().to_string()],
14868                    ..Default::default()
14869                }),
14870                top_k: 10,
14871                snippet_chars: 100,
14872            })
14873            .await
14874            .unwrap();
14875        assert!(
14876            fts_hits.is_empty(),
14877            "compensation must remove FTS document after vector failure; got {fts_hits:?}"
14878        );
14879    }
14880
14881    #[tokio::test]
14882    async fn create_entity_single_model_reports_primary_and_compensation_failures() {
14883        const MODEL: &str = "partial-persistence-single";
14884
14885        let rt = KhiveRuntime::memory().unwrap();
14886        let (provider, _counter) = ConstVecProvider::new(MODEL, 4);
14887        rt.register_embedder(provider);
14888
14889        let ns = Namespace::parse("partial-persistence-single").unwrap();
14890        let tok = NamespaceToken::for_namespace(ns.clone());
14891        let _vector_arm = arm_vector_fail_scoped(ns.as_str());
14892        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
14893
14894        let error = rt
14895            .create_entity(
14896                &tok,
14897                "concept",
14898                None,
14899                "single-model partial persistence",
14900                Some("the FTS document lands before the injected vector failure"),
14901                None,
14902                vec![],
14903            )
14904            .await
14905            .expect_err("vector and compensation failures must fail create_entity");
14906
14907        let error_message = error.to_string();
14908        assert!(error_message.contains("injected vector failure"));
14909        assert!(error_message.contains("injected compensation failure"));
14910        assert!(error_message.contains("partial persistence is possible"));
14911
14912        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
14913        assert_eq!(
14914            entities.len(),
14915            1,
14916            "the failed row cleanup must leave residue"
14917        );
14918        let record_id = entities[0].id;
14919        assert!(
14920            error_message.contains(&record_id.to_string()),
14921            "the caller-visible error must carry the recovery record ID"
14922        );
14923        assert!(
14924            rt.text(&tok)
14925                .unwrap()
14926                .get_document(ns.as_str(), record_id)
14927                .await
14928                .unwrap()
14929                .is_none(),
14930            "independent FTS compensation must still complete"
14931        );
14932        assert_eq!(
14933            rt.vectors_for_model(&tok, MODEL)
14934                .unwrap()
14935                .count()
14936                .await
14937                .unwrap(),
14938            0,
14939            "the failed model must be cleaned even though INSERT returned an error"
14940        );
14941    }
14942
14943    // Multi-model create_entity: second model's vector INSERT fails after the
14944    // first model's insert succeeds, triggering inserted_models rollback.
14945    // Uses arm_vector_fail_after(1) so the first insert passes and the second fails,
14946    // exercising the inserted_models compensation path in create_entity.
14947    // Thread-local VECTOR_FAIL_AFTER is per-thread isolated (current-thread tokio runtime),
14948    // so this test does not race with namespace-targeted VECTOR_FAIL_NS tests.
14949    #[tokio::test]
14950    async fn create_entity_multi_model_second_vector_failure_rolls_back_all() {
14951        const DIMS: usize = 4;
14952
14953        let rt = KhiveRuntime::memory().unwrap();
14954        let (provider_a, _ca) = ConstVecProvider::new("model-a", DIMS);
14955        let (provider_b, _cb) = ConstVecProvider::new("model-b", DIMS);
14956        rt.register_embedder(provider_a);
14957        rt.register_embedder(provider_b);
14958
14959        let ns = Namespace::parse("fault-entity-multi").unwrap();
14960        let tok = NamespaceToken::for_namespace(ns.clone());
14961
14962        // Let the first vector insert succeed, fail on the second.
14963        arm_vector_fail_after(1);
14964
14965        let result = rt
14966            .create_entity(
14967                &tok,
14968                "concept",
14969                None,
14970                "multi-model rollback target",
14971                Some("description for embedding"),
14972                None,
14973                vec![],
14974            )
14975            .await;
14976
14977        assert!(
14978            result.is_err(),
14979            "create_entity must propagate the injected multi-model vector failure"
14980        );
14981
14982        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
14983        assert!(
14984            entities.is_empty(),
14985            "compensation must remove entity row; got {entities:?}"
14986        );
14987
14988        // Both model-a and model-b vector stores must be empty for the entity id.
14989        // (The entity was never returned so we can't get its id from the result;
14990        // list_entities returning empty is the primary assertion. Additionally confirm
14991        // both stores have zero rows via a broad vector search.)
14992        use khive_storage::types::VectorSearchRequest;
14993        let query_vec = vec![1.0_f32; DIMS];
14994        let hits_a = rt
14995            .vectors_for_model(&tok, "model-a")
14996            .unwrap()
14997            .search(VectorSearchRequest {
14998                query_vectors: vec![query_vec.clone()],
14999                top_k: 100,
15000                namespace: Some(ns.as_str().to_string()),
15001                kind: Some(khive_types::SubstrateKind::Entity),
15002                embedding_model: Some("model-a".to_string()),
15003                filter: None,
15004                backend_hints: None,
15005            })
15006            .await
15007            .unwrap();
15008        assert!(
15009            hits_a.is_empty(),
15010            "model-a vector store must be empty after rollback; got {hits_a:?}"
15011        );
15012        let hits_b = rt
15013            .vectors_for_model(&tok, "model-b")
15014            .unwrap()
15015            .search(VectorSearchRequest {
15016                query_vectors: vec![query_vec],
15017                top_k: 100,
15018                namespace: Some(ns.as_str().to_string()),
15019                kind: Some(khive_types::SubstrateKind::Entity),
15020                embedding_model: Some("model-b".to_string()),
15021                filter: None,
15022                backend_hints: None,
15023            })
15024            .await
15025            .unwrap();
15026        assert!(
15027            hits_b.is_empty(),
15028            "model-b vector store must be empty after rollback; got {hits_b:?}"
15029        );
15030    }
15031
15032    #[tokio::test]
15033    async fn create_entity_multi_model_reports_cleanup_failure_and_removes_all_vectors() {
15034        let rt = KhiveRuntime::memory().unwrap();
15035        let (provider_a, _ca) = ConstVecProvider::new("partial-multi-a", 4);
15036        let (provider_b, _cb) = ConstVecProvider::new("partial-multi-b", 4);
15037        rt.register_embedder(provider_a);
15038        rt.register_embedder(provider_b);
15039
15040        let ns = Namespace::parse("partial-persistence-multi").unwrap();
15041        let tok = NamespaceToken::for_namespace(ns.clone());
15042        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
15043        arm_vector_fail_after(1);
15044
15045        let error = rt
15046            .create_entity(
15047                &tok,
15048                "concept",
15049                None,
15050                "multi-model partial persistence",
15051                Some("the second model fails after the first vector lands"),
15052                None,
15053                vec![],
15054            )
15055            .await
15056            .expect_err("second vector and compensation failures must fail create_entity");
15057
15058        let error_message = error.to_string();
15059        assert!(
15060            error_message.contains("injected vector insert failure"),
15061            "primary cause must be retained: {error_message}"
15062        );
15063        assert!(error_message.contains("injected compensation failure"));
15064
15065        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
15066        assert_eq!(
15067            entities.len(),
15068            1,
15069            "the failed row cleanup must leave residue"
15070        );
15071        let record_id = entities[0].id;
15072        assert!(error_message.contains(&record_id.to_string()));
15073
15074        for model in ["partial-multi-a", "partial-multi-b"] {
15075            assert_eq!(
15076                rt.vectors_for_model(&tok, model)
15077                    .unwrap()
15078                    .count()
15079                    .await
15080                    .unwrap(),
15081                0,
15082                "compensation must clean both the successful and failed model ({model})"
15083            );
15084        }
15085        assert!(
15086            rt.text(&tok)
15087                .unwrap()
15088                .get_document(ns.as_str(), record_id)
15089                .await
15090                .unwrap()
15091                .is_none(),
15092            "FTS compensation must succeed even when row cleanup fails"
15093        );
15094    }
15095
15096    // ADR-103 Amendment 2 regression: multi-model create_entity spawns one
15097    // embed task per configured model via tokio::spawn. Task-locals do not
15098    // cross a spawn boundary, so each spawned task must re-enter the
15099    // dispatch's usage scope explicitly for its embed to be counted.
15100    #[tokio::test]
15101    async fn create_entity_multi_model_counts_all_executed_embeds() {
15102        const DIMS: usize = 4;
15103
15104        let rt = KhiveRuntime::memory().unwrap();
15105        let (provider_a, _ca) = ConstVecProvider::new("usage-entity-model-a", DIMS);
15106        let (provider_b, _cb) = ConstVecProvider::new("usage-entity-model-b", DIMS);
15107        rt.register_embedder(provider_a);
15108        rt.register_embedder(provider_b);
15109
15110        let ns = Namespace::parse("usage-entity-multi").unwrap();
15111        let tok = NamespaceToken::for_namespace(ns.clone());
15112
15113        let ctx = crate::usage::UsageContext::new();
15114        crate::usage::scope(ctx.clone(), async {
15115            rt.create_entity(
15116                &tok,
15117                "concept",
15118                None,
15119                "usage-counted entity",
15120                Some("description so embed body is non-empty"),
15121                None,
15122                vec![],
15123            )
15124            .await
15125        })
15126        .await
15127        .expect("create_entity must succeed");
15128
15129        let snap = ctx.snapshot();
15130        assert_eq!(
15131            snap["embed_calls"], 2,
15132            "both configured models' executed embeds must be counted; got {snap:?}"
15133        );
15134    }
15135
15136    // Same regression for the note create path's multi-model embed fan-out.
15137    #[tokio::test]
15138    async fn create_note_multi_model_counts_all_executed_embeds() {
15139        const DIMS: usize = 4;
15140
15141        let rt = KhiveRuntime::memory().unwrap();
15142        let (provider_a, _ca) = ConstVecProvider::new("usage-note-model-a", DIMS);
15143        let (provider_b, _cb) = ConstVecProvider::new("usage-note-model-b", DIMS);
15144        rt.register_embedder(provider_a);
15145        rt.register_embedder(provider_b);
15146
15147        let ns = Namespace::parse("usage-note-multi").unwrap();
15148        let tok = NamespaceToken::for_namespace(ns.clone());
15149
15150        let ctx = crate::usage::UsageContext::new();
15151        crate::usage::scope(ctx.clone(), async {
15152            rt.create_note(
15153                &tok,
15154                "observation",
15155                None,
15156                "usage-counted note body",
15157                None,
15158                None,
15159                vec![],
15160            )
15161            .await
15162        })
15163        .await
15164        .expect("create_note must succeed");
15165
15166        let snap = ctx.snapshot();
15167        assert_eq!(
15168            snap["embed_calls"], 2,
15169            "both configured models' executed embeds must be counted; got {snap:?}"
15170        );
15171    }
15172
15173    // Embed calls are counted when issued, so detached completion after a
15174    // sibling failure cannot change the response's usage snapshot.
15175    #[tokio::test]
15176    async fn create_entity_multi_model_error_keeps_issued_usage_stable() {
15177        const DIMS: usize = 4;
15178
15179        let rt = KhiveRuntime::memory().unwrap();
15180        rt.register_embedder(FailFastProvider::new("usage-entity-fail-fast"));
15181        rt.register_embedder(SlowVecProvider::new("usage-entity-slow", DIMS));
15182
15183        let ns = Namespace::parse("usage-entity-error-drain").unwrap();
15184        let tok = NamespaceToken::for_namespace(ns.clone());
15185
15186        let ctx = crate::usage::UsageContext::new();
15187        let result = crate::usage::scope(ctx.clone(), async {
15188            rt.create_entity(
15189                &tok,
15190                "concept",
15191                None,
15192                "usage-drain entity",
15193                Some("description so embed body is non-empty"),
15194                None,
15195                vec![],
15196            )
15197            .await
15198        })
15199        .await;
15200
15201        assert!(
15202            result.is_err(),
15203            "one model failing must fail the whole create_entity call"
15204        );
15205
15206        let snap_immediately_after = ctx.snapshot();
15207        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
15208        let snap_after_delay = ctx.snapshot();
15209
15210        assert_eq!(
15211            snap_immediately_after, snap_after_delay,
15212            "embed completion after create_entity returns must not change issued \
15213             usage; got immediately_after={snap_immediately_after:?} \
15214             after_delay={snap_after_delay:?}"
15215        );
15216    }
15217
15218    // Same regression for the note create path's multi-model embed fan-out.
15219    #[tokio::test]
15220    async fn create_note_multi_model_error_keeps_issued_usage_stable() {
15221        const DIMS: usize = 4;
15222
15223        let rt = KhiveRuntime::memory().unwrap();
15224        rt.register_embedder(FailFastProvider::new("usage-note-fail-fast"));
15225        rt.register_embedder(SlowVecProvider::new("usage-note-slow", DIMS));
15226
15227        let ns = Namespace::parse("usage-note-error-drain").unwrap();
15228        let tok = NamespaceToken::for_namespace(ns.clone());
15229
15230        let ctx = crate::usage::UsageContext::new();
15231        let result = crate::usage::scope(ctx.clone(), async {
15232            rt.create_note(
15233                &tok,
15234                "observation",
15235                None,
15236                "usage-drain note body",
15237                None,
15238                None,
15239                vec![],
15240            )
15241            .await
15242        })
15243        .await;
15244
15245        assert!(
15246            result.is_err(),
15247            "one model failing must fail the whole create_note call"
15248        );
15249
15250        let snap_immediately_after = ctx.snapshot();
15251        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
15252        let snap_after_delay = ctx.snapshot();
15253
15254        assert_eq!(
15255            snap_immediately_after, snap_after_delay,
15256            "embed completion after create_note returns must not change issued \
15257             usage; got immediately_after={snap_immediately_after:?} \
15258             after_delay={snap_after_delay:?}"
15259        );
15260    }
15261
15262    // A fast provider failure must not wait on a slow sibling: the drain
15263    // aborts remaining embed tasks on the first error instead of awaiting
15264    // them to completion. The sibling here parks until a release that never
15265    // fires, so under await-to-completion this call would never return —
15266    // a bounded prompt error return is only reachable through the abort path.
15267    #[tokio::test]
15268    async fn create_entity_fast_embed_failure_does_not_wait_for_hung_sibling() {
15269        const DIMS: usize = 4;
15270
15271        let rt = KhiveRuntime::memory().unwrap();
15272        rt.register_embedder(FailFastProvider::new("latency-fail-fast"));
15273        let (parked, _release, _entered) = ParkedVecProvider::new("latency-parked", DIMS);
15274        rt.register_embedder(parked);
15275
15276        let ns = Namespace::parse("usage-entity-latency").unwrap();
15277        let tok = NamespaceToken::for_namespace(ns.clone());
15278
15279        let started = std::time::Instant::now();
15280        // Outer timeout so a regression to await-to-completion FAILS this test
15281        // within the bound instead of hanging the suite on the parked sibling.
15282        let result = tokio::time::timeout(
15283            std::time::Duration::from_secs(60),
15284            rt.create_entity(
15285                &tok,
15286                "concept",
15287                None,
15288                "latency entity",
15289                Some("description so embed body is non-empty"),
15290                None,
15291                vec![],
15292            ),
15293        )
15294        .await
15295        .expect("create_entity must return within the timeout — a hang means the abort path regressed to await-to-completion");
15296        let elapsed = started.elapsed();
15297
15298        assert!(
15299            result.is_err(),
15300            "one model failing must fail the whole create_entity call"
15301        );
15302        assert!(
15303            elapsed < std::time::Duration::from_secs(5),
15304            "a fast embed failure must return without waiting on the hung \
15305             sibling (which parks forever); took {elapsed:?}"
15306        );
15307    }
15308
15309    #[test]
15310    fn create_entity_embed_failure_returns_under_single_worker_saturation() {
15311        let (blocking, controls) = BlockingVecProvider::new("latency-blocking", 4);
15312        let fail_after_entry = FailFastProvider::after_signal(
15313            "latency-fail-after-entry",
15314            Arc::clone(&controls.entered),
15315        );
15316        let (result_tx, result_rx) = std::sync::mpsc::sync_channel(1);
15317
15318        let runtime_thread = std::thread::spawn(move || {
15319            let runtime = tokio::runtime::Builder::new_multi_thread()
15320                .worker_threads(1)
15321                .enable_all()
15322                .build()
15323                .expect("single-worker runtime must build");
15324            let rt = KhiveRuntime::memory().unwrap();
15325            rt.register_embedder(blocking);
15326            rt.register_embedder(fail_after_entry);
15327            let tok =
15328                NamespaceToken::for_namespace(Namespace::parse("embed-failure-latency").unwrap());
15329            let result = runtime.block_on(rt.create_entity(
15330                &tok,
15331                "concept",
15332                None,
15333                "blocked sibling entity",
15334                None,
15335                None,
15336                vec![],
15337            ));
15338            result_tx
15339                .send(result.map_err(|error| error.to_string()))
15340                .expect("test receiver must remain connected");
15341        });
15342
15343        let result = result_rx.recv_timeout(std::time::Duration::from_secs(3));
15344
15345        let (released, wake) = &*controls.release;
15346        *released.lock().expect("release lock must not be poisoned") = true;
15347        wake.notify_all();
15348        runtime_thread
15349            .join()
15350            .expect("single-worker runtime thread must join after release");
15351
15352        let error = result
15353            .expect("embed failure must return while synchronous inference remains blocked")
15354            .expect_err("one failed model must fail entity creation");
15355        assert!(error.contains("injected embed failure"));
15356    }
15357
15358    // Issued-at-dispatch accounting: an embed call that was handed to the
15359    // provider must count toward embed_calls even if the task is aborted
15360    // while parked on the provider await — the increment sits before the
15361    // await, so cancellation cannot undercount issued work.
15362    #[tokio::test]
15363    async fn aborted_embed_task_still_counts_issued_embed_call() {
15364        const DIMS: usize = 4;
15365
15366        let rt = std::sync::Arc::new(KhiveRuntime::memory().unwrap());
15367        let (parked, _release, entered) = ParkedVecProvider::new("abort-count-parked", DIMS);
15368        rt.register_embedder(parked);
15369
15370        let ctx = crate::usage::UsageContext::new();
15371        let task = {
15372            let rt = std::sync::Arc::clone(&rt);
15373            let ctx = ctx.clone();
15374            tokio::spawn(crate::usage::scope(ctx, async move {
15375                rt.embed_document_with_model("abort-count-parked", "abort count body")
15376                    .await
15377            }))
15378        };
15379
15380        // Wait until the parked service's embed was entered — the dispatch
15381        // point (and its count) is strictly before that entry.
15382        entered.notified().await;
15383        task.abort();
15384        let joined = task.await;
15385        assert!(
15386            joined.is_err() && joined.unwrap_err().is_cancelled(),
15387            "task must end as cancelled by the abort"
15388        );
15389
15390        assert_eq!(
15391            ctx.snapshot()["embed_calls"],
15392            1,
15393            "an issued embed call must be counted even when the task is \
15394             aborted while parked on the provider await"
15395        );
15396    }
15397
15398    // Note search must count its FTS5 execution the same way entity
15399    // hybrid_search does (retrieval.rs:435) — the search_notes FTS leg was
15400    // silently uncounted.
15401    #[tokio::test]
15402    async fn search_notes_counts_one_fts_pass() {
15403        let rt = KhiveRuntime::memory().unwrap();
15404        let ns = Namespace::parse("usage-note-search").unwrap();
15405        let tok = NamespaceToken::for_namespace(ns.clone());
15406
15407        rt.create_note(
15408            &tok,
15409            "observation",
15410            None,
15411            "usage counted note search body",
15412            None,
15413            None,
15414            vec![],
15415        )
15416        .await
15417        .expect("create_note must succeed");
15418
15419        let ctx = crate::usage::UsageContext::new();
15420        crate::usage::scope(ctx.clone(), async {
15421            rt.search_notes(&tok, "usage counted", None, 10, None, false, &[], None)
15422                .await
15423        })
15424        .await
15425        .expect("search_notes must succeed");
15426
15427        let snap = ctx.snapshot();
15428        assert!(
15429            snap["fts_passes"].as_u64().unwrap_or(0) >= 1,
15430            "note search FTS execution must count fts_passes; got {snap:?}"
15431        );
15432    }
15433
15434    #[tokio::test]
15435    async fn search_notes_batches_supersedes_suppression_round_trip() {
15436        let rt = KhiveRuntime::memory().unwrap();
15437        let ns = Namespace::parse("usage-note-supersedes-batch").unwrap();
15438        let tok = NamespaceToken::for_namespace(ns);
15439
15440        let mut notes = Vec::new();
15441        for ordinal in 0..4 {
15442            notes.push(
15443                rt.create_note(
15444                    &tok,
15445                    "observation",
15446                    None,
15447                    &format!("batchsupersedesprobe live candidate {ordinal}"),
15448                    None,
15449                    None,
15450                    vec![],
15451                )
15452                .await
15453                .expect("create_note must succeed"),
15454            );
15455        }
15456        rt.link(
15457            &tok,
15458            notes[3].id,
15459            notes[0].id,
15460            EdgeRelation::Supersedes,
15461            1.0,
15462            None,
15463        )
15464        .await
15465        .expect("supersedes link must succeed");
15466
15467        let ctx = crate::usage::UsageContext::new();
15468        let hits = crate::usage::scope(ctx.clone(), async {
15469            rt.search_notes(
15470                &tok,
15471                "batchsupersedesprobe",
15472                None,
15473                10,
15474                None,
15475                false,
15476                &[],
15477                None,
15478            )
15479            .await
15480        })
15481        .await
15482        .expect("search_notes must succeed");
15483
15484        let hit_ids: std::collections::HashSet<Uuid> = hits.iter().map(|hit| hit.note_id).collect();
15485        assert_eq!(
15486            hit_ids.len(),
15487            3,
15488            "all live, non-superseded notes must remain"
15489        );
15490        assert!(
15491            !hit_ids.contains(&notes[0].id),
15492            "the superseded note must be excluded"
15493        );
15494        assert!(
15495            notes[1..].iter().all(|note| hit_ids.contains(&note.id)),
15496            "every live, non-superseded note must be returned"
15497        );
15498
15499        let snap = ctx.snapshot();
15500        assert_eq!(
15501            snap["db_round_trips"], 1,
15502            "supersedes suppression must use one batched adjacency query; got {snap:?}"
15503        );
15504    }
15505
15506    // update_entity fans out to ALL registered models.
15507    // After create + update with a changed description, both model-a and model-b
15508    // vector stores hold a row for the entity id.
15509    #[tokio::test]
15510    async fn update_entity_fans_out_to_all_registered_models() {
15511        const DIMS: usize = 4;
15512
15513        let rt = KhiveRuntime::memory().unwrap();
15514        let (provider_a, _ca) = ConstVecProvider::new("embed-a", DIMS);
15515        let (provider_b, _cb) = ConstVecProvider::new("embed-b", DIMS);
15516        rt.register_embedder(provider_a);
15517        rt.register_embedder(provider_b);
15518
15519        let ns = Namespace::parse("update-entity-fanout").unwrap();
15520        let tok = NamespaceToken::for_namespace(ns.clone());
15521
15522        let entity = rt
15523            .create_entity(
15524                &tok,
15525                "concept",
15526                None,
15527                "FanOutEntity",
15528                Some("initial description"),
15529                None,
15530                vec![],
15531            )
15532            .await
15533            .expect("create_entity must succeed");
15534
15535        use crate::curation::EntityPatch;
15536        let patch = EntityPatch {
15537            description: Some(Some("updated description after fan-out fix".to_string())),
15538            ..Default::default()
15539        };
15540        rt.update_entity(&tok, entity.id, patch)
15541            .await
15542            .expect("update_entity must succeed");
15543
15544        use khive_storage::types::VectorSearchRequest;
15545        let query_vec = vec![1.0_f32; DIMS];
15546
15547        let hits_a = rt
15548            .vectors_for_model(&tok, "embed-a")
15549            .unwrap()
15550            .search(VectorSearchRequest {
15551                query_vectors: vec![query_vec.clone()],
15552                top_k: 10,
15553                namespace: Some(ns.as_str().to_string()),
15554                kind: Some(khive_types::SubstrateKind::Entity),
15555                embedding_model: Some("embed-a".to_string()),
15556                filter: None,
15557                backend_hints: None,
15558            })
15559            .await
15560            .unwrap();
15561        assert!(
15562            hits_a.iter().any(|h| h.subject_id == entity.id),
15563            "embed-a must hold a vector for the entity after update; got {hits_a:?}"
15564        );
15565
15566        let hits_b = rt
15567            .vectors_for_model(&tok, "embed-b")
15568            .unwrap()
15569            .search(VectorSearchRequest {
15570                query_vectors: vec![query_vec],
15571                top_k: 10,
15572                namespace: Some(ns.as_str().to_string()),
15573                kind: Some(khive_types::SubstrateKind::Entity),
15574                embedding_model: Some("embed-b".to_string()),
15575                filter: None,
15576                backend_hints: None,
15577            })
15578            .await
15579            .unwrap();
15580        assert!(
15581            hits_b.iter().any(|h| h.subject_id == entity.id),
15582            "embed-b must hold a vector for the entity after update; got {hits_b:?}"
15583        );
15584    }
15585
15586    // update_note fans out to ALL registered models.
15587    // After create + update with changed content, both embed-a and embed-b
15588    // vector stores hold a row for the note id.
15589    #[tokio::test]
15590    async fn update_note_fans_out_to_all_registered_models() {
15591        const DIMS: usize = 4;
15592
15593        let rt = KhiveRuntime::memory().unwrap();
15594        let (provider_a, _ca) = ConstVecProvider::new("embed-a", DIMS);
15595        let (provider_b, _cb) = ConstVecProvider::new("embed-b", DIMS);
15596        rt.register_embedder(provider_a);
15597        rt.register_embedder(provider_b);
15598
15599        let ns = Namespace::parse("update-note-fanout").unwrap();
15600        let tok = NamespaceToken::for_namespace(ns.clone());
15601
15602        let note = rt
15603            .create_note(
15604                &tok,
15605                "observation",
15606                None,
15607                "initial note content for fan-out test",
15608                None,
15609                None,
15610                vec![],
15611            )
15612            .await
15613            .expect("create_note must succeed");
15614
15615        use crate::curation::NotePatch;
15616        let patch = NotePatch {
15617            content: Some("updated content after fan-out fix".to_string()),
15618            ..Default::default()
15619        };
15620        rt.update_note(&tok, note.id, patch)
15621            .await
15622            .expect("update_note must succeed");
15623
15624        use khive_storage::types::VectorSearchRequest;
15625        let query_vec = vec![1.0_f32; DIMS];
15626
15627        let hits_a = rt
15628            .vectors_for_model(&tok, "embed-a")
15629            .unwrap()
15630            .search(VectorSearchRequest {
15631                query_vectors: vec![query_vec.clone()],
15632                top_k: 10,
15633                namespace: Some(ns.as_str().to_string()),
15634                kind: Some(khive_types::SubstrateKind::Note),
15635                embedding_model: Some("embed-a".to_string()),
15636                filter: None,
15637                backend_hints: None,
15638            })
15639            .await
15640            .unwrap();
15641        assert!(
15642            hits_a.iter().any(|h| h.subject_id == note.id),
15643            "embed-a must hold a vector for the note after update; got {hits_a:?}"
15644        );
15645
15646        let hits_b = rt
15647            .vectors_for_model(&tok, "embed-b")
15648            .unwrap()
15649            .search(VectorSearchRequest {
15650                query_vectors: vec![query_vec],
15651                top_k: 10,
15652                namespace: Some(ns.as_str().to_string()),
15653                kind: Some(khive_types::SubstrateKind::Note),
15654                embedding_model: Some("embed-b".to_string()),
15655                filter: None,
15656                backend_hints: None,
15657            })
15658            .await
15659            .unwrap();
15660        assert!(
15661            hits_b.iter().any(|h| h.subject_id == note.id),
15662            "embed-b must hold a vector for the note after update; got {hits_b:?}"
15663        );
15664    }
15665
15666    // ── By-ID ops must not filter by namespace ──────────────────────────────
15667    //
15668    // A namespace-gated by-ID op on an entity stamped "foreign" from a "local"
15669    // token would return NotFound, causing gtd.complete / update blindness.
15670    // UUID is globally unique; by-ID ops find the record regardless of
15671    // which namespace the caller's token carries.
15672
15673    #[tokio::test]
15674    async fn get_entity_cross_namespace_succeeds() {
15675        let rt = rt();
15676        // Create under "lambda:leo".
15677        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
15678        let entity = rt
15679            .create_entity(&leo_tok, "concept", None, "Peer-Entity", None, None, vec![])
15680            .await
15681            .unwrap();
15682        assert_eq!(entity.namespace, "lambda:leo");
15683
15684        // Read from "local" — must succeed (no namespace gate on by-ID get).
15685        let local_tok = NamespaceToken::local();
15686        let fetched = rt.get_entity(&local_tok, entity.id).await;
15687        assert!(
15688            fetched.is_ok(),
15689            "get_entity from local token must find lambda:leo entity; got {:?}",
15690            fetched
15691        );
15692        assert_eq!(fetched.unwrap().id, entity.id);
15693    }
15694
15695    #[tokio::test]
15696    async fn update_entity_cross_namespace_succeeds() {
15697        let rt = rt();
15698        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
15699        let entity = rt
15700            .create_entity(
15701                &leo_tok,
15702                "concept",
15703                None,
15704                "Peer-Entity-Update",
15705                None,
15706                None,
15707                vec![],
15708            )
15709            .await
15710            .unwrap();
15711
15712        // Update from "local" token — must not error with NotFound.
15713        let local_tok = NamespaceToken::local();
15714        let patch = crate::curation::EntityPatch {
15715            name: Some("Peer-Entity-Updated".to_string()),
15716            ..Default::default()
15717        };
15718        let result = rt.update_entity(&local_tok, entity.id, patch).await;
15719        assert!(
15720            result.is_ok(),
15721            "update_entity from local token must succeed on lambda:leo entity; got {:?}",
15722            result
15723        );
15724        assert_eq!(result.unwrap().name, "Peer-Entity-Updated");
15725    }
15726
15727    #[tokio::test]
15728    async fn delete_entity_cross_namespace_succeeds() {
15729        let rt = rt();
15730        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
15731        let entity = rt
15732            .create_entity(
15733                &leo_tok,
15734                "concept",
15735                None,
15736                "Peer-Entity-Delete",
15737                None,
15738                None,
15739                vec![],
15740            )
15741            .await
15742            .unwrap();
15743
15744        // Delete from "local" token — must succeed.
15745        let local_tok = NamespaceToken::local();
15746        let deleted = rt.delete_entity(&local_tok, entity.id, false).await;
15747        assert!(
15748            deleted.is_ok(),
15749            "delete_entity from local token must succeed on lambda:leo entity; got {:?}",
15750            deleted
15751        );
15752        assert!(
15753            deleted.unwrap(),
15754            "delete must return true when entity existed"
15755        );
15756    }
15757
15758    #[tokio::test]
15759    async fn namespace_preserved_on_entity_after_cross_namespace_get() {
15760        let rt = rt();
15761        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
15762        let entity = rt
15763            .create_entity(
15764                &leo_tok,
15765                "concept",
15766                None,
15767                "NS-Preserved",
15768                None,
15769                None,
15770                vec![],
15771            )
15772            .await
15773            .unwrap();
15774
15775        // The namespace column on the fetched record must still say "lambda:leo".
15776        let local_tok = NamespaceToken::local();
15777        let fetched = rt.get_entity(&local_tok, entity.id).await.unwrap();
15778        assert_eq!(
15779            fetched.namespace, "lambda:leo",
15780            "namespace column must be preserved; not overwritten with caller's namespace"
15781        );
15782    }
15783
15784    // ── PackByIdResolver unit tests ──────────────────────────────────────────
15785
15786    use crate::pack::PackByIdResolver;
15787    use tokio::sync::Mutex as TokioMutex;
15788
15789    #[derive(Debug, Default)]
15790    struct MockResolverState {
15791        owned: Vec<Uuid>,
15792        deleted: Vec<Uuid>,
15793        delete_calls: Vec<(Uuid, bool)>,
15794    }
15795
15796    struct MockPackResolver(TokioMutex<MockResolverState>);
15797
15798    impl MockPackResolver {
15799        fn new() -> Self {
15800            Self(TokioMutex::new(MockResolverState::default()))
15801        }
15802    }
15803
15804    #[async_trait::async_trait]
15805    impl crate::pack::PackByIdResolver for MockPackResolver {
15806        async fn resolve_by_id(&self, id: Uuid) -> Result<Option<Resolved>, RuntimeError> {
15807            let state = self.0.lock().await;
15808            if state.owned.contains(&id) && !state.deleted.contains(&id) {
15809                Ok(Some(Resolved::PackRecord {
15810                    pack: "mock".into(),
15811                    kind: "widget".into(),
15812                    data: serde_json::json!({ "id": id.to_string(), "name": "test-widget" }),
15813                }))
15814            } else {
15815                Ok(None)
15816            }
15817        }
15818
15819        async fn resolve_by_id_including_deleted(
15820            &self,
15821            id: Uuid,
15822        ) -> Result<Option<Resolved>, RuntimeError> {
15823            let state = self.0.lock().await;
15824            if state.owned.contains(&id) {
15825                Ok(Some(Resolved::PackRecord {
15826                    pack: "mock".into(),
15827                    kind: "widget".into(),
15828                    data: serde_json::json!({ "id": id.to_string(), "name": "test-widget" }),
15829                }))
15830            } else {
15831                Ok(None)
15832            }
15833        }
15834
15835        async fn delete_by_id(
15836            &self,
15837            id: Uuid,
15838            hard: bool,
15839        ) -> Result<serde_json::Value, RuntimeError> {
15840            let mut state = self.0.lock().await;
15841            if !state.owned.contains(&id) {
15842                return Err(RuntimeError::NotFound(format!(
15843                    "mock widget not found: {id}"
15844                )));
15845            }
15846            state.delete_calls.push((id, hard));
15847            if hard {
15848                state.owned.retain(|&x| x != id);
15849                state.deleted.retain(|&x| x != id);
15850            } else {
15851                state.deleted.push(id);
15852            }
15853            Ok(
15854                serde_json::json!({ "deleted": true, "id": id.to_string(), "kind": "widget", "hard": hard }),
15855            )
15856        }
15857    }
15858
15859    fn registry_with_mock_resolver(
15860        rt: KhiveRuntime,
15861        resolver: Box<dyn crate::pack::PackByIdResolver>,
15862    ) -> crate::VerbRegistry {
15863        use crate::pack::{PackRuntime, VerbRegistryBuilder};
15864        use khive_types::{HandlerDef, VerbCategory, Visibility};
15865
15866        static MINIMAL_HANDLERS: &[HandlerDef] = &[HandlerDef {
15867            name: "minimal.noop",
15868            description: "noop",
15869            visibility: Visibility::Verb,
15870            category: VerbCategory::Commissive,
15871            params: &[],
15872        }];
15873
15874        struct MinimalPack;
15875        impl khive_types::Pack for MinimalPack {
15876            const NAME: &'static str = "minimal";
15877            const NOTE_KINDS: &'static [&'static str] = &[];
15878            const ENTITY_KINDS: &'static [&'static str] = &[];
15879            const HANDLERS: &'static [HandlerDef] = MINIMAL_HANDLERS;
15880        }
15881        #[async_trait::async_trait]
15882        impl PackRuntime for MinimalPack {
15883            fn name(&self) -> &str {
15884                "minimal"
15885            }
15886            fn note_kinds(&self) -> &'static [&'static str] {
15887                &[]
15888            }
15889            fn entity_kinds(&self) -> &'static [&'static str] {
15890                &[]
15891            }
15892            fn handlers(&self) -> &'static [HandlerDef] {
15893                MINIMAL_HANDLERS
15894            }
15895            async fn dispatch(
15896                &self,
15897                _verb: &str,
15898                _params: serde_json::Value,
15899                _registry: &crate::VerbRegistry,
15900                _token: &NamespaceToken,
15901            ) -> Result<serde_json::Value, RuntimeError> {
15902                Err(RuntimeError::InvalidInput("stub".into()))
15903            }
15904        }
15905
15906        let _ = rt;
15907        let mut builder = VerbRegistryBuilder::new();
15908        builder.register(MinimalPack);
15909        builder.register_resolver("mock", resolver);
15910        builder.build().expect("registry build failed")
15911    }
15912
15913    #[tokio::test]
15914    async fn pack_record_resolved_pair_returns_none() {
15915        let pr = Resolved::PackRecord {
15916            pack: "knowledge".into(),
15917            kind: "atom".into(),
15918            data: serde_json::json!({}),
15919        };
15920        assert!(
15921            resolved_pair(Some(&pr)).is_none(),
15922            "PackRecord must not be a valid edge endpoint"
15923        );
15924    }
15925
15926    #[test]
15927    fn resolved_pair_surfaces_entity_type() {
15928        let e = Resolved::Entity(
15929            Entity::new("mathlib", "concept", "Nat.add_comm").with_entity_type(Some("theorem")),
15930        );
15931        assert_eq!(
15932            resolved_pair(Some(&e)),
15933            Some(("entity", "concept", Some("theorem"))),
15934            "entity_type subtype must be surfaced alongside base kind"
15935        );
15936    }
15937
15938    #[test]
15939    fn endpoint_of_type_matches_subtype_not_base_kind() {
15940        // An entity whose base kind is "concept" and subtype is "theorem".
15941        let kind = "concept";
15942        let et = Some("theorem");
15943
15944        // EntityOfType matches only when BOTH base kind and subtype match.
15945        assert!(endpoint_matches(
15946            &EndpointKind::EntityOfType {
15947                kind: "concept",
15948                entity_type: "theorem",
15949            },
15950            "entity",
15951            kind,
15952            et
15953        ));
15954        assert!(!endpoint_matches(
15955            &EndpointKind::EntityOfType {
15956                kind: "concept",
15957                entity_type: "definition",
15958            },
15959            "entity",
15960            kind,
15961            et
15962        ));
15963
15964        // The silently-inert trap: EntityOfKind sees only the BASE
15965        // kind, so EntityOfKind("theorem") never matches a concept/theorem.
15966        assert!(!endpoint_matches(
15967            &EndpointKind::EntityOfKind("theorem"),
15968            "entity",
15969            kind,
15970            et
15971        ));
15972        // EntityOfKind still matches the base kind.
15973        assert!(endpoint_matches(
15974            &EndpointKind::EntityOfKind("concept"),
15975            "entity",
15976            kind,
15977            et
15978        ));
15979
15980        // EntityOfType rejects non-entity substrates and entities with no subtype.
15981        assert!(!endpoint_matches(
15982            &EndpointKind::EntityOfType {
15983                kind: "concept",
15984                entity_type: "theorem",
15985            },
15986            "note",
15987            "task",
15988            None
15989        ));
15990        assert!(!endpoint_matches(
15991            &EndpointKind::EntityOfType {
15992                kind: "concept",
15993                entity_type: "theorem",
15994            },
15995            "entity",
15996            kind,
15997            None
15998        ));
15999    }
16000
16001    #[test]
16002    fn endpoint_of_type_requires_base_kind_match() {
16003        // Regression: an entity with entity_type="theorem" but base kind != "concept"
16004        // must NOT match a formal concept rule. This was the exact bypass:
16005        // before the fix, EntityOfType("theorem") ignored the base kind entirely.
16006        let wrong_base_kind = "project"; // not "concept"
16007        let et = Some("theorem");
16008
16009        // The formal rule requires kind="concept". A "project" entity with
16010        // entity_type="theorem" must not match — even though the subtype string
16011        // matches — because the base kind differs.
16012        assert!(
16013            !endpoint_matches(
16014                &EndpointKind::EntityOfType {
16015                    kind: "concept",
16016                    entity_type: "theorem",
16017                },
16018                "entity",
16019                wrong_base_kind,
16020                et
16021            ),
16022            "EntityOfType must reject an entity whose base kind != rule.kind \
16023             even when entity_type matches — the pre-fix bug admitted this"
16024        );
16025
16026        // The correct concept entity with the same subtype still matches.
16027        assert!(endpoint_matches(
16028            &EndpointKind::EntityOfType {
16029                kind: "concept",
16030                entity_type: "theorem",
16031            },
16032            "entity",
16033            "concept",
16034            et
16035        ));
16036    }
16037
16038    #[tokio::test]
16039    async fn registry_resolvers_accessor_returns_registered() {
16040        let resolver = Box::new(MockPackResolver::new());
16041        let registry = registry_with_mock_resolver(rt(), resolver);
16042        assert_eq!(registry.resolvers().len(), 1);
16043        assert_eq!(registry.resolvers()[0].0, "mock");
16044    }
16045
16046    #[tokio::test]
16047    async fn mock_resolver_resolve_by_id_returns_pack_record() {
16048        let id = Uuid::new_v4();
16049        let resolver: Box<dyn PackByIdResolver> = Box::new(MockPackResolver::new());
16050        // We need interior access — downcast first, then use via trait.
16051        let inner = MockPackResolver::new();
16052        inner.0.lock().await.owned.push(id);
16053        let result: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
16054        match result.unwrap() {
16055            Some(Resolved::PackRecord { pack, kind, data }) => {
16056                assert_eq!(pack, "mock");
16057                assert_eq!(kind, "widget");
16058                assert_eq!(data["id"].as_str().unwrap(), id.to_string());
16059            }
16060            other => panic!("expected PackRecord, got {:?}", other),
16061        }
16062        let _ = resolver;
16063    }
16064
16065    #[tokio::test]
16066    async fn mock_resolver_resolve_unknown_uuid_returns_none() {
16067        let inner = MockPackResolver::new();
16068        let id = Uuid::new_v4();
16069        let result: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
16070        assert!(result.unwrap().is_none());
16071    }
16072
16073    #[tokio::test]
16074    async fn mock_resolver_delete_soft_records_call() {
16075        let id = Uuid::new_v4();
16076        let inner = MockPackResolver::new();
16077        inner.0.lock().await.owned.push(id);
16078
16079        let result: Result<serde_json::Value, RuntimeError> = inner.delete_by_id(id, false).await;
16080        let result = result.unwrap();
16081        assert_eq!(result["deleted"], serde_json::json!(true));
16082        assert_eq!(result["hard"], serde_json::json!(false));
16083
16084        // After soft-delete: resolve_by_id returns None, but including_deleted returns Some.
16085        let live: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
16086        assert!(live.unwrap().is_none());
16087        let incl: Result<Option<Resolved>, RuntimeError> =
16088            inner.resolve_by_id_including_deleted(id).await;
16089        assert!(incl.unwrap().is_some());
16090    }
16091
16092    #[tokio::test]
16093    async fn mock_resolver_delete_hard_removes_record() {
16094        let id = Uuid::new_v4();
16095        let inner = MockPackResolver::new();
16096        inner.0.lock().await.owned.push(id);
16097
16098        let result: Result<serde_json::Value, RuntimeError> = inner.delete_by_id(id, true).await;
16099        assert_eq!(result.unwrap()["hard"], serde_json::json!(true));
16100
16101        // After hard-delete: neither probe finds the record.
16102        let incl: Result<Option<Resolved>, RuntimeError> =
16103            inner.resolve_by_id_including_deleted(id).await;
16104        assert!(incl.unwrap().is_none());
16105    }
16106
16107    #[tokio::test]
16108    async fn pack_record_not_valid_context_entity() {
16109        // Validates the GTD handler arm compiles and returns InvalidInput.
16110        // We exercise the match logic directly by constructing a PackRecord Resolved.
16111        let pr = Resolved::PackRecord {
16112            pack: "knowledge".into(),
16113            kind: "atom".into(),
16114            data: serde_json::json!({}),
16115        };
16116        // The match in GTD handlers.rs now handles PackRecord → InvalidInput.
16117        // We can verify the enum variant is reachable.
16118        assert!(matches!(pr, Resolved::PackRecord { .. }));
16119    }
16120
16121    // ── Batched enrich_neighbor_hits / enrich_path_nodes ────────────────────
16122
16123    fn neighbor_hit(node_id: Uuid) -> NeighborHit {
16124        NeighborHit {
16125            node_id,
16126            edge_id: Uuid::new_v4(),
16127            relation: EdgeRelation::Extends,
16128            weight: 1.0,
16129            name: None,
16130            kind: None,
16131            entity_type: None,
16132        }
16133    }
16134
16135    fn path_node(node_id: Uuid, depth: usize) -> PathNode {
16136        PathNode {
16137            node_id,
16138            via_edge: None,
16139            depth,
16140            name: None,
16141            kind: None,
16142            properties: None,
16143            weight: 0.0,
16144        }
16145    }
16146
16147    /// merge_traversal_paths_by_root: three namespaces each contribute the
16148    /// same root plus 2 distinct non-root nodes (each namespace already at
16149    /// its own `limit`, matching the per-namespace SQL-layer cap). The
16150    /// union across namespaces is 6 distinct non-root nodes; the merge must
16151    /// re-enforce `limit` on that union rather than passing it through.
16152    #[test]
16153    fn merge_traversal_paths_reenforces_limit_across_namespaces() {
16154        let root = Uuid::new_v4();
16155        let path_for = |n: usize| GraphPath {
16156            root_id: root,
16157            nodes: (0..n).map(|_| path_node(Uuid::new_v4(), 1)).collect(),
16158            total_weight: 1.0,
16159        };
16160
16161        let paths = vec![path_for(2), path_for(2), path_for(2)];
16162        let merged = merge_traversal_paths_by_root(paths, Some(2));
16163
16164        assert_eq!(merged.len(), 1);
16165        assert_eq!(
16166            merged[0].nodes.len(),
16167            2,
16168            "merge must re-enforce limit=2 on the unioned nodes, got {:?}",
16169            merged[0].nodes
16170        );
16171    }
16172
16173    /// merge_traversal_paths_by_root: a node reachable at different depths
16174    /// via two namespaces must report its shallowest depth and the
16175    /// `via_edge` that produced that depth, and the merged node order must
16176    /// be BFS (ascending depth) rather than the concatenation order of the
16177    /// per-namespace inputs.
16178    #[test]
16179    fn merge_traversal_paths_keeps_shortest_depth_and_bfs_order() {
16180        let root = Uuid::new_v4();
16181        let shared = Uuid::new_v4();
16182        let far_node = Uuid::new_v4();
16183        let deep_edge = Uuid::new_v4();
16184        let shallow_edge = Uuid::new_v4();
16185
16186        // Namespace processed first: an unrelated node at depth 1, and the
16187        // shared node reached the long way, at depth 4.
16188        let ns_first = GraphPath {
16189            root_id: root,
16190            nodes: vec![
16191                path_node(far_node, 1),
16192                PathNode {
16193                    node_id: shared,
16194                    via_edge: Some(deep_edge),
16195                    depth: 4,
16196                    name: None,
16197                    kind: None,
16198                    properties: None,
16199                    weight: 0.0,
16200                },
16201            ],
16202            total_weight: 1.0,
16203        };
16204        // Namespace processed second: the same shared node, reached at depth 2.
16205        let ns_second = GraphPath {
16206            root_id: root,
16207            nodes: vec![PathNode {
16208                node_id: shared,
16209                via_edge: Some(shallow_edge),
16210                depth: 2,
16211                name: None,
16212                kind: None,
16213                properties: None,
16214                weight: 0.0,
16215            }],
16216            total_weight: 1.0,
16217        };
16218
16219        let merged = merge_traversal_paths_by_root(vec![ns_first, ns_second], None);
16220
16221        assert_eq!(merged.len(), 1);
16222        let nodes = &merged[0].nodes;
16223        assert!(
16224            nodes.windows(2).all(|w| w[0].depth <= w[1].depth),
16225            "merged nodes must be in BFS (ascending depth) order, got {:?}",
16226            nodes
16227                .iter()
16228                .map(|n| (n.node_id, n.depth))
16229                .collect::<Vec<_>>()
16230        );
16231        let shared_node = nodes
16232            .iter()
16233            .find(|n| n.node_id == shared)
16234            .expect("shared node must survive the merge");
16235        assert_eq!(
16236            shared_node.depth, 2,
16237            "shared node must report its shortest depth across namespaces"
16238        );
16239        assert_eq!(
16240            shared_node.via_edge,
16241            Some(shallow_edge),
16242            "shared node must carry the via_edge that produced the shortest path"
16243        );
16244    }
16245
16246    /// merge_traversal_paths_by_root: `total_weight` must describe the nodes
16247    /// the caller is actually handed. The heaviest node here sits deepest, so
16248    /// re-applying `limit` to the merged union drops it — and the reported
16249    /// weight has to drop with it rather than keep quoting a node that was
16250    /// screened out.
16251    #[test]
16252    fn merge_traversal_paths_total_weight_drops_with_the_node_it_described() {
16253        let root = Uuid::new_v4();
16254        let weighted = |depth: usize, weight: f64| PathNode {
16255            node_id: Uuid::new_v4(),
16256            via_edge: None,
16257            depth,
16258            name: None,
16259            kind: None,
16260            properties: None,
16261            weight,
16262        };
16263
16264        let path = GraphPath {
16265            root_id: root,
16266            nodes: vec![weighted(1, 0.5), weighted(1, 0.4), weighted(2, 9.0)],
16267            total_weight: 9.0,
16268        };
16269
16270        let merged = merge_traversal_paths_by_root(vec![path], Some(2));
16271
16272        assert_eq!(merged.len(), 1);
16273        assert_eq!(
16274            merged[0].nodes.len(),
16275            2,
16276            "limit=2 must drop the depth-2 node"
16277        );
16278        assert_eq!(
16279            merged[0].total_weight, 0.5,
16280            "total_weight must be the max over surviving nodes, not the 9.0 \
16281             carried by the node the limit removed"
16282        );
16283    }
16284
16285    /// enrich_neighbor_hits: entity hit resolved, note hit resolved with
16286    /// name-fallback to "[kind]", bogus UUID left as None.  Order preserved.
16287    #[tokio::test]
16288    async fn enrich_neighbor_hits_batch_entity_note_and_bogus() {
16289        let rt = rt();
16290        let tok = NamespaceToken::local();
16291
16292        // Create an entity neighbor.
16293        let entity = rt
16294            .create_entity(&tok, "concept", None, "MyEntity", None, None, vec![])
16295            .await
16296            .unwrap();
16297
16298        // Nameless note — name falls back to "[observation]".
16299        let note = rt
16300            .create_note(&tok, "observation", None, "body", Some(0.5), None, vec![])
16301            .await
16302            .unwrap();
16303
16304        let bogus_id = Uuid::new_v4();
16305
16306        let mut hits = vec![
16307            neighbor_hit(entity.id),
16308            neighbor_hit(note.id),
16309            neighbor_hit(bogus_id),
16310        ];
16311
16312        rt.enrich_neighbor_hits(&tok, &mut hits).await;
16313
16314        assert_eq!(hits[0].name.as_deref(), Some("MyEntity"));
16315        assert_eq!(hits[0].kind.as_deref(), Some("concept"));
16316
16317        assert_eq!(hits[1].name.as_deref(), Some("[observation]"));
16318        assert_eq!(hits[1].kind.as_deref(), Some("observation"));
16319
16320        assert!(hits[2].name.is_none());
16321        assert!(hits[2].kind.is_none());
16322    }
16323
16324    /// enrich_neighbor_hits: note with a non-empty name uses the actual name.
16325    #[tokio::test]
16326    async fn enrich_neighbor_hits_note_with_name_uses_name() {
16327        let rt = rt();
16328        let tok = NamespaceToken::local();
16329
16330        let note = rt
16331            .create_note(
16332                &tok,
16333                "insight",
16334                Some("NoteTitle"),
16335                "body",
16336                Some(0.5),
16337                None,
16338                vec![],
16339            )
16340            .await
16341            .unwrap();
16342
16343        let mut hits = vec![neighbor_hit(note.id)];
16344        rt.enrich_neighbor_hits(&tok, &mut hits).await;
16345
16346        assert_eq!(hits[0].name.as_deref(), Some("NoteTitle"));
16347        assert_eq!(hits[0].kind.as_deref(), Some("insight"));
16348    }
16349
16350    /// enrich_path_nodes: two paths sharing a repeated node_id; each node
16351    /// enriched from a single batch; unresolved node stays None.
16352    #[tokio::test]
16353    async fn enrich_path_nodes_batch_dedup_and_unresolved() {
16354        let rt = rt();
16355        let tok = NamespaceToken::local();
16356
16357        let ea = rt
16358            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
16359            .await
16360            .unwrap();
16361        let eb = rt
16362            .create_entity(&tok, "document", None, "Beta", None, None, vec![])
16363            .await
16364            .unwrap();
16365        let bogus_id = Uuid::new_v4();
16366
16367        // Path 1: ea → eb → bogus  |  Path 2: eb → ea  (shared nodes, reversed)
16368        let mut paths = vec![
16369            GraphPath {
16370                root_id: ea.id,
16371                nodes: vec![
16372                    path_node(ea.id, 0),
16373                    path_node(eb.id, 1),
16374                    path_node(bogus_id, 2),
16375                ],
16376                total_weight: 1.0,
16377            },
16378            GraphPath {
16379                root_id: eb.id,
16380                nodes: vec![path_node(eb.id, 0), path_node(ea.id, 1)],
16381                total_weight: 1.0,
16382            },
16383        ];
16384
16385        rt.enrich_path_nodes(&tok, &mut paths, false).await;
16386
16387        assert_eq!(paths[0].nodes[0].name.as_deref(), Some("Alpha"));
16388        assert_eq!(paths[0].nodes[0].kind.as_deref(), Some("concept"));
16389        assert_eq!(paths[0].nodes[1].name.as_deref(), Some("Beta"));
16390        assert_eq!(paths[0].nodes[1].kind.as_deref(), Some("document"));
16391        assert!(paths[0].nodes[2].name.is_none());
16392        assert!(paths[0].nodes[2].kind.is_none());
16393
16394        // Shared nodes resolve from the same HashMap — order within each path is preserved.
16395        assert_eq!(paths[1].nodes[0].name.as_deref(), Some("Beta"));
16396        assert_eq!(paths[1].nodes[0].kind.as_deref(), Some("document"));
16397        assert_eq!(paths[1].nodes[1].name.as_deref(), Some("Alpha"));
16398        assert_eq!(paths[1].nodes[1].kind.as_deref(), Some("concept"));
16399    }
16400
16401    /// enrich_neighbor_hits and enrich_path_nodes must resolve entities whose
16402    /// namespace is in the token's extra-visible set (not only the primary).
16403    ///
16404    /// Regression: the old `get_entities_by_ids`
16405    /// call left `filter.namespaces` unset, which collapses to
16406    /// `namespace = primary` in `build_entity_where`.  Graph expansion already
16407    /// crosses visible namespaces, so enrichment must match that scope.
16408    #[tokio::test]
16409    async fn enrich_resolves_entities_in_extra_visible_namespace() {
16410        let rt = KhiveRuntime::memory().unwrap();
16411
16412        let ns_a = Namespace::parse("enrich-ns-a").unwrap();
16413        let ns_b = Namespace::parse("enrich-ns-b").unwrap();
16414
16415        let tok_b = rt.authorize(ns_b.clone()).unwrap();
16416
16417        // Entity lives in ns-b.
16418        let entity_b = rt
16419            .create_entity(&tok_b, "concept", None, "EntityInB", None, None, vec![])
16420            .await
16421            .unwrap();
16422        assert_eq!(entity_b.namespace, "enrich-ns-b");
16423
16424        // Token whose primary is ns-a but ns-b is in the visible set.
16425        let vis_tok = rt
16426            .authorize_with_visibility(ns_a.clone(), vec![ns_b.clone()])
16427            .unwrap();
16428
16429        // ── neighbor hits ──────────────────────────────────────────────────
16430        let mut hits = vec![neighbor_hit(entity_b.id)];
16431        rt.enrich_neighbor_hits(&vis_tok, &mut hits).await;
16432
16433        assert_eq!(
16434            hits[0].name.as_deref(),
16435            Some("EntityInB"),
16436            "entity in extra-visible ns must be enriched by enrich_neighbor_hits"
16437        );
16438        assert_eq!(hits[0].kind.as_deref(), Some("concept"));
16439
16440        // ── path nodes ─────────────────────────────────────────────────────
16441        let mut paths = vec![GraphPath {
16442            root_id: entity_b.id,
16443            nodes: vec![path_node(entity_b.id, 0)],
16444            total_weight: 1.0,
16445        }];
16446        rt.enrich_path_nodes(&vis_tok, &mut paths, false).await;
16447
16448        assert_eq!(
16449            paths[0].nodes[0].name.as_deref(),
16450            Some("EntityInB"),
16451            "entity in extra-visible ns must be enriched by enrich_path_nodes"
16452        );
16453        assert_eq!(paths[0].nodes[0].kind.as_deref(), Some("concept"));
16454    }
16455
16456    /// enrich_neighbor_hits populates entity_type from the already-fetched entity
16457    /// batch when the entity has a non-null entity_type.  Entities without one and
16458    /// note nodes leave entity_type as None.
16459    #[tokio::test]
16460    async fn enrich_neighbor_hits_populates_entity_type() {
16461        let rt = rt();
16462        let tok = NamespaceToken::local();
16463
16464        let props = serde_json::json!({"domain": "attention"});
16465        let entity = rt
16466            .create_entity(
16467                &tok,
16468                "concept",
16469                Some("algorithm"),
16470                "FlashAttn",
16471                None,
16472                Some(props),
16473                vec![],
16474            )
16475            .await
16476            .unwrap();
16477
16478        let entity_no_type = rt
16479            .create_entity(&tok, "concept", None, "PlainConcept", None, None, vec![])
16480            .await
16481            .unwrap();
16482
16483        let mut hits = vec![neighbor_hit(entity.id), neighbor_hit(entity_no_type.id)];
16484        rt.enrich_neighbor_hits(&tok, &mut hits).await;
16485
16486        assert_eq!(hits[0].entity_type.as_deref(), Some("algorithm"));
16487        assert!(
16488            hits[1].entity_type.is_none(),
16489            "entity without entity_type must leave the field as None"
16490        );
16491    }
16492
16493    /// enrich_path_nodes populates properties from the already-fetched entity
16494    /// batch when the entity has a non-null properties blob.  Entities without
16495    /// properties leave the field as None.
16496    #[tokio::test]
16497    async fn enrich_path_nodes_populates_properties() {
16498        let rt = rt();
16499        let tok = NamespaceToken::local();
16500
16501        let props = serde_json::json!({"year": 2024, "venue": "NeurIPS"});
16502        let entity_with_props = rt
16503            .create_entity(
16504                &tok,
16505                "document",
16506                None,
16507                "AttentionPaper",
16508                None,
16509                Some(props.clone()),
16510                vec![],
16511            )
16512            .await
16513            .unwrap();
16514
16515        let entity_no_props = rt
16516            .create_entity(&tok, "concept", None, "BareConceptNode", None, None, vec![])
16517            .await
16518            .unwrap();
16519
16520        let mut paths = vec![GraphPath {
16521            root_id: entity_with_props.id,
16522            nodes: vec![
16523                path_node(entity_with_props.id, 0),
16524                path_node(entity_no_props.id, 1),
16525            ],
16526            total_weight: 1.0,
16527        }];
16528
16529        rt.enrich_path_nodes(&tok, &mut paths, true).await;
16530
16531        assert_eq!(
16532            paths[0].nodes[0].properties.as_ref(),
16533            Some(&props),
16534            "properties must be filled when entity has a non-null properties blob"
16535        );
16536        assert!(
16537            paths[0].nodes[1].properties.is_none(),
16538            "entity without properties must leave the field as None"
16539        );
16540    }
16541
16542    /// The runtime enforces the public root cap before doing any root-existence
16543    /// lookups or handing work to storage.
16544    #[tokio::test]
16545    async fn traverse_rejects_root_count_above_public_cap_before_lookup() {
16546        use khive_storage::types::{TraversalOptions, MAX_TRAVERSAL_ROOTS};
16547
16548        let rt = rt();
16549        let tok = NamespaceToken::local();
16550        let err = rt
16551            .traverse(
16552                &tok,
16553                TraversalRequest {
16554                    roots: (0..=MAX_TRAVERSAL_ROOTS)
16555                        .map(|_| uuid::Uuid::new_v4())
16556                        .collect(),
16557                    options: TraversalOptions {
16558                        max_depth: 1,
16559                        direction: Direction::Out,
16560                        relations: None,
16561                        min_weight: None,
16562                        limit: None,
16563                    },
16564                    include_roots: false,
16565                    include_properties: false,
16566                    execution_budget: Default::default(),
16567                },
16568            )
16569            .await
16570            .unwrap_err();
16571
16572        assert!(matches!(
16573            err,
16574            RuntimeError::InvalidInput(message)
16575                if message.contains("roots must contain at most 100 entries")
16576        ));
16577    }
16578
16579    // ── Additive EDGE_RULES composition: pack EntityOfType rules must not shadow
16580    // the base EntityOfKind contract for the same relation. ──────────────────────
16581    //
16582    // When a pack contributes EntityOfType rules for a relation (e.g. variant_of:
16583    // goal -> theorem and goal -> definition), the base contract's EntityOfKind
16584    // rule for the same relation (concept -> concept) must still fire for entities
16585    // whose base kind is "concept" but whose EntityOfType pair is not in any pack rule.
16586    //
16587    // Specifically: a goal entity resolves to base kind "concept". A goal -> goal
16588    // variant_of edge has no matching pack rule (goal -> goal is not declared), so
16589    // pack_rule_allows returns false. The validator then extracts the base kind
16590    // ("concept") and checks base_entity_rule_allows, which returns true.
16591    // The edge is therefore allowed: additive composition holds.
16592
16593    #[test]
16594    fn pack_entity_of_type_rules_do_not_shadow_base_entity_of_kind_rule() {
16595        // Formal-style EntityOfType rules for variant_of: goal -> theorem, goal -> definition.
16596        // goal -> goal is deliberately absent — that case must fall through to the base rule.
16597        let pack_rules: Vec<EdgeEndpointRule> = vec![
16598            EdgeEndpointRule {
16599                relation: EdgeRelation::VariantOf,
16600                source: EndpointKind::EntityOfType {
16601                    kind: "concept",
16602                    entity_type: "goal",
16603                },
16604                target: EndpointKind::EntityOfType {
16605                    kind: "concept",
16606                    entity_type: "theorem",
16607                },
16608            },
16609            EdgeEndpointRule {
16610                relation: EdgeRelation::VariantOf,
16611                source: EndpointKind::EntityOfType {
16612                    kind: "concept",
16613                    entity_type: "goal",
16614                },
16615                target: EndpointKind::EntityOfType {
16616                    kind: "concept",
16617                    entity_type: "definition",
16618                },
16619            },
16620        ];
16621
16622        let goal_a =
16623            Resolved::Entity(Entity::new("local", "concept", "G-a").with_entity_type(Some("goal")));
16624        let goal_b =
16625            Resolved::Entity(Entity::new("local", "concept", "G-b").with_entity_type(Some("goal")));
16626
16627        // Pack rules do not cover goal -> goal, so pack_rule_allows must return false.
16628        assert!(
16629            !pack_rule_allows(
16630                &pack_rules,
16631                EdgeRelation::VariantOf,
16632                Some(&goal_a),
16633                Some(&goal_b)
16634            ),
16635            "pack rules must not cover goal->goal variant_of (no such rule declared)"
16636        );
16637
16638        // The base contract allows concept -> concept for variant_of.
16639        // A goal entity's base kind is "concept", so this must return true.
16640        assert!(
16641            base_entity_rule_allows("concept", EdgeRelation::VariantOf, "concept"),
16642            "base contract must allow concept->concept variant_of regardless of pack EntityOfType rules"
16643        );
16644    }
16645
16646    // Integration path: pack EntityOfType rules installed on the runtime must not
16647    // block a goal->goal variant_of link that the base contract already permits.
16648    // Exercises validate_edge_relation_endpoints lines 1173-1223:
16649    //   pack miss -> extract e.kind ("concept") -> base_entity_rule_allows -> Ok.
16650    #[tokio::test]
16651    async fn link_variant_of_goal_to_goal_allowed_when_pack_has_entity_of_type_rules() {
16652        let rt = rt();
16653        let tok = NamespaceToken::local();
16654
16655        // Install formal-style EntityOfType rules for variant_of (goal -> theorem/definition).
16656        // goal -> goal is absent so the base concept->concept rule must carry this case.
16657        rt.install_edge_rules(vec![
16658            EdgeEndpointRule {
16659                relation: EdgeRelation::VariantOf,
16660                source: EndpointKind::EntityOfType {
16661                    kind: "concept",
16662                    entity_type: "goal",
16663                },
16664                target: EndpointKind::EntityOfType {
16665                    kind: "concept",
16666                    entity_type: "theorem",
16667                },
16668            },
16669            EdgeEndpointRule {
16670                relation: EdgeRelation::VariantOf,
16671                source: EndpointKind::EntityOfType {
16672                    kind: "concept",
16673                    entity_type: "goal",
16674                },
16675                target: EndpointKind::EntityOfType {
16676                    kind: "concept",
16677                    entity_type: "definition",
16678                },
16679            },
16680        ]);
16681
16682        let a = rt
16683            .create_entity(
16684                &tok,
16685                "concept",
16686                Some("goal"),
16687                "Goal Alpha",
16688                None,
16689                None,
16690                vec![],
16691            )
16692            .await
16693            .unwrap();
16694        let b = rt
16695            .create_entity(
16696                &tok,
16697                "concept",
16698                Some("goal"),
16699                "Goal Beta",
16700                None,
16701                None,
16702                vec![],
16703            )
16704            .await
16705            .unwrap();
16706
16707        // Neither endpoint matches any pack rule (no goal->goal rule).
16708        // The base concept->concept rule must fire and allow the edge.
16709        let result = rt
16710            .link(&tok, a.id, b.id, EdgeRelation::VariantOf, 1.0, None)
16711            .await;
16712        assert!(
16713            result.is_ok(),
16714            "goal->goal variant_of must be allowed via the base concept->concept rule \
16715             even when EntityOfType rules for variant_of are installed; got {result:?}"
16716        );
16717
16718        // Fail-closed check: additive rules must not make validation fail-open.
16719        // A goal(concept) -> project variant_of edge has no matching pack rule
16720        // (project is not in the installed variant_of rules) and no matching base
16721        // rule (no (concept, VariantOf, project) row). It must be rejected.
16722        let p = rt
16723            .create_entity(&tok, "project", None, "Proj", None, None, vec![])
16724            .await
16725            .unwrap();
16726        let bad = rt
16727            .link(&tok, a.id, p.id, EdgeRelation::VariantOf, 1.0, None)
16728            .await;
16729        assert!(
16730            bad.is_err(),
16731            "additive pack rules must not make validation fail-open; \
16732             goal(concept)->project variant_of must be rejected (pack miss + base miss); \
16733             got {bad:?}"
16734        );
16735    }
16736
16737    // Load-bearing positive: a pack EntityOfType rule adds an endpoint the base contract
16738    // does not cover. The base contract has no (concept, DependsOn, concept) row (the
16739    // DependsOn rows are project/service/artifact only). A theorem->definition DependsOn
16740    // edge can therefore ONLY pass through the pack rule, proving the union is load-bearing.
16741    #[tokio::test]
16742    async fn link_depends_on_theorem_to_definition_allowed_only_via_pack_rule() {
16743        let rt = rt();
16744        let tok = NamespaceToken::local();
16745
16746        // Confirm the base contract does NOT allow concept->concept DependsOn.
16747        // (Documented here so the assertion below is not a tautology.)
16748        assert!(
16749            !base_entity_rule_allows("concept", EdgeRelation::DependsOn, "concept"),
16750            "base contract must not allow concept->concept DependsOn; \
16751             test would be vacuous if this precondition fails"
16752        );
16753
16754        // Install a single EntityOfType rule: theorem depends_on definition.
16755        // With no rules, the link would be rejected by the base contract.
16756        // With this rule, it must be accepted via the pack path (lines 1173-1179).
16757        rt.install_edge_rules(vec![EdgeEndpointRule {
16758            relation: EdgeRelation::DependsOn,
16759            source: EndpointKind::EntityOfType {
16760                kind: "concept",
16761                entity_type: "theorem",
16762            },
16763            target: EndpointKind::EntityOfType {
16764                kind: "concept",
16765                entity_type: "definition",
16766            },
16767        }]);
16768
16769        let thm = rt
16770            .create_entity(&tok, "concept", Some("theorem"), "T1", None, None, vec![])
16771            .await
16772            .unwrap();
16773        let def = rt
16774            .create_entity(
16775                &tok,
16776                "concept",
16777                Some("definition"),
16778                "D1",
16779                None,
16780                None,
16781                vec![],
16782            )
16783            .await
16784            .unwrap();
16785
16786        // This can only pass through the pack rule — the base contract rejects it.
16787        let result = rt
16788            .link(&tok, thm.id, def.id, EdgeRelation::DependsOn, 1.0, None)
16789            .await;
16790        assert!(
16791            result.is_ok(),
16792            "theorem->definition DependsOn must be allowed by the installed pack rule; \
16793             the base contract has no concept->concept DependsOn row; got {result:?}"
16794        );
16795    }
16796
16797    // ── Provenance endpoint pairs ────────────────────────────────────────────
16798    // Four base endpoint pairs: document->person and document->org (document
16799    // authorship), concept->org (concept origination by an org), and
16800    // document->document (normative document dependency). Positive links for
16801    // each pair, plus a direction-matters negative guard.
16802
16803    #[tokio::test]
16804    async fn link_document_introduced_by_person_allowed() {
16805        let rt = rt();
16806        let tok = NamespaceToken::local();
16807
16808        let doc = rt
16809            .create_entity(&tok, "document", None, "Paper", None, None, vec![])
16810            .await
16811            .unwrap();
16812        let author = rt
16813            .create_entity(&tok, "person", None, "Author", None, None, vec![])
16814            .await
16815            .unwrap();
16816
16817        let result = rt
16818            .link(
16819                &tok,
16820                doc.id,
16821                author.id,
16822                EdgeRelation::IntroducedBy,
16823                1.0,
16824                None,
16825            )
16826            .await;
16827        assert!(
16828            result.is_ok(),
16829            "document->person introduced_by must be allowed by the ADR-002 \
16830             endpoint amendment; got {result:?}"
16831        );
16832    }
16833
16834    #[tokio::test]
16835    async fn link_document_introduced_by_org_allowed() {
16836        let rt = rt();
16837        let tok = NamespaceToken::local();
16838
16839        let doc = rt
16840            .create_entity(&tok, "document", None, "Whitepaper", None, None, vec![])
16841            .await
16842            .unwrap();
16843        let org = rt
16844            .create_entity(&tok, "org", None, "Publisher", None, None, vec![])
16845            .await
16846            .unwrap();
16847
16848        let result = rt
16849            .link(&tok, doc.id, org.id, EdgeRelation::IntroducedBy, 1.0, None)
16850            .await;
16851        assert!(
16852            result.is_ok(),
16853            "document->org introduced_by must be allowed by the ADR-002 \
16854             endpoint amendment; got {result:?}"
16855        );
16856    }
16857
16858    #[tokio::test]
16859    async fn link_concept_introduced_by_org_allowed() {
16860        let rt = rt();
16861        let tok = NamespaceToken::local();
16862
16863        let concept = rt
16864            .create_entity(&tok, "concept", None, "Architecture", None, None, vec![])
16865            .await
16866            .unwrap();
16867        let org = rt
16868            .create_entity(&tok, "org", None, "Originator", None, None, vec![])
16869            .await
16870            .unwrap();
16871
16872        let result = rt
16873            .link(
16874                &tok,
16875                concept.id,
16876                org.id,
16877                EdgeRelation::IntroducedBy,
16878                1.0,
16879                None,
16880            )
16881            .await;
16882        assert!(
16883            result.is_ok(),
16884            "concept->org introduced_by must be allowed by the ADR-002 \
16885             endpoint amendment; got {result:?}"
16886        );
16887    }
16888
16889    #[tokio::test]
16890    async fn link_document_depends_on_document_allowed() {
16891        let rt = rt();
16892        let tok = NamespaceToken::local();
16893
16894        let doc_a = rt
16895            .create_entity(&tok, "document", None, "Spec A", None, None, vec![])
16896            .await
16897            .unwrap();
16898        let doc_b = rt
16899            .create_entity(&tok, "document", None, "Spec B", None, None, vec![])
16900            .await
16901            .unwrap();
16902
16903        let result = rt
16904            .link(&tok, doc_a.id, doc_b.id, EdgeRelation::DependsOn, 1.0, None)
16905            .await;
16906        assert!(
16907            result.is_ok(),
16908            "document->document depends_on must be allowed by the ADR-002 \
16909             endpoint amendment; got {result:?}"
16910        );
16911        let edge = result.unwrap();
16912        let dk = edge
16913            .metadata
16914            .as_ref()
16915            .and_then(|m| m.get("dependency_kind"))
16916            .and_then(|v| v.as_str());
16917        assert_eq!(
16918            dk,
16919            Some("normative"),
16920            "document->document depends_on must infer dependency_kind=normative"
16921        );
16922    }
16923
16924    #[tokio::test]
16925    async fn link_org_introduced_by_document_rejected_direction_matters() {
16926        let rt = rt();
16927        let tok = NamespaceToken::local();
16928
16929        let org = rt
16930            .create_entity(&tok, "org", None, "Publisher", None, None, vec![])
16931            .await
16932            .unwrap();
16933        let doc = rt
16934            .create_entity(&tok, "document", None, "Paper", None, None, vec![])
16935            .await
16936            .unwrap();
16937
16938        // The amendment adds document->org, not org->document. Direction matters:
16939        // an org is not "introduced by" a document it published.
16940        let result = rt
16941            .link(&tok, org.id, doc.id, EdgeRelation::IntroducedBy, 1.0, None)
16942            .await;
16943        assert!(
16944            result.is_err(),
16945            "org->document introduced_by must remain rejected; only \
16946             document->org is permitted, not the reverse; got {result:?}"
16947        );
16948    }
16949
16950    // ── Service provenance endpoint pair (ADR-167) ──────────────────────────
16951    // service->document is the only introduced_by pair with a service
16952    // endpoint: a service's provenance is stated by the document that
16953    // introduced it. Neighboring pairs and the reverse stay rejected.
16954
16955    #[tokio::test]
16956    async fn link_service_introduced_by_document_allowed() {
16957        let rt = rt();
16958        let tok = NamespaceToken::local();
16959
16960        let svc = rt
16961            .create_entity(&tok, "service", None, "Search API", None, None, vec![])
16962            .await
16963            .unwrap();
16964        let doc = rt
16965            .create_entity(&tok, "document", None, "Design doc", None, None, vec![])
16966            .await
16967            .unwrap();
16968
16969        let result = rt
16970            .link(&tok, svc.id, doc.id, EdgeRelation::IntroducedBy, 1.0, None)
16971            .await;
16972        assert!(
16973            result.is_ok(),
16974            "service->document introduced_by must be allowed by the ADR-167 \
16975             endpoint amendment; got {result:?}"
16976        );
16977    }
16978
16979    #[tokio::test]
16980    async fn link_service_introduced_by_person_rejected() {
16981        let rt = rt();
16982        let tok = NamespaceToken::local();
16983
16984        let svc = rt
16985            .create_entity(&tok, "service", None, "Search API", None, None, vec![])
16986            .await
16987            .unwrap();
16988        let person = rt
16989            .create_entity(&tok, "person", None, "Operator", None, None, vec![])
16990            .await
16991            .unwrap();
16992
16993        let result = rt
16994            .link(
16995                &tok,
16996                svc.id,
16997                person.id,
16998                EdgeRelation::IntroducedBy,
16999                1.0,
17000                None,
17001            )
17002            .await;
17003        assert!(
17004            result.is_err(),
17005            "service->person introduced_by is not in the endpoint table and \
17006             must be rejected; got {result:?}"
17007        );
17008    }
17009
17010    #[tokio::test]
17011    async fn link_service_introduced_by_org_rejected() {
17012        let rt = rt();
17013        let tok = NamespaceToken::local();
17014
17015        let svc = rt
17016            .create_entity(&tok, "service", None, "Search API", None, None, vec![])
17017            .await
17018            .unwrap();
17019        let org = rt
17020            .create_entity(&tok, "org", None, "Vendor", None, None, vec![])
17021            .await
17022            .unwrap();
17023
17024        let result = rt
17025            .link(&tok, svc.id, org.id, EdgeRelation::IntroducedBy, 1.0, None)
17026            .await;
17027        assert!(
17028            result.is_err(),
17029            "service->org introduced_by is not in the endpoint table and \
17030             must be rejected; got {result:?}"
17031        );
17032    }
17033
17034    #[tokio::test]
17035    async fn link_document_introduced_by_service_rejected_direction_matters() {
17036        let rt = rt();
17037        let tok = NamespaceToken::local();
17038
17039        let doc = rt
17040            .create_entity(&tok, "document", None, "Design doc", None, None, vec![])
17041            .await
17042            .unwrap();
17043        let svc = rt
17044            .create_entity(&tok, "service", None, "Search API", None, None, vec![])
17045            .await
17046            .unwrap();
17047
17048        let result = rt
17049            .link(&tok, doc.id, svc.id, EdgeRelation::IntroducedBy, 1.0, None)
17050            .await;
17051        assert!(
17052            result.is_err(),
17053            "document->service introduced_by must remain rejected; only \
17054             service->document is permitted, not the reverse; got {result:?}"
17055        );
17056    }
17057
17058    #[tokio::test]
17059    async fn link_service_derived_from_document_rejected() {
17060        let rt = rt();
17061        let tok = NamespaceToken::local();
17062
17063        let svc = rt
17064            .create_entity(&tok, "service", None, "Search API", None, None, vec![])
17065            .await
17066            .unwrap();
17067        let doc = rt
17068            .create_entity(&tok, "document", None, "Design doc", None, None, vec![])
17069            .await
17070            .unwrap();
17071
17072        let result = rt
17073            .link(&tok, svc.id, doc.id, EdgeRelation::DerivedFrom, 1.0, None)
17074            .await;
17075        assert!(
17076            result.is_err(),
17077            "service->document is permitted only for introduced_by; the same \
17078             endpoints under derived_from must be rejected; got {result:?}"
17079        );
17080    }
17081
17082    // ── create_note_with_embedding_content ──────────────────────────────────
17083
17084    /// Like `ConstVecService`/`ConstVecProvider` above, but records every text
17085    /// it is asked to embed so a test can assert exactly what reached the
17086    /// "provider" — used to verify the effective embed text is the capped
17087    /// override, not the full note content.
17088    struct CapturingVecService {
17089        dims: usize,
17090        captured: Arc<std::sync::Mutex<Vec<String>>>,
17091    }
17092
17093    #[async_trait]
17094    impl EmbeddingService for CapturingVecService {
17095        async fn embed(
17096            &self,
17097            texts: &[String],
17098            _model: EmbeddingModel,
17099        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
17100            for text in texts {
17101                if text.len() > MAX_TEXT_BYTES {
17102                    return Err(EmbedError::TextTooLong {
17103                        length: text.len(),
17104                        max: MAX_TEXT_BYTES,
17105                    });
17106                }
17107            }
17108            self.captured.lock().unwrap().extend(texts.iter().cloned());
17109            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
17110        }
17111
17112        fn supports_model(&self, _model: EmbeddingModel) -> bool {
17113            true
17114        }
17115
17116        fn name(&self) -> &'static str {
17117            "capturing-vec"
17118        }
17119    }
17120
17121    struct CapturingVecProvider {
17122        provider_name: String,
17123        dims: usize,
17124        captured: Arc<std::sync::Mutex<Vec<String>>>,
17125    }
17126
17127    #[async_trait]
17128    impl EmbedderProvider for CapturingVecProvider {
17129        fn name(&self) -> &str {
17130            &self.provider_name
17131        }
17132
17133        fn dimensions(&self) -> usize {
17134            self.dims
17135        }
17136
17137        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
17138            Ok(Arc::new(CapturingVecService {
17139                dims: self.dims,
17140                captured: Arc::clone(&self.captured),
17141            }))
17142        }
17143    }
17144
17145    #[tokio::test]
17146    async fn create_bounds_embedding_input_without_truncating_stored_content() {
17147        let rt = rt();
17148        let tok = NamespaceToken::local();
17149        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
17150        rt.register_embedder(CapturingVecProvider {
17151            provider_name: "strict-length-test".into(),
17152            dims: 4,
17153            captured: Arc::clone(&captured),
17154        });
17155
17156        let content = format!("{}\u{1f980}tail", "a".repeat(MAX_TEXT_BYTES - 1));
17157        let note = rt
17158            .create_note(&tok, "observation", None, &content, None, None, vec![])
17159            .await
17160            .expect("over-length note create must succeed");
17161        let fetched = rt
17162            .notes(&tok)
17163            .unwrap()
17164            .get_note(note.id)
17165            .await
17166            .unwrap()
17167            .expect("created note must be retrievable");
17168        assert_eq!(fetched.content, content, "stored content must remain full");
17169
17170        let embedded = captured.lock().unwrap().clone();
17171        assert_eq!(embedded.len(), 1);
17172        assert_eq!(embedded[0].len(), MAX_TEXT_BYTES - 1);
17173        assert!(embedded[0].is_char_boundary(embedded[0].len()));
17174        assert!(!embedded[0].contains('\u{1f980}'));
17175
17176        let vector_info = rt
17177            .vectors_for_model(&tok, "strict-length-test")
17178            .expect("vector store")
17179            .info()
17180            .await
17181            .expect("vector info");
17182        assert_eq!(vector_info.dimensions, 4);
17183        assert_eq!(vector_info.entry_count, 1);
17184
17185        captured.lock().unwrap().clear();
17186        rt.reindex_note(&tok, &fetched)
17187            .await
17188            .expect("reindex must bound the same stored content");
17189        assert_eq!(captured.lock().unwrap()[0].len(), MAX_TEXT_BYTES - 1);
17190
17191        captured.lock().unwrap().clear();
17192        rt.embed_document_batch_with_model("strict-length-test", std::slice::from_ref(&content))
17193            .await
17194            .expect("batch reindex seam must bound stored content");
17195        assert_eq!(captured.lock().unwrap()[0].len(), MAX_TEXT_BYTES - 1);
17196
17197        let normal = "normal byte-identical embedding input";
17198        rt.create_note(&tok, "observation", None, normal, None, None, vec![])
17199            .await
17200            .expect("normal note create must succeed");
17201        assert_eq!(captured.lock().unwrap().last().unwrap(), normal);
17202
17203        let long_description = format!("{}\u{1f980}tail", "b".repeat(MAX_TEXT_BYTES));
17204        rt.create_entity(
17205            &tok,
17206            "concept",
17207            None,
17208            "entity",
17209            Some(&long_description),
17210            None,
17211            vec![],
17212        )
17213        .await
17214        .expect("over-length entity create must succeed");
17215    }
17216
17217    #[tokio::test]
17218    async fn create_note_with_embedding_content_none_matches_create_note() {
17219        let rt = rt();
17220        let tok = NamespaceToken::local();
17221        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
17222        rt.register_embedder(CapturingVecProvider {
17223            provider_name: "capturing-vec".into(),
17224            dims: 4,
17225            captured: Arc::clone(&captured),
17226        });
17227
17228        let note = rt
17229            .create_note_with_embedding_content(
17230                &tok,
17231                "observation",
17232                None,
17233                "full content, no override",
17234                None,
17235                None,
17236                None,
17237                vec![],
17238            )
17239            .await
17240            .expect("create with None override must behave like create_note");
17241        assert_eq!(note.content, "full content, no override");
17242        let seen = captured.lock().unwrap().clone();
17243        assert_eq!(
17244            seen,
17245            vec!["full content, no override".to_string()],
17246            "with no override the embedder must see the full content"
17247        );
17248    }
17249
17250    #[tokio::test]
17251    async fn create_note_with_embedding_content_embeds_capped_override_and_stores_full_content() {
17252        let rt = rt();
17253        let tok = NamespaceToken::local();
17254        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
17255        rt.register_embedder(CapturingVecProvider {
17256            provider_name: "capturing-vec".into(),
17257            dims: 4,
17258            captured: Arc::clone(&captured),
17259        });
17260
17261        let full = "head-term and then a very long tail-term that exceeds any cap";
17262        let head = &full[.."head-term and then a very long".len()];
17263
17264        let note = rt
17265            .create_note_with_embedding_content(
17266                &tok,
17267                "observation",
17268                None,
17269                full,
17270                Some(head),
17271                None,
17272                None,
17273                vec![],
17274            )
17275            .await
17276            .expect("proper-prefix override must be accepted");
17277        assert_eq!(note.content, full, "stored content must be the full text");
17278
17279        let seen = captured.lock().unwrap().clone();
17280        assert_eq!(
17281            seen,
17282            vec![head.to_string()],
17283            "embedder must see only the capped override"
17284        );
17285    }
17286
17287    #[tokio::test]
17288    async fn create_note_with_embedding_content_fans_out_identical_override_to_multiple_models() {
17289        let rt = rt();
17290        let tok = NamespaceToken::local();
17291        let captured_a = Arc::new(std::sync::Mutex::new(Vec::new()));
17292        let captured_b = Arc::new(std::sync::Mutex::new(Vec::new()));
17293        rt.register_embedder(CapturingVecProvider {
17294            provider_name: "capturing-vec-a".into(),
17295            dims: 4,
17296            captured: Arc::clone(&captured_a),
17297        });
17298        rt.register_embedder(CapturingVecProvider {
17299            provider_name: "capturing-vec-b".into(),
17300            dims: 4,
17301            captured: Arc::clone(&captured_b),
17302        });
17303
17304        let full = "head-only-embedded plus a long discarded tail";
17305        let head = &full[.."head-only-embedded".len()];
17306
17307        rt.create_note_with_embedding_content(
17308            &tok,
17309            "observation",
17310            None,
17311            full,
17312            Some(head),
17313            None,
17314            None,
17315            vec![],
17316        )
17317        .await
17318        .expect("create ok");
17319
17320        assert_eq!(
17321            captured_a.lock().unwrap().clone(),
17322            vec![head.to_string()],
17323            "model A must receive the identical capped override"
17324        );
17325        assert_eq!(
17326            captured_b.lock().unwrap().clone(),
17327            vec![head.to_string()],
17328            "model B must receive the identical capped override"
17329        );
17330
17331        // Both models actually persisted a vector row for the note (not just
17332        // an embed call that was discarded before insertion).
17333        let vs_a = rt
17334            .vectors_for_model(&tok, "capturing-vec-a")
17335            .expect("vector store for model A");
17336        assert_eq!(
17337            vs_a.count().await.expect("vector count A"),
17338            1,
17339            "model A must have exactly one vector row for the note"
17340        );
17341        let vs_b = rt
17342            .vectors_for_model(&tok, "capturing-vec-b")
17343            .expect("vector store for model B");
17344        assert_eq!(
17345            vs_b.count().await.expect("vector count B"),
17346            1,
17347            "model B must have exactly one vector row for the note"
17348        );
17349    }
17350
17351    #[tokio::test]
17352    async fn create_note_with_embedding_content_rejects_empty_override() {
17353        let rt = rt();
17354        let tok = NamespaceToken::local();
17355
17356        let err = rt
17357            .create_note_with_embedding_content(
17358                &tok,
17359                "observation",
17360                None,
17361                "some content",
17362                Some(""),
17363                None,
17364                None,
17365                vec![],
17366            )
17367            .await
17368            .expect_err("empty override must be rejected");
17369        assert!(matches!(err, RuntimeError::InvalidInput(_)));
17370    }
17371
17372    #[tokio::test]
17373    async fn create_note_with_embedding_content_rejects_non_prefix_override() {
17374        let rt = rt();
17375        let tok = NamespaceToken::local();
17376
17377        let err = rt
17378            .create_note_with_embedding_content(
17379                &tok,
17380                "observation",
17381                None,
17382                "the actual content",
17383                Some("an unrelated string"),
17384                None,
17385                None,
17386                vec![],
17387            )
17388            .await
17389            .expect_err("non-prefix override must be rejected");
17390        assert!(matches!(err, RuntimeError::InvalidInput(ref m) if m.contains("prefix")));
17391    }
17392
17393    #[tokio::test]
17394    async fn create_note_with_embedding_content_rejects_equal_length_override() {
17395        let rt = rt();
17396        let tok = NamespaceToken::local();
17397
17398        // Same length and same text as `content` is not a *proper* prefix.
17399        let err = rt
17400            .create_note_with_embedding_content(
17401                &tok,
17402                "observation",
17403                None,
17404                "identical text",
17405                Some("identical text"),
17406                None,
17407                None,
17408                vec![],
17409            )
17410            .await
17411            .expect_err("an equal-length override must be rejected as not a proper prefix");
17412        assert!(matches!(err, RuntimeError::InvalidInput(ref m) if m.contains("prefix")));
17413    }
17414
17415    #[tokio::test]
17416    async fn create_note_with_embedding_content_rejects_secret_bearing_override() {
17417        let rt = rt();
17418        let tok = NamespaceToken::local();
17419
17420        let token_span = "ghp_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
17421        let content = format!("{token_span} plus extra trailing content beyond the override");
17422        let embedding_content = format!("{token_span} plus extra");
17423
17424        let err = rt
17425            .create_note_with_embedding_content(
17426                &tok,
17427                "observation",
17428                None,
17429                &content,
17430                Some(&embedding_content),
17431                None,
17432                None,
17433                vec![],
17434            )
17435            .await
17436            .expect_err("a credential-shaped override must fail the secret gate");
17437        assert!(
17438            matches!(err, RuntimeError::SecretDetected(_)),
17439            "expected SecretDetected, got {err:?}"
17440        );
17441
17442        // Fail-closed: no note survives the rejected create.
17443        let count = rt
17444            .notes(&tok)
17445            .unwrap()
17446            .count_notes(tok.namespace().as_str(), None)
17447            .await
17448            .unwrap();
17449        assert_eq!(count, 0, "a rejected create must leave no note behind");
17450    }
17451
17452    // ── ADR-002 base endpoint contract conformance (issue #1715) ────────────
17453    // Parses the "### Base endpoint contract" tables straight out of
17454    // docs/adr/ADR-002-edge-ontology.md and asserts set-equality against
17455    // `BASE_ENTITY_ENDPOINT_RULES`. The ADR and the runtime allowlist are
17456    // maintained by hand in two places with nothing else comparing them; this
17457    // is the comparator, so a future amendment landing in only one of the two
17458    // fails CI instead of shipping a silent false refusal (or a silent
17459    // over-grant).
17460
17461    /// Subsections of the "Base endpoint contract" that are intentionally
17462    /// excluded from `BASE_ENTITY_ENDPOINT_RULES`:
17463    /// - "Annotation relation": `Note -> any substrate UUID` is a substrate-level
17464    ///   rule (source is always a note), not an entity-kind pair.
17465    /// - "KG pack extensions": additive rows declared via the KG pack's
17466    ///   `EDGE_RULES`, not part of the runtime's base allowlist.
17467    const ADR002_EXCLUDED_SUBSECTIONS: &[&str] = &["Annotation relation", "KG pack extensions"];
17468
17469    /// Parse the ADR-002 "Base endpoint contract" markdown tables into the same
17470    /// `(source_kind, relation, target_kind)` shape as `BASE_ENTITY_ENDPOINT_RULES`.
17471    fn parse_adr002_base_entity_endpoint_matrix(
17472    ) -> std::collections::HashSet<(String, EdgeRelation, String)> {
17473        let adr_path = format!(
17474            "{}/../../docs/adr/ADR-002-edge-ontology.md",
17475            env!("CARGO_MANIFEST_DIR")
17476        );
17477        let text = std::fs::read_to_string(&adr_path)
17478            .unwrap_or_else(|e| panic!("failed to read {adr_path}: {e}"));
17479        let lines: Vec<&str> = text.lines().collect();
17480
17481        let start = lines
17482            .iter()
17483            .position(|l| l.trim() == "### Base endpoint contract")
17484            .expect("ADR-002 must contain a '### Base endpoint contract' heading");
17485        let end = lines[start + 1..]
17486            .iter()
17487            .position(|l| l.starts_with("## "))
17488            .map(|i| start + 1 + i)
17489            .unwrap_or(lines.len());
17490        let section = &lines[start..end];
17491
17492        let mut triples = std::collections::HashSet::new();
17493        let mut excluded = false;
17494
17495        for line in section {
17496            let trimmed = line.trim();
17497            if let Some(title) = trimmed.strip_prefix("#### ") {
17498                excluded = ADR002_EXCLUDED_SUBSECTIONS
17499                    .iter()
17500                    .any(|ex| title.starts_with(ex));
17501                continue;
17502            }
17503            if excluded || !trimmed.starts_with('|') {
17504                continue;
17505            }
17506
17507            let cells: Vec<&str> = trimmed
17508                .trim_matches('|')
17509                .split('|')
17510                .map(|c| c.trim())
17511                .collect();
17512            if cells.len() != 3 {
17513                continue;
17514            }
17515            let is_header = cells[0].eq_ignore_ascii_case("Source");
17516            let is_separator = cells
17517                .iter()
17518                .all(|c| !c.is_empty() && c.chars().all(|ch| ch == '-'));
17519            if is_header || is_separator {
17520                continue;
17521            }
17522
17523            let src_raw = cells[0].trim_matches('`');
17524            let rel_raw = cells[1].trim_matches('`');
17525            let tgt_raw = cells[2].trim_matches('`');
17526
17527            let relation: EdgeRelation = rel_raw.parse().unwrap_or_else(|_| {
17528                panic!("ADR-002 base endpoint contract row has unparseable relation: {trimmed:?}")
17529            });
17530
17531            let src = if src_raw.eq_ignore_ascii_case("any entity") {
17532                "*".to_string()
17533            } else {
17534                src_raw.to_ascii_lowercase()
17535            };
17536            let tgt = tgt_raw.to_ascii_lowercase();
17537
17538            triples.insert((src, relation, tgt));
17539        }
17540
17541        triples
17542    }
17543
17544    #[test]
17545    fn base_entity_endpoint_rules_match_adr002_base_endpoint_contract() {
17546        // ADR-002 lives at the repository root, outside this crate's package.
17547        // In the repository the workspace manifest sits two levels up and the
17548        // ADR must be readable — a missing file there is a hard failure so a
17549        // rename cannot silently disarm this gate. From a published package
17550        // tarball neither exists; skip with disclosure instead of failing an
17551        // environment that cannot carry the canonical document.
17552        let workspace_manifest = format!("{}/../Cargo.toml", env!("CARGO_MANIFEST_DIR"));
17553        if !std::path::Path::new(&workspace_manifest).exists() {
17554            eprintln!(
17555                "skipping ADR-002 conformance: workspace manifest not present \
17556                 (published-package context); the check runs in the repository"
17557            );
17558            return;
17559        }
17560        let adr_matrix = parse_adr002_base_entity_endpoint_matrix();
17561        assert!(
17562            !adr_matrix.is_empty(),
17563            "parsed zero rows from ADR-002's base endpoint contract — parser or heading drift"
17564        );
17565
17566        let runtime_rules: std::collections::HashSet<(String, EdgeRelation, String)> =
17567            base_entity_endpoint_rules()
17568                .iter()
17569                .map(|(src, rel, tgt)| (src.to_string(), *rel, tgt.to_string()))
17570                .collect();
17571
17572        let missing_from_runtime: Vec<_> = adr_matrix.difference(&runtime_rules).collect();
17573        let extra_in_runtime: Vec<_> = runtime_rules.difference(&adr_matrix).collect();
17574
17575        assert!(
17576            missing_from_runtime.is_empty() && extra_in_runtime.is_empty(),
17577            "BASE_ENTITY_ENDPOINT_RULES has drifted from ADR-002's base endpoint contract.\n\
17578             In the ADR but not enforced by the runtime: {missing_from_runtime:#?}\n\
17579             Enforced by the runtime but not in the ADR: {extra_in_runtime:#?}"
17580        );
17581    }
17582
17583    // ── Universal reserved-key reservation (ADR-115 Amendment 1, first rung) ──
17584
17585    fn reserved_key_props() -> serde_json::Value {
17586        serde_json::json!({"khive:secret_gate": "exempted:content-sha256-manifest-v1"})
17587    }
17588
17589    #[tokio::test]
17590    async fn create_entity_rejects_reserved_secret_gate_key() {
17591        let rt = rt();
17592        let tok = NamespaceToken::local();
17593        let err = rt
17594            .create_entity(
17595                &tok,
17596                "concept",
17597                None,
17598                "reserved-key-entity",
17599                None,
17600                Some(reserved_key_props()),
17601                vec![],
17602            )
17603            .await
17604            .expect_err("caller-supplied reserved key must be rejected");
17605        assert!(
17606            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
17607            "unexpected error: {err:?}"
17608        );
17609        // No partial mutation: the record must not exist under any name/search.
17610        let found = rt
17611            .list_entities(&tok, Some("concept"), None, 10, 0)
17612            .await
17613            .expect("list must succeed");
17614        assert!(
17615            found.iter().all(|e| e.name != "reserved-key-entity"),
17616            "rejected create must leave no row behind"
17617        );
17618    }
17619
17620    #[tokio::test]
17621    async fn create_note_rejects_reserved_secret_gate_key() {
17622        let rt = rt();
17623        let tok = NamespaceToken::local();
17624        let err = rt
17625            .create_note(
17626                &tok,
17627                "observation",
17628                None,
17629                "reserved-key note content",
17630                None,
17631                Some(reserved_key_props()),
17632                vec![],
17633            )
17634            .await
17635            .expect_err("caller-supplied reserved key must be rejected");
17636        assert!(
17637            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
17638            "unexpected error: {err:?}"
17639        );
17640    }
17641
17642    #[tokio::test]
17643    async fn create_many_rejects_reserved_secret_gate_key_atomically() {
17644        let rt = rt();
17645        let tok = NamespaceToken::local();
17646        let specs = vec![
17647            EntityCreateSpec {
17648                kind: "concept".to_string(),
17649                entity_type: None,
17650                name: "clean-entity".to_string(),
17651                description: None,
17652                properties: None,
17653                tags: vec![],
17654            },
17655            EntityCreateSpec {
17656                kind: "concept".to_string(),
17657                entity_type: None,
17658                name: "reserved-key-entity".to_string(),
17659                description: None,
17660                properties: Some(reserved_key_props()),
17661                tags: vec![],
17662            },
17663        ];
17664        let err = rt
17665            .create_many(&tok, specs)
17666            .await
17667            .expect_err("a reserved key anywhere in the batch must reject the whole batch");
17668        assert!(
17669            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
17670            "unexpected error: {err:?}"
17671        );
17672        // No partial mutation: the leading clean spec must not have been written either.
17673        let found = rt
17674            .list_entities(&tok, Some("concept"), None, 10, 0)
17675            .await
17676            .expect("list must succeed");
17677        assert!(
17678            found.is_empty(),
17679            "batch rejection must leave zero rows behind, found: {found:?}"
17680        );
17681    }
17682
17683    #[tokio::test]
17684    async fn create_entity_with_attachments_commits_roles_and_projects_content() {
17685        use khive_db::stores::blob::FsBlobStore;
17686        use khive_storage::BlobStore as _;
17687
17688        let runtime = rt();
17689        let token = NamespaceToken::local();
17690        let blob_dir = tempfile::tempdir().expect("blob tempdir");
17691        let blob_store =
17692            Arc::new(FsBlobStore::new(blob_dir.path().to_path_buf(), 0).expect("blob store"));
17693        let content_ref = blob_store
17694            .put(b"bundle".to_vec())
17695            .await
17696            .expect("publish bundle");
17697        let network_ref = blob_store
17698            .put(b"network".to_vec())
17699            .await
17700            .expect("publish network");
17701        runtime
17702            .install_blob_store(blob_store)
17703            .expect("install blob store");
17704
17705        let created = runtime
17706            .create_entity_with_attachments(
17707                &token,
17708                "artifact",
17709                None,
17710                "role-keyed artifact",
17711                None,
17712                None,
17713                vec![],
17714                vec![
17715                    NewAttachment {
17716                        role: "content".to_string(),
17717                        content_ref: content_ref.clone(),
17718                        media_type: Some("application/json".to_string()),
17719                        size_bytes: Some(6),
17720                    },
17721                    NewAttachment {
17722                        role: "fann-network".to_string(),
17723                        content_ref: network_ref.clone(),
17724                        media_type: Some("application/octet-stream".to_string()),
17725                        size_bytes: Some(7),
17726                    },
17727                ],
17728            )
17729            .await
17730            .expect("atomic record + attachments publication");
17731
17732        assert_eq!(created.content_ref.as_deref(), Some(content_ref.as_str()));
17733        let reloaded = runtime
17734            .get_entity(&token, created.id)
17735            .await
17736            .expect("reload entity");
17737        assert_eq!(reloaded.content_ref.as_deref(), Some(content_ref.as_str()));
17738        let attachments = runtime
17739            .attachments()
17740            .expect("main attachment store")
17741            .list_attachments(created.id)
17742            .await
17743            .expect("list attachments");
17744        assert_eq!(attachments.len(), 2);
17745        assert_eq!(attachments[0].role, "content");
17746        assert_eq!(attachments[0].content_ref, content_ref);
17747        assert_eq!(attachments[1].role, "fann-network");
17748        assert_eq!(attachments[1].content_ref, network_ref);
17749    }
17750}