Skip to main content

khive_runtime/
operations.rs

1// FILE SIZE JUSTIFICATION: operations.rs is the single coherent surface for all
2// runtime verb implementations (create, get, list, search, link, traverse, query,
3// recall, etc.). All verbs share internal helpers (namespace checks, edge validation,
4// canonical-endpoint logic) that require pub(crate) access — splitting into submodules
5// would require pub(crate) re-exports across every helper or circular dependencies.
6// Inline tests exercise those private helpers directly. Split plan: once the verb
7// surface stabilises post-retrieval-refactor, group by substrate (entity,
8// note, edge, search) into submodules under an `operations/` directory.
9//! High-level operations composing storage capabilities into user-facing verbs.
10//!
11//! # Fault-injection arm migration
12//!
13//! Namespace-targeted fault injection uses scoped guards. The former
14//! `arm_fts_fail`, `arm_fts_fail_many`, `arm_fts_fail_many_partial`, and
15//! `arm_vector_fail` names were removed in favor of their `_scoped` variants so
16//! stale statement-form calls fail to compile. Statement-form arming cannot be
17//! preserved because dropping the returned guard at the semicolon disarms an
18//! unconsumed injection.
19
20use std::collections::HashMap;
21use std::str::FromStr;
22
23use serde::Serialize;
24use uuid::Uuid;
25
26use khive_score::DeterministicScore;
27use khive_storage::note::Note;
28use khive_storage::types::{
29    DeleteMode, DirectedNeighborHit, Direction, EdgeSortField, GraphPath, LinkId, NeighborHit,
30    NeighborQuery, Page, PageRequest, SeekCursor, SortOrder, SqlRow, SqlStatement, SqlValue,
31    TextFilter, TextQueryMode, TextSearchRequest, TraversalRequest,
32};
33use khive_storage::{Edge, EdgeRelation, Entity, EntityFilter, Event, EventFilter};
34use khive_types::{EdgeEndpointRule, EndpointKind, EventKind, KhiveError, SubstrateKind};
35
36use khive_db::stores::entity::{entity_hard_delete_statement, entity_upsert_statement};
37use khive_db::stores::event::hard_delete_lineage_warning_statements;
38use khive_db::stores::graph::{edge_hard_delete_statement, purge_incident_edges_statement};
39use khive_db::stores::note::note_hard_delete_statement;
40use khive_db::stores::text::insert_document_statement;
41use khive_db::SqliteError;
42use rusqlite::OptionalExtension;
43
44use crate::atomic_plan::{
45    AddEntityPlan, AffectedRowGuard, DeletePlan, PlanStatement, PostCommitEffect,
46};
47use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
48use crate::curation::{entity_fts_document, note_embedding_text, note_fts_document};
49use crate::error::{GuardedWriteFailure, RuntimeError, RuntimeResult};
50use crate::runtime::{KhiveRuntime, NamespaceToken};
51
52// Test-only failure injection for `create_note_inner`. Namespace-targeted so only
53// calls for the armed namespace fire, avoiding cross-test races without `#[serial]`.
54// Gated behind `cfg(any(test, feature = "fault-injection"))` so no lock acquisitions
55// or injection surface exist in production/published binaries. External integration
56// test crates enable it via a dev-dependency: khive-runtime = { ..., features = ["fault-injection"] }
57#[cfg(test)]
58std::thread_local! {
59    static LINK_FAIL_AFTER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
60}
61
62// Count-targetable vector-INSERT fault injection: when set to N (N > 0), the next N
63// vector insert calls (entity or note, single- or multi-model) succeed and the
64// (N+1)-th returns an injected error, then the counter resets to 0.
65// `thread_local!` provides per-thread isolation (`#[tokio::test]` uses a
66// current-thread runtime, so there is no thread migration mid-test), letting a
67// test fail one specific model's insert in a multi-model fan-out and giving any
68// caller whose test suite shares a default namespace a deterministic, race-free
69// injection instead of depending on `VECTOR_FAIL_NS`'s namespace match.
70#[cfg(any(test, feature = "fault-injection"))]
71std::thread_local! {
72    static VECTOR_FAIL_AFTER: std::cell::Cell<Option<usize>> =
73        const { std::cell::Cell::new(None) };
74}
75
76/// Arm the count-targetable vector-INSERT fault: let `n` inserts succeed, then fail
77/// the next one (entity or note, single- or multi-model). Set `n = 0` to fail
78/// immediately on the first insert. Thread-local, so unlike `arm_vector_fail_scoped`
79/// it cannot be won or disarmed by a concurrently-running test on another
80/// thread — prefer this one whenever the caller cannot guarantee it is the
81/// only test writing into the namespace it cares about.
82/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
83#[cfg(any(test, feature = "fault-injection"))]
84pub fn arm_vector_fail_after(n: usize) {
85    VECTOR_FAIL_AFTER.with(|cell| cell.set(Some(n)));
86}
87
88// Namespace-keyed one-shot arms, not a single `Option<String>` slot:
89// `create_note_inner` and `create_entity_inner` share this flag, and a
90// single-slot design let a concurrently running test's `arm_fts_fail_scoped(other_ns)`
91// overwrite this test's armed namespace before its own create call consumed
92// it, so the intended injection silently never fired (#1095). Keying by
93// namespace fixes that at the root — arming `ns_B` inserts `ns_B` without
94// evicting `ns_A`. Process-wide (not thread-local) so a caller may arm on
95// one OS thread and run the triggering `create_note`/`create_entity` on
96// another (e.g. via `tokio::spawn` on a multi-thread runtime); the
97// check-and-remove under the mutex lock keeps exactly-once semantics even
98// under concurrent same-namespace creates.
99#[cfg(any(test, feature = "fault-injection"))]
100type FaultArmSet = std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<()>>>;
101#[cfg(any(test, feature = "fault-injection"))]
102const MAX_FAULT_ARMS: usize = 64;
103#[cfg(any(test, feature = "fault-injection"))]
104static FTS_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
105    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
106// Vector insertion failures use the same namespace-keyed one-shot semantics.
107#[cfg(any(test, feature = "fault-injection"))]
108static VECTOR_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
109    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
110/// Entity-create compensation failure injection. The matching compensation
111/// skips only the entity-row delete; FTS/vector cleanup still runs so tests can
112/// inspect the exact residual state and combined error contract.
113#[cfg(any(test, feature = "fault-injection"))]
114static ENTITY_COMPENSATION_FAIL_NS: std::sync::LazyLock<FaultArmSet> =
115    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
116/// FTS failure injection for `create_many` — separate from `FTS_FAIL_NS` so that
117/// create_note_inner and create_many tests cannot disarm each other. Namespace-keyed
118/// set (not a single `Option<String>` slot) for the same reason as `VECTOR_FAIL_NS` (#1263).
119#[cfg(any(test, feature = "fault-injection"))]
120static FTS_FAIL_MANY_NS: std::sync::LazyLock<FaultArmSet> =
121    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
122/// FTS partial-failure injection for `create_many` — returns `Ok(BatchWriteSummary)`
123/// with `failed > 0` so that the `summary.failed > 0` rollback branch is exercised.
124/// Distinct from `FTS_FAIL_MANY_NS` which injects a hard `Err`. Namespace-keyed set
125/// for the same reason as `VECTOR_FAIL_NS` (#1263).
126#[cfg(any(test, feature = "fault-injection"))]
127static FTS_FAIL_MANY_PARTIAL_NS: std::sync::LazyLock<FaultArmSet> =
128    std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
129
130/// Scoped ownership of a process-wide fault-injection arm.
131#[cfg(any(test, feature = "fault-injection"))]
132#[must_use = "the fault injection is disarmed when this guard is dropped"]
133pub struct FaultInjectionArm {
134    namespace: String,
135    token: std::sync::Arc<()>,
136    arms: &'static FaultArmSet,
137}
138
139#[cfg(any(test, feature = "fault-injection"))]
140impl Drop for FaultInjectionArm {
141    fn drop(&mut self) {
142        let mut arms = self.arms.lock().unwrap();
143        if arms
144            .get(&self.namespace)
145            .is_some_and(|token| std::sync::Arc::ptr_eq(token, &self.token))
146        {
147            arms.remove(&self.namespace);
148        }
149    }
150}
151
152#[cfg(any(test, feature = "fault-injection"))]
153fn arm_fault(arms: &'static FaultArmSet, namespace: &str, max_arms: usize) -> FaultInjectionArm {
154    let token = std::sync::Arc::new(());
155    let refusal = {
156        let mut active = arms.lock().unwrap();
157        if active.contains_key(namespace) {
158            Some("the namespace is already armed")
159        } else if active.len() >= max_arms {
160            Some("the arm set is at capacity")
161        } else {
162            active.insert(namespace.to_string(), std::sync::Arc::clone(&token));
163            None
164        }
165    };
166    if let Some(reason) = refusal {
167        panic!("cannot arm fault injection for namespace `{namespace}`: {reason}");
168    }
169    FaultInjectionArm {
170        namespace: namespace.to_string(),
171        token,
172        arms,
173    }
174}
175
176#[cfg(any(test, feature = "fault-injection"))]
177fn consume_fault(arms: &FaultArmSet, namespace: &str) -> bool {
178    arms.lock().unwrap().remove(namespace).is_some()
179}
180/// Non-parser FTS *search*-leg failure injection for `search_notes`: distinct
181/// from `FTS_FAIL_NS` (which injects at the FTS *upsert*/write step of
182/// `create_note_inner`). Injects a `StorageError::Timeout` at the `search()`
183/// call the FTS fail-open arm guards, so the arm's `is_fts5_syntax_error()`
184/// gate can be exercised against a genuine non-parser failure and asserted to
185/// propagate rather than degrade.
186#[cfg(any(test, feature = "fault-injection"))]
187static FTS_SEARCH_FAIL_NS: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
188
189/// Arm a one-shot FTS failure injection for `create_note_inner`/`create_entity_inner`
190/// targeting namespace `ns`.
191///
192/// The next `create_note` or `create_entity` call whose namespace equals `ns` returns
193/// an injected error at the FTS upsert step (after the row is committed), then disarms
194/// — only that namespace's entry is consumed. The arm is process-wide and thread
195/// independent: it may be set from one OS thread and consumed by a `create_note`/
196/// `create_entity` call running on another (e.g. inside `tokio::spawn`). Concurrent
197/// arms of distinct namespaces do not interfere with each other.
198/// Keep the returned guard alive until the triggering call completes; dropping it
199/// disarms an unconsumed injection.
200/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
201#[cfg(any(test, feature = "fault-injection"))]
202pub fn arm_fts_fail_scoped(ns: &str) -> FaultInjectionArm {
203    arm_fault(&FTS_FAIL_NS, ns, MAX_FAULT_ARMS)
204}
205
206/// Arm the FTS failure injection for `create_many` targeting namespace `ns`.
207///
208/// The next `create_many` call whose namespace equals `ns` returns an injected
209/// error at the first FTS statement inside the atomic batch, then disarms.
210/// Calls on other namespaces are unaffected, and concurrent arms of distinct
211/// namespaces do not overwrite each other.
212/// Keep the returned guard alive until the triggering call completes; dropping it
213/// disarms an unconsumed injection.
214/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
215#[cfg(any(test, feature = "fault-injection"))]
216pub fn arm_fts_fail_many_scoped(ns: &str) -> FaultInjectionArm {
217    arm_fault(&FTS_FAIL_MANY_NS, ns, MAX_FAULT_ARMS)
218}
219
220/// Arm a mid-batch FTS failure for `create_many` targeting namespace `ns`.
221///
222/// The next matching call fails the second FTS statement when the batch contains at
223/// least two entities, after one entity/FTS pair has executed in the transaction.
224/// A one-entity batch fails its first FTS statement. Then disarms only that namespace.
225/// Keep the returned guard alive until the triggering call completes; dropping it
226/// disarms an unconsumed injection.
227/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
228#[cfg(any(test, feature = "fault-injection"))]
229pub fn arm_fts_fail_many_partial_scoped(ns: &str) -> FaultInjectionArm {
230    arm_fault(&FTS_FAIL_MANY_PARTIAL_NS, ns, MAX_FAULT_ARMS)
231}
232
233/// Arm a non-parser FTS *search*-leg failure injection for `search_notes` targeting
234/// any call whose visible namespaces include `ns`.
235///
236/// The next `search_notes` call touching `ns` returns `StorageError::Timeout` from
237/// the FTS leg instead of calling the real `TextSearch::search`, then disarms.
238/// Used to prove the fail-open arm in `search_notes` propagates non-parser
239/// `StorageError`s instead of silently degrading them the way a genuine FTS5
240/// parser syntax error is degraded.
241/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
242#[cfg(any(test, feature = "fault-injection"))]
243pub fn arm_fts_search_fail(ns: &str) {
244    *FTS_SEARCH_FAIL_NS.lock().unwrap() = Some(ns.to_string());
245}
246
247/// Arm the vector insertion failure injection for `create_note_inner` targeting `ns`.
248///
249/// The next `create_note` call whose note namespace equals `ns` returns an injected
250/// error at the first vector insert step, then disarms.  Calls on other namespaces
251/// are unaffected, and concurrent arms of distinct namespaces do not overwrite
252/// each other.
253/// Keep the returned guard alive until the triggering call completes; dropping it
254/// disarms an unconsumed injection.
255/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
256#[cfg(any(test, feature = "fault-injection"))]
257pub fn arm_vector_fail_scoped(ns: &str) -> FaultInjectionArm {
258    arm_fault(&VECTOR_FAIL_NS, ns, MAX_FAULT_ARMS)
259}
260
261/// Arm a one-shot entity-row cleanup failure for `create_entity`
262/// compensation in namespace `ns`.
263#[cfg(any(test, feature = "fault-injection"))]
264pub fn arm_entity_compensation_fail_scoped(ns: &str) -> FaultInjectionArm {
265    arm_fault(&ENTITY_COMPENSATION_FAIL_NS, ns, MAX_FAULT_ARMS)
266}
267
268/// Failure injection for `delete_note_row_first_for_compensation`'s post-row-removal
269/// cleanup step: distinct from `FTS_FAIL_NS`/`VECTOR_FAIL_NS`, which target
270/// `create_note_inner`. Lets tests prove that a rollback compensation's cleanup
271/// failure still leaves the note row (and thus the live message) gone.
272#[cfg(any(test, feature = "fault-injection"))]
273static ROLLBACK_CLEANUP_FAIL_NS: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
274
275/// Arm the rollback-compensation cleanup failure injection targeting `ns`.
276///
277/// The next `delete_note_row_first_for_compensation` call whose note namespace
278/// equals `ns` removes the row as usual, then returns an injected cleanup error
279/// instead of running the real graph/FTS/vector cleanup, then disarms.
280/// Available when compiled with `cfg(test)` or `feature = "fault-injection"`.
281#[cfg(any(test, feature = "fault-injection"))]
282pub fn arm_rollback_cleanup_fail(ns: &str) {
283    *ROLLBACK_CLEANUP_FAIL_NS.lock().unwrap() = Some(ns.to_string());
284}
285
286/// `atomic_message::create_notes_atomic` equivalents of the `FTS_FAIL_NS`/
287/// `VECTOR_FAIL_NS` checks above, reusing the SAME arm sets (and thus the
288/// SAME `arm_fts_fail_scoped`/`arm_vector_fail_scoped` test API) so a test
289/// can arm one call and exercise either write path. `create_notes_atomic`
290/// builds raw `PlanStatement`s instead of calling `text_for_notes()`/
291/// `vectors_for_model().insert()`, so it cannot reuse `consume_fault`
292/// in-line the way `create_note_inner` does above; these wrappers are the
293/// seam that lets it check the same arms.
294#[cfg(any(test, feature = "fault-injection"))]
295pub(crate) fn consume_fts_fail_fault(ns: &str) -> bool {
296    consume_fault(&FTS_FAIL_NS, ns)
297}
298#[cfg(any(test, feature = "fault-injection"))]
299pub(crate) fn consume_vector_fail_fault(ns: &str) -> bool {
300    consume_fault(&VECTOR_FAIL_NS, ns)
301}
302
303/// A note search result with UUID, salience-weighted RRF score, and display text.
304#[derive(Clone, Debug)]
305pub struct NoteSearchHit {
306    pub note_id: Uuid,
307    pub score: DeterministicScore,
308    pub source: crate::SearchSource,
309    pub title: Option<String>,
310    pub snippet: Option<String>,
311}
312
313/// Re-insert hyphens at canonical UUID positions (8-4-4-4-12) into a
314/// hyphen-free hex prefix, so a `LIKE '<pattern>%'` scan against the
315/// hyphenated `id` column matches correctly. Prefixes that already
316/// contain a hyphen are passed through unchanged. No-op for len <= 8
317/// (already correct). Input longer than 32 hex chars is NOT truncated: the
318/// extra hex chars are appended past the canonical 12-char final segment
319/// with no further hyphen, so the resulting `LIKE` pattern requires literal
320/// characters beyond position 36 that no real (36-char) UUID string can
321/// ever have — the scan naturally fails closed instead of silently
322/// resolving `<valid-32-hex><extra-hex>` to the valid UUID.
323pub fn hex_prefix_to_uuid_pattern(prefix: &str) -> String {
324    if prefix.contains('-') {
325        return prefix.to_string();
326    }
327    const BOUNDARIES: [usize; 4] = [8, 13, 18, 23]; // post-hyphen-insertion offsets
328    let mut out = String::with_capacity(36);
329    for c in prefix.chars() {
330        if BOUNDARIES.contains(&out.len()) {
331            out.push('-');
332        }
333        out.push(c);
334    }
335    out
336}
337
338fn text_preview(text: &str, max_chars: usize) -> Option<String> {
339    let trimmed = text.trim();
340    if trimmed.is_empty() {
341        None
342    } else {
343        Some(trimmed.chars().take(max_chars).collect())
344    }
345}
346
347/// Symmetric relations (`competes_with`, `composed_with`) are stored with a
348/// canonical source (lower UUID wins), so a directed `Out` or `In` query may
349/// miss results. When the relations filter is non-empty and contains **only**
350/// symmetric relations, override direction to `Both` so callers always see all
351/// edges for these relations regardless of storage canonicalization.
352fn normalize_symmetric_direction(
353    direction: Direction,
354    relations: Option<&[EdgeRelation]>,
355) -> Direction {
356    let Some(rels) = relations else {
357        return direction;
358    };
359    if rels.is_empty() {
360        return direction;
361    }
362    let all_symmetric = rels
363        .iter()
364        .all(|r| matches!(r, EdgeRelation::CompetesWith | EdgeRelation::ComposedWith));
365    if all_symmetric {
366        Direction::Both
367    } else {
368        direction
369    }
370}
371
372/// Stable tie-break rank for [`Direction`] — `Out` before `In` — used to make
373/// the both-direction sort/dedup key total over self-loop edges. A self-loop
374/// (`source_id == target_id == node_id`) produces two `UNION ALL` rows with
375/// the same `(node_id, edge_id)` but opposite directions; without direction in
376/// the key, sort-then-dedup collapses them to one and drops the direction
377/// parity a separate `Out` call plus a separate `In` call would preserve.
378fn direction_sort_rank(direction: &Direction) -> u8 {
379    match direction {
380        Direction::Out => 0,
381        Direction::In => 1,
382        Direction::Both => 2,
383    }
384}
385
386fn note_title(note: &Note) -> Option<String> {
387    note.name
388        .clone()
389        .filter(|s| !s.trim().is_empty())
390        .or_else(|| Some(format!("[{}]", note.kind.as_str())))
391}
392
393fn note_snippet(note: &Note) -> Option<String> {
394    text_preview(&note.content, 200)
395}
396
397/// Result of resolving a UUID to its substrate kind.
398#[derive(Clone, Debug)]
399pub enum Resolved {
400    Entity(Entity),
401    Note(Note),
402    Event(Event),
403    /// A record owned by a pack's private tables.
404    ///
405    /// `pack` identifies the owning pack by name, `kind` is the pack-local
406    /// record type (e.g. "domain", "atom"), and `data` is the full record as
407    /// a JSON Value. Pack-private records are not valid edge endpoints,
408    /// annotates sources, or task context entities.
409    PackRecord {
410        pack: String,
411        kind: String,
412        data: serde_json::Value,
413    },
414}
415
416/// A by-ID edge-endpoint substrate kind, including `Edge` itself.
417///
418/// Unlike [`Resolved`], this carries no record data — it is used where only
419/// the substrate classification is needed (coordinator locate/link parity
420/// with `get`, ADR-002 rule 1: `annotates` target may be entity, note, edge,
421/// or event).
422#[derive(Clone, Copy, Debug, Eq, PartialEq)]
423pub enum EdgeEndpointKind {
424    Entity,
425    Note,
426    Event,
427    Edge,
428}
429
430/// Map a resolved endpoint to its `(substrate, kind, entity_type)` triple, or
431/// `None` if the substrate is not a valid edge endpoint (events, edges).
432///
433/// `entity_type` carries the pack-owned granular subtype (`Entity::entity_type`,
434/// e.g. `"theorem"`); it is `None` for notes and for entities with no subtype.
435fn resolved_pair(r: Option<&Resolved>) -> Option<(&'static str, &str, Option<&str>)> {
436    match r? {
437        Resolved::Entity(e) => Some(("entity", e.kind.as_str(), e.entity_type.as_deref())),
438        Resolved::Note(n) => Some(("note", n.kind.as_str(), None)),
439        Resolved::Event(_) => None,
440        Resolved::PackRecord { .. } => None,
441    }
442}
443
444/// `true` if `spec` matches the given substrate + kind + entity_type triple.
445///
446/// Pure and DB-free — exposed so offline consumers (e.g. `kkernel kg
447/// validate`, which parses `(substrate, kind, entity_type)` straight out of
448/// NDJSON with no live record to resolve) can apply the exact same
449/// `EdgeEndpointRule` matching semantics `pack_rule_allows` uses internally,
450/// instead of re-deriving a parallel matcher that could drift out of sync.
451pub fn endpoint_matches(
452    spec: &EndpointKind,
453    substrate: &str,
454    kind: &str,
455    entity_type: Option<&str>,
456) -> bool {
457    match spec {
458        EndpointKind::EntityOfKind(k) => substrate == "entity" && *k == kind,
459        EndpointKind::NoteOfKind(k) => substrate == "note" && *k == kind,
460        EndpointKind::EntityOfType {
461            kind: k,
462            entity_type: t,
463        } => substrate == "entity" && *k == kind && entity_type == Some(*t),
464    }
465}
466
467/// `true` if `spec` matches the given substrate + kind + entity_type triple,
468/// treating an *absent* `entity_type` on the query side as unconstrained
469/// rather than an exact match against "no subtype".
470///
471/// Used only by the static GQL impossibility hint (`static_impossible_edge_pattern_warnings`,
472/// `accepted_entity_kind_pairs_for_relation`), which reasons over a *pattern*
473/// endpoint, not a resolved entity. A pattern endpoint that names a kind but
474/// no `entity_type` (`(a:concept)-[:depends_on]->(b:concept)`) has not ruled
475/// out any subtype, so an `EntityOfType` rule for that kind still makes the
476/// triple possible — unlike `endpoint_matches`, which the live link
477/// validator applies to *resolved* entities, where a `None` `entity_type`
478/// means the entity genuinely has no subtype and must be an exact miss
479/// against a typed rule. Do not use this for validation.
480fn pattern_endpoint_matches(
481    spec: &EndpointKind,
482    substrate: &str,
483    kind: &str,
484    entity_type: Option<&str>,
485) -> bool {
486    match spec {
487        EndpointKind::EntityOfType {
488            kind: k,
489            entity_type: t,
490        } => substrate == "entity" && *k == kind && entity_type.is_none_or(|et| et == *t),
491        _ => endpoint_matches(spec, substrate, kind, entity_type),
492    }
493}
494
495/// Relations that a composed pack `EDGE_RULES` set accepts for a given
496/// `(entity_kind, entity_type)` endpoint pair, using the EXACT SAME
497/// `endpoint_matches` semantics `pack_rule_allows` applies internally
498/// (`EntityOfKind`, `EntityOfType`, `NoteOfKind`) — never a re-filtered copy.
499///
500/// Both endpoints are treated as entities (substrate `"entity"`), matching
501/// the only case pack-layer error-hint code needs (issue #543): a rejected
502/// `link` between two already-resolved entities. `entity_type` is the
503/// pack-owned granular subtype (e.g. `"theorem"`); pass `None` for
504/// untyped entities. Exposed so `khive-pack-kg`'s hint derivation cannot
505/// silently diverge from the validator by only matching `EntityOfKind` and
506/// missing pack rules declared via `EntityOfType` (e.g. `khive-pack-formal`'s
507/// typed `theorem -> definition` `depends_on` rules).
508pub fn accepted_pack_relations_for_entities(
509    rules: &[EdgeEndpointRule],
510    src_kind: &str,
511    src_entity_type: Option<&str>,
512    tgt_kind: &str,
513    tgt_entity_type: Option<&str>,
514) -> Vec<EdgeRelation> {
515    let mut relations: Vec<EdgeRelation> = rules
516        .iter()
517        .filter(|r| {
518            endpoint_matches(&r.source, "entity", src_kind, src_entity_type)
519                && endpoint_matches(&r.target, "entity", tgt_kind, tgt_entity_type)
520        })
521        .map(|r| r.relation)
522        .collect();
523    relations.sort_by_key(|r| r.as_str());
524    relations.dedup();
525    relations
526}
527
528/// Relations accepted for one resolved entity endpoint pair under the full
529/// live contract: the base allowlist plus the loaded packs' additive rules.
530///
531/// This is the pair-oriented counterpart to the private
532/// `accepted_entity_kind_pairs_for_relation` helper. It is shared by validation
533/// errors and pack-layer hints so every write path can tell a caller which
534/// relations would be legal without maintaining a second endpoint table.
535/// Pack declarations for relations with dedicated substrate branches are
536/// excluded because the live validator resolves `annotates` and the three
537/// same-substrate special relations before pack rules are consulted.
538pub fn accepted_entity_relations_for_entities(
539    rules: &[EdgeEndpointRule],
540    src_kind: &str,
541    src_entity_type: Option<&str>,
542    tgt_kind: &str,
543    tgt_entity_type: Option<&str>,
544) -> Vec<EdgeRelation> {
545    let mut relations: Vec<EdgeRelation> = BASE_ENTITY_ENDPOINT_RULES
546        .iter()
547        .filter(|(src, _relation, tgt)| (*src == "*" || *src == src_kind) && *tgt == tgt_kind)
548        .map(|(_src, relation, _tgt)| *relation)
549        .collect();
550    relations.extend(
551        accepted_pack_relations_for_entities(
552            rules,
553            src_kind,
554            src_entity_type,
555            tgt_kind,
556            tgt_entity_type,
557        )
558        .into_iter()
559        .filter(|relation| {
560            *relation != EdgeRelation::Annotates && !crate::pack::is_special_relation(*relation)
561        }),
562    );
563    relations.sort_by_key(|relation| relation.as_str());
564    relations.dedup();
565    relations
566}
567
568fn accepted_entity_relations_description(
569    rules: &[EdgeEndpointRule],
570    src_kind: &str,
571    src_entity_type: Option<&str>,
572    tgt_kind: &str,
573    tgt_entity_type: Option<&str>,
574) -> String {
575    let relations = accepted_entity_relations_for_entities(
576        rules,
577        src_kind,
578        src_entity_type,
579        tgt_kind,
580        tgt_entity_type,
581    );
582    if relations.is_empty() {
583        "none".to_string()
584    } else {
585        relations
586            .iter()
587            .map(EdgeRelation::as_str)
588            .collect::<Vec<_>>()
589            .join(", ")
590    }
591}
592
593/// Hint-only counterpart to [`accepted_pack_relations_for_entities`] that
594/// matches via [`pattern_endpoint_matches`] instead of [`endpoint_matches`],
595/// so an absent `entity_type` is treated as unconstrained rather than an
596/// exact-match miss against `EntityOfType` rules. Used exclusively by the
597/// static GQL impossibility hint — never by validation.
598fn accepted_pack_relations_for_pattern_entities(
599    rules: &[EdgeEndpointRule],
600    src_kind: &str,
601    src_entity_type: Option<&str>,
602    tgt_kind: &str,
603    tgt_entity_type: Option<&str>,
604) -> Vec<EdgeRelation> {
605    let mut relations: Vec<EdgeRelation> = rules
606        .iter()
607        .filter(|r| {
608            pattern_endpoint_matches(&r.source, "entity", src_kind, src_entity_type)
609                && pattern_endpoint_matches(&r.target, "entity", tgt_kind, tgt_entity_type)
610        })
611        .map(|r| r.relation)
612        .collect();
613    relations.sort_by_key(|r| r.as_str());
614    relations.dedup();
615    relations
616}
617
618/// All `(source_kind, target_kind)` entity-kind pairs — restricted to the closed
619/// 8-kind base [`khive_types::EntityKind`] taxonomy — that accept `relation`
620/// under the composed base allowlist plus pack `EDGE_RULES`.
621///
622/// Reuses [`base_entity_rule_allows`] and [`accepted_pack_relations_for_pattern_entities`]
623/// (the pattern-side, unconstrained-`None` counterpart of the functions the live
624/// validator consults) over the closed kind set, rather than re-deriving a
625/// parallel table — issue #543 precedent, applied to GQL query-pattern hint
626/// derivation (issue #593).
627///
628/// Pack rules are skipped when `crate::pack::is_special_relation` is true
629/// (supersedes / supports / refutes): the live validator's special-relation branch
630/// (`validate_edge_relation_endpoints`, this file) resolves those relations
631/// before `pack_rule_allows` is ever reached, so a pack `EDGE_RULES` entry for
632/// one of them is never actually enforced (see `pack.rs`'s
633/// `edge_endpoint_table` doc comment for the authoritative statement of this).
634fn accepted_entity_kind_pairs_for_relation(
635    pack_rules: &[EdgeEndpointRule],
636    relation: EdgeRelation,
637) -> Vec<(&'static str, &'static str)> {
638    let mut pairs = Vec::new();
639    for src in khive_types::EntityKind::ALL {
640        for tgt in khive_types::EntityKind::ALL {
641            let allowed = base_entity_rule_allows(src.name(), relation, tgt.name())
642                || (!crate::pack::is_special_relation(relation)
643                    && accepted_pack_relations_for_pattern_entities(
644                        pack_rules,
645                        src.name(),
646                        None,
647                        tgt.name(),
648                        None,
649                    )
650                    .contains(&relation));
651            if allowed {
652                pairs.push((src.name(), tgt.name()));
653            }
654        }
655    }
656    pairs
657}
658
659/// Scans a GQL `MATCH` pattern for edges that name an explicit relation and
660/// explicit entity kinds on both endpoints — a single mandatory hop, a fixed
661/// direction — where the `(source_kind, relation, target_kind)` triple can
662/// never match under the composed edge endpoint contract. Returns one warning
663/// per statically-impossible edge.
664///
665/// Deliberately conservative: unlabeled nodes, unlabeled/multi-relation edges,
666/// undirected edges, variable-length hops, and note-kind endpoints are left
667/// unchecked, since none of those name a single static triple to test against
668/// the validator (issue #593).
669///
670/// Mirrors the validator's special-relation precedence for `supersedes` /
671/// `supports` / `refutes` (see [`accepted_entity_kind_pairs_for_relation`]):
672/// pack rules never make those triples possible, only the base allowlist does.
673fn static_impossible_edge_pattern_warnings(
674    language: khive_query::QueryLanguage,
675    pattern: &khive_query::ast::MatchPattern,
676    pack_rules: &[EdgeEndpointRule],
677) -> Vec<String> {
678    use khive_query::ast::{EdgeDirection, PatternElement};
679
680    if language != khive_query::QueryLanguage::Gql {
681        return Vec::new();
682    }
683
684    let elements = &pattern.elements;
685    let mut warnings = Vec::new();
686
687    for (i, el) in elements.iter().enumerate() {
688        let PatternElement::Edge(edge) = el else {
689            continue;
690        };
691        if edge.relations.len() != 1 || edge.min_hops != 1 || edge.max_hops != 1 {
692            continue;
693        }
694        let (left, right) = match (elements.get(i.wrapping_sub(1)), elements.get(i + 1)) {
695            (Some(PatternElement::Node(l)), Some(PatternElement::Node(r))) => (l, r),
696            _ => continue,
697        };
698        let (src_node, tgt_node) = match edge.direction {
699            EdgeDirection::Out => (left, right),
700            EdgeDirection::In => (right, left),
701            EdgeDirection::Both => continue,
702        };
703        let (Some(src_raw), Some(tgt_raw)) = (src_node.kind.as_deref(), tgt_node.kind.as_deref())
704        else {
705            continue;
706        };
707        let (Ok(src_kind), Ok(tgt_kind)) = (
708            src_raw.parse::<khive_types::EntityKind>(),
709            tgt_raw.parse::<khive_types::EntityKind>(),
710        ) else {
711            continue;
712        };
713        let Ok(relation) = edge.relations[0].parse::<EdgeRelation>() else {
714            continue;
715        };
716
717        let possible = base_entity_rule_allows(src_kind.name(), relation, tgt_kind.name())
718            || (!crate::pack::is_special_relation(relation)
719                && accepted_pack_relations_for_pattern_entities(
720                    pack_rules,
721                    src_kind.name(),
722                    src_node.entity_type.as_deref(),
723                    tgt_kind.name(),
724                    tgt_node.entity_type.as_deref(),
725                )
726                .contains(&relation));
727        if possible {
728            continue;
729        }
730
731        let accepted = accepted_entity_kind_pairs_for_relation(pack_rules, relation);
732        let accepted_str = if accepted.is_empty() {
733            "none".to_string()
734        } else {
735            accepted
736                .iter()
737                .map(|(s, t)| format!("{s}->{t}"))
738                .collect::<Vec<_>>()
739                .join(", ")
740        };
741        warnings.push(format!(
742            "pattern ({src})-[:{relation}]->({tgt}) can never match: '{relation}' does not accept \
743             {src}->{tgt} endpoints; accepted source->target kinds for '{relation}': {accepted_str}",
744            src = src_kind.name(),
745            tgt = tgt_kind.name(),
746        ));
747    }
748
749    warnings
750}
751
752/// `true` if any pack-declared edge endpoint rule allows the
753/// `(source, relation, target)` triple. Pack rules are additive only.
754fn pack_rule_allows(
755    rules: &[EdgeEndpointRule],
756    relation: EdgeRelation,
757    src: Option<&Resolved>,
758    tgt: Option<&Resolved>,
759) -> bool {
760    let Some((src_sub, src_kind, src_type)) = resolved_pair(src) else {
761        return false;
762    };
763    let Some((tgt_sub, tgt_kind, tgt_type)) = resolved_pair(tgt) else {
764        return false;
765    };
766    rules.iter().any(|r| {
767        r.relation == relation
768            && endpoint_matches(&r.source, src_sub, src_kind, src_type)
769            && endpoint_matches(&r.target, tgt_sub, tgt_kind, tgt_type)
770    })
771}
772
773/// Base entity endpoint allowlist — the closed set of permitted entity→entity
774/// relation triples.
775///
776/// Each entry `(src_kind, relation, tgt_kind)` explicitly allows that combination.
777/// `"*"` as `src_kind` means "any entity kind" (used by `instance_of` whose source
778/// is unrestricted).
779///
780/// Pack rules (via `EDGE_RULES`) are additive — they cannot remove rows here.
781/// Exposed via `base_entity_endpoint_rules()` for the ADR-076 certificate tests.
782pub const BASE_ENTITY_ENDPOINT_RULES: &[(&str, EdgeRelation, &str)] = &[
783    // Structure
784    ("concept", EdgeRelation::Contains, "concept"),
785    ("project", EdgeRelation::Contains, "project"),
786    ("project", EdgeRelation::Contains, "artifact"),
787    ("org", EdgeRelation::Contains, "project"),
788    ("org", EdgeRelation::Contains, "service"),
789    ("concept", EdgeRelation::PartOf, "concept"),
790    ("project", EdgeRelation::PartOf, "project"),
791    ("project", EdgeRelation::PartOf, "org"),
792    ("*", EdgeRelation::InstanceOf, "concept"),
793    ("service", EdgeRelation::InstanceOf, "project"),
794    // Derivation
795    ("concept", EdgeRelation::Extends, "concept"),
796    ("concept", EdgeRelation::VariantOf, "concept"),
797    ("artifact", EdgeRelation::VariantOf, "artifact"),
798    ("concept", EdgeRelation::IntroducedBy, "document"),
799    ("concept", EdgeRelation::IntroducedBy, "person"),
800    ("artifact", EdgeRelation::IntroducedBy, "document"),
801    ("document", EdgeRelation::IntroducedBy, "person"),
802    ("document", EdgeRelation::IntroducedBy, "org"),
803    ("concept", EdgeRelation::IntroducedBy, "org"),
804    // Provenance
805    ("artifact", EdgeRelation::DerivedFrom, "dataset"),
806    ("artifact", EdgeRelation::DerivedFrom, "document"),
807    ("artifact", EdgeRelation::DerivedFrom, "project"),
808    ("artifact", EdgeRelation::DerivedFrom, "artifact"),
809    // Temporal
810    ("document", EdgeRelation::Precedes, "document"),
811    ("dataset", EdgeRelation::Precedes, "dataset"),
812    ("artifact", EdgeRelation::Precedes, "artifact"),
813    ("service", EdgeRelation::Precedes, "service"),
814    ("project", EdgeRelation::Precedes, "project"),
815    // Dependency
816    ("project", EdgeRelation::DependsOn, "project"),
817    ("service", EdgeRelation::DependsOn, "project"),
818    ("service", EdgeRelation::DependsOn, "service"),
819    ("service", EdgeRelation::DependsOn, "artifact"),
820    ("service", EdgeRelation::DependsOn, "dataset"),
821    ("artifact", EdgeRelation::DependsOn, "project"),
822    ("artifact", EdgeRelation::DependsOn, "service"),
823    ("document", EdgeRelation::DependsOn, "document"),
824    ("concept", EdgeRelation::Enables, "concept"),
825    ("service", EdgeRelation::Enables, "concept"),
826    ("dataset", EdgeRelation::Enables, "concept"),
827    // Implementation
828    ("project", EdgeRelation::Implements, "concept"),
829    ("service", EdgeRelation::Implements, "concept"),
830    // Lateral
831    ("concept", EdgeRelation::CompetesWith, "concept"),
832    ("project", EdgeRelation::CompetesWith, "project"),
833    ("service", EdgeRelation::CompetesWith, "service"),
834    ("concept", EdgeRelation::ComposedWith, "concept"),
835    ("project", EdgeRelation::ComposedWith, "project"),
836    // Versioning (Supersedes — Concept/Document/Artifact/Service/Dataset only)
837    ("concept", EdgeRelation::Supersedes, "concept"),
838    ("document", EdgeRelation::Supersedes, "document"),
839    ("artifact", EdgeRelation::Supersedes, "artifact"),
840    ("service", EdgeRelation::Supersedes, "service"),
841    ("dataset", EdgeRelation::Supersedes, "dataset"),
842    // Epistemic (Supports/Refutes — evidence sources → Concept claim only)
843    ("concept", EdgeRelation::Supports, "concept"),
844    ("document", EdgeRelation::Supports, "concept"),
845    ("dataset", EdgeRelation::Supports, "concept"),
846    ("artifact", EdgeRelation::Supports, "concept"),
847    ("concept", EdgeRelation::Refutes, "concept"),
848    ("document", EdgeRelation::Refutes, "concept"),
849    ("dataset", EdgeRelation::Refutes, "concept"),
850    ("artifact", EdgeRelation::Refutes, "concept"),
851];
852
853/// Returns the base entity endpoint allowlist.
854///
855/// The returned slice is the same data that `base_entity_rule_allows` consults at
856/// runtime. Exposed for the ADR-076 certificate tests in `khive-pack-kg`, which
857/// must audit live rules rather than hand-copied snapshots.
858pub fn base_entity_endpoint_rules() -> &'static [(&'static str, EdgeRelation, &'static str)] {
859    BASE_ENTITY_ENDPOINT_RULES
860}
861
862/// `true` if `(src_kind, relation, tgt_kind)` is in the base entity endpoint
863/// allowlist. Pure and DB-free — exposed alongside [`base_entity_endpoint_rules`]
864/// so offline consumers (e.g. `kkernel kg validate`) can apply the exact same
865/// base-table membership test the live validator uses, instead of re-deriving
866/// a parallel `.any()` predicate over a hand-copied allowlist.
867pub fn base_entity_rule_allows(src_kind: &str, relation: EdgeRelation, tgt_kind: &str) -> bool {
868    BASE_ENTITY_ENDPOINT_RULES.iter().any(|(src, rel, tgt)| {
869        *rel == relation && (*src == "*" || *src == src_kind) && *tgt == tgt_kind
870    })
871}
872
873/// Canonical endpoint order for symmetric relations (F012).
874///
875/// For `competes_with` and `composed_with`, normalises direction so that
876/// `source_uuid < target_uuid` (lexicographic on the UUID bytes). This
877/// collapses A→B and B→A into a single canonical row, preventing duplicates.
878pub(crate) fn canonical_edge_endpoints(
879    relation: EdgeRelation,
880    source_id: Uuid,
881    target_id: Uuid,
882) -> (Uuid, Uuid) {
883    if relation.is_symmetric() && target_id < source_id {
884        (target_id, source_id)
885    } else {
886        (source_id, target_id)
887    }
888}
889
890/// Infer the default `dependency_kind` from endpoint entity kinds.
891///
892/// `pub(crate)` so `crate::atomic_prepare::prepare_link` can reuse this exact
893/// inference table, keeping `--atomic link` byte-for-byte consistent with the
894/// non-atomic `link()` rather than re-deriving the table.
895pub(crate) fn infer_dependency_kind(src_kind: &str, tgt_kind: &str) -> Option<&'static str> {
896    match (src_kind, tgt_kind) {
897        ("project", "project") => Some("build"),
898        ("service", "service") => Some("runtime"),
899        ("service", "dataset") => Some("data"),
900        ("service", "artifact") => Some("artifact"),
901        ("artifact", "project") | ("artifact", "service") => Some("tooling"),
902        ("document", "document") => Some("normative"),
903        _ => None,
904    }
905}
906
907/// Merge an inferred `dependency_kind` into `depends_on` edge metadata.
908///
909/// If `metadata` already carries a `dependency_kind` key the existing value is
910/// preserved. If the key is absent and the endpoint pair has a known default,
911/// the inferred value is added. Returns `metadata` unchanged for all other
912/// cases (no matching default, or metadata already has the key).
913///
914/// `pub(crate)` so `crate::atomic_prepare::prepare_link` can reuse it for
915/// atomic/non-atomic parity.
916pub(crate) fn merge_dependency_kind(
917    src_kind: &str,
918    tgt_kind: &str,
919    metadata: Option<serde_json::Value>,
920) -> Option<serde_json::Value> {
921    if let Some(ref m) = metadata {
922        if m.get("dependency_kind").is_some() {
923            return metadata;
924        }
925    }
926    let inferred = infer_dependency_kind(src_kind, tgt_kind)?;
927    let mut obj = metadata.unwrap_or_else(|| serde_json::json!({}));
928    if let Some(o) = obj.as_object_mut() {
929        o.insert("dependency_kind".to_string(), serde_json::json!(inferred));
930    }
931    Some(obj)
932}
933
934/// Merge a caller-supplied top-level `dependency_kind` param into an edge's
935/// `metadata` object, filling the key only if `metadata` doesn't already
936/// carry one. This is distinct from `merge_dependency_kind` above (which
937/// infers a default from endpoint entity kinds when no explicit value was
938/// given at all) — this one folds in an EXPLICIT `dependency_kind` argument
939/// the caller passed alongside `metadata`.
940///
941/// `pub`: the single source both `khive-pack-kg::handlers::link::handle_link`
942/// (via `khive_runtime::merge_entry_metadata`) and
943/// `crate::atomic_prepare::prepare_link` call. Lives in `khive-runtime` (not
944/// pack-kg) because packs depend on `khive-runtime`, never the reverse: the
945/// only direction that lets both call sites share one copy instead of a
946/// hand-duplicated block.
947pub fn merge_entry_metadata(
948    metadata: Option<serde_json::Value>,
949    dependency_kind: Option<String>,
950) -> RuntimeResult<Option<serde_json::Value>> {
951    let Some(dk) = dependency_kind else {
952        return Ok(metadata);
953    };
954    let mut obj = metadata.unwrap_or_else(|| serde_json::json!({}));
955    let map = obj
956        .as_object_mut()
957        .ok_or_else(|| RuntimeError::InvalidInput("metadata must be a JSON object".into()))?;
958    map.entry("dependency_kind".to_string())
959        .or_insert_with(|| serde_json::json!(dk));
960    Ok(Some(obj))
961}
962
963/// Valid `dependency_kind` values for `depends_on` edges.
964const VALID_DEPENDENCY_KINDS: &[&str] = &[
965    "build",
966    "runtime",
967    "data",
968    "artifact",
969    "tooling",
970    "normative",
971];
972
973/// Validate that an edge weight is finite and within `[0.0, 1.0]`.
974///
975/// Rejects NaN, infinities, negative values, and values exceeding 1.0.
976/// Used by `link` and `import_kg` to enforce the weight invariant consistently
977/// across all edge creation paths.
978pub(crate) fn validate_edge_weight(weight: f64) -> RuntimeResult<()> {
979    if !weight.is_finite() || !(0.0..=1.0).contains(&weight) {
980        return Err(RuntimeError::InvalidInput(format!(
981            "edge weight must be finite and in [0.0, 1.0], got {weight}"
982        )));
983    }
984    Ok(())
985}
986
987/// Validate governed edge metadata keys.
988///
989/// Currently enforces:
990/// - `dependency_kind` is only valid on `depends_on` edges.
991/// - `dependency_kind`, when present, must be one of the governed values.
992pub(crate) fn validate_edge_metadata(
993    relation: EdgeRelation,
994    metadata: Option<&serde_json::Value>,
995) -> RuntimeResult<()> {
996    let Some(meta) = metadata else {
997        return Ok(());
998    };
999    if let Some(dk) = meta.get("dependency_kind") {
1000        if relation != EdgeRelation::DependsOn {
1001            return Err(RuntimeError::InvalidInput(format!(
1002                "dependency_kind is only valid on depends_on edges (got {})",
1003                relation.as_str()
1004            )));
1005        }
1006        let dk_str = dk
1007            .as_str()
1008            .ok_or_else(|| RuntimeError::InvalidInput("dependency_kind must be a string".into()))?;
1009        if !VALID_DEPENDENCY_KINDS.contains(&dk_str) {
1010            return Err(RuntimeError::InvalidInput(format!(
1011                "unknown dependency_kind {dk_str:?}; valid: {}",
1012                VALID_DEPENDENCY_KINDS.join(" | ")
1013            )));
1014        }
1015    }
1016    Ok(())
1017}
1018
1019/// Returns `true` when `note_props` is a superset of all key-value pairs in `filter`.
1020///
1021/// Mirrors the semantics of `khive_pack_kg::handlers::common::props_match` so that the
1022/// storage-leg predicate in `search_notes` is identical to the handler-side post-filter.
1023fn note_props_match(note_props: Option<&serde_json::Value>, filter: &serde_json::Value) -> bool {
1024    let required = match filter.as_object() {
1025        Some(obj) if !obj.is_empty() => obj,
1026        _ => return true,
1027    };
1028    let actual = match note_props.and_then(serde_json::Value::as_object) {
1029        Some(obj) => obj,
1030        None => return false,
1031    };
1032    required
1033        .iter()
1034        .all(|(k, v)| actual.get(k).is_some_and(|av| av == v))
1035}
1036
1037fn note_graph_name(note: &Note) -> String {
1038    note.name
1039        .as_deref()
1040        .filter(|name| !name.trim().is_empty())
1041        .map(str::to_owned)
1042        .unwrap_or_else(|| format!("[{}]", note.kind))
1043}
1044
1045/// Collapse per-namespace `GraphPath`s from [`KhiveRuntime::traverse`] down to
1046/// exactly one entry per distinct `root_id`.
1047///
1048/// `traverse` queries every namespace in the token's visible set
1049/// independently — including namespaces that don't own the root at all,
1050/// which still contribute a root-only entry when `include_roots` is set —
1051/// and each of those per-namespace calls already enforces `limit` on its own
1052/// results. Concatenating them naively before this function would let a root
1053/// visible in N namespaces return up to N * limit nodes, would keep
1054/// whichever namespace's copy of a shared node happened to arrive first
1055/// (wrong depth/`via_edge` when that wasn't the shortest path, and
1056/// non-BFS ordering), and would rebuild a seen-set from scratch per
1057/// namespace (quadratic in namespace count).
1058///
1059/// This merges by `(root_id, node_id)` keeping the node's shallowest depth
1060/// and the `via_edge` that produced it (first-namespace-processed wins ties
1061/// at equal depth — namespace processing order is deterministic but which
1062/// tied edge is "more correct" is not otherwise decidable), reorders the
1063/// merged result BFS-style (ascending depth), and re-applies `limit` to the
1064/// merged non-root node count so the response honors the contract each
1065/// individual namespace call already tried to.
1066fn merge_traversal_paths_by_root(paths: Vec<GraphPath>, limit: Option<u32>) -> Vec<GraphPath> {
1067    let mut order: Vec<Uuid> = Vec::new();
1068    let mut merged: HashMap<Uuid, GraphPath> = HashMap::new();
1069    // root_id -> (node_id -> index into merged[root_id].nodes), so a
1070    // shallower depth for an already-seen node updates in place instead of
1071    // rebuilding a seen-set from every prior namespace's contribution.
1072    let mut node_index: HashMap<Uuid, HashMap<Uuid, usize>> = HashMap::new();
1073
1074    for path in paths {
1075        let existing = merged.entry(path.root_id).or_insert_with(|| {
1076            order.push(path.root_id);
1077            GraphPath {
1078                root_id: path.root_id,
1079                nodes: Vec::new(),
1080                total_weight: 0.0,
1081            }
1082        });
1083        let index = node_index.entry(path.root_id).or_default();
1084        for node in path.nodes {
1085            match index.get(&node.node_id) {
1086                Some(&i) => {
1087                    if node.depth < existing.nodes[i].depth {
1088                        existing.nodes[i] = node;
1089                    }
1090                }
1091                None => {
1092                    index.insert(node.node_id, existing.nodes.len());
1093                    existing.nodes.push(node);
1094                }
1095            }
1096        }
1097    }
1098
1099    order
1100        .into_iter()
1101        .filter_map(|root_id| merged.remove(&root_id))
1102        .map(|mut path| {
1103            // BFS order: ascending depth, stable within a depth.
1104            path.nodes.sort_by_key(|n| n.depth);
1105            if let Some(lim) = limit {
1106                let lim = lim as usize;
1107                let mut non_root_kept = 0usize;
1108                path.nodes.retain(|n| {
1109                    if n.depth == 0 {
1110                        return true;
1111                    }
1112                    if non_root_kept < lim {
1113                        non_root_kept += 1;
1114                        true
1115                    } else {
1116                        false
1117                    }
1118                });
1119            }
1120            recompute_total_weight(&mut path);
1121            path
1122        })
1123        .collect()
1124}
1125
1126/// Set `total_weight` to the maximum cumulative path weight among the nodes
1127/// the path currently holds, matching how storage derives it for a
1128/// single-namespace traversal.
1129///
1130/// Call this after any edit to `nodes`. Carrying a weight across an edit is
1131/// what lets the field describe a node the caller was never shown: the
1132/// highest-weighted candidate is exactly the one a `limit` or a
1133/// soft-delete screen can remove while the summary keeps quoting it.
1134fn recompute_total_weight(path: &mut GraphPath) {
1135    path.total_weight = path.nodes.iter().map(|n| n.weight).fold(0.0_f64, f64::max);
1136}
1137
1138/// Await every spawned multi-model embed task in `join_set`, returning one
1139/// vector per model (in model order) on full success.
1140///
1141/// `join_set` entries are `(model_index, embed_result)` — the index lets
1142/// completion order (which is arrival order, not spawn order) be reassembled
1143/// into the caller's model order. On the first failure (an embed error or a
1144/// task panic), every remaining handle is aborted and detached so the error
1145/// return is not gated on a sibling reaching a cancellation point. A sibling
1146/// already inside synchronous native inference may finish that call in the
1147/// background. Embed calls are counted when issued, before the provider
1148/// await, so detached completion cannot change the operation's usage count.
1149/// Each task owns cloned runtime/provider state and only computes an embedding;
1150/// storage writes remain in the parent after this drain succeeds.
1151async fn drain_embed_join_set<T: Send + 'static>(
1152    mut join_set: tokio::task::JoinSet<(usize, RuntimeResult<T>)>,
1153    model_count: usize,
1154) -> RuntimeResult<Vec<T>> {
1155    let mut vectors: Vec<Option<T>> = (0..model_count).map(|_| None).collect();
1156
1157    while let Some(joined) = join_set.join_next().await {
1158        match joined {
1159            Ok((idx, Ok(vector))) => vectors[idx] = Some(vector),
1160            Ok((_idx, Err(e))) => {
1161                join_set.abort_all();
1162                return Err(e);
1163            }
1164            Err(join_err) => {
1165                join_set.abort_all();
1166                return Err(RuntimeError::Internal(format!(
1167                    "embed task panicked: {join_err}"
1168                )));
1169            }
1170        }
1171    }
1172
1173    Ok(vectors
1174        .into_iter()
1175        .map(|v| v.expect("every model index observed exactly once by join_set drain"))
1176        .collect())
1177}
1178
1179impl KhiveRuntime {
1180    // ---- Entity operations ----
1181
1182    async fn compensate_entity_create(
1183        &self,
1184        token: &NamespaceToken,
1185        entity_id: Uuid,
1186        namespace: &str,
1187        vector_models: &[String],
1188    ) -> Vec<String> {
1189        let mut cleanup_errors = Vec::new();
1190
1191        #[cfg(any(test, feature = "fault-injection"))]
1192        let entity_delete_injected = consume_fault(&ENTITY_COMPENSATION_FAIL_NS, namespace);
1193        #[cfg(not(any(test, feature = "fault-injection")))]
1194        let entity_delete_injected = false;
1195
1196        if entity_delete_injected {
1197            cleanup_errors.push("entity row delete: injected compensation failure".to_string());
1198        } else {
1199            match self.entities(token) {
1200                Ok(store) => {
1201                    if let Err(error) = store.delete_entity(entity_id, DeleteMode::Hard).await {
1202                        cleanup_errors.push(format!("entity row delete: {error}"));
1203                    }
1204                }
1205                Err(error) => cleanup_errors.push(format!("entity store access: {error}")),
1206            }
1207        }
1208
1209        match self.text(token) {
1210            Ok(fts) => {
1211                if let Err(error) = fts.delete_document(namespace, entity_id).await {
1212                    cleanup_errors.push(format!("FTS document delete: {error}"));
1213                }
1214            }
1215            Err(error) => cleanup_errors.push(format!("FTS store access: {error}")),
1216        }
1217
1218        for model_name in vector_models {
1219            match self.vectors_for_model(token, model_name) {
1220                Ok(vectors) => {
1221                    if let Err(error) = vectors.delete(entity_id).await {
1222                        cleanup_errors
1223                            .push(format!("vector delete for model {model_name}: {error}"));
1224                    }
1225                }
1226                Err(error) => cleanup_errors.push(format!(
1227                    "vector store access for model {model_name}: {error}"
1228                )),
1229            }
1230        }
1231
1232        cleanup_errors
1233    }
1234
1235    fn entity_create_failure(
1236        entity_id: Uuid,
1237        primary: RuntimeError,
1238        cleanup_errors: Vec<String>,
1239    ) -> RuntimeError {
1240        if cleanup_errors.is_empty() {
1241            primary
1242        } else {
1243            RuntimeError::Khive(KhiveError::internal(format!(
1244                "create_entity indexing failed for record {entity_id}; primary failure: \
1245                 {primary}; compensation failure(s): {}; partial persistence is possible; \
1246                 inspect and reconcile this record before retrying",
1247                cleanup_errors.join("; ")
1248            )))
1249        }
1250    }
1251
1252    /// Create and persist a new entity.
1253    ///
1254    /// Indexing failures trigger compensation across the entity row, FTS
1255    /// document, and any vector models touched by this call. If compensation
1256    /// also fails, the returned structured internal error identifies possible
1257    /// partial persistence, includes both failure classes, and carries the
1258    /// entity ID as a reconciliation handle.
1259    // REASON: entity creation requires kind, type, name, description, properties, tags, and
1260    // namespace token — refactoring into a builder would add indirection without reducing
1261    // caller complexity; this signature mirrors the MCP verb surface directly.
1262    #[allow(clippy::too_many_arguments)]
1263    pub async fn create_entity(
1264        &self,
1265        token: &NamespaceToken,
1266        kind: &str,
1267        entity_type: Option<&str>,
1268        name: &str,
1269        description: Option<&str>,
1270        properties: Option<serde_json::Value>,
1271        tags: Vec<String>,
1272    ) -> RuntimeResult<Entity> {
1273        Ok(self
1274            .create_entity_with_embedding_report(
1275                token,
1276                kind,
1277                entity_type,
1278                name,
1279                description,
1280                properties,
1281                tags,
1282            )
1283            .await?
1284            .0)
1285    }
1286
1287    #[allow(clippy::too_many_arguments)]
1288    pub async fn create_entity_with_embedding_report(
1289        &self,
1290        token: &NamespaceToken,
1291        kind: &str,
1292        entity_type: Option<&str>,
1293        name: &str,
1294        description: Option<&str>,
1295        properties: Option<serde_json::Value>,
1296        tags: Vec<String>,
1297    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
1298        self.validate_entity_kind(kind)?;
1299        // Secret gate: scan name, description, structured properties, and tags.
1300        crate::secret_gate::check(name)?;
1301        if let Some(d) = description {
1302            crate::secret_gate::check(d)?;
1303        }
1304        if let Some(ref p) = properties {
1305            crate::secret_gate::check_json(p)?;
1306        }
1307        crate::secret_gate::check_tags(&tags)?;
1308        let ns = token.namespace().as_str();
1309        let mut entity = Entity::new(ns, kind, name).with_entity_type(entity_type);
1310        if let Some(d) = description {
1311            entity = entity.with_description(d);
1312        }
1313        if let Some(p) = properties {
1314            entity = entity.with_properties(p);
1315        }
1316        if !tags.is_empty() {
1317            entity = entity.with_tags(tags);
1318        }
1319        self.entities(token)?.upsert_entity(entity.clone()).await?;
1320
1321        let doc = entity_fts_document(&entity);
1322        let embed_body = doc.body.clone();
1323
1324        // FTS step — compensate entity row on failure (mirrors create_note_inner).
1325        {
1326            #[cfg(any(test, feature = "fault-injection"))]
1327            let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
1328            #[cfg(not(any(test, feature = "fault-injection")))]
1329            let fts_inject = false;
1330            let fts_result: RuntimeResult<()> = if fts_inject {
1331                Err(RuntimeError::Internal("injected FTS failure".to_string()))
1332            } else {
1333                match self.text(token) {
1334                    Ok(fts) => fts.upsert_document(doc).await.map_err(RuntimeError::from),
1335                    Err(e) => Err(e),
1336                }
1337            };
1338            if let Err(e) = fts_result {
1339                let cleanup_errors = self
1340                    .compensate_entity_create(token, entity.id, ns, &[])
1341                    .await;
1342                return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1343            }
1344        }
1345
1346        // Vector embedding + insert step — compensate entity row + FTS doc on failure.
1347        // Fan out to ALL registered models (mirrors create_note_inner multi-model path).
1348        let embed_model_names = {
1349            let names = self.registered_embedding_model_names();
1350            if names.is_empty() {
1351                vec![]
1352            } else {
1353                names
1354            }
1355        };
1356
1357        let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
1358        if embed_model_names.len() == 1 {
1359            let model_name = &embed_model_names[0];
1360            let vec_result = self
1361                .embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
1362                .await;
1363
1364            #[cfg(any(test, feature = "fault-injection"))]
1365            let vec_inject = consume_fault(&VECTOR_FAIL_NS, ns);
1366            #[cfg(not(any(test, feature = "fault-injection")))]
1367            let vec_inject = false;
1368            let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
1369                if vec_inject {
1370                    Err(RuntimeError::Internal(
1371                        "injected vector failure".to_string(),
1372                    ))
1373                } else {
1374                    vec_result
1375                };
1376
1377            let single_result: RuntimeResult<()> = match vec_result {
1378                Ok(outcome) => {
1379                    embedding_report.observe(&outcome);
1380                    match self.vectors_for_model(token, model_name) {
1381                        Ok(vs) => vs
1382                            .insert(
1383                                entity.id,
1384                                SubstrateKind::Entity,
1385                                ns,
1386                                "entity.body",
1387                                vec![outcome.vector],
1388                            )
1389                            .await
1390                            .map_err(RuntimeError::from),
1391                        Err(e) => Err(e),
1392                    }
1393                }
1394                Err(e) => Err(e),
1395            };
1396            if let Err(e) = single_result {
1397                let cleanup_errors = self
1398                    .compensate_entity_create(
1399                        token,
1400                        entity.id,
1401                        ns,
1402                        std::slice::from_ref(model_name),
1403                    )
1404                    .await;
1405                return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1406            }
1407        } else if !embed_model_names.is_empty() {
1408            // Multi-model path: embed with each model in parallel, then insert sequentially
1409            // with inserted_models tracking for rollback on partial failure.
1410            let rt_clone = self.clone();
1411            let body_owned = embed_body.clone();
1412            let usage_ctx = crate::usage::current();
1413            let mut join_set = tokio::task::JoinSet::new();
1414            for (idx, model_name) in embed_model_names.iter().enumerate() {
1415                let rt = rt_clone.clone();
1416                let text = body_owned.clone();
1417                let name = model_name.clone();
1418                let ctx = usage_ctx.clone();
1419                let token = (*token).clone();
1420                join_set.spawn(async move {
1421                    let fut = rt.embed_document_with_model_outcome_for_token(&token, &name, &text);
1422                    let result = match ctx {
1423                        Some(ctx) => crate::usage::scope(ctx, fut).await,
1424                        None => fut.await,
1425                    };
1426                    (idx, result)
1427                });
1428            }
1429            // The first failed or panicked handle aborts and detaches its
1430            // siblings. Embed usage is counted at dispatch, so a synchronous
1431            // provider winding down in the background cannot change it.
1432            let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
1433                Ok(outcomes) => outcomes,
1434                Err(e) => {
1435                    let cleanup_errors = self
1436                        .compensate_entity_create(token, entity.id, ns, &[])
1437                        .await;
1438                    return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1439                }
1440            };
1441            // TODO(P2): parallelize vector inserts
1442            let mut inserted_models: Vec<String> = Vec::with_capacity(embed_model_names.len());
1443            for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
1444                embedding_report.observe(&outcome);
1445                // Count-targetable fault injection for multi-model insert path.
1446                #[cfg(any(test, feature = "fault-injection"))]
1447                let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
1448                    Some(0) => {
1449                        cell.set(None);
1450                        true
1451                    }
1452                    Some(n) => {
1453                        cell.set(Some(n - 1));
1454                        false
1455                    }
1456                    None => false,
1457                });
1458                #[cfg(not(any(test, feature = "fault-injection")))]
1459                let count_inject = false;
1460
1461                let insert_result = if count_inject {
1462                    Err(RuntimeError::Internal(
1463                        "injected vector insert failure".to_string(),
1464                    ))
1465                } else {
1466                    match self.vectors_for_model(token, model_name) {
1467                        Ok(vs) => vs
1468                            .insert(
1469                                entity.id,
1470                                SubstrateKind::Entity,
1471                                ns,
1472                                "entity.body",
1473                                vec![outcome.vector],
1474                            )
1475                            .await
1476                            .map_err(RuntimeError::from),
1477                        Err(e) => Err(e),
1478                    }
1479                };
1480                if let Err(e) = insert_result {
1481                    // Include the model whose INSERT returned an error: a backend
1482                    // error does not prove the write had no side effects.
1483                    let mut cleanup_models = inserted_models.clone();
1484                    cleanup_models.push(model_name.clone());
1485                    let cleanup_errors = self
1486                        .compensate_entity_create(token, entity.id, ns, &cleanup_models)
1487                        .await;
1488                    return Err(Self::entity_create_failure(entity.id, e, cleanup_errors));
1489                }
1490                inserted_models.push(model_name.clone());
1491            }
1492        }
1493
1494        Ok((entity, embedding_report))
1495    }
1496
1497    /// Retrieve an entity by ID.
1498    ///
1499    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1500    ///
1501    /// Interim identifier-continuity disclosure (precedes the full transitive
1502    /// redirect chase): a miss is probed once against the tombstone row. If
1503    /// the id was consumed by `merge(into_id, from_id)` — `merged_into` set —
1504    /// the `NotFound` message names the kept id so the caller can requery it
1505    /// directly. Single-level only: it does not chase a chain of merges and
1506    /// does not return the kept entity in place of the miss. The probe only
1507    /// runs after the live-row lookup misses, so the happy path pays no
1508    /// extra query.
1509    pub async fn get_entity(&self, token: &NamespaceToken, id: Uuid) -> RuntimeResult<Entity> {
1510        let store = self.entities(token)?;
1511        if let Some(entity) = store.get_entity(id).await? {
1512            return Ok(entity);
1513        }
1514        if let Some(tombstone) = store.get_entity_including_deleted(id).await? {
1515            if let Some(kept_id) = tombstone.merged_into {
1516                return Err(RuntimeError::NotFound(format!(
1517                    "{id} was merged into {kept_id}; query the kept id"
1518                )));
1519            }
1520        }
1521        Err(RuntimeError::NotFound(format!("entity {id}")))
1522    }
1523
1524    /// Retrieve an entity by ID including soft-deleted rows.
1525    ///
1526    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1527    pub async fn get_entity_including_deleted(
1528        &self,
1529        token: &NamespaceToken,
1530        id: Uuid,
1531    ) -> RuntimeResult<Option<Entity>> {
1532        self.entities(token)?
1533            .get_entity_including_deleted(id)
1534            .await
1535            .map_err(Into::into)
1536    }
1537
1538    /// Retrieve a note by ID including soft-deleted rows.
1539    ///
1540    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
1541    pub async fn get_note_including_deleted(
1542        &self,
1543        token: &NamespaceToken,
1544        id: Uuid,
1545    ) -> RuntimeResult<Option<khive_storage::note::Note>> {
1546        self.notes(token)?
1547            .get_note_including_deleted(id)
1548            .await
1549            .map_err(Into::into)
1550    }
1551
1552    /// Fetch multiple entities by ID, returning only those that exist in the
1553    /// caller's namespace.  Missing or namespace-mismatched IDs are silently
1554    /// omitted so that batch lookups don't abort on a single stale reference.
1555    pub async fn get_entities_by_ids(
1556        &self,
1557        token: &NamespaceToken,
1558        ids: &[Uuid],
1559    ) -> RuntimeResult<Vec<Entity>> {
1560        if ids.is_empty() {
1561            return Ok(vec![]);
1562        }
1563        let filter = EntityFilter {
1564            ids: ids.to_vec(),
1565            ..Default::default()
1566        };
1567        let page = self
1568            .entities(token)?
1569            .query_entities(
1570                token.namespace().as_str(),
1571                filter,
1572                PageRequest {
1573                    offset: 0,
1574                    limit: ids.len() as u32,
1575                },
1576            )
1577            .await?;
1578        Ok(page.items)
1579    }
1580
1581    /// Like `get_entities_by_ids` but scoped to the token's full visible-namespace
1582    /// set (`primary ∪ extra_visible`) instead of primary only.
1583    ///
1584    /// Graph expansion (`neighbors`, `traverse`) iterates over all visible
1585    /// namespaces, so enrichment must use the same scope — otherwise neighbors
1586    /// or path nodes whose entities live in an extra-visible namespace are left
1587    /// with `name = None`, `kind = None`.  Missing or out-of-scope IDs are
1588    /// silently omitted (best-effort, same as `get_entities_by_ids`).
1589    async fn get_entities_by_ids_visible(
1590        &self,
1591        token: &NamespaceToken,
1592        ids: &[Uuid],
1593    ) -> RuntimeResult<Vec<Entity>> {
1594        if ids.is_empty() {
1595            return Ok(vec![]);
1596        }
1597        let namespaces: Vec<String> = token
1598            .visible_namespaces()
1599            .iter()
1600            .map(|ns| ns.as_str().to_owned())
1601            .collect();
1602        let filter = EntityFilter {
1603            ids: ids.to_vec(),
1604            namespaces,
1605            ..Default::default()
1606        };
1607        let page = self
1608            .entities(token)?
1609            .query_entities(
1610                token.namespace().as_str(),
1611                filter,
1612                PageRequest {
1613                    offset: 0,
1614                    limit: ids.len() as u32,
1615                },
1616            )
1617            .await?;
1618        Ok(page.items)
1619    }
1620
1621    /// Enforce that `record_ns` is within the caller's visible namespace set.
1622    ///
1623    /// Returns `Err(NotFound)` when the record namespace is not in the visible
1624    /// set — wrong-namespace and absent UUIDs must be indistinguishable
1625    /// externally (no existence oracle).
1626    ///
1627    /// When the visible set is a single entry equal to `caller_primary_ns`, this
1628    /// is identical to the former strict-equality check (backward-compatible).
1629    pub(crate) fn ensure_namespace(record_ns: &str, caller_primary_ns: &str) -> RuntimeResult<()> {
1630        if record_ns == caller_primary_ns {
1631            return Ok(());
1632        }
1633        Err(RuntimeError::NotFound("not found in this namespace".into()))
1634    }
1635
1636    /// Enforce that `record_ns` is a member of the token's visible namespace set.
1637    ///
1638    /// This is the multi-namespace-aware variant used when the token carries an
1639    /// extended visibility set. For single-namespace tokens (visible == [primary])
1640    /// this degenerates to the same strict-equality check as `ensure_namespace`.
1641    pub(crate) fn ensure_namespace_visible(
1642        record_ns: &str,
1643        token: &NamespaceToken,
1644    ) -> RuntimeResult<()> {
1645        for ns in token.visible_namespaces() {
1646            if record_ns == ns.as_str() {
1647                return Ok(());
1648            }
1649        }
1650        Err(RuntimeError::NotFound("not found in this namespace".into()))
1651    }
1652
1653    /// List entities visible to the token, optionally filtered by kind and entity_type.
1654    ///
1655    /// When the token carries a multi-namespace visible set, entities from all
1656    /// visible namespaces are returned. When the visible set is `[primary]`
1657    /// (the default) this behaves identically to the pre-visibility behaviour.
1658    pub async fn list_entities(
1659        &self,
1660        token: &NamespaceToken,
1661        kind: Option<&str>,
1662        entity_type: Option<&str>,
1663        limit: u32,
1664        offset: u32,
1665    ) -> RuntimeResult<Vec<Entity>> {
1666        let ns_strs: Vec<String> = token
1667            .visible_namespaces()
1668            .iter()
1669            .map(|ns| ns.as_str().to_owned())
1670            .collect();
1671        let filter = EntityFilter {
1672            kinds: match kind {
1673                Some(k) => vec![k.to_string()],
1674                None => vec![],
1675            },
1676            entity_types: match entity_type {
1677                Some(t) => vec![t.to_string()],
1678                None => vec![],
1679            },
1680            namespaces: ns_strs,
1681            ..Default::default()
1682        };
1683        let page = self
1684            .entities(token)?
1685            .query_entities(
1686                token.namespace().as_str(),
1687                filter,
1688                PageRequest {
1689                    offset: offset.into(),
1690                    limit,
1691                },
1692            )
1693            .await?;
1694        Ok(page.items)
1695    }
1696
1697    /// List an immutable insertion-sequence page of visible entities.
1698    ///
1699    /// The public cursor remains the UUID of the last returned entity. We
1700    /// resolve its immutable database-assigned sequence before querying so callers do
1701    /// not need to serialize storage details. A missing or out-of-scope cursor
1702    /// fails explicitly instead of silently resuming from the wrong boundary.
1703    pub async fn list_entities_after(
1704        &self,
1705        token: &NamespaceToken,
1706        kind: Option<&str>,
1707        entity_type: Option<&str>,
1708        tags_any: &[String],
1709        after: Option<Uuid>,
1710        limit: u32,
1711    ) -> RuntimeResult<(Vec<Entity>, Option<Uuid>)> {
1712        let store = self.entities(token)?;
1713        let after = match after {
1714            Some(id) => {
1715                let entity = self
1716                    .get_entity_including_deleted(token, id)
1717                    .await?
1718                    .ok_or_else(|| RuntimeError::NotFound(format!("entity cursor {id}")))?;
1719                Self::ensure_namespace_visible(&entity.namespace, token)?;
1720                let sequence = store.entity_sequence(id).await?.ok_or_else(|| {
1721                    RuntimeError::Internal(format!(
1722                        "entity cursor {id} has no insertion-sequence ledger row"
1723                    ))
1724                })?;
1725                Some(SeekCursor { sequence, id })
1726            }
1727            None => None,
1728        };
1729        let filter = EntityFilter {
1730            kinds: kind
1731                .map(|value| vec![value.to_string()])
1732                .unwrap_or_default(),
1733            entity_types: entity_type
1734                .map(|value| vec![value.to_string()])
1735                .unwrap_or_default(),
1736            tags_any: tags_any.to_vec(),
1737            namespaces: token
1738                .visible_namespaces()
1739                .iter()
1740                .map(|namespace| namespace.as_str().to_owned())
1741                .collect(),
1742            ..Default::default()
1743        };
1744        let page = store
1745            .query_entities_after(token.namespace().as_str(), filter, after, limit)
1746            .await?;
1747        Ok((page.items, page.next_after.map(|cursor| cursor.id)))
1748    }
1749
1750    /// List entities filtered by kind, optional domain tag, limit, and offset.
1751    ///
1752    /// When `domain_tag` is Some, the query is restricted at the storage layer via
1753    /// `EntityFilter::tags_any` so the page result already reflects the domain
1754    /// constraint.  This avoids the silent truncation that occurs when filtering
1755    /// post-page (K-3). Multi-namespace visibility from the token is applied.
1756    pub async fn list_entities_tagged(
1757        &self,
1758        token: &NamespaceToken,
1759        kind: Option<&str>,
1760        domain_tag: Option<&str>,
1761        limit: u32,
1762        offset: u32,
1763    ) -> RuntimeResult<Vec<Entity>> {
1764        let ns_strs: Vec<String> = token
1765            .visible_namespaces()
1766            .iter()
1767            .map(|ns| ns.as_str().to_owned())
1768            .collect();
1769        let filter = EntityFilter {
1770            kinds: match kind {
1771                Some(k) => vec![k.to_string()],
1772                None => vec![],
1773            },
1774            tags_any: match domain_tag {
1775                Some(t) if !t.is_empty() => vec![t.to_string()],
1776                _ => vec![],
1777            },
1778            namespaces: ns_strs,
1779            ..Default::default()
1780        };
1781        let page = self
1782            .entities(token)?
1783            .query_entities(
1784                token.namespace().as_str(),
1785                filter,
1786                PageRequest {
1787                    offset: offset.into(),
1788                    limit,
1789                },
1790            )
1791            .await?;
1792        Ok(page.items)
1793    }
1794
1795    /// Count entities filtered by kind and optional domain tag.
1796    ///
1797    /// Used to report a meaningful `total` alongside a paginated listing (K-6).
1798    /// Multi-namespace visibility from the token is applied.
1799    pub async fn count_entities_tagged(
1800        &self,
1801        token: &NamespaceToken,
1802        kind: Option<&str>,
1803        domain_tag: Option<&str>,
1804    ) -> RuntimeResult<u64> {
1805        let ns_strs: Vec<String> = token
1806            .visible_namespaces()
1807            .iter()
1808            .map(|ns| ns.as_str().to_owned())
1809            .collect();
1810        let filter = EntityFilter {
1811            kinds: match kind {
1812                Some(k) => vec![k.to_string()],
1813                None => vec![],
1814            },
1815            tags_any: match domain_tag {
1816                Some(t) if !t.is_empty() => vec![t.to_string()],
1817                _ => vec![],
1818            },
1819            namespaces: ns_strs,
1820            ..Default::default()
1821        };
1822        Ok(self
1823            .entities(token)?
1824            .count_entities(token.namespace().as_str(), filter)
1825            .await?)
1826    }
1827
1828    /// List events in the namespace proven by the caller token.
1829    pub async fn list_events(
1830        &self,
1831        token: &NamespaceToken,
1832        filter: EventFilter,
1833        page: PageRequest,
1834    ) -> RuntimeResult<Page<Event>> {
1835        self.events(token)?
1836            .query_events(filter, page)
1837            .await
1838            .map_err(Into::into)
1839    }
1840
1841    // ---- Edge operations ----
1842
1843    /// Validate that `source_id` and `target_id` are legal endpoints for `relation`.
1844    ///
1845    /// Centralises the three-case relation contract so that both
1846    /// `link()` and `update_edge()` share identical enforcement:
1847    ///
1848    /// - `annotates`: source MUST be a note; target may be any substrate.
1849    /// - `supersedes` / `supports` / `refutes`: same-substrate only (note→note or entity→entity).
1850    /// - All other 13 relations: both endpoints MUST be entities.
1851    ///
1852    /// Returns `Ok(())` when valid; otherwise `InvalidInput` or `NotFound` with
1853    /// the same messages as the previous inline block (byte-identical behaviour).
1854    ///
1855    /// `pub(crate)`: the atomic prepare pass (`crate::atomic_prepare`) reuses
1856    /// this exact endpoint-type validation during its async prepare step,
1857    /// before building a `LinkPlan`, rather than re-deriving the checks.
1858    pub(crate) async fn validate_edge_relation_endpoints(
1859        &self,
1860        token: &NamespaceToken,
1861        source_id: Uuid,
1862        target_id: Uuid,
1863        relation: EdgeRelation,
1864    ) -> RuntimeResult<()> {
1865        if source_id == target_id {
1866            return Err(RuntimeError::InvalidInput(
1867                "self-loop edges are not allowed: source_id and target_id must be different".into(),
1868            ));
1869        }
1870        if relation == EdgeRelation::Annotates {
1871            // Source must be a note. By-ID endpoint resolution is namespace-agnostic:
1872            // link consumes two by-ID endpoints, so it must resolve exactly what
1873            // get() resolves, regardless of caller namespace.
1874            match self.resolve_edge_endpoint(token, source_id).await? {
1875                Some(Resolved::Note(_)) => {}
1876                Some(_) => {
1877                    return Err(RuntimeError::InvalidInput(format!(
1878                        "annotates source {source_id} must be a note"
1879                    )));
1880                }
1881                None => {
1882                    // Existing edge used as annotates source: wrong kind, not absent.
1883                    if self.get_edge(token, source_id).await?.is_some() {
1884                        return Err(RuntimeError::InvalidInput(format!(
1885                            "annotates source {source_id} must be a note"
1886                        )));
1887                    }
1888                    return Err(RuntimeError::NotFound(format!(
1889                        "link source {source_id} not found"
1890                    )));
1891                }
1892            }
1893            // Target may be any substrate (entity, note, event, or edge) — by-ID, unfiltered.
1894            if !self.substrate_exists_by_id(token, target_id).await? {
1895                return Err(RuntimeError::NotFound(format!(
1896                    "link target {target_id} not found"
1897                )));
1898            }
1899        } else if crate::pack::is_special_relation(relation) {
1900            // supersedes / supports / refutes: same-substrate only (note→note or entity→entity).
1901            // Event and edge endpoints are invalid regardless of the other endpoint.
1902            // Endpoint resolution is by-ID and namespace-agnostic.
1903            let rel_name = relation.as_str();
1904            let src = match self.resolve_edge_endpoint(token, source_id).await? {
1905                Some(r) => r,
1906                None => {
1907                    if self.get_edge(token, source_id).await?.is_some() {
1908                        return Err(RuntimeError::InvalidInput(format!(
1909                            "{rel_name} source {source_id} must be a note or entity (got edge)"
1910                        )));
1911                    }
1912                    return Err(RuntimeError::NotFound(format!(
1913                        "link source {source_id} not found"
1914                    )));
1915                }
1916            };
1917            let tgt = match self.resolve_edge_endpoint(token, target_id).await? {
1918                Some(r) => r,
1919                None => {
1920                    if self.get_edge(token, target_id).await?.is_some() {
1921                        return Err(RuntimeError::InvalidInput(format!(
1922                            "{rel_name} target {target_id} must be a note or entity (got edge)"
1923                        )));
1924                    }
1925                    return Err(RuntimeError::NotFound(format!(
1926                        "link target {target_id} not found"
1927                    )));
1928                }
1929            };
1930            match (&src, &tgt) {
1931                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
1932                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
1933                        let legal_relations = accepted_entity_relations_description(
1934                            &self.pack_edge_rules(),
1935                            &src_e.kind,
1936                            src_e.entity_type.as_deref(),
1937                            &tgt_e.kind,
1938                            tgt_e.entity_type.as_deref(),
1939                        );
1940                        let rule_hint = match relation {
1941                            EdgeRelation::Supports | EdgeRelation::Refutes => {
1942                                "requires concept|document|dataset|artifact -> concept \
1943                                 (or same-substrate note -> note)"
1944                            }
1945                            _ => "requires same-kind entity endpoints",
1946                        };
1947                        return Err(RuntimeError::InvalidInput(format!(
1948                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
1949                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
1950                             {} -> {} under the loaded endpoint rules: {legal_relations}",
1951                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
1952                        )));
1953                    }
1954                }
1955                (Resolved::Note(_), Resolved::Note(_)) => {}
1956                (Resolved::Event(_), _) => {
1957                    return Err(RuntimeError::InvalidInput(format!(
1958                        "{rel_name} does not apply to events; source {source_id} is an event"
1959                    )));
1960                }
1961                (_, Resolved::Event(_)) => {
1962                    return Err(RuntimeError::InvalidInput(format!(
1963                        "{rel_name} does not apply to events; target {target_id} is an event"
1964                    )));
1965                }
1966                (Resolved::Entity(_), Resolved::Note(_)) => {
1967                    return Err(RuntimeError::InvalidInput(format!(
1968                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
1969                         got source={source_id} (entity) target={target_id} (note)"
1970                    )));
1971                }
1972                (Resolved::Note(_), Resolved::Entity(_)) => {
1973                    return Err(RuntimeError::InvalidInput(format!(
1974                        "{rel_name} endpoints must be the same substrate (note→note or entity→entity); \
1975                         got source={source_id} (note) target={target_id} (entity)"
1976                    )));
1977                }
1978                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
1979                    return Err(RuntimeError::InvalidInput(format!(
1980                        "pack-private record is not a valid edge endpoint for {rel_name}"
1981                    )));
1982                }
1983            }
1984        } else {
1985            // All remaining base relations require entity→entity with kind-level
1986            // restrictions (see base allowlist). Packs may extend the allowlist
1987            // additively via EDGE_RULES.
1988            //
1989            // Strategy: resolve both endpoints once (by-ID, unfiltered), consult pack
1990            // rules; on miss, fall through to the original base-rule error messages.
1991            let src_res = self.resolve_edge_endpoint(token, source_id).await?;
1992            let tgt_res = self.resolve_edge_endpoint(token, target_id).await?;
1993            let pack_rules = self.pack_edge_rules();
1994
1995            if pack_rule_allows(&pack_rules, relation, src_res.as_ref(), tgt_res.as_ref()) {
1996                return Ok(());
1997            }
1998
1999            // Substrate check: both endpoints must be entities.
2000            let (src_kind, src_entity_type) = match src_res.as_ref() {
2001                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2002                Some(_) => {
2003                    return Err(RuntimeError::InvalidInput(format!(
2004                        "link source {source_id} must be an entity for relation {relation:?} \
2005                         (only `annotates` crosses substrates)"
2006                    )));
2007                }
2008                None => {
2009                    if self.get_edge(token, source_id).await?.is_some() {
2010                        return Err(RuntimeError::InvalidInput(format!(
2011                            "link source {source_id} must be an entity for relation {relation:?} \
2012                             (only `annotates` crosses substrates)"
2013                        )));
2014                    }
2015                    return Err(RuntimeError::NotFound(format!(
2016                        "link source {source_id} not found"
2017                    )));
2018                }
2019            };
2020            let (tgt_kind, tgt_entity_type) = match tgt_res.as_ref() {
2021                Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2022                Some(_) => {
2023                    return Err(RuntimeError::InvalidInput(format!(
2024                        "link target {target_id} must be an entity for relation {relation:?} \
2025                         (only `annotates` crosses substrates)"
2026                    )));
2027                }
2028                None => {
2029                    if self.get_edge(token, target_id).await?.is_some() {
2030                        return Err(RuntimeError::InvalidInput(format!(
2031                            "link target {target_id} must be an entity for relation {relation:?} \
2032                             (only `annotates` crosses substrates)"
2033                        )));
2034                    }
2035                    return Err(RuntimeError::NotFound(format!(
2036                        "link target {target_id} not found"
2037                    )));
2038                }
2039            };
2040            if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
2041                let legal_relations = accepted_entity_relations_description(
2042                    &pack_rules,
2043                    src_kind,
2044                    src_entity_type,
2045                    tgt_kind,
2046                    tgt_entity_type,
2047                );
2048                return Err(RuntimeError::InvalidInput(format!(
2049                    "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
2050                     allowlist; use pack EDGE_RULES to extend the allowlist; currently legal \
2051                     relations for {src_kind} -> {tgt_kind} under the loaded endpoint rules: \
2052                     {legal_relations}",
2053                    relation.as_str()
2054                )));
2055            }
2056        }
2057        Ok(())
2058    }
2059
2060    /// Public delegator for cross-backend link validation.
2061    ///
2062    /// Exposes `validate_edge_relation_endpoints` for the `SubstrateCoordinator`
2063    /// so it can validate the relation before writing the edge on the source backend.
2064    pub async fn validate_link_endpoints(
2065        &self,
2066        token: &NamespaceToken,
2067        source_id: Uuid,
2068        target_id: Uuid,
2069        relation: EdgeRelation,
2070    ) -> RuntimeResult<()> {
2071        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
2072            .await
2073    }
2074
2075    /// Validate an edge relation using pre-fetched endpoint records.
2076    ///
2077    /// For cross-backend links the source and target live on different backends —
2078    /// the source runtime cannot resolve the target. The coordinator fetches each
2079    /// endpoint from its own backend, then calls this method to enforce the
2080    /// kind-pairing rules without a second DB round-trip.
2081    ///
2082    /// `src` and `tgt` are the `resolve_edge_endpoint` results from each backend. The
2083    /// `token` supplies the pack edge rules installed on this (source) runtime;
2084    /// no DB access is performed.
2085    pub fn validate_link_endpoints_by_resolved(
2086        &self,
2087        source_id: Uuid,
2088        target_id: Uuid,
2089        relation: EdgeRelation,
2090        src: Option<&Resolved>,
2091        tgt: Option<&Resolved>,
2092    ) -> RuntimeResult<()> {
2093        if source_id == target_id {
2094            return Err(RuntimeError::InvalidInput(
2095                "self-loop edges are not allowed: source_id and target_id must be different".into(),
2096            ));
2097        }
2098
2099        if relation == EdgeRelation::Annotates {
2100            match src {
2101                Some(Resolved::Note(_)) => {}
2102                Some(_) => {
2103                    return Err(RuntimeError::InvalidInput(format!(
2104                        "annotates source {source_id} must be a note"
2105                    )));
2106                }
2107                None => {
2108                    return Err(RuntimeError::NotFound(format!(
2109                        "link source {source_id} not found"
2110                    )));
2111                }
2112            }
2113            if tgt.is_none() {
2114                return Err(RuntimeError::NotFound(format!(
2115                    "link target {target_id} not found"
2116                )));
2117            }
2118            return Ok(());
2119        }
2120
2121        if crate::pack::is_special_relation(relation) {
2122            let rel_name = relation.as_str();
2123            let src = src.ok_or_else(|| {
2124                RuntimeError::NotFound(format!("link source {source_id} not found"))
2125            })?;
2126            let tgt = tgt.ok_or_else(|| {
2127                RuntimeError::NotFound(format!("link target {target_id} not found"))
2128            })?;
2129            match (src, tgt) {
2130                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
2131                    if !base_entity_rule_allows(&src_e.kind, relation, &tgt_e.kind) {
2132                        let legal_relations = accepted_entity_relations_description(
2133                            &self.pack_edge_rules(),
2134                            &src_e.kind,
2135                            src_e.entity_type.as_deref(),
2136                            &tgt_e.kind,
2137                            tgt_e.entity_type.as_deref(),
2138                        );
2139                        let rule_hint = match relation {
2140                            EdgeRelation::Supports | EdgeRelation::Refutes => {
2141                                "requires concept|document|dataset|artifact -> concept \
2142                                 (or same-substrate note -> note)"
2143                            }
2144                            _ => "requires same-kind entity endpoints",
2145                        };
2146                        return Err(RuntimeError::InvalidInput(format!(
2147                            "({}) -[{rel_name}]-> ({}) is not in the base endpoint \
2148                             allowlist; {rel_name} {rule_hint}; currently legal relations for \
2149                             {} -> {} under the loaded endpoint rules: {legal_relations}",
2150                            src_e.kind, tgt_e.kind, src_e.kind, tgt_e.kind
2151                        )));
2152                    }
2153                }
2154                (Resolved::Note(_), Resolved::Note(_)) => {}
2155                (Resolved::Entity(_), Resolved::Note(_)) => {
2156                    return Err(RuntimeError::InvalidInput(format!(
2157                        "{rel_name} endpoints must be the same substrate \
2158                         (note→note or entity→entity); got source={source_id} (entity) \
2159                         target={target_id} (note)"
2160                    )));
2161                }
2162                (Resolved::Note(_), Resolved::Entity(_)) => {
2163                    return Err(RuntimeError::InvalidInput(format!(
2164                        "{rel_name} endpoints must be the same substrate \
2165                         (note→note or entity→entity); got source={source_id} (note) \
2166                         target={target_id} (entity)"
2167                    )));
2168                }
2169                (Resolved::PackRecord { .. }, _) | (_, Resolved::PackRecord { .. }) => {
2170                    return Err(RuntimeError::InvalidInput(format!(
2171                        "pack-private record is not a valid edge endpoint for {rel_name}"
2172                    )));
2173                }
2174                _ => {
2175                    return Err(RuntimeError::InvalidInput(format!(
2176                        "{rel_name} endpoints must be notes or entities (not events)"
2177                    )));
2178                }
2179            }
2180            return Ok(());
2181        }
2182
2183        // All remaining base relations: entity→entity with kind-level restrictions.
2184        // Consult pack rules installed on this (source) runtime first.
2185        let pack_rules = self.pack_edge_rules();
2186        if pack_rule_allows(&pack_rules, relation, src, tgt) {
2187            return Ok(());
2188        }
2189
2190        let (src_kind, src_entity_type) = match src {
2191            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2192            Some(_) => {
2193                return Err(RuntimeError::InvalidInput(format!(
2194                    "link source {source_id} must be an entity for relation {relation:?} \
2195                     (only `annotates` crosses substrates)"
2196                )));
2197            }
2198            None => {
2199                return Err(RuntimeError::NotFound(format!(
2200                    "link source {source_id} not found"
2201                )));
2202            }
2203        };
2204        let (tgt_kind, tgt_entity_type) = match tgt {
2205            Some(Resolved::Entity(e)) => (e.kind.as_str(), e.entity_type.as_deref()),
2206            Some(_) => {
2207                return Err(RuntimeError::InvalidInput(format!(
2208                    "link target {target_id} must be an entity for relation {relation:?} \
2209                     (only `annotates` crosses substrates)"
2210                )));
2211            }
2212            None => {
2213                return Err(RuntimeError::NotFound(format!(
2214                    "link target {target_id} not found"
2215                )));
2216            }
2217        };
2218
2219        if !base_entity_rule_allows(src_kind, relation, tgt_kind) {
2220            let legal_relations = accepted_entity_relations_description(
2221                &pack_rules,
2222                src_kind,
2223                src_entity_type,
2224                tgt_kind,
2225                tgt_entity_type,
2226            );
2227            return Err(RuntimeError::InvalidInput(format!(
2228                "({src_kind}) -[{}]-> ({tgt_kind}) is not in the base endpoint \
2229                 allowlist; use pack EDGE_RULES to extend the allowlist; currently legal relations \
2230                 for {src_kind} -> {tgt_kind} under the loaded endpoint rules: {legal_relations}",
2231                relation.as_str()
2232            )));
2233        }
2234
2235        Ok(())
2236    }
2237
2238    /// Validate an `annotates` edge relation using pre-located endpoint kinds.
2239    ///
2240    /// Sibling of [`Self::validate_link_endpoints_by_resolved`] for callers that
2241    /// only have an [`EdgeEndpointKind`] (entity/note/event/edge) rather than a
2242    /// full [`Resolved`] record — the `SubstrateCoordinator`'s cross-backend
2243    /// `locate_endpoint` resolves edge-substrate UUIDs too (matching `get`'s
2244    /// by-ID resolution order), but edges have no `Resolved` variant, so
2245    /// `validate_link_endpoints_by_resolved` cannot express them.
2246    ///
2247    /// `annotates` is the only relation this covers: source must be a note,
2248    /// target may be any substrate (entity, note, event, or edge).
2249    pub fn validate_annotates_endpoint_kinds(
2250        &self,
2251        source_id: Uuid,
2252        target_id: Uuid,
2253        source: Option<EdgeEndpointKind>,
2254        target: Option<EdgeEndpointKind>,
2255    ) -> RuntimeResult<()> {
2256        if source_id == target_id {
2257            return Err(RuntimeError::InvalidInput(
2258                "self-loop edges are not allowed: source_id and target_id must be different".into(),
2259            ));
2260        }
2261        match source {
2262            Some(EdgeEndpointKind::Note) => {}
2263            Some(_) => {
2264                return Err(RuntimeError::InvalidInput(format!(
2265                    "annotates source {source_id} must be a note"
2266                )));
2267            }
2268            None => {
2269                return Err(RuntimeError::NotFound(format!(
2270                    "link source {source_id} not found"
2271                )));
2272            }
2273        }
2274        if target.is_none() {
2275            return Err(RuntimeError::NotFound(format!(
2276                "link target {target_id} not found"
2277            )));
2278        }
2279        Ok(())
2280    }
2281
2282    /// Create a directed edge between two substrates.
2283    ///
2284    /// Enforces the three-case relation contract via
2285    /// `validate_edge_relation_endpoints`. See that method for the full contract.
2286    ///
2287    /// For symmetric relations (`competes_with`, `composed_with`) the endpoint
2288    /// pair is canonicalised to `source_uuid < target_uuid` so that A→B and B→A
2289    /// deduplicate to one row.
2290    ///
2291    /// `metadata` is validated against governed keys; `dependency_kind` is
2292    /// inferred for `depends_on` edges when absent.
2293    ///
2294    /// `target_backend` is always `None` for locally-routed edges written through
2295    /// this path. Both endpoints must exist in the local namespace, so setting
2296    /// `target_backend = None` is the only valid choice.
2297    ///
2298    /// Endpoint existence is a by-ID check and namespace-agnostic: a record
2299    /// that exists in a different namespace than the caller still resolves,
2300    /// exactly as `get()` would.
2301    pub async fn link(
2302        &self,
2303        token: &NamespaceToken,
2304        source_id: Uuid,
2305        target_id: Uuid,
2306        relation: EdgeRelation,
2307        weight: f64,
2308        metadata: Option<serde_json::Value>,
2309    ) -> RuntimeResult<Edge> {
2310        validate_edge_weight(weight)?;
2311        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
2312            .await?;
2313        let (source_id, target_id) = canonical_edge_endpoints(relation, source_id, target_id);
2314        let metadata = if relation == EdgeRelation::DependsOn {
2315            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
2316            // above. The visible-set-scoped `resolve` would silently drop the
2317            // dependency_kind inference for endpoints validation now allows outside
2318            // the caller's visible set.
2319            match (
2320                self.resolve_edge_endpoint(token, source_id).await?,
2321                self.resolve_edge_endpoint(token, target_id).await?,
2322            ) {
2323                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
2324                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
2325                }
2326                _ => metadata,
2327            }
2328        } else {
2329            metadata
2330        };
2331        validate_edge_metadata(relation, metadata.as_ref())?;
2332        let now = chrono::Utc::now();
2333        let ns = token.namespace().as_str();
2334        let edge = Edge {
2335            id: LinkId::from(Uuid::new_v4()),
2336            namespace: ns.to_string(),
2337            source_id,
2338            target_id,
2339            relation,
2340            weight,
2341            created_at: now,
2342            updated_at: now,
2343            deleted_at: None,
2344            metadata,
2345            target_backend: None,
2346        };
2347        // `upsert_edge_guarded` re-checks both endpoints exist as part of the same
2348        // write, not the separate `validate_edge_relation_endpoints` read above: a
2349        // concurrent hard-delete landing between that read and this write can no
2350        // longer create a durably dangling edge. Which endpoint(s) were missing is
2351        // reported by the guard's own in-transaction probe (`GuardedWriteOutcome::
2352        // Refused`), not reconstructed here by re-reading the endpoints after the
2353        // fact: a second concurrent write landing between the refusal and a
2354        // post-hoc read could otherwise misreport which endpoint was actually
2355        // missing at write time.
2356        match self.graph(token)?.upsert_edge_guarded(edge).await? {
2357            khive_storage::GuardedWriteOutcome::Written => {}
2358            khive_storage::GuardedWriteOutcome::Refused(missing) => {
2359                return Err(RuntimeError::GuardedWriteFailed(GuardedWriteFailure {
2360                    entry_index: None,
2361                    missing_source: missing.source.then_some(source_id),
2362                    missing_target: missing.target.then_some(target_id),
2363                }));
2364            }
2365        }
2366
2367        // Read back the persisted row by natural key so the returned
2368        // edge ID is always the one stored in the database, not the locally
2369        // generated UUID that was displaced by an ON CONFLICT DO UPDATE.
2370        // Under parallel calls for the same triple, every caller now returns
2371        // the same persisted edge ID — the winner's insert or the updated row.
2372        let persisted = self
2373            .list_edges(
2374                token,
2375                crate::curation::EdgeListFilter {
2376                    source_id: Some(source_id),
2377                    target_id: Some(target_id),
2378                    relations: vec![relation],
2379                    ..Default::default()
2380                },
2381                1,
2382                0,
2383            )
2384            .await?
2385            .into_iter()
2386            .next()
2387            .ok_or_else(|| {
2388                crate::RuntimeError::Internal(format!(
2389                    "upsert_edge succeeded but natural-key lookup for ({source_id}, {target_id}, {relation}) returned nothing"
2390                ))
2391            })?;
2392        Ok(persisted)
2393    }
2394
2395    /// Write an edge with an explicit `target_backend` stamp (ADR-029 D3).
2396    ///
2397    /// Called by the `SubstrateCoordinator` when source and target are on
2398    /// different backends. The coordinator validates endpoints before calling
2399    /// this method via [`Self::validate_link_endpoints`], so endpoint validation is
2400    /// skipped here. The edge is written on the source backend only.
2401    #[allow(clippy::too_many_arguments)]
2402    pub async fn link_with_target_backend(
2403        &self,
2404        token: &NamespaceToken,
2405        source_id: Uuid,
2406        target_id: Uuid,
2407        relation: EdgeRelation,
2408        weight: f64,
2409        metadata: Option<serde_json::Value>,
2410        target_backend: Option<String>,
2411    ) -> RuntimeResult<Edge> {
2412        validate_edge_weight(weight)?;
2413        let (source_id, target_id) = canonical_edge_endpoints(relation, source_id, target_id);
2414        validate_edge_metadata(relation, metadata.as_ref())?;
2415        let now = chrono::Utc::now();
2416        let ns = token.namespace().as_str();
2417        let edge = Edge {
2418            id: LinkId::from(Uuid::new_v4()),
2419            namespace: ns.to_string(),
2420            source_id,
2421            target_id,
2422            relation,
2423            weight,
2424            created_at: now,
2425            updated_at: now,
2426            deleted_at: None,
2427            metadata,
2428            target_backend,
2429        };
2430        self.graph(token)?.upsert_edge(edge).await?;
2431        let persisted = self
2432            .list_edges(
2433                token,
2434                crate::curation::EdgeListFilter {
2435                    source_id: Some(source_id),
2436                    target_id: Some(target_id),
2437                    relations: vec![relation],
2438                    ..Default::default()
2439                },
2440                1,
2441                0,
2442            )
2443            .await?
2444            .into_iter()
2445            .next()
2446            .ok_or_else(|| {
2447                crate::RuntimeError::Internal(format!(
2448                    "upsert_edge succeeded but natural-key lookup for ({source_id}, {target_id}, {relation}) returned nothing"
2449                ))
2450            })?;
2451        Ok(persisted)
2452    }
2453
2454    /// Returns `true` if `id` resolves to a live substrate record in the
2455    /// caller's visible namespace set.
2456    ///
2457    /// Covers entity, note, event (via `resolve`) and edge (via `get_edge_visible`).
2458    /// Only records that are accessible to the caller (primary or configured visible
2459    /// namespaces) return `true`; absent or foreign-invisible records return `false`.
2460    pub(crate) async fn substrate_exists_in_ns(
2461        &self,
2462        token: &NamespaceToken,
2463        id: Uuid,
2464    ) -> RuntimeResult<bool> {
2465        if self.resolve(token, id).await?.is_some() {
2466            return Ok(true);
2467        }
2468        match self.get_edge_visible(token, id).await {
2469            Ok(Some(_)) => Ok(true),
2470            Ok(None) | Err(RuntimeError::NotFound(_)) => Ok(false),
2471            Err(err) => Err(err),
2472        }
2473    }
2474
2475    /// Returns `true` if `id` resolves to a live substrate record, by ID, with
2476    /// no namespace filter.
2477    ///
2478    /// Used from `annotates` endpoint validation (`link` and `create`'s
2479    /// `annotates` targets), which consume a by-ID endpoint and so must follow
2480    /// the same namespace-agnostic by-ID contract as `get()`.
2481    pub(crate) async fn substrate_exists_by_id(
2482        &self,
2483        token: &NamespaceToken,
2484        id: Uuid,
2485    ) -> RuntimeResult<bool> {
2486        if self.resolve_edge_endpoint(token, id).await?.is_some() {
2487            return Ok(true);
2488        }
2489        match self.get_edge(token, id).await {
2490            Ok(Some(_)) => Ok(true),
2491            Ok(None) | Err(RuntimeError::NotFound(_)) => Ok(false),
2492            Err(err) => Err(err),
2493        }
2494    }
2495
2496    /// Get immediate neighbors of a node, optionally filtered by relation type.
2497    ///
2498    /// Pass `relations: Some(vec![EdgeRelation::Annotates])` to retrieve only
2499    /// annotation edges, enabling cross-substrate navigation.
2500    ///
2501    /// Symmetric relations (`competes_with`, `composed_with`) are stored
2502    /// with the canonical source as the lower UUID. Direction normalization is
2503    /// applied in `neighbors_with_query` so both callers see correct results.
2504    pub async fn neighbors(
2505        &self,
2506        token: &NamespaceToken,
2507        node_id: Uuid,
2508        direction: Direction,
2509        limit: Option<u32>,
2510        relations: Option<Vec<EdgeRelation>>,
2511    ) -> RuntimeResult<Vec<NeighborHit>> {
2512        self.neighbors_with_query(
2513            token,
2514            node_id,
2515            NeighborQuery {
2516                direction,
2517                relations,
2518                limit,
2519                min_weight: None,
2520            },
2521        )
2522        .await
2523    }
2524
2525    /// Get neighbors with full query control (includes `min_weight`).
2526    ///
2527    /// Applies symmetric-relation direction normalization: if the
2528    /// relations filter contains only symmetric relations the direction is
2529    /// overridden to `Both` so edges stored in canonical order are always found.
2530    ///
2531    /// Soft-deleted entity nodes are excluded from results unless the caller
2532    /// explicitly requested them (future: `include_deleted` flag; currently
2533    /// always false).
2534    pub async fn neighbors_with_query(
2535        &self,
2536        token: &NamespaceToken,
2537        node_id: Uuid,
2538        mut query: NeighborQuery,
2539    ) -> RuntimeResult<Vec<NeighborHit>> {
2540        if !self.substrate_exists_in_ns(token, node_id).await? {
2541            return Ok(Vec::new());
2542        }
2543
2544        query.direction =
2545            normalize_symmetric_direction(query.direction, query.relations.as_deref());
2546        let mut hits = Vec::new();
2547        for ns in token.visible_namespaces() {
2548            let temp = NamespaceToken::for_namespace(ns.clone());
2549            let mut ns_hits = self.graph(&temp)?.neighbors(node_id, query.clone()).await?;
2550            hits.append(&mut ns_hits);
2551        }
2552        hits.sort_by_key(|h| (h.node_id, h.edge_id));
2553        hits.dedup_by_key(|h| (h.node_id, h.edge_id));
2554        self.enrich_neighbor_hits(token, &mut hits).await;
2555        // Filter out soft-deleted entity nodes.
2556        let candidate_ids: Vec<Uuid> = hits.iter().map(|h| h.node_id).collect();
2557        let deleted = self.deleted_entity_ids(candidate_ids).await;
2558        if !deleted.is_empty() {
2559            hits.retain(|h| !deleted.contains(&h.node_id));
2560        }
2561        // Restore the weight-descending, node_id-ascending order the storage
2562        // layer established (khive-db graph.rs `ORDER BY weight DESC, node_id
2563        // ASC`) — the (node_id, edge_id) sort above exists only to make
2564        // `dedup_by_key` adjacent-comparable and otherwise discards it. This
2565        // ordering contract must hold at every call site of this op (context
2566        // and neighbors verb alike), for every direction.
2567        hits.sort_by(|a, b| {
2568            b.weight
2569                .partial_cmp(&a.weight)
2570                .unwrap_or(std::cmp::Ordering::Equal)
2571                .then(a.node_id.cmp(&b.node_id))
2572        });
2573        Ok(hits)
2574    }
2575
2576    /// Find live `annotates` edges targeting one record without applying a
2577    /// namespace predicate.
2578    ///
2579    /// This is the graph counterpart to the namespace-agnostic by-ID `get`
2580    /// contract (ADR-007 Rev 6). Multi-record neighbor traversal remains
2581    /// visibility-scoped; callers should use this only after resolving a live
2582    /// target through a by-ID operation.
2583    pub async fn annotation_neighbors_by_target_id(
2584        &self,
2585        target_id: Uuid,
2586    ) -> RuntimeResult<Vec<NeighborHit>> {
2587        let mut reader = self.sql().reader().await?;
2588        let rows = reader
2589            .query_all(SqlStatement {
2590                sql: "SELECT source_id, id, weight FROM graph_edges \
2591                      WHERE target_id = ?1 AND relation = ?2 AND deleted_at IS NULL \
2592                      ORDER BY weight DESC, source_id ASC"
2593                    .to_string(),
2594                params: vec![
2595                    SqlValue::Text(target_id.to_string()),
2596                    SqlValue::Text(EdgeRelation::Annotates.to_string()),
2597                ],
2598                label: Some("annotations.by_target_id_unfiltered".into()),
2599            })
2600            .await?;
2601
2602        rows.into_iter()
2603            .map(|row| {
2604                let parse_uuid = |name: &str| match row.get(name) {
2605                    Some(SqlValue::Text(value)) => Uuid::from_str(value).map_err(|error| {
2606                        RuntimeError::Internal(format!("graph_edges.{name} is not a UUID: {error}"))
2607                    }),
2608                    Some(value) => Err(RuntimeError::Internal(format!(
2609                        "graph_edges.{name} has unexpected SQL value {value:?}"
2610                    ))),
2611                    None => Err(RuntimeError::Internal(format!(
2612                        "graph_edges row missing {name}"
2613                    ))),
2614                };
2615                let weight = match row.get("weight") {
2616                    Some(SqlValue::Float(value)) => Ok(*value),
2617                    Some(value) => Err(RuntimeError::Internal(format!(
2618                        "graph_edges.weight has unexpected SQL value {value:?}"
2619                    ))),
2620                    None => Err(RuntimeError::Internal(
2621                        "graph_edges row missing weight".into(),
2622                    )),
2623                }?;
2624
2625                Ok(NeighborHit {
2626                    node_id: parse_uuid("source_id")?,
2627                    edge_id: parse_uuid("id")?,
2628                    relation: EdgeRelation::Annotates,
2629                    weight,
2630                    name: None,
2631                    kind: None,
2632                    entity_type: None,
2633                })
2634            })
2635            .collect()
2636    }
2637
2638    /// Get both-direction neighbors, each tagged with the direction (`Out`/
2639    /// `In`) it was found in, via a single storage query per visible
2640    /// namespace instead of two separate direction-scoped `neighbors_with_query`
2641    /// calls: halving the neighbor SELECT count for `context(direction="both")`
2642    /// expansion. `query.direction` is ignored: always both.
2643    ///
2644    /// Mirrors `neighbors_with_query`'s dedup/enrich/soft-delete-filter/order
2645    /// pipeline exactly, carrying the per-hit direction tag through unchanged.
2646    pub async fn neighbors_with_query_directed(
2647        &self,
2648        token: &NamespaceToken,
2649        node_id: Uuid,
2650        query: NeighborQuery,
2651    ) -> RuntimeResult<Vec<(NeighborHit, Direction)>> {
2652        if !self.substrate_exists_in_ns(token, node_id).await? {
2653            return Ok(Vec::new());
2654        }
2655
2656        let mut hits: Vec<DirectedNeighborHit> = Vec::new();
2657        for ns in token.visible_namespaces() {
2658            let temp = NamespaceToken::for_namespace(ns.clone());
2659            let mut ns_hits = self
2660                .graph(&temp)?
2661                .neighbors_both_directions(node_id, query.clone())
2662                .await?;
2663            hits.append(&mut ns_hits);
2664        }
2665        // Direction is part of the key (not just node_id/edge_id) so a
2666        // self-loop's Out row and In row — same node_id and edge_id, opposite
2667        // direction: sort adjacent but distinct and both survive dedup.
2668        hits.sort_by_key(|h| {
2669            (
2670                h.hit.node_id,
2671                h.hit.edge_id,
2672                direction_sort_rank(&h.direction),
2673            )
2674        });
2675        hits.dedup_by_key(|h| {
2676            (
2677                h.hit.node_id,
2678                h.hit.edge_id,
2679                direction_sort_rank(&h.direction),
2680            )
2681        });
2682
2683        let mut plain_hits: Vec<NeighborHit> = hits.iter().map(|h| h.hit.clone()).collect();
2684        self.enrich_neighbor_hits(token, &mut plain_hits).await;
2685        for (dh, enriched) in hits.iter_mut().zip(plain_hits) {
2686            dh.hit = enriched;
2687        }
2688
2689        // Filter out soft-deleted entity nodes.
2690        let candidate_ids: Vec<Uuid> = hits.iter().map(|h| h.hit.node_id).collect();
2691        let deleted = self.deleted_entity_ids(candidate_ids).await;
2692        if !deleted.is_empty() {
2693            hits.retain(|h| !deleted.contains(&h.hit.node_id));
2694        }
2695        // Same global weight-descending/node_id-ascending restore as
2696        // `neighbors_with_query`: the (node_id, edge_id, direction) sort above
2697        // exists only to make `dedup_by_key` adjacent-comparable.
2698        hits.sort_by(|a, b| {
2699            b.hit
2700                .weight
2701                .partial_cmp(&a.hit.weight)
2702                .unwrap_or(std::cmp::Ordering::Equal)
2703                .then(a.hit.node_id.cmp(&b.hit.node_id))
2704        });
2705        Ok(hits.into_iter().map(|h| (h.hit, h.direction)).collect())
2706    }
2707
2708    /// Traverse the graph from a set of root nodes.
2709    ///
2710    /// Roots in a foreign namespace are silently filtered before storage expansion.
2711    /// Soft-deleted entity nodes are excluded from results.
2712    pub async fn traverse(
2713        &self,
2714        token: &NamespaceToken,
2715        request: TraversalRequest,
2716    ) -> RuntimeResult<Vec<GraphPath>> {
2717        let mut request = request;
2718        request.validate().map_err(RuntimeError::InvalidInput)?;
2719        let mut visible_roots = Vec::with_capacity(request.roots.len());
2720        let mut seen_roots = std::collections::HashSet::with_capacity(request.roots.len());
2721        for root in request.roots.drain(..) {
2722            if seen_roots.insert(root) && self.substrate_exists_in_ns(token, root).await? {
2723                visible_roots.push(root);
2724            }
2725        }
2726        request.roots = visible_roots;
2727        if request.roots.is_empty() {
2728            return Ok(Vec::new());
2729        }
2730
2731        let mut paths = Vec::new();
2732        for ns in token.visible_namespaces() {
2733            let temp = NamespaceToken::for_namespace(ns.clone());
2734            let mut ns_paths = self.graph(&temp)?.traverse(request.clone()).await?;
2735            paths.append(&mut ns_paths);
2736        }
2737        // Reconcile the per-namespace GraphPaths back down to one per
2738        // distinct root_id (see merge_traversal_paths_by_root for why this
2739        // is needed and what it enforces).
2740        let mut paths =
2741            merge_traversal_paths_by_root(paths, Some(request.options.effective_limit()));
2742        self.enrich_path_nodes(token, &mut paths, request.include_properties)
2743            .await;
2744        // Filter out soft-deleted entity nodes from all path nodes.
2745        let all_node_ids: Vec<Uuid> = paths
2746            .iter()
2747            .flat_map(|p| p.nodes.iter().map(|n| n.node_id))
2748            .collect();
2749        let deleted = self.deleted_entity_ids(all_node_ids).await;
2750        if !deleted.is_empty() {
2751            for path in paths.iter_mut() {
2752                path.nodes.retain(|n| !deleted.contains(&n.node_id));
2753                recompute_total_weight(path);
2754            }
2755            paths.retain(|p| !p.nodes.is_empty());
2756        }
2757        Ok(paths)
2758    }
2759
2760    /// Batch-query for soft-deleted UUIDs in `ids`, across BOTH the entities
2761    /// and notes tables.
2762    ///
2763    /// Neighbor/traverse candidates can be note-kind nodes (e.g. reached via
2764    /// `annotates` edges) as well as entities; a screen that only consults
2765    /// `entities` lets soft-deleted note targets leak through and hydrate as
2766    /// blank/missing hits. This is a view-layer read-only screen: it does
2767    /// not touch edges or mutate any data.
2768    ///
2769    /// Returns the subset of `ids` that have `deleted_at IS NOT NULL` in
2770    /// either table. Takes `Vec<Uuid>` (not an iterator) so the async state
2771    /// machine holds only owned data — no iterator borrow across yields.
2772    async fn deleted_entity_ids(&self, ids: Vec<Uuid>) -> std::collections::HashSet<Uuid> {
2773        if ids.is_empty() {
2774            return std::collections::HashSet::new();
2775        }
2776        let id_strs: Vec<String> = ids.iter().map(|u| u.to_string()).collect();
2777        let n = id_strs.len();
2778        // Each UNION half gets its OWN numbered-placeholder block (?1..?n for
2779        // entities, ?(n+1)..?(2n) for notes) — numbered SQLite params bind by
2780        // index, so reusing the same numbers across halves would silently
2781        // collapse to a single shared block instead of binding the full list
2782        // twice (see khive-db/src/stores/graph.rs batch_neighbors: "each half
2783        // is a fully independent positional-parameter block").
2784        let entities_placeholders = (0..n)
2785            .map(|i| format!("?{}", i + 1))
2786            .collect::<Vec<_>>()
2787            .join(",");
2788        let notes_placeholders = (0..n)
2789            .map(|i| format!("?{}", n + i + 1))
2790            .collect::<Vec<_>>()
2791            .join(",");
2792        let sql_str = format!(
2793            "SELECT id FROM entities WHERE id IN ({entities_placeholders}) AND deleted_at IS NOT NULL \
2794             UNION \
2795             SELECT id FROM notes WHERE id IN ({notes_placeholders}) AND deleted_at IS NOT NULL"
2796        );
2797        // Same id list bound twice — once per UNION arm's independent placeholder block.
2798        let params: Vec<SqlValue> = id_strs
2799            .iter()
2800            .chain(id_strs.iter())
2801            .cloned()
2802            .map(SqlValue::Text)
2803            .collect();
2804        let stmt = SqlStatement {
2805            sql: sql_str,
2806            params,
2807            label: Some("deleted_entity_ids".into()),
2808        };
2809        let mut out = std::collections::HashSet::new();
2810        let sql = self.sql();
2811        if let Ok(mut reader) = sql.reader().await {
2812            if let Ok(rows) = reader.query_all(stmt).await {
2813                for row in rows {
2814                    if let Some(col) = row.columns.first() {
2815                        if let SqlValue::Text(s) = &col.value {
2816                            if let Ok(u) = s.parse::<Uuid>() {
2817                                out.insert(u);
2818                            }
2819                        }
2820                    }
2821                }
2822            }
2823            // best-effort: on reader or query error, treat none as deleted
2824        }
2825        out
2826    }
2827
2828    /// Populate `name` and `kind` on each `NeighborHit` from the corresponding
2829    /// entity or note record. Best-effort: unresolved IDs leave the fields `None`.
2830    ///
2831    /// Uses a single batched entity lookup via `get_entities_by_ids_visible`
2832    /// (scoped to the token's full visible-namespace set so that neighbors in
2833    /// extra-visible namespaces are enriched), then a batched note lookup
2834    /// (`get_notes_batch`) for the residual IDs not resolved as entities.
2835    /// Order and identity of hits is preserved via `HashMap` re-index.
2836    async fn enrich_neighbor_hits(&self, token: &NamespaceToken, hits: &mut [NeighborHit]) {
2837        if hits.is_empty() {
2838            return;
2839        }
2840
2841        // Deduplicated IDs for the batch call.
2842        let unique_ids: Vec<Uuid> = {
2843            let mut seen = std::collections::HashSet::new();
2844            hits.iter()
2845                .filter_map(|h| {
2846                    if seen.insert(h.node_id) {
2847                        Some(h.node_id)
2848                    } else {
2849                        None
2850                    }
2851                })
2852                .collect()
2853        };
2854
2855        let entity_map: HashMap<Uuid, Entity> = self
2856            .get_entities_by_ids_visible(token, &unique_ids)
2857            .await
2858            .unwrap_or_default()
2859            .into_iter()
2860            .map(|e| (e.id, e))
2861            .collect();
2862
2863        // Batch note lookup for IDs not found as entities.
2864        let residual_ids: Vec<Uuid> = unique_ids
2865            .iter()
2866            .filter(|id| !entity_map.contains_key(id))
2867            .copied()
2868            .collect();
2869
2870        let note_map: HashMap<Uuid, Note> = if !residual_ids.is_empty() {
2871            if let Ok(store) = self.notes(token) {
2872                store
2873                    .get_notes_batch(&residual_ids)
2874                    .await
2875                    .unwrap_or_default()
2876                    .into_iter()
2877                    .map(|n| (n.id, n))
2878                    .collect()
2879            } else {
2880                HashMap::new()
2881            }
2882        } else {
2883            HashMap::new()
2884        };
2885
2886        for hit in hits.iter_mut() {
2887            if let Some(entity) = entity_map.get(&hit.node_id) {
2888                hit.name = Some(entity.name.clone());
2889                hit.kind = Some(entity.kind.clone());
2890                hit.entity_type = entity.entity_type.clone();
2891            } else if let Some(note) = note_map.get(&hit.node_id) {
2892                hit.name = Some(note_graph_name(note));
2893                hit.kind = Some(note.kind.clone());
2894            }
2895        }
2896    }
2897
2898    /// Populate `name` and `kind` on each `PathNode` from the corresponding
2899    /// entity or note record. Same best-effort policy as `enrich_neighbor_hits`.
2900    ///
2901    /// Uses `get_entities_by_ids_visible` so that path nodes whose entities
2902    /// live in extra-visible namespaces are enriched correctly. Node IDs that
2903    /// repeat across paths are fetched exactly once.
2904    ///
2905    /// `include_properties` gates whether `entity.properties` is cloned onto
2906    /// each node. When `false` (the default), the potentially large JSON blob
2907    /// is never read from the map, keeping the hot path allocation-free.
2908    async fn enrich_path_nodes(
2909        &self,
2910        token: &NamespaceToken,
2911        paths: &mut [GraphPath],
2912        include_properties: bool,
2913    ) {
2914        if paths.is_empty() {
2915            return;
2916        }
2917
2918        // Deduplicate node IDs across all paths before the batch call.
2919        let unique_ids: Vec<Uuid> = {
2920            let mut seen = std::collections::HashSet::new();
2921            paths
2922                .iter()
2923                .flat_map(|p| p.nodes.iter())
2924                .filter_map(|n| {
2925                    if seen.insert(n.node_id) {
2926                        Some(n.node_id)
2927                    } else {
2928                        None
2929                    }
2930                })
2931                .collect()
2932        };
2933
2934        let entity_map: HashMap<Uuid, Entity> = self
2935            .get_entities_by_ids_visible(token, &unique_ids)
2936            .await
2937            .unwrap_or_default()
2938            .into_iter()
2939            .map(|e| (e.id, e))
2940            .collect();
2941
2942        let residual_ids: Vec<Uuid> = unique_ids
2943            .iter()
2944            .filter(|id| !entity_map.contains_key(id))
2945            .copied()
2946            .collect();
2947
2948        let note_map: HashMap<Uuid, Note> = if !residual_ids.is_empty() {
2949            if let Ok(store) = self.notes(token) {
2950                store
2951                    .get_notes_batch(&residual_ids)
2952                    .await
2953                    .unwrap_or_default()
2954                    .into_iter()
2955                    .map(|n| (n.id, n))
2956                    .collect()
2957            } else {
2958                HashMap::new()
2959            }
2960        } else {
2961            HashMap::new()
2962        };
2963
2964        for path in paths.iter_mut() {
2965            for node in path.nodes.iter_mut() {
2966                if let Some(entity) = entity_map.get(&node.node_id) {
2967                    node.name = Some(entity.name.clone());
2968                    node.kind = Some(entity.kind.clone());
2969                    if include_properties {
2970                        node.properties = entity.properties.clone();
2971                    }
2972                } else if let Some(note) = note_map.get(&node.node_id) {
2973                    node.name = Some(note_graph_name(note));
2974                    node.kind = Some(note.kind.clone());
2975                }
2976            }
2977        }
2978    }
2979
2980    // ---- Note operations ----
2981
2982    /// Create and persist a note, optionally with properties and annotation targets.
2983    ///
2984    /// After creating the note:
2985    /// - Always indexes into FTS5 at the `notes_<namespace>` key.
2986    /// - If an embedding model is configured, indexes into the vector store with
2987    ///   `SubstrateKind::Note`.
2988    /// - For each UUID in `annotates`, creates an `EdgeRelation::Annotates` edge from
2989    ///   the note to that target.
2990    // REASON: note creation requires kind, name, content, salience, properties, annotates,
2991    // and namespace token — mirrors the MCP verb surface; a builder would not reduce
2992    // caller complexity for pack handler callers.
2993    #[allow(clippy::too_many_arguments)]
2994    pub async fn create_note(
2995        &self,
2996        token: &NamespaceToken,
2997        kind: &str,
2998        name: Option<&str>,
2999        content: &str,
3000        salience: Option<f64>,
3001        properties: Option<serde_json::Value>,
3002        annotates: Vec<Uuid>,
3003    ) -> RuntimeResult<Note> {
3004        Ok(self
3005            .create_note_inner(
3006                token, kind, name, content, None, salience, None, properties, annotates, None,
3007            )
3008            .await?
3009            .0)
3010    }
3011
3012    /// Like [`Self::create_note`], but lets the caller supply a smaller text
3013    /// to send to the vector embedder while the note's stored/FTS-indexed
3014    /// `content` remains the full text.
3015    ///
3016    /// `embedding_content`, when `Some`, must be non-empty and a proper
3017    /// prefix of `content` — anything else is rejected with `InvalidInput`
3018    /// before any write. `None` behaves exactly like [`Self::create_note`].
3019    /// Use this when `content` may exceed an embedder's input cap (e.g. a
3020    /// very long commit message) and only a capped head prefix should be
3021    /// embedded, while the full text is still stored and searchable via FTS.
3022    #[allow(clippy::too_many_arguments)]
3023    pub async fn create_note_with_embedding_content(
3024        &self,
3025        token: &NamespaceToken,
3026        kind: &str,
3027        name: Option<&str>,
3028        content: &str,
3029        embedding_content: Option<&str>,
3030        salience: Option<f64>,
3031        properties: Option<serde_json::Value>,
3032        annotates: Vec<Uuid>,
3033    ) -> RuntimeResult<Note> {
3034        Ok(self
3035            .create_note_inner(
3036                token,
3037                kind,
3038                name,
3039                content,
3040                embedding_content,
3041                salience,
3042                None,
3043                properties,
3044                annotates,
3045                None,
3046            )
3047            .await?
3048            .0)
3049    }
3050
3051    #[allow(clippy::too_many_arguments)]
3052    pub async fn create_note_with_embedding_content_and_report(
3053        &self,
3054        token: &NamespaceToken,
3055        kind: &str,
3056        name: Option<&str>,
3057        content: &str,
3058        embedding_content: Option<&str>,
3059        salience: Option<f64>,
3060        properties: Option<serde_json::Value>,
3061        annotates: Vec<Uuid>,
3062    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
3063        self.create_note_inner(
3064            token,
3065            kind,
3066            name,
3067            content,
3068            embedding_content,
3069            salience,
3070            None,
3071            properties,
3072            annotates,
3073            None,
3074        )
3075        .await
3076    }
3077
3078    /// Like [`Self::create_note`] but also sets a non-zero decay factor on the note.
3079    // REASON: extends create_note with an additional decay_factor parameter; same
3080    // rationale — mirrors the MCP surface and reduces an extra builder layer.
3081    #[allow(clippy::too_many_arguments)]
3082    pub async fn create_note_with_decay(
3083        &self,
3084        token: &NamespaceToken,
3085        kind: &str,
3086        name: Option<&str>,
3087        content: &str,
3088        salience: Option<f64>,
3089        decay_factor: f64,
3090        properties: Option<serde_json::Value>,
3091        annotates: Vec<Uuid>,
3092    ) -> RuntimeResult<Note> {
3093        self.create_note_with_decay_for_embedding_model(
3094            token,
3095            kind,
3096            name,
3097            content,
3098            salience,
3099            decay_factor,
3100            properties,
3101            annotates,
3102            None,
3103        )
3104        .await
3105    }
3106
3107    /// Like [`Self::create_note_with_decay`] but targets a specific embedding model.
3108    // REASON: adds an embedding_model parameter to the decay variant; the full parameter
3109    // set is required for correct MCP verb routing and cannot be collapsed without
3110    // introducing a separate config struct that would obscure call sites.
3111    #[allow(clippy::too_many_arguments)]
3112    pub async fn create_note_with_decay_for_embedding_model(
3113        &self,
3114        token: &NamespaceToken,
3115        kind: &str,
3116        name: Option<&str>,
3117        content: &str,
3118        salience: Option<f64>,
3119        decay_factor: f64,
3120        properties: Option<serde_json::Value>,
3121        annotates: Vec<Uuid>,
3122        embedding_model: Option<&str>,
3123    ) -> RuntimeResult<Note> {
3124        Ok(self
3125            .create_note_inner(
3126                token,
3127                kind,
3128                name,
3129                content,
3130                None,
3131                salience,
3132                Some(decay_factor),
3133                properties,
3134                annotates,
3135                embedding_model,
3136            )
3137            .await?
3138            .0)
3139    }
3140
3141    /// Insert a note using `INSERT OR IGNORE` semantics for atomic deduplication.
3142    ///
3143    /// Returns `Ok(Some(note))` when the note was newly written.  Returns
3144    /// `Ok(None)` when a unique constraint (e.g. the `external_id` partial
3145    /// index on comm message notes) was already satisfied by an existing row,
3146    /// making this call a no-op.  FTS indexing and vector embedding are
3147    /// attempted on success but treated as best-effort: failures are logged
3148    /// and do not abort the write.
3149    ///
3150    /// This method is intentionally narrower than `create_note`: it skips
3151    /// salience/decay, annotates edges, and embedding-model selection, which
3152    /// are not needed for channel-ingest paths.
3153    pub async fn try_create_note(
3154        &self,
3155        token: &NamespaceToken,
3156        kind: &str,
3157        name: Option<&str>,
3158        content: &str,
3159        properties: Option<serde_json::Value>,
3160    ) -> RuntimeResult<Option<Note>> {
3161        self.validate_note_kind(kind)?;
3162        crate::secret_gate::check(content)?;
3163        if let Some(n) = name {
3164            crate::secret_gate::check(n)?;
3165        }
3166        if let Some(ref p) = properties {
3167            crate::secret_gate::check_json(p)?;
3168        }
3169
3170        let ns = token.namespace().as_str();
3171        let mut note = Note::new(ns, kind, content);
3172        if let Some(n) = name {
3173            note = note.with_name(n);
3174        }
3175        if let Some(p) = properties {
3176            note = note.with_properties(p);
3177        }
3178
3179        let inserted = self.notes(token)?.try_insert_note(note.clone()).await?;
3180        if !inserted {
3181            return Ok(None);
3182        }
3183
3184        // Best-effort FTS: log and continue on failure.
3185        if let Ok(fts) = self.text_for_notes(token) {
3186            if let Err(e) = fts.upsert_document(note_fts_document(&note)).await {
3187                tracing::warn!(
3188                    note_id = %note.id,
3189                    error = %e,
3190                    "try_create_note: FTS indexing failed (non-fatal)"
3191                );
3192            }
3193        }
3194
3195        // Best-effort vector embedding: log and continue on failure.
3196        let embed_model_names = self.registered_embedding_model_names();
3197        for model_name in &embed_model_names {
3198            match self
3199                .embed_document_with_model_outcome_for_token(
3200                    token,
3201                    model_name,
3202                    &note_embedding_text(&note),
3203                )
3204                .await
3205            {
3206                Ok(outcome) => {
3207                    if outcome.truncated {
3208                        tracing::warn!(
3209                            note_id = %note.id,
3210                            model = %outcome.model_name,
3211                            source_bytes = outcome.source_bytes,
3212                            embedded_bytes = outcome.embedded_bytes,
3213                            "try_create_note: embedding input truncated; full content stored unchanged"
3214                        );
3215                    }
3216                    if let Ok(vs) = self.vectors_for_model(token, model_name) {
3217                        if let Err(e) = vs
3218                            .insert(
3219                                note.id,
3220                                SubstrateKind::Note,
3221                                ns,
3222                                "note.content",
3223                                vec![outcome.vector],
3224                            )
3225                            .await
3226                        {
3227                            tracing::warn!(
3228                                note_id = %note.id,
3229                                model = %model_name,
3230                                error = %e,
3231                                "try_create_note: vector insert failed (non-fatal)"
3232                            );
3233                        }
3234                    }
3235                }
3236                Err(e) => {
3237                    tracing::warn!(
3238                        note_id = %note.id,
3239                        model = %model_name,
3240                        error = %e,
3241                        "try_create_note: embedding failed (non-fatal)"
3242                    );
3243                }
3244            }
3245        }
3246
3247        Ok(Some(note))
3248    }
3249
3250    // REASON: private inner function unifies all create_note variants; it receives every
3251    // optional parameter individually so that public variants can pass None without
3252    // requiring callers to construct an intermediate struct.
3253    #[allow(clippy::too_many_arguments)]
3254    async fn create_note_inner(
3255        &self,
3256        token: &NamespaceToken,
3257        kind: &str,
3258        name: Option<&str>,
3259        content: &str,
3260        embedding_content: Option<&str>,
3261        salience: Option<f64>,
3262        decay_factor: Option<f64>,
3263        properties: Option<serde_json::Value>,
3264        annotates: Vec<Uuid>,
3265        embedding_model: Option<&str>,
3266    ) -> RuntimeResult<(Note, crate::retrieval::EmbeddingTruncationReport)> {
3267        self.validate_note_kind(kind)?;
3268        // Secret gate: scan content, optional name, and structured properties.
3269        crate::secret_gate::check(content)?;
3270        if let Some(n) = name {
3271            crate::secret_gate::check(n)?;
3272        }
3273        if let Some(ref p) = properties {
3274            crate::secret_gate::check_json(p)?;
3275        }
3276        // `embedding_content` is a caller-supplied alternate vector-embedding
3277        // input: it must be a non-empty proper prefix of `content` (never a
3278        // superset, an unrelated string, or the full text) and passes the
3279        // same secret gate as any other stored/embedded text. Rejected
3280        // before any write, same as the checks above.
3281        if let Some(ec) = embedding_content {
3282            if ec.is_empty() {
3283                return Err(RuntimeError::InvalidInput(
3284                    "embedding_content must not be empty".into(),
3285                ));
3286            }
3287            if ec.len() >= content.len() || !content.starts_with(ec) {
3288                return Err(RuntimeError::InvalidInput(
3289                    "embedding_content must be a proper prefix of content".into(),
3290                ));
3291            }
3292            crate::secret_gate::check(ec)?;
3293        }
3294        let ns = token.namespace().as_str();
3295
3296        // Validate all annotates targets before any write (atomicity: all-or-nothing).
3297        // Endpoint resolution is by-ID and namespace-agnostic.
3298        for &target_id in &annotates {
3299            if !self.substrate_exists_by_id(token, target_id).await? {
3300                return Err(RuntimeError::NotFound(format!(
3301                    "create_note annotates target {target_id} not found"
3302                )));
3303            }
3304        }
3305
3306        // Reject non-finite or out-of-range salience/decay at the runtime boundary
3307        // rather than letting storage silently clamp them (coding-standards §508-516).
3308        if let Some(s) = salience {
3309            if !s.is_finite() || !(0.0..=1.0).contains(&s) {
3310                return Err(RuntimeError::InvalidInput(format!(
3311                    "salience must be a finite value in [0.0, 1.0]; got {s}"
3312                )));
3313            }
3314        }
3315        if let Some(d) = decay_factor {
3316            if !d.is_finite() || d < 0.0 {
3317                return Err(RuntimeError::InvalidInput(format!(
3318                    "decay_factor must be a finite value >= 0.0; got {d}"
3319                )));
3320            }
3321        }
3322
3323        // Resolve embedding_model BEFORE any note/FTS/vector write so unknown-model
3324        // errors are atomic at the runtime layer, not just at one pack handler.
3325        // Direct Rust callers (other packs, integration tests) get the same guarantee.
3326        if let Some(model_name) = embedding_model {
3327            self.resolve_embedding_model(Some(model_name))?;
3328        }
3329
3330        let mut note = Note::new(ns, kind, content);
3331        if let Some(s) = salience {
3332            note = note.with_salience(s);
3333        }
3334        if let Some(df) = decay_factor {
3335            note = note.with_decay(df);
3336        }
3337        if let Some(n) = name {
3338            note = note.with_name(n);
3339        }
3340        if let Some(p) = properties {
3341            note = note.with_properties(p);
3342        }
3343        self.notes(token)?.upsert_note(note.clone()).await?;
3344
3345        // From here on, any error must compensate by removing the note row, its
3346        // FTS document, and any vector entries already inserted — the same
3347        // cleanup used by the annotates-edge block below.
3348
3349        // Decide which embedding models to use (before touching FTS/vectors).
3350        let embed_model_names: Vec<String> = if let Some(m) = embedding_model {
3351            vec![m.to_string()]
3352        } else {
3353            // Fan out to ALL registered models — includes both lattice models
3354            // from RuntimeConfig and any custom providers added via
3355            // register_embedder(). Gate on the registry, not
3356            // config().embedding_model, so that custom-only runtimes (no
3357            // lattice model in config) also fan out.
3358            let names = self.registered_embedding_model_names();
3359            if names.is_empty() {
3360                // No models configured at all — skip vector embedding.
3361                vec![]
3362            } else {
3363                names
3364            }
3365        };
3366
3367        // FTS step — compensate note row on failure.
3368        {
3369            // Injection: check FTS_FAIL_NS (armed by `arm_fts_fail_scoped(ns)`).
3370            // Fires only when `ns` is in the armed set, removing it on the way
3371            // out (one-shot, atomic check-and-remove under the mutex). No lock
3372            // acquisition in release builds — the cfg(not) branch is a const
3373            // false so the compiler eliminates the if-branch entirely.
3374            #[cfg(any(test, feature = "fault-injection"))]
3375            let fts_inject = consume_fault(&FTS_FAIL_NS, ns);
3376            #[cfg(not(any(test, feature = "fault-injection")))]
3377            let fts_inject = false;
3378            let fts_result: RuntimeResult<()> = if fts_inject {
3379                Err(RuntimeError::Internal("injected FTS failure".to_string()))
3380            } else {
3381                match self.text_for_notes(token) {
3382                    Ok(fts) => fts
3383                        .upsert_document(note_fts_document(&note))
3384                        .await
3385                        .map_err(RuntimeError::from),
3386                    Err(e) => Err(e),
3387                }
3388            };
3389
3390            if let Err(e) = fts_result {
3391                // Best-effort compensation — ignore cleanup errors.
3392                if let Ok(store) = self.notes(token) {
3393                    let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3394                }
3395                return Err(e);
3396            }
3397        }
3398
3399        // Vector embedding + insert step — compensate note row + FTS doc on failure.
3400        // Multi-model vector embedding:
3401        //   - explicit embedding_model → single model (existing behaviour)
3402        //   - None + any models registered → ALL registered models in parallel
3403        //   - None + no models configured → skip (text-only)
3404        // The effective text sent to every embedder: the caller-supplied
3405        // capped override when present, otherwise the full stored content.
3406        // FTS indexing above always used the full `note.content` — this cap
3407        // affects only the vector-embedding input.
3408        let canonical_embed_text = note_embedding_text(&note);
3409        let embed_text: &str = embedding_content.unwrap_or(&canonical_embed_text);
3410
3411        let mut embedding_report = crate::retrieval::EmbeddingTruncationReport::default();
3412        if embed_model_names.len() == 1 {
3413            // Single-model path: preserves original sequential behaviour.
3414            let model_name = &embed_model_names[0];
3415            let vec_result = self
3416                .embed_document_with_model_outcome_for_token(token, model_name, embed_text)
3417                .await;
3418
3419            // Injection: check VECTOR_FAIL_NS (armed by `arm_vector_fail_scoped(ns)`) or
3420            // VECTOR_FAIL_AFTER (armed by `arm_vector_fail_after(n)`). The former
3421            // fires only when the armed namespace matches this note's namespace;
3422            // callers that cannot guarantee no concurrently-running test also
3423            // writes a note into that same namespace (e.g. a test suite whose
3424            // fixtures share one default namespace) should prefer the latter,
3425            // thread-local count instead — see its doc comment. Either clears
3426            // (one-shot) once it fires. No lock/cell access in release builds —
3427            // the cfg(not) branch is a const false eliminating the if-branch.
3428            #[cfg(any(test, feature = "fault-injection"))]
3429            let vec_inject = {
3430                let ns_inject = consume_fault(&VECTOR_FAIL_NS, ns);
3431                let count_inject = VECTOR_FAIL_AFTER.with(|cell| match cell.get() {
3432                    Some(0) => {
3433                        cell.set(None);
3434                        true
3435                    }
3436                    Some(n) => {
3437                        cell.set(Some(n - 1));
3438                        false
3439                    }
3440                    None => false,
3441                });
3442                ns_inject || count_inject
3443            };
3444            #[cfg(not(any(test, feature = "fault-injection")))]
3445            let vec_inject = false;
3446            let vec_result: RuntimeResult<crate::retrieval::DocumentEmbeddingOutcome> =
3447                if vec_inject {
3448                    Err(RuntimeError::Internal(
3449                        "injected vector failure".to_string(),
3450                    ))
3451                } else {
3452                    vec_result
3453                };
3454
3455            let single_model_result: RuntimeResult<()> = match vec_result {
3456                Ok(outcome) => {
3457                    embedding_report.observe(&outcome);
3458                    match self.vectors_for_model(token, model_name) {
3459                        Ok(vs) => vs
3460                            .insert(
3461                                note.id,
3462                                SubstrateKind::Note,
3463                                ns,
3464                                "note.content",
3465                                vec![outcome.vector],
3466                            )
3467                            .await
3468                            .map_err(RuntimeError::from),
3469                        Err(e) => Err(e),
3470                    }
3471                }
3472                Err(e) => Err(e),
3473            };
3474            if let Err(e) = single_model_result {
3475                // Compensate note row + FTS.
3476                if let Ok(store) = self.notes(token) {
3477                    let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3478                }
3479                if let Ok(fts) = self.text_for_notes(token) {
3480                    let _ = fts.delete_document(ns, note.id).await;
3481                }
3482                return Err(e);
3483            }
3484        } else if !embed_model_names.is_empty() {
3485            // Multi-model path: embed with each model in parallel via spawned tasks,
3486            // then insert one VectorRecord per model.
3487            let rt_clone = self.clone();
3488            let content_owned = embed_text.to_string();
3489            let usage_ctx = crate::usage::current();
3490            let mut join_set = tokio::task::JoinSet::new();
3491            for (idx, model_name) in embed_model_names.iter().enumerate() {
3492                let rt = rt_clone.clone();
3493                let text = content_owned.clone();
3494                let name = model_name.clone();
3495                let ctx = usage_ctx.clone();
3496                let token = (*token).clone();
3497                join_set.spawn(async move {
3498                    let fut = rt.embed_document_with_model_outcome_for_token(&token, &name, &text);
3499                    let result = match ctx {
3500                        Some(ctx) => crate::usage::scope(ctx, fut).await,
3501                        None => fut.await,
3502                    };
3503                    (idx, result)
3504                });
3505            }
3506            // The first failed or panicked handle aborts and detaches its
3507            // siblings. Embed usage is counted at dispatch, so a synchronous
3508            // provider winding down in the background cannot change it.
3509            let outcomes = match drain_embed_join_set(join_set, embed_model_names.len()).await {
3510                Ok(outcomes) => outcomes,
3511                Err(e) => {
3512                    // Compensate note row + FTS (no vectors inserted yet).
3513                    if let Ok(store) = self.notes(token) {
3514                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3515                    }
3516                    if let Ok(fts) = self.text_for_notes(token) {
3517                        let _ = fts.delete_document(ns, note.id).await;
3518                    }
3519                    return Err(e);
3520                }
3521            };
3522            // TODO(P2): parallelize vector inserts
3523            let mut inserted_models: Vec<String> = Vec::with_capacity(embed_model_names.len());
3524            for (model_name, outcome) in embed_model_names.iter().zip(outcomes) {
3525                embedding_report.observe(&outcome);
3526                let insert_result = match self.vectors_for_model(token, model_name) {
3527                    Ok(vs) => vs
3528                        .insert(
3529                            note.id,
3530                            SubstrateKind::Note,
3531                            ns,
3532                            "note.content",
3533                            vec![outcome.vector],
3534                        )
3535                        .await
3536                        .map_err(RuntimeError::from),
3537                    Err(e) => Err(e),
3538                };
3539                if let Err(e) = insert_result {
3540                    // Compensate note row + FTS + already-inserted vectors.
3541                    if let Ok(store) = self.notes(token) {
3542                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3543                    }
3544                    if let Ok(fts) = self.text_for_notes(token) {
3545                        let _ = fts.delete_document(ns, note.id).await;
3546                    }
3547                    for m in &inserted_models {
3548                        if let Ok(vs) = self.vectors_for_model(token, m) {
3549                            let _ = vs.delete(note.id).await;
3550                        }
3551                    }
3552                    return Err(e);
3553                }
3554                inserted_models.push(model_name.clone());
3555            }
3556        }
3557
3558        // Create annotates edges, compensating on failure to preserve atomicity.
3559        //
3560        // Pre-validation (above) ensures all targets exist, so link failures are
3561        // unexpected. If one occurs: delete any edges already created, then remove
3562        // the note, its FTS document, and its vector entry.
3563        let mut created_edges: Vec<Uuid> = Vec::with_capacity(annotates.len());
3564
3565        // In test builds, iterate with an index so the failure-injection hook can
3566        // target a specific call.  In release builds, skip the enumerate overhead.
3567        #[cfg(test)]
3568        let annotates_iter: Vec<(usize, Uuid)> = annotates
3569            .iter()
3570            .enumerate()
3571            .map(|(i, &id)| (i, id))
3572            .collect();
3573        #[cfg(test)]
3574        macro_rules! next_target {
3575            ($pair:expr) => {
3576                $pair.1
3577            };
3578        }
3579        #[cfg(not(test))]
3580        let annotates_iter: Vec<Uuid> = annotates.to_vec();
3581        #[cfg(not(test))]
3582        macro_rules! next_target {
3583            ($pair:expr) => {
3584                $pair
3585            };
3586        }
3587
3588        for pair in annotates_iter {
3589            let target_id = next_target!(pair);
3590
3591            // Test-only: inject a failure on the configured call index (1-based).
3592            #[cfg(test)]
3593            let injected_err: Option<RuntimeError> = {
3594                let call_idx = pair.0;
3595                LINK_FAIL_AFTER.with(|cell| {
3596                    let n = cell.get();
3597                    if n > 0 && call_idx + 1 == n {
3598                        cell.set(0); // reset so subsequent calls are unaffected
3599                        Some(RuntimeError::Internal("injected link failure".to_string()))
3600                    } else {
3601                        None
3602                    }
3603                })
3604            };
3605            #[cfg(not(test))]
3606            let injected_err: Option<RuntimeError> = None;
3607
3608            let link_result = if let Some(e) = injected_err {
3609                Err(e)
3610            } else {
3611                self.link(
3612                    token,
3613                    note.id,
3614                    target_id,
3615                    EdgeRelation::Annotates,
3616                    1.0,
3617                    None,
3618                )
3619                .await
3620            };
3621
3622            match link_result {
3623                Ok(edge) => created_edges.push(edge.id.into()),
3624                Err(e) => {
3625                    // Best-effort compensation — ignore cleanup errors.
3626                    for edge_id in created_edges {
3627                        let _ = self.delete_edge(token, edge_id, true).await;
3628                    }
3629                    if let Ok(store) = self.notes(token) {
3630                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
3631                    }
3632                    if let Ok(fts) = self.text_for_notes(token) {
3633                        let _ = fts.delete_document(ns, note.id).await;
3634                    }
3635                    for model_name in &embed_model_names {
3636                        if let Ok(vs) = self.vectors_for_model(token, model_name) {
3637                            let _ = vs.delete(note.id).await;
3638                        }
3639                    }
3640                    return Err(e);
3641                }
3642            }
3643        }
3644
3645        Ok((note, embedding_report))
3646    }
3647
3648    /// List notes visible to the token, optionally filtered by kind.
3649    ///
3650    /// When the token carries a multi-namespace visible set, notes from all
3651    /// visible namespaces are returned. When the visible set is `[primary]`
3652    /// (the default) this behaves identically to the pre-visibility behaviour.
3653    pub async fn list_notes(
3654        &self,
3655        token: &NamespaceToken,
3656        kind: Option<&str>,
3657        limit: u32,
3658        offset: u32,
3659    ) -> RuntimeResult<Vec<Note>> {
3660        let visible = token.visible_namespaces();
3661        if visible.len() == 1 {
3662            // Fast path: single namespace — use the dedicated query_notes method.
3663            let page = self
3664                .notes(token)?
3665                .query_notes(
3666                    token.namespace().as_str(),
3667                    kind,
3668                    PageRequest {
3669                        offset: offset.into(),
3670                        limit,
3671                    },
3672                )
3673                .await?;
3674            return Ok(page.items);
3675        }
3676        // Multi-namespace path: use query_notes_filtered with the visible set.
3677        use khive_storage::note::NoteFilter;
3678        let ns_strs: Vec<String> = visible.iter().map(|ns| ns.as_str().to_owned()).collect();
3679        let filter = NoteFilter {
3680            kind: kind.map(|k| k.to_string()),
3681            namespaces: ns_strs,
3682            ..Default::default()
3683        };
3684        let page = self
3685            .notes(token)?
3686            .query_notes_filtered(
3687                token.namespace().as_str(),
3688                &filter,
3689                PageRequest {
3690                    offset: offset.into(),
3691                    limit,
3692                },
3693            )
3694            .await?;
3695        Ok(page.items)
3696    }
3697
3698    /// List an immutable insertion-sequence page of visible notes.
3699    ///
3700    /// Soft-deleting the prior page's last note does not invalidate the
3701    /// cursor because the boundary is resolved including tombstones. A hard
3702    /// deletion makes the cursor unresolvable and returns an explicit error.
3703    pub async fn list_notes_after(
3704        &self,
3705        token: &NamespaceToken,
3706        kind: Option<&str>,
3707        after: Option<Uuid>,
3708        limit: u32,
3709    ) -> RuntimeResult<(Vec<Note>, Option<Uuid>)> {
3710        let store = self.notes(token)?;
3711        let after = match after {
3712            Some(id) => {
3713                let note = self
3714                    .get_note_including_deleted(token, id)
3715                    .await?
3716                    .ok_or_else(|| RuntimeError::NotFound(format!("note cursor {id}")))?;
3717                Self::ensure_namespace_visible(&note.namespace, token)?;
3718                let sequence = store.note_sequence(id).await?.ok_or_else(|| {
3719                    RuntimeError::Internal(format!(
3720                        "note cursor {id} has no insertion-sequence ledger row"
3721                    ))
3722                })?;
3723                Some(SeekCursor { sequence, id })
3724            }
3725            None => None,
3726        };
3727        let filter = khive_storage::note::NoteFilter {
3728            kind: kind.map(str::to_string),
3729            namespaces: token
3730                .visible_namespaces()
3731                .iter()
3732                .map(|namespace| namespace.as_str().to_owned())
3733                .collect(),
3734            ..Default::default()
3735        };
3736        let page = store
3737            .query_notes_filtered_after(token.namespace().as_str(), &filter, after, limit)
3738            .await?;
3739        Ok((page.items, page.next_after.map(|cursor| cursor.id)))
3740    }
3741
3742    /// Count notes matching `kind` across the caller's visible namespaces.
3743    pub async fn count_notes(
3744        &self,
3745        token: &NamespaceToken,
3746        kind: Option<&str>,
3747    ) -> RuntimeResult<u64> {
3748        let namespaces: Vec<String> = token
3749            .visible_namespaces()
3750            .iter()
3751            .map(|namespace| namespace.as_str().to_owned())
3752            .collect();
3753        Ok(self
3754            .notes(token)?
3755            .count_notes_in_namespaces(&namespaces, kind)
3756            .await?)
3757    }
3758
3759    /// Search notes using a hybrid FTS5 + vector pipeline with salience weighting.
3760    ///
3761    /// Pipeline:
3762    /// 1. FTS5 query against `notes_<namespace>`.
3763    /// 2. If embedding model is configured: vector search filtered to `kind="note"`.
3764    /// 3. RRF fusion (k=60).
3765    /// 4. Salience-weighted rerank: `score *= (0.5 + 0.5 * note.salience)`.
3766    /// 5. Filter soft-deleted notes, apply optional kind / tag / properties predicates.
3767    ///    Tags and properties are pushed into the per-note fetch loop BEFORE truncation
3768    ///    so that matching notes ranked beyond `limit` in the raw fusion are not silently
3769    ///    dropped.
3770    /// 6. Truncate to `limit`.
3771    ///
3772    /// `tags_any`: when non-empty, only notes that have at least one of these tags
3773    /// (stored in `properties["tags"]`, case-insensitive match) are retained. The
3774    /// check happens inside the alive-note loop, before `hits.truncate(limit)`.
3775    ///
3776    /// `properties_filter`: when `Some`, only notes whose `properties` JSON object is
3777    /// a superset of the given filter object are retained. Also applied before truncation.
3778    #[allow(clippy::too_many_arguments)]
3779    pub async fn search_notes(
3780        &self,
3781        token: &NamespaceToken,
3782        query_text: &str,
3783        query_vector: Option<Vec<f32>>,
3784        limit: u32,
3785        note_kind: Option<&str>,
3786        include_superseded: bool,
3787        tags_any: &[String],
3788        properties_filter: Option<&serde_json::Value>,
3789    ) -> RuntimeResult<Vec<NoteSearchHit>> {
3790        const RRF_K: usize = 60;
3791        let candidates = limit.saturating_mul(4).max(limit);
3792        let visible_ns: Vec<String> = token
3793            .visible_namespaces()
3794            .iter()
3795            .map(|ns| ns.as_str().to_owned())
3796            .collect();
3797
3798        // FTS5 over the notes index — search all visible namespaces.
3799        //
3800        // `sanitize_fts5_query` strips known-unsafe FTS5 metacharacters, but
3801        // residual punctuation the sanitizer does not strip can still reach
3802        // the FTS5 parser and error. This fails loud instead of degrading to
3803        // vector-only fusion, so callers see the bad query instead of
3804        // silently losing the lexical leg. Errors from any other leg (vector
3805        // search, note hydration) still propagate normally.
3806        //
3807        // Injection: check FTS_SEARCH_FAIL_NS (armed by `arm_fts_search_fail(ns)`),
3808        // exercising the propagate branch above. Fires only when the armed
3809        // namespace is among this call's visible namespaces, then clears (one-shot).
3810        #[cfg(any(test, feature = "fault-injection"))]
3811        let fts_search_inject = {
3812            let mut g = FTS_SEARCH_FAIL_NS.lock().unwrap();
3813            match g.as_deref() {
3814                Some(armed) if visible_ns.iter().any(|ns| ns == armed) => {
3815                    *g = None;
3816                    true
3817                }
3818                _ => false,
3819            }
3820        };
3821        #[cfg(not(any(test, feature = "fault-injection")))]
3822        let fts_search_inject = false;
3823
3824        let text_search_result = if fts_search_inject {
3825            Err(khive_storage::StorageError::Timeout {
3826                operation: "fts_search".into(),
3827            })
3828        } else {
3829            self.text_for_notes(token)?
3830                .search(TextSearchRequest {
3831                    query: query_text.to_string(),
3832                    mode: TextQueryMode::Plain,
3833                    filter: Some(TextFilter {
3834                        namespaces: visible_ns.clone(),
3835                        ..TextFilter::default()
3836                    }),
3837                    top_k: candidates,
3838                    snippet_chars: 200,
3839                })
3840                .await
3841        };
3842
3843        // FtsPasses is counted inside the store's `search()` (khive-db
3844        // stores/text.rs), only once a real FTS5 statement is prepared —
3845        // an empty/fully-sanitized query short-circuits there before any
3846        // statement exists and must not count (nor does the injected-failure
3847        // branch above, which never reaches the store at all).
3848        let text_hits = crate::error::fts_text_leg_or_err(
3849            text_search_result.map_err(RuntimeError::from),
3850            "search_notes",
3851            query_text,
3852        )?;
3853
3854        // Vector search filtered to notes.
3855        let vector_hits = if query_vector.is_some() || self.config().embedding_model.is_some() {
3856            self.vector_search(
3857                token,
3858                query_vector,
3859                Some(query_text),
3860                candidates,
3861                Some(SubstrateKind::Note),
3862            )
3863            .await?
3864        } else {
3865            vec![]
3866        };
3867
3868        // Keep the full text∪vector union through RRF — salience weighting and
3869        // soft-delete/kind filtering happen *after* this, and the final
3870        // `hits.truncate(limit)` is the only result-limiting cut. Truncating to
3871        // `candidates` here would drop a high-salience note ranked just outside
3872        // the raw RRF cutoff before salience ever applied.
3873        let fuse_k = text_hits.len() + vector_hits.len();
3874        let fused = crate::fusion::rrf_fuse_k(text_hits, vector_hits, RRF_K, fuse_k)?;
3875
3876        let candidate_ids: Vec<Uuid> = fused.iter().map(|hit| hit.entity_id).collect();
3877        if candidate_ids.is_empty() {
3878            return Ok(vec![]);
3879        }
3880
3881        // Fetch each candidate note individually to get salience and apply
3882        // soft-delete + (optional) kind filtering. Notes whose `kind` doesn't
3883        // match `note_kind` are dropped post-fetch — they're a small set
3884        // bounded by the text∪vector union (≤ 2×candidates), so the read is cheap.
3885        let note_store = self.notes(token)?;
3886        let mut alive_notes: HashMap<Uuid, Note> = HashMap::new();
3887        for id in &candidate_ids {
3888            if let Some(note) = note_store.get_note(*id).await? {
3889                if note.deleted_at.is_some() {
3890                    continue;
3891                }
3892                if let Some(want_kind) = note_kind {
3893                    if note.kind != want_kind {
3894                        continue;
3895                    }
3896                }
3897                // Apply tag predicate before adding to alive set: tags on notes live
3898                // inside `properties["tags"]` (a JSON array). This pushes the filter
3899                // before truncation so matching notes ranked beyond `limit` in the raw
3900                // fusion are not silently dropped.
3901                if !tags_any.is_empty() {
3902                    let note_tags: Vec<String> = note
3903                        .properties
3904                        .as_ref()
3905                        .and_then(|p| p.get("tags"))
3906                        .and_then(serde_json::Value::as_array)
3907                        .map(|arr| {
3908                            arr.iter()
3909                                .filter_map(serde_json::Value::as_str)
3910                                .map(str::to_owned)
3911                                .collect()
3912                        })
3913                        .unwrap_or_default();
3914                    if !note_tags
3915                        .iter()
3916                        .any(|t| tags_any.iter().any(|w| t.eq_ignore_ascii_case(w)))
3917                    {
3918                        continue;
3919                    }
3920                }
3921                // Apply properties predicate before truncation, same reasoning as tags above.
3922                if let Some(pf) = properties_filter {
3923                    if !note_props_match(note.properties.as_ref(), pf) {
3924                        continue;
3925                    }
3926                }
3927                alive_notes.insert(*id, note);
3928            }
3929        }
3930
3931        // Drop superseded notes unless include_superseded is true: any note targeted
3932        // by a `supersedes` edge is obsolete and excluded from default search.
3933        if !include_superseded && !alive_notes.is_empty() {
3934            let graph = self.graph(token)?;
3935            let mut superseded: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
3936            for &note_id in alive_notes.keys() {
3937                let inbound = graph
3938                    .neighbors(
3939                        note_id,
3940                        NeighborQuery {
3941                            direction: Direction::In,
3942                            relations: Some(vec![EdgeRelation::Supersedes]),
3943                            limit: Some(1),
3944                            min_weight: None,
3945                        },
3946                    )
3947                    .await?;
3948                if !inbound.is_empty() {
3949                    superseded.insert(note_id);
3950                }
3951            }
3952            alive_notes.retain(|id, _| !superseded.contains(id));
3953        }
3954
3955        // Apply salience weighting and collect final hits.
3956        let mut hits: Vec<NoteSearchHit> = fused
3957            .into_iter()
3958            .filter_map(|hit| {
3959                let note = alive_notes.get(&hit.entity_id)?;
3960                let salience = note.salience.unwrap_or(0.5);
3961                let weight = 0.5 + 0.5 * salience;
3962                let weighted = DeterministicScore::from_f64(hit.score.to_f64() * weight);
3963                Some(NoteSearchHit {
3964                    note_id: hit.entity_id,
3965                    score: weighted,
3966                    source: hit.source,
3967                    title: hit.title.or_else(|| note_title(note)),
3968                    snippet: hit.snippet.or_else(|| note_snippet(note)),
3969                })
3970            })
3971            .collect();
3972
3973        hits.sort_by(|a, b| b.score.cmp(&a.score).then(a.note_id.cmp(&b.note_id)));
3974        hits.truncate(limit as usize);
3975        Ok(hits)
3976    }
3977
3978    /// Resolve a short UUID prefix (8+ hex chars) to a full UUID.
3979    ///
3980    /// Searches entities, notes, and edges tables for a UUID starting with the
3981    /// given prefix, scoped to the caller's primary namespace only. Returns
3982    /// `Ok(Some(uuid))` if exactly one match is found, `Ok(None)` if no
3983    /// matches, or an error if ambiguous (multiple matches).
3984    pub async fn resolve_prefix(
3985        &self,
3986        token: &NamespaceToken,
3987        prefix: &str,
3988    ) -> RuntimeResult<Option<Uuid>> {
3989        let namespaces = [token.namespace().as_str().to_owned()];
3990        self.resolve_prefix_inner(Some(&namespaces), prefix, false)
3991            .await
3992    }
3993
3994    pub async fn resolve_prefix_including_deleted(
3995        &self,
3996        token: &NamespaceToken,
3997        prefix: &str,
3998    ) -> RuntimeResult<Option<Uuid>> {
3999        let namespaces = [token.namespace().as_str().to_owned()];
4000        self.resolve_prefix_inner(Some(&namespaces), prefix, true)
4001            .await
4002    }
4003
4004    /// Resolve a short UUID prefix (8+ hex chars) to a full UUID with NO
4005    /// namespace filter at all: mirrors `resolve_by_id`'s by-ID contract:
4006    /// by-ID resolution is namespace-agnostic, since the Gate (not
4007    /// storage-layer filtering) is the authz seam. Used by the four by-ID
4008    /// CRUD verbs (get/update/delete/merge) so their prefix path matches
4009    /// their already-unfiltered full-UUID path. No token param: unlike
4010    /// `resolve_prefix`, there is no namespace to derive from one.
4011    pub async fn resolve_prefix_unfiltered(&self, prefix: &str) -> RuntimeResult<Option<Uuid>> {
4012        self.resolve_prefix_inner(None, prefix, false).await
4013    }
4014
4015    /// `resolve_prefix_unfiltered`, including soft-deleted rows — used by the
4016    /// hard-delete by-ID path.
4017    pub async fn resolve_prefix_unfiltered_including_deleted(
4018        &self,
4019        prefix: &str,
4020    ) -> RuntimeResult<Option<Uuid>> {
4021        self.resolve_prefix_inner(None, prefix, true).await
4022    }
4023
4024    /// Shared prefix-scan implementation over an explicit namespace set.
4025    ///
4026    /// `namespaces` selects the scan scope: `Some(&[ns])` reproduces the
4027    /// historical primary-only behaviour (`resolve_prefix` /
4028    /// `resolve_prefix_including_deleted`); `None` applies
4029    /// no namespace predicate at all (`resolve_prefix_unfiltered*`).
4030    /// Ambiguity (a prefix matching more than one UUID, even across
4031    /// different namespaces in the set, or across all namespaces when
4032    /// unfiltered) is still an error: UUIDs are globally unique, so two
4033    /// distinct rows sharing a prefix always requires caller disambiguation —
4034    /// no cross-namespace dedup is needed or performed.
4035    async fn resolve_prefix_inner(
4036        &self,
4037        namespaces: Option<&[String]>,
4038        prefix: &str,
4039        include_deleted: bool,
4040    ) -> RuntimeResult<Option<Uuid>> {
4041        use khive_storage::types::{SqlStatement, SqlValue};
4042
4043        // Every caller is expected to pre-validate hex-only input, but this is
4044        // the single choke point every `resolve_prefix*` variant funnels
4045        // through, so re-validate here too. A prefix containing anything other
4046        // than hex digits and
4047        // canonical hyphen separators (`%`, `_`, or other LIKE-wildcard /
4048        // injection-shaped input) never matches a real id and is rejected
4049        // before it can reach the LIKE pattern, instead of relying on bound
4050        // params alone to neutralize wildcard semantics.
4051        if !prefix.chars().all(|c| c.is_ascii_hexdigit() || c == '-') {
4052            return Ok(None);
4053        }
4054
4055        let pattern = format!("{}%", hex_prefix_to_uuid_pattern(prefix));
4056
4057        let tables = [
4058            ("entities", true),
4059            ("notes", true),
4060            ("events", false),
4061            ("graph_edges", false),
4062        ];
4063
4064        let ns_clause = namespaces.map(|ns| {
4065            let placeholders: Vec<String> = (0..ns.len()).map(|i| format!("?{}", i + 2)).collect();
4066            format!(" AND namespace IN ({})", placeholders.join(", "))
4067        });
4068
4069        // A UUID can legitimately exist in more than one scanned table
4070        // (e.g. an entity id string that also happens to be an edge id — the
4071        // scan is purely a text-prefix LIKE across independent tables, not a
4072        // substrate-exclusive lookup). Without dedup, a single record hit
4073        // twice across tables inflated `matches.len()` past 1 and produced a
4074        // false `AmbiguousPrefix` naming the SAME UUID twice. `seen` tracks
4075        // UUIDs already pushed so `matches` (and thus every length check,
4076        // including the early-exit below) reflects DISTINCT UUIDs only.
4077        let mut matches: Vec<String> = Vec::new();
4078        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
4079        let mut reader = self.sql().reader().await.map_err(RuntimeError::Storage)?;
4080
4081        for (table, has_deleted_at) in tables {
4082            let deleted_filter = if has_deleted_at && !include_deleted {
4083                " AND deleted_at IS NULL"
4084            } else {
4085                ""
4086            };
4087            let mut params = vec![SqlValue::Text(pattern.clone())];
4088            if let Some(ns) = namespaces {
4089                params.extend(ns.iter().map(|n| SqlValue::Text(n.clone())));
4090            }
4091            let sql = SqlStatement {
4092                sql: format!(
4093                    "SELECT id FROM {table} WHERE id LIKE ?1{ns_clause}{deleted_filter} LIMIT 2",
4094                    ns_clause = ns_clause.as_deref().unwrap_or("")
4095                ),
4096                params,
4097                label: Some("resolve_prefix".into()),
4098            };
4099            match reader.query_all(sql).await {
4100                Ok(rows) => {
4101                    for row in rows {
4102                        if let Some(col) = row.columns.first() {
4103                            if let SqlValue::Text(s) = &col.value {
4104                                if seen.insert(s.clone()) {
4105                                    matches.push(s.clone());
4106                                }
4107                            }
4108                        }
4109                    }
4110                }
4111                Err(e) => {
4112                    let msg = e.to_string();
4113                    if msg.contains("no such table") {
4114                        continue;
4115                    }
4116                    return Err(RuntimeError::Storage(e));
4117                }
4118            }
4119            if matches.len() > 1 {
4120                break;
4121            }
4122        }
4123
4124        match matches.len() {
4125            0 => Ok(None),
4126            1 => {
4127                let uuid = Uuid::from_str(&matches[0])
4128                    .map_err(|e| RuntimeError::Internal(format!("stored UUID is invalid: {e}")))?;
4129                Ok(Some(uuid))
4130            }
4131            _ => {
4132                let uuids: Vec<uuid::Uuid> = matches
4133                    .iter()
4134                    .filter_map(|s| Uuid::from_str(s).ok())
4135                    .collect();
4136                Err(RuntimeError::AmbiguousPrefix {
4137                    prefix: prefix.to_string(),
4138                    matches: uuids,
4139                })
4140            }
4141        }
4142    }
4143
4144    /// Resolve a UUID to its substrate kind with NO namespace filter.
4145    ///
4146    /// By-ID contract: UUID v4 is globally unique: by-ID substrate
4147    /// inference must return the record regardless of caller namespace.  Used by
4148    /// the public `update` and `delete` verb handlers when no explicit `kind` is
4149    /// supplied.
4150    ///
4151    /// Does NOT consult the visible set or the primary-namespace check.  The
4152    /// token is still required to route to the correct backend pool but its
4153    /// namespace value is not used as a filter.
4154    pub async fn resolve_by_id(
4155        &self,
4156        token: &NamespaceToken,
4157        id: Uuid,
4158    ) -> RuntimeResult<Option<Resolved>> {
4159        // Entity: direct by-UUID fetch (ID-only, no namespace check).
4160        if let Some(entity) = self.entities(token)?.get_entity(id).await? {
4161            return Ok(Some(Resolved::Entity(entity)));
4162        }
4163
4164        // Note: direct by-UUID fetch (ID-only).
4165        if let Some(note) = self.notes(token)?.get_note(id).await? {
4166            return Ok(Some(Resolved::Note(note)));
4167        }
4168
4169        // Edges and events are not returned here; the caller's `_` arm handles
4170        // those with a separate get_edge / get_event check.
4171        Ok(None)
4172    }
4173
4174    /// Resolve a UUID to its substrate kind with NO namespace filter, including
4175    /// soft-deleted rows.
4176    ///
4177    /// Used by the hard-delete path when no explicit `kind` is supplied, so
4178    /// already-soft-deleted records can still be located by UUID alone.
4179    pub async fn resolve_by_id_including_deleted(
4180        &self,
4181        token: &NamespaceToken,
4182        id: Uuid,
4183    ) -> RuntimeResult<Option<Resolved>> {
4184        // Entity: including soft-deleted, no namespace check.
4185        if let Some(entity) = self
4186            .entities(token)?
4187            .get_entity_including_deleted(id)
4188            .await?
4189        {
4190            return Ok(Some(Resolved::Entity(entity)));
4191        }
4192
4193        // Note: including soft-deleted, no namespace check.
4194        if let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? {
4195            return Ok(Some(Resolved::Note(note)));
4196        }
4197
4198        // Edges and events are not returned here; the caller's `_` arm handles
4199        // those with a separate get_edge_including_deleted check.
4200        Ok(None)
4201    }
4202
4203    /// Resolve a UUID to its substrate kind by trying entity, then note, then event stores.
4204    ///
4205    /// Returns `None` if the UUID is not found in any substrate.
4206    /// Cost: at most 3 store lookups per call (cheap for v0.1).
4207    pub async fn resolve(
4208        &self,
4209        token: &NamespaceToken,
4210        id: Uuid,
4211    ) -> RuntimeResult<Option<Resolved>> {
4212        // Entity: use the namespace-checked getter (errors on mismatch/absent).
4213        match self.get_entity(token, id).await {
4214            Ok(entity) => return Ok(Some(Resolved::Entity(entity))),
4215            Err(RuntimeError::NotFound(_) | RuntimeError::NamespaceMismatch { .. }) => {}
4216            Err(e) => return Err(e),
4217        }
4218
4219        // Note: storage get_note is ID-only — verify against visible set.
4220        if let Some(note) = self.notes(token)?.get_note(id).await? {
4221            if Self::ensure_namespace_visible(&note.namespace, token).is_ok() {
4222                return Ok(Some(Resolved::Note(note)));
4223            }
4224        }
4225
4226        // Event: storage get_event is ID-only — verify against visible set.
4227        if let Some(event) = self.events(token)?.get_event(id).await? {
4228            if Self::ensure_namespace_visible(&event.namespace, token).is_ok() {
4229                return Ok(Some(Resolved::Event(event)));
4230            }
4231        }
4232
4233        Ok(None)
4234    }
4235
4236    /// Resolve a UUID to its substrate kind with NO namespace filter, for edge
4237    /// endpoint validation.
4238    ///
4239    /// `link` and `create`'s `annotates` targets consume by-ID endpoints, so
4240    /// their existence check must follow the same by-ID contract as `get()`:
4241    /// by-ID ops are namespace-agnostic: the Gate, not storage-layer
4242    /// filtering, is the authz seam. Mirrors `resolve_by_id`
4243    /// (entity + note, unfiltered) and additionally resolves events,
4244    /// unfiltered, so edge endpoint validation resolves exactly what `get()`
4245    /// resolves regardless of the caller's namespace.
4246    pub async fn resolve_edge_endpoint(
4247        &self,
4248        token: &NamespaceToken,
4249        id: Uuid,
4250    ) -> RuntimeResult<Option<Resolved>> {
4251        if let Some(resolved) = self.resolve_by_id(token, id).await? {
4252            return Ok(Some(resolved));
4253        }
4254        if let Some(event) = self.events(token)?.get_event(id).await? {
4255            return Ok(Some(Resolved::Event(event)));
4256        }
4257        Ok(None)
4258    }
4259
4260    /// Resolve a UUID to its substrate kind using primary-namespace-only enforcement.
4261    ///
4262    /// Unlike `resolve`, never consults the visible set. Use from GTD dependency
4263    /// validation paths where strict primary ownership is required.
4264    pub async fn resolve_primary(
4265        &self,
4266        token: &NamespaceToken,
4267        id: Uuid,
4268    ) -> RuntimeResult<Option<Resolved>> {
4269        let ns = token.namespace().as_str();
4270
4271        // Entity: primary-only check (exclude entities in visible-only namespaces).
4272        if let Some(entity) = self.entities(token)?.get_entity(id).await? {
4273            if Self::ensure_namespace(&entity.namespace, ns).is_ok() {
4274                return Ok(Some(Resolved::Entity(entity)));
4275            }
4276        }
4277
4278        // Note: primary-only check.
4279        if let Some(note) = self.notes(token)?.get_note(id).await? {
4280            if Self::ensure_namespace(&note.namespace, ns).is_ok() {
4281                return Ok(Some(Resolved::Note(note)));
4282            }
4283        }
4284
4285        // Event: primary-only check.
4286        if let Some(event) = self.events(token)?.get_event(id).await? {
4287            if Self::ensure_namespace(&event.namespace, ns).is_ok() {
4288                return Ok(Some(Resolved::Event(event)));
4289            }
4290        }
4291
4292        Ok(None)
4293    }
4294
4295    /// Resolve a UUID to its substrate kind, including soft-deleted rows.
4296    ///
4297    /// Used exclusively by the hard-delete path to locate records that have
4298    /// already been soft-deleted. Namespace isolation is still enforced.
4299    pub async fn resolve_including_deleted(
4300        &self,
4301        token: &NamespaceToken,
4302        id: Uuid,
4303    ) -> RuntimeResult<Option<Resolved>> {
4304        let ns = token.namespace().as_str();
4305
4306        if let Some(entity) = self
4307            .entities(token)?
4308            .get_entity_including_deleted(id)
4309            .await?
4310        {
4311            if Self::ensure_namespace(&entity.namespace, ns).is_ok() {
4312                return Ok(Some(Resolved::Entity(entity)));
4313            }
4314        }
4315
4316        if let Some(note) = self.notes(token)?.get_note_including_deleted(id).await? {
4317            if Self::ensure_namespace(&note.namespace, ns).is_ok() {
4318                return Ok(Some(Resolved::Note(note)));
4319            }
4320        }
4321
4322        if let Some(event) = self.events(token)?.get_event(id).await? {
4323            if Self::ensure_namespace(&event.namespace, ns).is_ok() {
4324                return Ok(Some(Resolved::Event(event)));
4325            }
4326        }
4327
4328        Ok(None)
4329    }
4330
4331    /// Hard-delete a single graph node (entity, note, or edge-as-node row)
4332    /// AND purge its incident edges in ONE write transaction.
4333    ///
4334    /// The endpoint row delete and the incident-edge cascade used
4335    /// to run as two independently-committing storage calls. A concurrent
4336    /// guarded write (`upsert_edge_guarded`/`upsert_edges_guarded`) landing
4337    /// between them could see the endpoint still live, insert a fresh edge
4338    /// against it, and then survive the cascade that already ran — a
4339    /// durably dangling edge with no second purge. Routing both statements
4340    /// through one [`run_atomic_unit`] call closes the window: since every
4341    /// write (this one and the guarded insert) funnels through the same
4342    /// single-writer queue, a concurrent guarded write either fully commits
4343    /// before this unit starts (and its edge is then swept by the purge
4344    /// below, in the same transaction as the row delete) or fully commits
4345    /// after this unit has already committed (and its own endpoint-existence
4346    /// check then sees the endpoint gone and refuses the write) — there is
4347    /// no state in which it can observe the endpoint alive with edges
4348    /// already purged.
4349    ///
4350    /// `row_statement` is the exact hard-delete `DELETE` for the target row
4351    /// (entity, note, or edge). Before the incident-edge purge, the same plan
4352    /// appends any ADR-002 lineage-loss warnings from the still-present edge
4353    /// rows, so the warning payload and cascade commit or roll back together.
4354    /// Returns `Ok(true)` if the row was deleted,
4355    /// `Ok(false)` if it no longer existed (lost a race with a concurrent
4356    /// delete of the same row) — never an error for that case, matching the
4357    /// non-atomic bool-returning shape callers had before this fix.
4358    async fn atomic_hard_delete_with_edge_purge(
4359        &self,
4360        row_statement: SqlStatement,
4361        node_id: Uuid,
4362        namespace: &str,
4363        actor: &str,
4364        substrate: SubstrateKind,
4365    ) -> RuntimeResult<bool> {
4366        let mut statements = vec![PlanStatement {
4367            statement: row_statement,
4368            guard: Some(AffectedRowGuard::exactly(1)),
4369        }];
4370        statements.extend(
4371            hard_delete_lineage_warning_statements(namespace, actor, node_id, substrate)
4372                .into_iter()
4373                .map(|statement| PlanStatement {
4374                    statement,
4375                    guard: None,
4376                }),
4377        );
4378        statements.push(PlanStatement {
4379            statement: purge_incident_edges_statement(node_id),
4380            guard: None,
4381        });
4382        let plan = AtomicOpPlan::Delete(DeletePlan {
4383            target_id: node_id,
4384            statements,
4385            post_commit: PostCommitEffect::None,
4386        });
4387        match run_atomic_unit(self.sql().as_ref(), vec![plan]).await {
4388            Ok(AtomicRunOutcome::Committed { .. }) => Ok(true),
4389            Ok(AtomicRunOutcome::RolledBack {
4390                failure: AtomicOpFailure::GuardFailed { .. },
4391                ..
4392            }) => Ok(false),
4393            Ok(AtomicRunOutcome::RolledBack {
4394                failure: AtomicOpFailure::SqlError { message, .. },
4395                ..
4396            }) => Err(RuntimeError::Internal(format!(
4397                "hard delete + edge purge for {node_id} failed: {message}"
4398            ))),
4399            Err(e) => Err(RuntimeError::Internal(format!(
4400                "hard delete + edge purge for {node_id}: atomic unit seam failure: {}",
4401                e.0
4402            ))),
4403        }
4404    }
4405
4406    /// Soft-delete or hard-delete a note by ID.
4407    ///
4408    /// On hard delete, cascades to remove all incident edges (both inbound and
4409    /// outbound) and cleans up FTS and vector indexes, preventing dangling
4410    /// references for `annotates` edges that target this note.
4411    /// Soft delete also cleans FTS and vector indexes; edges are left in place.
4412    ///
4413    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
4414    /// Cascade and index cleanup target the RECORD's stored namespace, not the caller token's.
4415    /// Returns `Ok(false)` if the note does not exist.
4416    pub async fn delete_note(
4417        &self,
4418        token: &NamespaceToken,
4419        id: Uuid,
4420        hard: bool,
4421    ) -> RuntimeResult<bool> {
4422        let note_store = self.notes(token)?;
4423        let note = if hard {
4424            match note_store.get_note_including_deleted(id).await? {
4425                Some(n) => n,
4426                None => return Ok(false),
4427            }
4428        } else {
4429            match note_store.get_note(id).await? {
4430                Some(n) => n,
4431                None => return Ok(false),
4432            }
4433        };
4434        let mode = if hard {
4435            DeleteMode::Hard
4436        } else {
4437            DeleteMode::Soft
4438        };
4439
4440        // Route index cleanup through the RECORD's namespace, not the caller's.
4441        let record_tok = NamespaceToken::for_namespace(
4442            khive_types::Namespace::parse(&note.namespace)
4443                .map_err(|e| RuntimeError::Internal(format!("note namespace invalid: {e}")))?,
4444        );
4445        let record_ns = note.namespace.clone();
4446        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
4447
4448        // On hard delete, the row delete and the incident-edge cascade (including
4449        // already-soft-deleted edges) run as ONE write transaction: see
4450        // `atomic_hard_delete_with_edge_purge`. Index cleanup follows the
4451        // commit; it is best-effort and idempotent, unlike the row/edge pair.
4452        let deleted = if hard {
4453            let deleted = self
4454                .atomic_hard_delete_with_edge_purge(
4455                    note_hard_delete_statement(id),
4456                    id,
4457                    &record_ns,
4458                    &actor,
4459                    SubstrateKind::Note,
4460                )
4461                .await?;
4462            self.text_for_notes(&record_tok)?
4463                .delete_document(&record_ns, id)
4464                .await?;
4465            // Scoped delete: iterate over EVERY registered embedding model's
4466            // vector store so non-default vectors don't orphan when the note is deleted.
4467            for model_name in self.registered_embedding_model_names() {
4468                self.vectors_for_model(&record_tok, &model_name)?
4469                    .delete(id)
4470                    .await?;
4471            }
4472            deleted
4473        } else {
4474            let deleted = note_store.delete_note(id, mode).await?;
4475            if deleted {
4476                self.text_for_notes(&record_tok)?
4477                    .delete_document(&record_ns, id)
4478                    .await?;
4479                for model_name in self.registered_embedding_model_names() {
4480                    self.vectors_for_model(&record_tok, &model_name)?
4481                        .delete(id)
4482                        .await?;
4483                }
4484            }
4485            deleted
4486        };
4487        if deleted {
4488            let event_store = self.events(token)?;
4489            let event = khive_storage::event::Event::new(
4490                record_ns.clone(),
4491                "delete",
4492                EventKind::NoteDeleted,
4493                SubstrateKind::Note,
4494                "",
4495            )
4496            .with_target(id)
4497            .with_payload(serde_json::json!({"id": id, "namespace": record_ns, "hard": hard}));
4498            event_store.append_event(event).await.map_err(|e| {
4499                RuntimeError::Internal(format!("delete_note: event store write failed: {e}"))
4500            })?;
4501            // A soft OR hard delete removes the note's vectors/FTS document
4502            // above: any pack-owned vector-derived cache (e.g.
4503            // khive-pack-memory's warm ANN index) needs to know the corpus
4504            // changed, reached via this generic hook so khive-runtime never
4505            // takes a dependency on khive-pack-memory. No-op when no pack has
4506            // installed a hook.
4507            self.fire_note_mutation_hook(&note.kind, id).await;
4508        }
4509        Ok(deleted)
4510    }
4511
4512    /// Row-first compensating delete for rolling back a partially-written note
4513    /// (e.g. `dual_write_message` rollback after a later delivery step fails).
4514    /// Unlike [`KhiveRuntime::delete_note`], which cleans up graph/FTS/
4515    /// vector indexes *before* removing the row, this removes the row first so
4516    /// that a cleanup failure afterward cannot leave the compensated note live.
4517    ///
4518    /// Returns `Ok(())` once the row is gone (whether or not cleanup fully
4519    /// succeeded). Returns `Err(RuntimeError::Internal)` naming the failed
4520    /// cleanup legs when row removal succeeded but cleanup did not — the
4521    /// message is gone, but stale index entries may remain and should be
4522    /// surfaced to the caller rather than silently discarded.
4523    ///
4524    /// Returns `Ok(())` immediately, with no cleanup attempted, if the note
4525    /// does not exist (nothing to compensate).
4526    ///
4527    /// Not a general-purpose replacement for `delete_note(..., hard=true)`:
4528    /// normal hard delete still needs cleanup-first semantics (no dangling
4529    /// references) since a caller-visible error there should not remove the row.
4530    pub async fn delete_note_row_first_for_compensation(
4531        &self,
4532        token: &NamespaceToken,
4533        id: Uuid,
4534    ) -> RuntimeResult<()> {
4535        let note_store = self.notes(token)?;
4536        let Some(note) = note_store.get_note_including_deleted(id).await? else {
4537            return Ok(());
4538        };
4539        let record_tok = NamespaceToken::for_namespace(
4540            khive_types::Namespace::parse(&note.namespace)
4541                .map_err(|e| RuntimeError::Internal(format!("note namespace invalid: {e}")))?,
4542        );
4543        let record_ns = note.namespace.clone();
4544
4545        // Critical ordering: remove the row before any cleanup that can fail.
4546        note_store.delete_note(id, DeleteMode::Hard).await?;
4547
4548        #[cfg(any(test, feature = "fault-injection"))]
4549        {
4550            let armed = ROLLBACK_CLEANUP_FAIL_NS.lock().unwrap().take();
4551            if armed.as_deref() == Some(record_ns.as_str()) {
4552                return Err(RuntimeError::Internal(
4553                    "row removed but compensation cleanup failed: injected=true".to_string(),
4554                ));
4555            }
4556        }
4557
4558        let mut cleanup_errors = Vec::new();
4559        if let Err(e) = self.graph(&record_tok)?.purge_incident_edges(id).await {
4560            cleanup_errors.push(format!("graph={e}"));
4561        }
4562        if let Err(e) = self
4563            .text_for_notes(&record_tok)?
4564            .delete_document(&record_ns, id)
4565            .await
4566        {
4567            cleanup_errors.push(format!("fts={e}"));
4568        }
4569        for model_name in self.registered_embedding_model_names() {
4570            if let Err(e) = self
4571                .vectors_for_model(&record_tok, &model_name)?
4572                .delete(id)
4573                .await
4574            {
4575                cleanup_errors.push(format!("vector[{model_name}]={e}"));
4576            }
4577        }
4578        if cleanup_errors.is_empty() {
4579            Ok(())
4580        } else {
4581            Err(RuntimeError::Internal(format!(
4582                "row removed but compensation cleanup failed: {}",
4583                cleanup_errors.join("; ")
4584            )))
4585        }
4586    }
4587}
4588
4589/// Result of a GQL/SPARQL query with optional validation warnings.
4590#[derive(Clone, Debug, Serialize)]
4591pub struct QueryResult {
4592    pub rows: Vec<SqlRow>,
4593    #[serde(skip_serializing_if = "Vec::is_empty")]
4594    pub warnings: Vec<String>,
4595    /// `true` when the server-side row cap bound this result — `rows` is a
4596    /// prefix of the true match set, not the whole thing (#1168, #1247). A
4597    /// structural flag so a caller can detect an incomplete result without
4598    /// parsing the human-oriented `warnings` text.
4599    pub truncated: bool,
4600}
4601
4602impl KhiveRuntime {
4603    // ---- Query operations ----
4604
4605    /// Execute a GQL or SPARQL query string, returning raw SQL rows.
4606    ///
4607    /// The query is compiled to SQL with the namespace scope applied.
4608    /// GQL syntax: `MATCH (a:concept)-[e:extends]->(b) RETURN a, b LIMIT 10`
4609    /// SPARQL syntax: `SELECT ?a WHERE { ?a :kind "concept" . }`
4610    pub async fn query(&self, token: &NamespaceToken, query: &str) -> RuntimeResult<Vec<SqlRow>> {
4611        Ok(self
4612            .query_with_metadata(token, query, khive_query::CompileOptions::default())
4613            .await?
4614            .rows)
4615    }
4616
4617    /// Execute a GQL/SPARQL query, returning rows and any validation warnings.
4618    pub async fn query_with_metadata(
4619        &self,
4620        token: &NamespaceToken,
4621        query: &str,
4622        mut opts: khive_query::CompileOptions,
4623    ) -> RuntimeResult<QueryResult> {
4624        use khive_query::QueryValue;
4625        use khive_storage::types::SqlValue;
4626
4627        let (language, ast) = khive_query::language::parse_auto_with_language(query)?;
4628        opts.scopes = token
4629            .visible_namespaces()
4630            .iter()
4631            .map(|ns| ns.as_str().to_string())
4632            .collect();
4633        let compiled = khive_query::compile(&ast, &opts)?;
4634        let mut warnings = compiled.warnings;
4635        let truncation_check = compiled.truncation_check;
4636
4637        warnings.extend(self.with_pack_edge_rules(|pack_rules| {
4638            static_impossible_edge_pattern_warnings(language, &ast.pattern, pack_rules)
4639        }));
4640
4641        // Convert QueryValue params (query-layer type) to SqlValue (storage-layer type)
4642        // at the query–storage boundary.
4643        let params: Vec<SqlValue> = compiled
4644            .params
4645            .into_iter()
4646            .map(|qv| match qv {
4647                QueryValue::Null => SqlValue::Null,
4648                QueryValue::Integer(n) => SqlValue::Integer(n),
4649                QueryValue::Float(f) => SqlValue::Float(f),
4650                QueryValue::Text(s) => SqlValue::Text(s),
4651                QueryValue::Blob(b) => SqlValue::Blob(b),
4652            })
4653            .collect();
4654
4655        let mut reader = self.sql().reader().await?;
4656        let stmt = SqlStatement {
4657            sql: compiled.sql,
4658            params,
4659            label: None,
4660        };
4661        let mut rows = reader.query_all(stmt).await?;
4662
4663        // When the server-side cap was the binding constraint, the compiled
4664        // SQL asked for one extra (sentinel) row. Its presence in the actual
4665        // result set — not the requested LIMIT — is the truncation signal
4666        // (a `LIMIT 1000` that only matches 20 rows must not warn, and a
4667        // query with no `LIMIT` that matches 501+ rows must).
4668        let mut truncated = false;
4669        if let Some(check) = truncation_check {
4670            if rows.len() > check.max_limit {
4671                rows.truncate(check.max_limit);
4672                truncated = true;
4673                // GQL has no SKIP/OFFSET/ORDER BY today (#1168) — the prior
4674                // wording here recommended a paging path that does not exist.
4675                // `truncated` is the structural signal (#1247); this message
4676                // stays prose-only context for a human reader.
4677                warnings.push(match check.requested_limit {
4678                    Some(requested) => format!(
4679                        "result set capped at {} rows; requested limit {requested} exceeds the \
4680                         cap. This query language does not support SKIP/OFFSET paging yet — \
4681                         check the `truncated` field, not this message, to detect an incomplete \
4682                         result programmatically.",
4683                        check.max_limit
4684                    ),
4685                    None => format!(
4686                        "result set capped at {} rows; more than {} rows matched with no LIMIT \
4687                         clause. This query language does not support SKIP/OFFSET paging yet — \
4688                         check the `truncated` field, not this message, to detect an incomplete \
4689                         result programmatically.",
4690                        check.max_limit, check.max_limit
4691                    ),
4692                });
4693            }
4694        }
4695
4696        Ok(QueryResult {
4697            rows,
4698            warnings,
4699            truncated,
4700        })
4701    }
4702
4703    /// Soft-delete or hard-delete an entity by ID (soft delete by default).
4704    ///
4705    /// On hard delete, cascades to remove all incident edges (both inbound and
4706    /// outbound) to prevent dangling references. Soft delete also cleans FTS
4707    /// and vector indexes; edges are left in place.
4708    ///
4709    /// UUID v4 is globally unique: no namespace filter on by-ID ops.
4710    pub async fn delete_entity(
4711        &self,
4712        token: &NamespaceToken,
4713        id: Uuid,
4714        hard: bool,
4715    ) -> RuntimeResult<bool> {
4716        let entity = if hard {
4717            match self
4718                .entities(token)?
4719                .get_entity_including_deleted(id)
4720                .await?
4721            {
4722                Some(e) => e,
4723                None => return Ok(false),
4724            }
4725        } else {
4726            match self.entities(token)?.get_entity(id).await? {
4727                Some(e) => e,
4728                None => return Ok(false),
4729            }
4730        };
4731        let mode = if hard {
4732            DeleteMode::Hard
4733        } else {
4734            DeleteMode::Soft
4735        };
4736
4737        // Route cascade and index cleanup through the RECORD's namespace, not the caller's.
4738        let record_tok = NamespaceToken::for_namespace(
4739            khive_types::Namespace::parse(&entity.namespace)
4740                .map_err(|e| RuntimeError::Internal(format!("entity namespace invalid: {e}")))?,
4741        );
4742        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
4743
4744        // On hard delete, the row delete and the incident-edge cascade (including
4745        // already-soft-deleted edges) run as ONE write transaction: see
4746        // `atomic_hard_delete_with_edge_purge`. Index cleanup follows the
4747        // commit; it is best-effort and idempotent, unlike the row/edge pair.
4748        let deleted = if hard {
4749            let deleted = self
4750                .atomic_hard_delete_with_edge_purge(
4751                    entity_hard_delete_statement(id),
4752                    id,
4753                    &entity.namespace,
4754                    &actor,
4755                    SubstrateKind::Entity,
4756                )
4757                .await?;
4758            self.remove_from_indexes(&record_tok, id).await?;
4759            deleted
4760        } else {
4761            let deleted = self.entities(token)?.delete_entity(id, mode).await?;
4762            if deleted {
4763                self.remove_from_indexes(&record_tok, id).await?;
4764            }
4765            deleted
4766        };
4767        if deleted {
4768            let event_store = self.events(token)?;
4769            let ns = entity.namespace.clone();
4770            let event = khive_storage::event::Event::new(
4771                ns.clone(),
4772                "delete",
4773                EventKind::EntityDeleted,
4774                SubstrateKind::Entity,
4775                "",
4776            )
4777            .with_target(id)
4778            .with_payload(serde_json::json!({"id": id, "namespace": ns, "hard": hard}));
4779            event_store.append_event(event).await.map_err(|e| {
4780                RuntimeError::Internal(format!("delete_entity: event store write failed: {e}"))
4781            })?;
4782        }
4783        Ok(deleted)
4784    }
4785
4786    /// Count entities in a namespace, optionally filtered.
4787    pub async fn count_entities(
4788        &self,
4789        token: &NamespaceToken,
4790        kind: Option<&str>,
4791    ) -> RuntimeResult<u64> {
4792        let ns_strs: Vec<String> = token
4793            .visible_namespaces()
4794            .iter()
4795            .map(|ns| ns.as_str().to_owned())
4796            .collect();
4797        let filter = EntityFilter {
4798            kinds: match kind {
4799                Some(k) => vec![k.to_string()],
4800                None => vec![],
4801            },
4802            namespaces: ns_strs,
4803            ..Default::default()
4804        };
4805        Ok(self
4806            .entities(token)?
4807            .count_entities(token.namespace().as_str(), filter)
4808            .await?)
4809    }
4810
4811    // ---- Edge CRUD operations ----
4812
4813    /// Fetch a single edge by id.
4814    ///
4815    /// UUID v4 is globally unique: returns the edge regardless of which
4816    /// namespace the token carries. `Ok(None)` means the edge does not exist at all.
4817    pub async fn get_edge(
4818        &self,
4819        _token: &NamespaceToken,
4820        edge_id: Uuid,
4821    ) -> RuntimeResult<Option<Edge>> {
4822        let mut reader = self.sql().reader().await?;
4823        let record_ns = reader
4824            .query_scalar(SqlStatement {
4825                sql: "SELECT namespace FROM graph_edges \
4826                      WHERE id = ?1 AND deleted_at IS NULL LIMIT 1"
4827                    .into(),
4828                params: vec![SqlValue::Text(edge_id.to_string())],
4829                label: Some("get_edge_namespace".into()),
4830            })
4831            .await?;
4832
4833        let Some(SqlValue::Text(record_ns)) = record_ns else {
4834            return Ok(None);
4835        };
4836        // Route the storage fetch through the record's own namespace — the token is
4837        // just the caller context; by-ID ops cross namespace boundaries.
4838        let record_tok = NamespaceToken::for_namespace(
4839            khive_types::Namespace::parse(&record_ns)
4840                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
4841        );
4842        Ok(self
4843            .graph(&record_tok)?
4844            .get_edge(LinkId::from(edge_id))
4845            .await?)
4846    }
4847
4848    /// Fetch a single edge by id.
4849    ///
4850    /// Delegates to `get_edge`: no visible-set check.  By-ID ops are
4851    /// namespace-agnostic; UUID v4 is globally unique.
4852    pub async fn get_edge_visible(
4853        &self,
4854        token: &NamespaceToken,
4855        edge_id: Uuid,
4856    ) -> RuntimeResult<Option<Edge>> {
4857        self.get_edge(token, edge_id).await
4858    }
4859
4860    /// Fetch an edge by UUID including soft-deleted rows.
4861    ///
4862    /// Returns the edge regardless of which namespace the token carries:
4863    /// UUID v4 is globally unique. Used by the hard-delete path so that a
4864    /// soft-deleted edge can still be purged via its edge ID.
4865    pub async fn get_edge_including_deleted(
4866        &self,
4867        _token: &NamespaceToken,
4868        edge_id: Uuid,
4869    ) -> RuntimeResult<Option<Edge>> {
4870        let mut reader = self.sql().reader().await?;
4871        let record_ns = reader
4872            .query_scalar(SqlStatement {
4873                sql: "SELECT namespace FROM graph_edges WHERE id = ?1 LIMIT 1".into(),
4874                params: vec![SqlValue::Text(edge_id.to_string())],
4875                label: Some("get_edge_including_deleted_namespace".into()),
4876            })
4877            .await?;
4878
4879        let Some(SqlValue::Text(record_ns)) = record_ns else {
4880            return Ok(None);
4881        };
4882        // Route through the record's own namespace store (no namespace equality check).
4883        let record_tok = NamespaceToken::for_namespace(
4884            khive_types::Namespace::parse(&record_ns)
4885                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
4886        );
4887        Ok(self
4888            .graph(&record_tok)?
4889            .get_edge_including_deleted(LinkId::from(edge_id))
4890            .await?)
4891    }
4892
4893    /// Fetch an edge by natural key (namespace, canonical source/target, relation)
4894    /// including soft-deleted rows. Unlike [`Self::list_edges`]/[`Self::list_edges_after`],
4895    /// which always filter `deleted_at IS NULL`, this can render a tombstoned symmetric-edge
4896    /// survivor (ADR-039 DO NOTHING conflict absorption) — used by the atomic-apply
4897    /// post-commit result renderer, which otherwise reports "not found" for a committed
4898    /// update whose surviving row happens to be soft-deleted.
4899    ///
4900    /// `token` selects the store instance; `namespace` is the natural key's own
4901    /// namespace and is bound into the query explicitly. These can legitimately differ:
4902    /// the record namespace is fixed at prepare time (`EdgeNaturalKey::namespace`) and by-ID
4903    /// edge updates are namespace-agnostic (ADR-007 Rev 6), so the caller's ambient `token`
4904    /// namespace is never a safe substitute for the record's own — the prior implicit
4905    /// `self.namespace` scoping is exactly the bug this parameter closes (khive#1213/#1214).
4906    pub async fn get_edge_by_natural_key_including_deleted(
4907        &self,
4908        token: &NamespaceToken,
4909        namespace: &str,
4910        source_id: Uuid,
4911        target_id: Uuid,
4912        relation: EdgeRelation,
4913    ) -> RuntimeResult<Option<Edge>> {
4914        Ok(self
4915            .graph(token)?
4916            .get_edge_by_natural_key_including_deleted(namespace, source_id, target_id, relation)
4917            .await?)
4918    }
4919
4920    /// Maximum rows returned by a single [`Self::list_edges`] /
4921    /// [`Self::list_edges_after`] page. A lower bound the docs promise callers
4922    /// can rely on; kept as a named constant so tests can exercise pagination
4923    /// (page tiling, out-of-range offsets) without needing >1000 real rows.
4924    pub const EDGE_LIST_MAX_LIMIT: u32 = 1000;
4925
4926    /// List edges matching `filter`, paging by `offset`. `limit` is capped at
4927    /// [`Self::EDGE_LIST_MAX_LIMIT`]; defaults to 100.
4928    ///
4929    /// `offset` pages through the full matching set (previously hard-coded to
4930    /// 0, so every page returned the same first rows). For
4931    /// O(1)-at-depth walks over large edge populations, prefer
4932    /// [`Self::list_edges_after`] instead of paging offset deep.
4933    pub async fn list_edges(
4934        &self,
4935        token: &NamespaceToken,
4936        filter: crate::curation::EdgeListFilter,
4937        limit: u32,
4938        offset: u32,
4939    ) -> RuntimeResult<Vec<Edge>> {
4940        let limit = limit.clamp(1, Self::EDGE_LIST_MAX_LIMIT);
4941        let visible = token.visible_namespaces();
4942
4943        // Common case: a single visible namespace — page directly against the
4944        // store so `offset`/`limit` reach SQL unmodified.
4945        if let [ns] = visible {
4946            let temp = NamespaceToken::for_namespace(ns.clone());
4947            let page = self
4948                .graph(&temp)?
4949                .query_edges(
4950                    filter.into(),
4951                    vec![SortOrder {
4952                        field: EdgeSortField::CreatedAt,
4953                        direction: khive_storage::types::SortDirection::Asc,
4954                    }],
4955                    PageRequest {
4956                        offset: offset.into(),
4957                        limit,
4958                    },
4959                )
4960                .await?;
4961            return Ok(page.items);
4962        }
4963
4964        // Multi-namespace visibility: `offset` must apply to the combined,
4965        // deduplicated set rather than per-namespace pages, so fetch enough
4966        // of each namespace's page to cover it, merge, then slice.
4967        let fetch_limit = offset.saturating_add(limit);
4968        let mut results = Vec::new();
4969        for ns in visible {
4970            let temp = NamespaceToken::for_namespace(ns.clone());
4971            let page = self
4972                .graph(&temp)?
4973                .query_edges(
4974                    filter.clone().into(),
4975                    vec![SortOrder {
4976                        field: EdgeSortField::CreatedAt,
4977                        direction: khive_storage::types::SortDirection::Asc,
4978                    }],
4979                    PageRequest {
4980                        offset: 0,
4981                        limit: fetch_limit,
4982                    },
4983                )
4984                .await?;
4985            results.extend(page.items);
4986        }
4987        results.sort_by_key(|e| Uuid::from(e.id));
4988        results.dedup_by_key(|e| Uuid::from(e.id));
4989        let start = (offset as usize).min(results.len());
4990        let end = (start + limit as usize).min(results.len());
4991        Ok(results[start..end].to_vec())
4992    }
4993
4994    /// Keyset (seek) page of edges matching `filter`, ordered by immutable
4995    /// database-assigned insertion sequence. `after` is the last edge id from the
4996    /// previous page (exclusive); omit to start from the beginning. Returns
4997    /// `(items, next_after)` — `next_after` is `Some` when more rows remain
4998    /// past this page.
4999    ///
5000    /// Unlike [`Self::list_edges`], this is O(log n + limit) at any depth and
5001    /// genuinely new inserts are appended after already-issued boundaries. The
5002    /// cursor row is resolved including tombstones; a hard-deleted or
5003    /// out-of-scope cursor fails explicitly rather than hiding an incomplete
5004    /// traversal.
5005    pub async fn list_edges_after(
5006        &self,
5007        token: &NamespaceToken,
5008        filter: crate::curation::EdgeListFilter,
5009        after: Option<Uuid>,
5010        limit: u32,
5011    ) -> RuntimeResult<(Vec<Edge>, Option<Uuid>)> {
5012        let limit = limit.clamp(1, Self::EDGE_LIST_MAX_LIMIT);
5013        let visible = token.visible_namespaces();
5014        let limit_usize = limit as usize;
5015        let cursor_store = self.graph(token)?;
5016        let after = match after {
5017            Some(id) => {
5018                let edge = self
5019                    .get_edge_including_deleted(token, id)
5020                    .await?
5021                    .ok_or_else(|| RuntimeError::NotFound(format!("edge cursor {id}")))?;
5022                Self::ensure_namespace_visible(&edge.namespace, token)?;
5023                let sequence = cursor_store.edge_sequence(id).await?.ok_or_else(|| {
5024                    RuntimeError::Internal(format!(
5025                        "edge cursor {id} has no insertion-sequence ledger row"
5026                    ))
5027                })?;
5028                Some(SeekCursor { sequence, id })
5029            }
5030            None => None,
5031        };
5032
5033        if let [ns] = visible {
5034            let temp = NamespaceToken::for_namespace(ns.clone());
5035            let page = self
5036                .graph(&temp)?
5037                .query_edges_sequence_after(filter.into(), after, limit)
5038                .await?;
5039            return Ok((page.items, page.next_after.map(|cursor| cursor.id)));
5040        }
5041
5042        // Multi-namespace visibility: seek each namespace from the same
5043        // immutable boundary, merge in global insertion order, then take the head of
5044        // the merged set as this page.
5045        let probe_limit = limit.saturating_add(1);
5046        let mut results = Vec::new();
5047        for ns in visible {
5048            let temp = NamespaceToken::for_namespace(ns.clone());
5049            let page = self
5050                .graph(&temp)?
5051                .query_edges_sequence_after(filter.clone().into(), after, probe_limit)
5052                .await?;
5053            results.extend(page.items);
5054        }
5055        let ids = results
5056            .iter()
5057            .map(|edge| Uuid::from(edge.id))
5058            .collect::<Vec<_>>();
5059        let sequences = cursor_store
5060            .edge_sequences(&ids)
5061            .await?
5062            .into_iter()
5063            .collect::<HashMap<_, _>>();
5064        if let Some(missing) = ids.iter().find(|id| !sequences.contains_key(id)) {
5065            return Err(RuntimeError::Internal(format!(
5066                "edge {missing} has no insertion-sequence ledger row"
5067            )));
5068        }
5069        results.sort_by_key(|edge| {
5070            let id = Uuid::from(edge.id);
5071            (sequences[&id], id)
5072        });
5073        results.dedup_by_key(|e| Uuid::from(e.id));
5074        let has_more = results.len() > limit_usize;
5075        if has_more {
5076            results.truncate(limit_usize);
5077        }
5078        let next_after = if has_more {
5079            results.last().map(|e| Uuid::from(e.id))
5080        } else {
5081            None
5082        };
5083        Ok((results, next_after))
5084    }
5085
5086    /// Count edges by relation, ignoring soft-deleted rows. Used by
5087    /// `stats()` to report the true per-relation population so full-graph
5088    /// audits know what they're sampling from before they walk it.
5089    pub async fn count_edges_by_relation(
5090        &self,
5091        token: &NamespaceToken,
5092    ) -> RuntimeResult<std::collections::HashMap<String, u64>> {
5093        let namespaces: Vec<String> = token
5094            .visible_namespaces()
5095            .iter()
5096            .map(|namespace| namespace.as_str().to_owned())
5097            .collect();
5098        let graph = self.graph(token)?;
5099        let counts = match graph
5100            .count_edges_by_relation_in_namespaces(&namespaces)
5101            .await
5102        {
5103            Ok(counts) => counts,
5104            Err(khive_storage::StorageError::Unsupported { operation, .. })
5105                if operation == "count_edges_by_relation_in_namespaces" =>
5106            {
5107                let mut totals = HashMap::new();
5108                for namespace in token.visible_namespaces() {
5109                    let scoped = NamespaceToken::for_namespace(namespace.clone());
5110                    for (relation, count) in self.graph(&scoped)?.count_edges_by_relation().await? {
5111                        *totals.entry(relation).or_insert(0) += count;
5112                    }
5113                }
5114                return Ok(totals
5115                    .into_iter()
5116                    .map(|(relation, count)| (relation.to_string(), count))
5117                    .collect());
5118            }
5119            Err(error) => return Err(error.into()),
5120        };
5121        Ok(counts
5122            .into_iter()
5123            .map(|(relation, count)| (relation.to_string(), count))
5124            .collect())
5125    }
5126
5127    /// DML-only body of the symmetric-relation conflict-resolution path in
5128    /// [`Self::update_edge`]. Runs the conflict-check SELECT, then either the
5129    /// DELETE+UPDATE (case b, a canonical row already exists) or the
5130    /// in-place UPDATE (case a, no conflict). Callers own the surrounding transaction
5131    /// boundary — this function issues DML only, no `BEGIN`/`COMMIT`/`ROLLBACK`.
5132    ///
5133    /// Returns `Ok(Some(existing_id))` when a canonical conflict was absorbed (the
5134    /// requested edge was deleted, the existing canonical row left untouched per
5135    /// ADR-039 DO NOTHING), or `Ok(None)` when the requested edge was updated in
5136    /// place.
5137    ///
5138    /// DML text is the single source of truth shared with the atomic
5139    /// `prepare_update_edge` symmetric branch:
5140    /// [`khive_db::stores::graph::EDGE_SYMMETRIC_CONFLICT_PROBE_SQL`] /
5141    /// `EDGE_SYMMETRIC_DELETE_NONCANONICAL_SQL` /
5142    /// `EDGE_SYMMETRIC_UPDATE_INPLACE_SQL` — this function binds them against
5143    /// `rusqlite::params!` (it runs inside an existing transaction on a
5144    /// borrowed `&rusqlite::Connection`), the atomic path binds the same text
5145    /// via `SqlValue` plan params; see the constants' doc comment in
5146    /// `khive-db` for why a single bridge type isn't used for both.
5147    #[allow(clippy::too_many_arguments)]
5148    fn update_edge_symmetric_dml(
5149        conn: &rusqlite::Connection,
5150        ns: &str,
5151        edge_id_str: &str,
5152        canon_src_str: &str,
5153        canon_tgt_str: &str,
5154        relation_str: &str,
5155        weight: f64,
5156        metadata: Option<String>,
5157    ) -> Result<Option<String>, SqliteError> {
5158        // `updated_at` is stored in MICROSECONDS on `graph_edges` (every other
5159        // write path — `edge_upsert_statement`, `edge_soft_delete_statement` —
5160        // uses `timestamp_micros()`; the column is read back via
5161        // `micros_to_datetime`). `timestamp()` (seconds) here was a
5162        // pre-existing bug in this raw-SQL path, found while unifying it with
5163        // the atomic builder (which already used `timestamp_micros()`
5164        // correctly).
5165        let now_ts = chrono::Utc::now().timestamp_micros();
5166
5167        // Check for a conflicting canonical row (same namespace + natural key,
5168        // different id). This catches conflicts whether or not endpoints were flipped.
5169        let conflict_id: Option<String> = conn
5170            .query_row(
5171                khive_db::stores::graph::EDGE_SYMMETRIC_CONFLICT_PROBE_SQL,
5172                rusqlite::params![
5173                    &ns,
5174                    &canon_src_str,
5175                    &canon_tgt_str,
5176                    &relation_str,
5177                    &edge_id_str
5178                ],
5179                |row| row.get(0),
5180            )
5181            .optional()
5182            .map_err(SqliteError::Rusqlite)?;
5183
5184        if let Some(existing_id) = conflict_id {
5185            // Case (b): canonical row already exists — ADR-039's edge-conflict
5186            // contract is ON CONFLICT DO NOTHING: drop the non-canonical edge
5187            // and leave the existing canonical row untouched (live or
5188            // tombstoned). Refreshing it from the discarded edge's
5189            // weight/target_backend/metadata and forcing deleted_at = NULL
5190            // would silently overwrite the survivor and resurrect a
5191            // tombstone — the same defect already fixed on the merge-rewire
5192            // path (`merge_entity_sql`/`merge_note_sql`); this path binds the
5193            // same shared `EDGE_SYMMETRIC_*_SQL` text and must honor the same
5194            // contract. Return the surviving id unchanged so the caller
5195            // re-fetches its real (unmodified) attributes.
5196            conn.execute(
5197                khive_db::stores::graph::EDGE_SYMMETRIC_DELETE_NONCANONICAL_SQL,
5198                rusqlite::params![&ns, &edge_id_str],
5199            )
5200            .map_err(SqliteError::Rusqlite)?;
5201            Ok(Some(existing_id))
5202        } else {
5203            // Case (a): no conflict — update source_id/target_id in-place,
5204            // preserving the original edge UUID.
5205            let affected = conn
5206                .execute(
5207                    khive_db::stores::graph::EDGE_SYMMETRIC_UPDATE_INPLACE_SQL,
5208                    rusqlite::params![
5209                        &canon_src_str,
5210                        &canon_tgt_str,
5211                        &relation_str,
5212                        weight,
5213                        now_ts,
5214                        metadata,
5215                        &ns,
5216                        &edge_id_str,
5217                    ],
5218                )
5219                .map_err(SqliteError::Rusqlite)?;
5220            if affected == 0 {
5221                // The edge row was not found under the record's namespace.
5222                // This must never happen because ns = record_ns (fetched above).
5223                return Err(SqliteError::InvalidData(format!(
5224                    "update_edge: zero rows affected updating edge {edge_id_str} \
5225                     in namespace {ns} — row vanished between fetch and update"
5226                )));
5227            }
5228            Ok(None)
5229        }
5230    }
5231
5232    /// Patch-style edge update. Only `Some(_)` fields are applied.
5233    ///
5234    /// When `relation` is `Some(new_rel)`, validates that the edge's existing endpoints
5235    /// are legal for `new_rel` before persisting. Weight-only updates (`relation = None`)
5236    /// skip validation. Returns `InvalidInput` if the new relation would violate the
5237    /// three-case endpoint contract; the edge is NOT mutated on error.
5238    ///
5239    /// For symmetric relations (`competes_with`, `composed_with`), endpoint order is
5240    /// canonicalised to `source_uuid < target_uuid` after validation. If a canonical
5241    /// row already exists at the target triple, the non-canonical edge is deleted and
5242    /// the existing canonical row is preserved unchanged (ADR-039 ON CONFLICT DO
5243    /// NOTHING, mirroring `merge_entity_sql`) — its attributes, including a soft-deleted
5244    /// `deleted_at`, are never overwritten by the discarded edge's patch.
5245    pub async fn update_edge(
5246        &self,
5247        token: &NamespaceToken,
5248        edge_id: Uuid,
5249        patch: crate::curation::EdgePatch,
5250    ) -> RuntimeResult<Edge> {
5251        // Fetch the edge by UUID: ID-only, no namespace check.
5252        // get_edge already uses the record's stored namespace internally.
5253        let graph_for_fetch = self.graph(token)?;
5254        let mut edge = graph_for_fetch
5255            .get_edge(LinkId::from(edge_id))
5256            .await?
5257            .ok_or_else(|| crate::RuntimeError::NotFound(format!("edge {edge_id}")))?;
5258
5259        // After fetching, all mutations and validation must use the
5260        // RECORD's namespace, not the caller's.  Derive record_tok from the stored edge
5261        // namespace so that endpoint validation, raw-SQL predicates, and graph routing
5262        // all address the correct backend partition.
5263        let record_ns: String = edge.namespace.clone();
5264        let record_tok = NamespaceToken::for_namespace(
5265            khive_types::Namespace::parse(&record_ns)
5266                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5267        );
5268        let graph = self.graph(&record_tok)?;
5269
5270        let mut changed_fields: Vec<&'static str> = Vec::new();
5271        if let Some(r) = patch.relation {
5272            // Validate before mutating — use the existing endpoints with the new relation.
5273            // Use record_tok so that endpoint existence checks look in the edge's own namespace.
5274            self.validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, r)
5275                .await?;
5276            edge.relation = r;
5277            changed_fields.push("relation");
5278        }
5279        if let Some(w) = patch.weight {
5280            // Reject non-finite or out-of-range weight explicitly; do not silently
5281            // clamp invalid caller input (coding-standards §608-622).
5282            if !w.is_finite() || !(0.0..=1.0).contains(&w) {
5283                return Err(RuntimeError::InvalidInput(format!(
5284                    "edge weight must be a finite value in [0.0, 1.0]; got {w}"
5285                )));
5286            }
5287            edge.weight = w;
5288            changed_fields.push("weight");
5289        }
5290        if let Some(props) = patch.properties {
5291            edge.metadata = Some(props);
5292        }
5293
5294        // For symmetric relations, canonicalise endpoint order and check
5295        // for natural-key conflicts regardless of whether endpoints were flipped.
5296        //
5297        // The raw-SQL path is used for ALL symmetric relations because `upsert_edge`
5298        // resolves ON CONFLICT(namespace,id) first and cannot detect a duplicate at
5299        // the natural key (namespace, source_id, target_id, relation) with a different
5300        // id. Bug-fix: this path must also run when endpoints are already canonical
5301        // (endpoints_flipped=false) to catch conflicts arising from a relation change
5302        // that collides with an existing canonical row.
5303        let (canon_src, canon_tgt) =
5304            canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
5305
5306        if edge.relation.is_symmetric() {
5307            // Raw-SQL path (mirrors merge_entity_sql).
5308            // Use record_ns (the stored edge namespace) — NOT token.namespace() — so that
5309            // WHERE namespace = ?N predicates match the actual row.
5310            let ns = record_ns.clone();
5311            let edge_id_str = edge_id.to_string();
5312            let relation_str = edge.relation.to_string();
5313            let canon_src_str = canon_src.to_string();
5314            let canon_tgt_str = canon_tgt.to_string();
5315            let weight = edge.weight;
5316            let metadata = edge
5317                .metadata
5318                .as_ref()
5319                .map(|v| serde_json::to_string(v).unwrap_or_default());
5320
5321            let pool = self.backend().pool_arc();
5322            // Route through the single-writer task when the write queue is
5323            // enabled; best-effort lookup degrades to the legacy pool-mutex
5324            // path (mirrors merge_entity/merge_note above).
5325            let writer_task = pool.writer_task_handle().ok().flatten();
5326
5327            // Some(surviving_id) when a canonical conflict was absorbed (the requested
5328            // edge was deleted, existing canonical row left untouched per ADR-039 DO
5329            // NOTHING), or None when the requested edge was updated in-place.
5330            let surviving_id: Option<String> = if let Some(writer_task) = writer_task {
5331                writer_task
5332                    .send(move |conn| {
5333                        Self::update_edge_symmetric_dml(
5334                            conn,
5335                            &ns,
5336                            &edge_id_str,
5337                            &canon_src_str,
5338                            &canon_tgt_str,
5339                            &relation_str,
5340                            weight,
5341                            metadata,
5342                        )
5343                        .map_err(|e| {
5344                            khive_storage::StorageError::driver(
5345                                khive_storage::StorageCapability::Graph,
5346                                "update_edge",
5347                                e,
5348                            )
5349                        })
5350                    })
5351                    .await
5352                    .map_err(RuntimeError::Storage)?
5353            } else {
5354                tokio::task::spawn_blocking(move || {
5355                    let guard = pool.writer()?;
5356                    guard.transaction(|conn| {
5357                        Self::update_edge_symmetric_dml(
5358                            conn,
5359                            &ns,
5360                            &edge_id_str,
5361                            &canon_src_str,
5362                            &canon_tgt_str,
5363                            &relation_str,
5364                            weight,
5365                            metadata,
5366                        )
5367                    })
5368                })
5369                .await
5370                .map_err(|e| {
5371                    RuntimeError::Internal(format!("update_edge: spawn_blocking join: {e}"))
5372                })?
5373                .map_err(RuntimeError::Sqlite)?
5374            };
5375
5376            if let Some(sid) = surviving_id {
5377                // A conflict was absorbed (ADR-039 DO NOTHING): re-fetch the surviving
5378                // canonical row so the caller receives its real, UNMODIFIED attributes —
5379                // including soft-deleted rows, since the survivor's tombstone state (if
5380                // any) must not be resurrected by the absorbed update either. Use
5381                // record_tok — the surviving row lives in the same namespace as the
5382                // original.
5383                let surviving_uuid = Uuid::parse_str(&sid).map_err(|e| {
5384                    RuntimeError::Internal(format!("update_edge: surviving id parse failed: {e}"))
5385                })?;
5386                edge = self
5387                    .get_edge_including_deleted(&record_tok, surviving_uuid)
5388                    .await?
5389                    .ok_or_else(|| {
5390                        RuntimeError::Internal(format!(
5391                            "update_edge: surviving canonical row {surviving_uuid} vanished after update"
5392                        ))
5393                    })?;
5394            } else {
5395                // Reflect canonical endpoints in the returned edge (no conflict absorbed).
5396                edge.source_id = canon_src;
5397                edge.target_id = canon_tgt;
5398            }
5399        } else {
5400            // Non-symmetric: upsert_edge takes namespace from edge.namespace (not from the
5401            // graph store's routing namespace), so this is already record-namespace correct.
5402            // `graph` is already self.graph(&record_tok)?.
5403            graph.upsert_edge(edge.clone()).await?;
5404        }
5405
5406        // Audit event: use the record's namespace (record_ns) for the event payload.
5407        let event_store = self.events(&record_tok)?;
5408        let event = khive_storage::event::Event::new(
5409            record_ns.clone(),
5410            "update",
5411            EventKind::EdgeUpdated,
5412            SubstrateKind::Entity,
5413            "",
5414        )
5415        .with_target(edge_id)
5416        .with_payload(
5417            serde_json::json!({"id": edge_id, "namespace": record_ns, "changed_fields": changed_fields}),
5418        );
5419        event_store.append_event(event).await.map_err(|e| {
5420            RuntimeError::Internal(format!("update_edge: event store write failed: {e}"))
5421        })?;
5422
5423        Ok(edge)
5424    }
5425
5426    /// Hard-delete an edge by id.
5427    ///
5428    /// Cascades to remove any `annotates` edges whose target is the deleted edge
5429    /// (`annotates` is note → anything; deleting an edge target leaves annotation
5430    /// edges dangling if not cleaned up). Returns `true` if the primary
5431    /// edge was removed.
5432    ///
5433    /// If `edge_id` does not refer to an edge (e.g. the caller passes an entity or
5434    /// note UUID by mistake), this method returns `Ok(false)` immediately with no
5435    /// side effects — it does **not** cascade inbound edges of the non-edge record.
5436    pub async fn delete_edge(
5437        &self,
5438        token: &NamespaceToken,
5439        edge_id: Uuid,
5440        hard: bool,
5441    ) -> RuntimeResult<bool> {
5442        let mode = if hard {
5443            DeleteMode::Hard
5444        } else {
5445            DeleteMode::Soft
5446        };
5447
5448        // Fetch the edge first to obtain the record's own namespace.
5449        // By-ID ops cross namespace boundaries; all graph routing and audit
5450        // events must use the record namespace, not the caller's (mirrors update_edge).
5451        // For hard delete we also check soft-deleted rows so a soft-deleted edge
5452        // can still be purged via its edge ID.
5453        let edge = if hard {
5454            self.get_edge_including_deleted(token, edge_id).await?
5455        } else {
5456            self.get_edge(token, edge_id).await?
5457        };
5458        let Some(edge) = edge else {
5459            return Ok(false);
5460        };
5461
5462        // Derive record_ns / record_tok from the fetched edge (mirrors update_edge).
5463        let record_ns: String = edge.namespace.clone();
5464        let record_tok = NamespaceToken::for_namespace(
5465            khive_types::Namespace::parse(&record_ns)
5466                .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
5467        );
5468        let graph = self.graph(&record_tok)?;
5469        let actor = format!("{}:{}", token.actor().kind, token.actor().id);
5470
5471        // Cascade: on hard delete, remove ALL annotates edges targeting this edge — including
5472        // already-soft-deleted ones: to prevent dangling graph_edges rows. The row
5473        // delete and the cascade purge run as ONE write transaction: see
5474        // `atomic_hard_delete_with_edge_purge`.
5475        // On soft delete the cascade is skipped (data-vs-view principle: soft-deleting the base
5476        // edge does not cascade to annotation edges; only a hard purge cleans up incident rows).
5477        let deleted = if hard {
5478            self.atomic_hard_delete_with_edge_purge(
5479                edge_hard_delete_statement(edge_id),
5480                edge_id,
5481                &record_ns,
5482                &actor,
5483                SubstrateKind::Entity,
5484            )
5485            .await?
5486        } else {
5487            graph.delete_edge(LinkId::from(edge_id), mode).await?
5488        };
5489        if deleted {
5490            // Audit event: use the record's namespace (record_ns), not the caller's namespace.
5491            let event_store = self.events(&record_tok)?;
5492            let event = khive_storage::event::Event::new(
5493                record_ns.clone(),
5494                "delete",
5495                EventKind::EdgeDeleted,
5496                SubstrateKind::Entity,
5497                "",
5498            )
5499            .with_target(edge_id)
5500            .with_payload(serde_json::json!({"id": edge_id, "namespace": record_ns, "hard": hard}));
5501            event_store.append_event(event).await.map_err(|e| {
5502                RuntimeError::Internal(format!("delete_edge: event store write failed: {e}"))
5503            })?;
5504        }
5505        Ok(deleted)
5506    }
5507
5508    /// Count edges matching `filter` across the caller's visible namespaces.
5509    pub async fn count_edges(
5510        &self,
5511        token: &NamespaceToken,
5512        filter: crate::curation::EdgeListFilter,
5513    ) -> RuntimeResult<u64> {
5514        let namespaces: Vec<String> = token
5515            .visible_namespaces()
5516            .iter()
5517            .map(|namespace| namespace.as_str().to_owned())
5518            .collect();
5519        let graph = self.graph(token)?;
5520        match graph
5521            .count_edges_in_namespaces(&namespaces, filter.clone().into())
5522            .await
5523        {
5524            Ok(count) => Ok(count),
5525            Err(khive_storage::StorageError::Unsupported { operation, .. })
5526                if operation == "count_edges_in_namespaces" =>
5527            {
5528                let mut total = 0;
5529                for namespace in token.visible_namespaces() {
5530                    let scoped = NamespaceToken::for_namespace(namespace.clone());
5531                    total += self
5532                        .graph(&scoped)?
5533                        .count_edges(filter.clone().into())
5534                        .await?;
5535                }
5536                Ok(total)
5537            }
5538            Err(error) => Err(error.into()),
5539        }
5540    }
5541
5542    /// Validate and construct an edge from a [`LinkSpec`] without writing to storage.
5543    ///
5544    /// Applies the full edge contract (endpoint validation, symmetric
5545    /// canonicalization, `dependency_kind` inference and metadata validation).
5546    /// Returns the constructed `Edge` on success; the caller is responsible for
5547    /// persisting it (e.g. via `upsert_edge` or `link_many`).
5548    ///
5549    /// The `token` must be a pre-authorized namespace token from the dispatch
5550    /// layer. If `spec.namespace` is set it must match `token.namespace()`;
5551    /// a mismatch returns `RuntimeError::InvalidInput`.
5552    pub async fn build_edge(&self, token: &NamespaceToken, spec: &LinkSpec) -> RuntimeResult<Edge> {
5553        let ns_str = match &spec.namespace {
5554            Some(s) => {
5555                let spec_ns = crate::Namespace::parse(s)
5556                    .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}")))?;
5557                if &spec_ns != token.namespace() {
5558                    return Err(RuntimeError::InvalidInput(
5559                        "LinkSpec namespace does not match token namespace".into(),
5560                    ));
5561                }
5562                s.as_str()
5563            }
5564            None => token.namespace().as_str(),
5565        };
5566        self.validate_edge_relation_endpoints(token, spec.source_id, spec.target_id, spec.relation)
5567            .await?;
5568        let (source_id, target_id) =
5569            canonical_edge_endpoints(spec.relation, spec.source_id, spec.target_id);
5570        let metadata = if spec.relation == EdgeRelation::DependsOn {
5571            // By-ID, unfiltered — matches the namespace-agnostic endpoint validation
5572            // above. The visible-set-scoped `resolve` would silently drop the
5573            // dependency_kind inference for endpoints validation now allows outside
5574            // the caller's visible set.
5575            match (
5576                self.resolve_edge_endpoint(token, source_id).await?,
5577                self.resolve_edge_endpoint(token, target_id).await?,
5578            ) {
5579                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
5580                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, spec.metadata.clone())
5581                }
5582                _ => spec.metadata.clone(),
5583            }
5584        } else {
5585            spec.metadata.clone()
5586        };
5587        validate_edge_metadata(spec.relation, metadata.as_ref())?;
5588        let now = chrono::Utc::now();
5589        Ok(Edge {
5590            id: LinkId::from(Uuid::new_v4()),
5591            namespace: ns_str.to_string(),
5592            source_id,
5593            target_id,
5594            relation: spec.relation,
5595            weight: spec.weight,
5596            created_at: now,
5597            updated_at: now,
5598            deleted_at: None,
5599            metadata,
5600            target_backend: None,
5601        })
5602    }
5603
5604    /// Validate and atomically upsert a batch of edges.
5605    ///
5606    /// All edges are validated and constructed with `build_edge` before any
5607    /// write. If validation fails for any entry the entire batch is rejected
5608    /// (no writes occur). On success, all edges are persisted in a single
5609    /// atomic transaction via `upsert_edges`.
5610    ///
5611    /// After the bulk upsert, each edge is read back by its natural key
5612    /// (namespace, source_id, target_id, relation) so that the returned IDs
5613    /// are always the persisted row IDs, not the locally-generated UUIDs that
5614    /// may have been displaced by an ON CONFLICT DO UPDATE. This mirrors the
5615    /// same read-back applied to singleton `link()` and prevents phantom-ID
5616    /// exposure when callers upsert overlapping triples with `verbose=true`.
5617    ///
5618    /// All specs must share the same namespace; the namespace is taken from
5619    /// `token` (or validated against it if `spec.namespace` is set).
5620    pub async fn link_many(
5621        &self,
5622        token: &NamespaceToken,
5623        specs: Vec<LinkSpec>,
5624    ) -> RuntimeResult<Vec<Edge>> {
5625        if specs.is_empty() {
5626            return Ok(vec![]);
5627        }
5628        let mut edges = Vec::with_capacity(specs.len());
5629        for spec in &specs {
5630            edges.push(self.build_edge(token, spec).await?);
5631        }
5632        // `upsert_edges_guarded` re-checks every edge's endpoints as part of the
5633        // same write, not the separate per-spec `build_edge` validation reads
5634        // above. A concurrent hard-delete of any endpoint landing between those
5635        // reads and this write aborts the whole batch (all-or-nothing, no
5636        // partial write) instead of persisting a dangling edge. The failing
5637        // entry's index and its missing endpoint(s) come from the guard's own
5638        // in-transaction pre-check (`GuardedBatchOutcome::refused`), not a
5639        // post-hoc re-read of the batch after the write already failed.
5640        let outcome = self
5641            .graph(token)?
5642            .upsert_edges_guarded(edges.clone())
5643            .await?;
5644        if let Some(refusal) = outcome.refused {
5645            return Err(RuntimeError::GuardedWriteFailed(GuardedWriteFailure {
5646                entry_index: Some(refusal.entry_index),
5647                missing_source: refusal
5648                    .missing
5649                    .source
5650                    .then_some(edges[refusal.entry_index].source_id),
5651                missing_target: refusal
5652                    .missing
5653                    .target
5654                    .then_some(edges[refusal.entry_index].target_id),
5655            }));
5656        }
5657        if outcome.summary.affected != edges.len() as u64 {
5658            return Err(RuntimeError::NotFound(format!(
5659                "link_many: one or more edge endpoints no longer exist at write time: {}",
5660                outcome.summary.first_error
5661            )));
5662        }
5663
5664        // Read back each persisted edge by natural key so callers always
5665        // receive the stored row ID, not the pre-upsert generated UUID.
5666        let mut persisted = Vec::with_capacity(edges.len());
5667        for edge in &edges {
5668            let row = self
5669                .list_edges(
5670                    token,
5671                    crate::curation::EdgeListFilter {
5672                        source_id: Some(edge.source_id),
5673                        target_id: Some(edge.target_id),
5674                        relations: vec![edge.relation],
5675                        ..Default::default()
5676                    },
5677                    1,
5678                    0,
5679                )
5680                .await?
5681                .into_iter()
5682                .next()
5683                .ok_or_else(|| {
5684                    crate::RuntimeError::Internal(format!(
5685                        "upsert_edges succeeded but natural-key lookup for ({}, {}, {}) returned nothing",
5686                        edge.source_id, edge.target_id, edge.relation.as_str()
5687                    ))
5688                })?;
5689            persisted.push(row);
5690        }
5691        Ok(persisted)
5692    }
5693
5694    /// Create a batch of entities atomically.
5695    ///
5696    /// All specs are validated before any write. If ANY spec fails validation
5697    /// (unknown kind, empty name, secret-gate violation), the method returns
5698    /// that error and no entities are written.
5699    ///
5700    /// Entity rows and their FTS documents are written in one SQLite transaction.
5701    /// Any statement failure rolls back the entire batch across both surfaces.
5702    /// Embedding is intentionally skipped: bulk structural ingest is the expected
5703    /// use-case, and dense vectors are backfilled later via a `reindex` call.
5704    pub async fn create_many(
5705        &self,
5706        token: &NamespaceToken,
5707        specs: Vec<EntityCreateSpec>,
5708    ) -> RuntimeResult<Vec<Entity>> {
5709        if specs.is_empty() {
5710            return Ok(vec![]);
5711        }
5712        let ns = token.namespace().as_str();
5713
5714        // Phase 1: validate ALL specs before any write.
5715        // Includes entity-type validation via the pack-installed validator when available.
5716        // Any validation failure here guarantees zero rows are written.
5717        let mut entities = Vec::with_capacity(specs.len());
5718        for spec in &specs {
5719            self.validate_entity_kind(&spec.kind)?;
5720            // Validate entity_type at the runtime layer via pack-installed callback.
5721            // When no validator is installed (bare runtime, unit tests without packs),
5722            // the type passes through unchanged — same skip-when-absent pattern as
5723            // validate_entity_kind. The handler layer remains the primary enforcement point.
5724            let validated_type =
5725                self.validate_entity_type_for_kind(&spec.kind, spec.entity_type.as_deref())?;
5726            if spec.name.trim().is_empty() {
5727                return Err(RuntimeError::InvalidInput("name must not be empty".into()));
5728            }
5729            crate::secret_gate::check(&spec.name)?;
5730            if let Some(d) = &spec.description {
5731                crate::secret_gate::check(d)?;
5732            }
5733            if let Some(ref p) = spec.properties {
5734                crate::secret_gate::check_json(p)?;
5735            }
5736            crate::secret_gate::check_tags(&spec.tags)?;
5737
5738            let mut entity =
5739                Entity::new(ns, &spec.kind, &spec.name).with_entity_type(validated_type.as_deref());
5740            if let Some(d) = &spec.description {
5741                entity = entity.with_description(d);
5742            }
5743            if let Some(p) = spec.properties.clone() {
5744                entity = entity.with_properties(p);
5745            }
5746            if !spec.tags.is_empty() {
5747                entity = entity.with_tags(spec.tags.clone());
5748            }
5749            entities.push(entity);
5750        }
5751
5752        #[cfg(any(test, feature = "fault-injection"))]
5753        let fts_many_inject = consume_fault(&FTS_FAIL_MANY_NS, ns);
5754        #[cfg(not(any(test, feature = "fault-injection")))]
5755        let fts_many_inject = false;
5756
5757        #[cfg(any(test, feature = "fault-injection"))]
5758        let fts_many_inject_partial = consume_fault(&FTS_FAIL_MANY_PARTIAL_NS, ns);
5759        #[cfg(not(any(test, feature = "fault-injection")))]
5760        let fts_many_inject_partial = false;
5761
5762        let injected_failure_index = if fts_many_inject {
5763            Some(0)
5764        } else if fts_many_inject_partial {
5765            Some(usize::from(entities.len() > 1))
5766        } else {
5767            None
5768        };
5769
5770        let _ = self.entities(token)?;
5771        let _ = self.text(token)?;
5772
5773        let plans = entities
5774            .iter()
5775            .enumerate()
5776            .map(|(index, entity)| {
5777                let mut fts_statement =
5778                    insert_document_statement("fts_entities", &entity_fts_document(entity));
5779                if injected_failure_index == Some(index) {
5780                    fts_statement = SqlStatement {
5781                        sql: "INSERT INTO __khive_create_many_injected_failure__ DEFAULT VALUES"
5782                            .to_string(),
5783                        params: vec![],
5784                        label: Some("fts-insert-injected-failure".to_string()),
5785                    };
5786                }
5787                AtomicOpPlan::AddEntity(AddEntityPlan {
5788                    entity_id: entity.id,
5789                    statements: vec![
5790                        PlanStatement {
5791                            statement: entity_upsert_statement(entity),
5792                            guard: Some(AffectedRowGuard::exactly(1)),
5793                        },
5794                        PlanStatement {
5795                            statement: fts_statement,
5796                            guard: None,
5797                        },
5798                    ],
5799                    post_commit: PostCommitEffect::None,
5800                })
5801            })
5802            .collect();
5803
5804        match run_atomic_unit(self.sql().as_ref(), plans).await {
5805            Ok(AtomicRunOutcome::Committed { .. }) => Ok(entities),
5806            Ok(AtomicRunOutcome::RolledBack {
5807                failed_op_index,
5808                failure,
5809            }) => Err(RuntimeError::Internal(format!(
5810                "create_many: atomic batch rolled back at entity index {failed_op_index}: \
5811                 {failure:?}"
5812            ))),
5813            Err(e) => Err(RuntimeError::Internal(format!(
5814                "create_many: atomic batch failed: {}",
5815                e.0
5816            ))),
5817        }
5818    }
5819}
5820
5821/// Fully specified edge creation request — input to [`KhiveRuntime::build_edge`]
5822/// and [`KhiveRuntime::link_many`].
5823#[derive(Clone, Debug)]
5824pub struct LinkSpec {
5825    pub namespace: Option<String>,
5826    pub source_id: Uuid,
5827    pub target_id: Uuid,
5828    pub relation: EdgeRelation,
5829    pub weight: f64,
5830    pub metadata: Option<serde_json::Value>,
5831}
5832
5833/// Fully specified entity creation request — input to [`KhiveRuntime::create_many`].
5834///
5835/// `entity_type` is validated at the runtime layer by the pack-installed
5836/// entity-type validator. When a validator
5837/// is installed (e.g. by `KgPack`), unknown types are rejected with the valid
5838/// set listed. When no validator is installed (bare runtime without packs),
5839/// the value passes through — the handler layer is the primary enforcement point.
5840#[derive(Clone, Debug)]
5841pub struct EntityCreateSpec {
5842    pub kind: String,
5843    pub entity_type: Option<String>,
5844    pub name: String,
5845    pub description: Option<String>,
5846    pub properties: Option<serde_json::Value>,
5847    pub tags: Vec<String>,
5848}
5849
5850// INLINE TEST JUSTIFICATION: tests here exercise private helpers (canonical_edge_endpoints,
5851// validate_edge_metadata, merge_dependency_kind, link-fail injection) and runtime methods
5852// that require pub(crate) KhiveRuntime construction. Moving them to tests/ would require
5853// pub-exporting those private helpers, which would widen the crate's public API surface
5854// undesirably. Broad behavioral tests live in tests/integration.rs.
5855#[cfg(test)]
5856mod tests {
5857    use super::*;
5858    use crate::curation::EdgeListFilter;
5859    use crate::embedder_registry::{BlockingEmbeddingService, EmbedderProvider};
5860    use crate::error::RuntimeError;
5861    use crate::runtime::{KhiveRuntime, NamespaceToken};
5862    use crate::{ActorRef, Namespace};
5863    use async_trait::async_trait;
5864    use khive_storage::types::PathNode;
5865    use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService, MAX_TEXT_CHARS};
5866    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5867    use std::sync::Arc;
5868
5869    fn rt() -> KhiveRuntime {
5870        KhiveRuntime::memory().unwrap()
5871    }
5872
5873    #[test]
5874    fn fts_fault_arm_disarms_namespace_when_scope_panics() {
5875        let ns = format!("fault-arm-drop-{}", uuid::Uuid::new_v4().as_simple());
5876
5877        let panic_result = std::panic::catch_unwind(|| {
5878            let _arm = arm_fts_fail_scoped(&ns);
5879            panic!("leave the armed scope before consumption");
5880        });
5881
5882        assert!(panic_result.is_err());
5883        assert!(
5884            !consume_fault(&FTS_FAIL_NS, &ns),
5885            "unwinding an armed scope must remove its namespace"
5886        );
5887    }
5888
5889    #[test]
5890    fn fault_arm_set_rejects_entries_over_capacity() {
5891        static BOUNDED_ARMS: std::sync::LazyLock<FaultArmSet> =
5892            std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
5893        let first_ns = format!("fault-arm-bound-a-{}", uuid::Uuid::new_v4().as_simple());
5894        let overflow_ns = format!("fault-arm-bound-b-{}", uuid::Uuid::new_v4().as_simple());
5895        let arm = arm_fault(&BOUNDED_ARMS, &first_ns, 1);
5896
5897        let overflow = std::panic::catch_unwind(|| arm_fault(&BOUNDED_ARMS, &overflow_ns, 1));
5898
5899        assert!(
5900            overflow.is_err(),
5901            "an arm set must reject entries over its bound"
5902        );
5903        drop(arm);
5904        assert!(BOUNDED_ARMS.lock().unwrap().is_empty());
5905    }
5906
5907    // ── Custom embedder fan-out regression ──────────────────────────────────
5908    // A runtime with no `config.embedding_model` but a custom registered
5909    // embedder must fan out create_note through that embedder and store a
5910    // vector so recall can find the note.
5911
5912    /// Trivial constant-vector embedding service.  The model argument is ignored;
5913    /// the service always returns a synthetic `dims × 1.0f32` vector.
5914    struct ConstVecService {
5915        dims: usize,
5916    }
5917
5918    #[async_trait]
5919    impl EmbeddingService for ConstVecService {
5920        async fn embed(
5921            &self,
5922            texts: &[String],
5923            _model: EmbeddingModel,
5924        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
5925            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
5926        }
5927
5928        fn supports_model(&self, _model: EmbeddingModel) -> bool {
5929            true
5930        }
5931
5932        fn name(&self) -> &'static str {
5933            "const-vec"
5934        }
5935    }
5936
5937    struct ConstVecProvider {
5938        provider_name: String,
5939        dims: usize,
5940        pub build_count: Arc<AtomicUsize>,
5941    }
5942
5943    impl ConstVecProvider {
5944        fn new(name: &str, dims: usize) -> (Self, Arc<AtomicUsize>) {
5945            let counter = Arc::new(AtomicUsize::new(0));
5946            let provider = Self {
5947                provider_name: name.to_owned(),
5948                dims,
5949                build_count: Arc::clone(&counter),
5950            };
5951            (provider, counter)
5952        }
5953    }
5954
5955    #[async_trait]
5956    impl EmbedderProvider for ConstVecProvider {
5957        fn name(&self) -> &str {
5958            &self.provider_name
5959        }
5960
5961        fn dimensions(&self) -> usize {
5962            self.dims
5963        }
5964
5965        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
5966            self.build_count.fetch_add(1, Ordering::SeqCst);
5967            Ok(Arc::new(ConstVecService { dims: self.dims }))
5968        }
5969    }
5970
5971    /// Embedding service that sleeps briefly before returning, so its spawned
5972    /// embed task is still in flight when a sibling model's task resolves
5973    /// first — used to exercise the drain-before-return invariant on the
5974    /// multi-model embed fan-out.
5975    struct SlowVecService {
5976        dims: usize,
5977    }
5978
5979    #[async_trait]
5980    impl EmbeddingService for SlowVecService {
5981        async fn embed(
5982            &self,
5983            texts: &[String],
5984            _model: EmbeddingModel,
5985        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
5986            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
5987            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
5988        }
5989
5990        fn supports_model(&self, _model: EmbeddingModel) -> bool {
5991            true
5992        }
5993
5994        fn name(&self) -> &'static str {
5995            "slow-vec"
5996        }
5997    }
5998
5999    struct SlowVecProvider {
6000        provider_name: String,
6001        dims: usize,
6002    }
6003
6004    impl SlowVecProvider {
6005        fn new(name: &str, dims: usize) -> Self {
6006            Self {
6007                provider_name: name.to_owned(),
6008                dims,
6009            }
6010        }
6011    }
6012
6013    #[async_trait]
6014    impl EmbedderProvider for SlowVecProvider {
6015        fn name(&self) -> &str {
6016            &self.provider_name
6017        }
6018
6019        fn dimensions(&self) -> usize {
6020            self.dims
6021        }
6022
6023        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6024            Ok(Arc::new(SlowVecService { dims: self.dims }))
6025        }
6026    }
6027
6028    /// Embedder that fails inference immediately unless configured to wait for
6029    /// a sibling's entry signal first.
6030    struct FailFastProvider {
6031        provider_name: String,
6032        wait_for: Option<Arc<AtomicBool>>,
6033    }
6034
6035    impl FailFastProvider {
6036        fn new(name: &str) -> Self {
6037            Self {
6038                provider_name: name.to_owned(),
6039                wait_for: None,
6040            }
6041        }
6042
6043        fn after_signal(name: &str, wait_for: Arc<AtomicBool>) -> Self {
6044            Self {
6045                provider_name: name.to_owned(),
6046                wait_for: Some(wait_for),
6047            }
6048        }
6049    }
6050
6051    #[async_trait]
6052    impl EmbedderProvider for FailFastProvider {
6053        fn name(&self) -> &str {
6054            &self.provider_name
6055        }
6056
6057        fn dimensions(&self) -> usize {
6058            4
6059        }
6060
6061        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6062            Ok(Arc::new(FailFastService {
6063                wait_for: self.wait_for.clone(),
6064            }))
6065        }
6066    }
6067
6068    struct FailFastService {
6069        wait_for: Option<Arc<AtomicBool>>,
6070    }
6071
6072    #[async_trait]
6073    impl EmbeddingService for FailFastService {
6074        async fn embed(
6075            &self,
6076            _texts: &[String],
6077            _model: EmbeddingModel,
6078        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6079            if let Some(wait_for) = &self.wait_for {
6080                while !wait_for.load(Ordering::Acquire) {
6081                    tokio::task::yield_now().await;
6082                }
6083            }
6084            Err(EmbedError::InferenceFailed(
6085                "injected embed failure".to_string(),
6086            ))
6087        }
6088
6089        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6090            true
6091        }
6092
6093        fn name(&self) -> &'static str {
6094            "fail-fast"
6095        }
6096    }
6097
6098    /// Embedder whose synchronous inference section is controlled by a
6099    /// condition variable, matching native inference that cannot observe task
6100    /// cancellation until the encode call returns.
6101    struct BlockingVecProvider {
6102        provider_name: String,
6103        dims: usize,
6104        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6105        entered: Arc<AtomicBool>,
6106    }
6107
6108    struct BlockingVecControls {
6109        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6110        entered: Arc<AtomicBool>,
6111    }
6112
6113    impl BlockingVecProvider {
6114        fn new(name: &str, dims: usize) -> (Self, BlockingVecControls) {
6115            let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
6116            let entered = Arc::new(AtomicBool::new(false));
6117            (
6118                Self {
6119                    provider_name: name.to_owned(),
6120                    dims,
6121                    release: Arc::clone(&release),
6122                    entered: Arc::clone(&entered),
6123                },
6124                BlockingVecControls { release, entered },
6125            )
6126        }
6127    }
6128
6129    #[async_trait]
6130    impl EmbedderProvider for BlockingVecProvider {
6131        fn name(&self) -> &str {
6132            &self.provider_name
6133        }
6134
6135        fn dimensions(&self) -> usize {
6136            self.dims
6137        }
6138
6139        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6140            let service = Arc::new(BlockingVecService {
6141                dims: self.dims,
6142                release: Arc::clone(&self.release),
6143                entered: Arc::clone(&self.entered),
6144            });
6145            Ok(Arc::new(BlockingEmbeddingService::new(service)))
6146        }
6147    }
6148
6149    struct BlockingVecService {
6150        dims: usize,
6151        release: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
6152        entered: Arc<AtomicBool>,
6153    }
6154
6155    #[async_trait]
6156    impl EmbeddingService for BlockingVecService {
6157        async fn embed(
6158            &self,
6159            texts: &[String],
6160            _model: EmbeddingModel,
6161        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6162            self.entered.store(true, Ordering::Release);
6163            let (released, wake) = &*self.release;
6164            let guard = released.lock().expect("release lock must not be poisoned");
6165            let _guard = wake
6166                .wait_while(guard, |released| !*released)
6167                .expect("release lock must not be poisoned");
6168            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6169        }
6170
6171        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6172            true
6173        }
6174
6175        fn name(&self) -> &'static str {
6176            "blocking-vec"
6177        }
6178    }
6179
6180    /// Embedder whose `embed` parks until a release that never comes — models
6181    /// a hung provider. Only task abort can end its embed future. `entered`
6182    /// receives a permit when `embed` is reached, so a test can wait until the
6183    /// parked task is provably past the dispatch point before acting on it.
6184    struct ParkedVecProvider {
6185        provider_name: String,
6186        dims: usize,
6187        release: Arc<tokio::sync::Notify>,
6188        entered: Arc<tokio::sync::Notify>,
6189    }
6190
6191    impl ParkedVecProvider {
6192        fn new(
6193            name: &str,
6194            dims: usize,
6195        ) -> (Self, Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
6196            let release = Arc::new(tokio::sync::Notify::new());
6197            let entered = Arc::new(tokio::sync::Notify::new());
6198            (
6199                Self {
6200                    provider_name: name.to_owned(),
6201                    dims,
6202                    release: Arc::clone(&release),
6203                    entered: Arc::clone(&entered),
6204                },
6205                release,
6206                entered,
6207            )
6208        }
6209    }
6210
6211    #[async_trait]
6212    impl EmbedderProvider for ParkedVecProvider {
6213        fn name(&self) -> &str {
6214            &self.provider_name
6215        }
6216
6217        fn dimensions(&self) -> usize {
6218            self.dims
6219        }
6220
6221        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
6222            Ok(Arc::new(ParkedVecService {
6223                dims: self.dims,
6224                release: Arc::clone(&self.release),
6225                entered: Arc::clone(&self.entered),
6226            }))
6227        }
6228    }
6229
6230    struct ParkedVecService {
6231        dims: usize,
6232        release: Arc<tokio::sync::Notify>,
6233        entered: Arc<tokio::sync::Notify>,
6234    }
6235
6236    #[async_trait]
6237    impl EmbeddingService for ParkedVecService {
6238        async fn embed(
6239            &self,
6240            texts: &[String],
6241            _model: EmbeddingModel,
6242        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
6243            // notify_one stores a permit when no waiter is registered yet, so
6244            // the entered signal cannot be lost to a start-order race.
6245            self.entered.notify_one();
6246            self.release.notified().await;
6247            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
6248        }
6249
6250        fn supports_model(&self, _model: EmbeddingModel) -> bool {
6251            true
6252        }
6253
6254        fn name(&self) -> &'static str {
6255            "parked-vec"
6256        }
6257    }
6258
6259    /// Custom embedder with no lattice model in config must participate in
6260    /// fan-out: the gate must check `registered_embedding_model_names()`, not
6261    /// `config().embedding_model.is_some()`: the latter falls through to
6262    /// `vec![]` when only a custom provider is registered.
6263    #[tokio::test]
6264    async fn custom_embedder_only_runtime_fanout_stores_vector() {
6265        const MODEL_NAME: &str = "test-custom-encoder";
6266        const DIMS: usize = 8;
6267
6268        // Build a runtime with no lattice embedding_model.
6269        let rt = KhiveRuntime::memory().unwrap();
6270
6271        // Register the custom provider — this is the only embedder configured.
6272        let (provider, _counter) = ConstVecProvider::new(MODEL_NAME, DIMS);
6273        rt.register_embedder(provider);
6274
6275        // Sanity: config.embedding_model is None, but the registry has one entry.
6276        assert!(rt.config().embedding_model.is_none());
6277        assert_eq!(rt.registered_embedding_model_names(), vec![MODEL_NAME]);
6278
6279        let tok = NamespaceToken::local();
6280
6281        // create_note should fan out to the custom embedder and store a vector.
6282        let note = rt
6283            .create_note(
6284                &tok,
6285                "memory",
6286                None,
6287                "custom embedder integration test content",
6288                Some(0.7),
6289                None,
6290                vec![],
6291            )
6292            .await
6293            .expect("create_note with custom-only embedder must succeed");
6294
6295        // Verify: a vector was written in the custom model's store.
6296        use khive_storage::types::VectorSearchRequest;
6297        let query_vec = vec![1.0_f32; DIMS];
6298        let hits = rt
6299            .vectors_for_model(&tok, MODEL_NAME)
6300            .expect("vector store for custom model must be accessible")
6301            .search(VectorSearchRequest {
6302                query_vectors: vec![query_vec],
6303                top_k: 5,
6304                namespace: Some(tok.namespace().as_str().to_string()),
6305                kind: Some(khive_types::SubstrateKind::Note),
6306                embedding_model: Some(MODEL_NAME.to_string()),
6307                filter: None,
6308                backend_hints: None,
6309            })
6310            .await
6311            .expect("vector search succeeds");
6312
6313        assert!(
6314            hits.iter().any(|h| h.subject_id == note.id),
6315            "custom embedder must have written a vector for note {}: hits={hits:?}",
6316            note.id
6317        );
6318    }
6319
6320    /// Custom-only embedder participates in `embed_with_model` so recall
6321    /// fan-out also works: the lattice alias parse must be optional, with
6322    /// the embedder registry consulted directly, since requiring a lattice
6323    /// alias would reject valid custom provider names with `UnknownModel`.
6324    #[tokio::test]
6325    async fn embed_with_model_accepts_custom_provider_name() {
6326        const MODEL_NAME: &str = "my-custom-enc";
6327        const DIMS: usize = 4;
6328
6329        let rt = KhiveRuntime::memory().unwrap();
6330        let (provider, _counter) = ConstVecProvider::new(MODEL_NAME, DIMS);
6331        rt.register_embedder(provider);
6332
6333        let result = rt
6334            .embed_with_model(MODEL_NAME, "hello world")
6335            .await
6336            .expect("embed_with_model must accept custom provider names");
6337
6338        assert_eq!(
6339            result.len(),
6340            DIMS,
6341            "embedding dimension must match provider"
6342        );
6343        assert!(
6344            result.iter().all(|&v| (v - 1.0_f32).abs() < 1e-6),
6345            "ConstVecService must produce all-ones vector; got: {result:?}"
6346        );
6347    }
6348
6349    /// `embed_with_model` must still reject names that are not in the
6350    /// registry (neither lattice aliases nor custom providers).
6351    #[tokio::test]
6352    async fn embed_with_model_rejects_unregistered_name() {
6353        let rt = KhiveRuntime::memory().unwrap();
6354        let result = rt.embed_with_model("nonexistent-model", "hello").await;
6355        assert!(
6356            matches!(result.unwrap_err(), RuntimeError::UnknownModel(ref n) if n == "nonexistent-model"),
6357            "unregistered model name must return UnknownModel"
6358        );
6359    }
6360
6361    // ── No-embeddings config regression ─────────────────────────────────────
6362    // `RuntimeConfig::no_embeddings()` must register zero embedders, so
6363    // `create_note` never attempts to lazily build a lattice embedding model —
6364    // this is what lets `memory.remember` succeed on a machine with no local
6365    // model files present.
6366
6367    #[tokio::test]
6368    async fn no_embeddings_config_registers_zero_embedders() {
6369        let config = crate::config::RuntimeConfig {
6370            db_path: None,
6371            packs: vec!["kg".to_string()],
6372            ..crate::config::RuntimeConfig::no_embeddings()
6373        };
6374        let rt = KhiveRuntime::new(config).expect("runtime construction must succeed");
6375
6376        assert!(rt.config().embedding_model.is_none());
6377        assert!(
6378            rt.registered_embedding_model_names().is_empty(),
6379            "no_embeddings() runtime must register zero embedders"
6380        );
6381    }
6382
6383    #[tokio::test]
6384    async fn no_embeddings_runtime_create_note_succeeds_without_model_fanout() {
6385        let config = crate::config::RuntimeConfig {
6386            db_path: None,
6387            packs: vec!["kg".to_string()],
6388            ..crate::config::RuntimeConfig::no_embeddings()
6389        };
6390        let rt = KhiveRuntime::new(config).expect("runtime construction must succeed");
6391        let tok = NamespaceToken::local();
6392
6393        // With zero registered embedders, create_note's embed fan-out list is
6394        // empty and no lattice model build is ever attempted -- the write must
6395        // succeed, degrading to FTS-only.
6396        let note = rt
6397            .create_note(
6398                &tok,
6399                "memory",
6400                None,
6401                "issue-396 regression: model-less remember must succeed",
6402                Some(0.7),
6403                None,
6404                vec![],
6405            )
6406            .await
6407            .expect("create_note must succeed with zero registered embedders");
6408
6409        assert_eq!(
6410            note.content,
6411            "issue-396 regression: model-less remember must succeed"
6412        );
6413    }
6414
6415    #[tokio::test]
6416    async fn update_edge_changes_weight() {
6417        let rt = rt();
6418        let tok = NamespaceToken::local();
6419        let a = rt
6420            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6421            .await
6422            .unwrap();
6423        let b = rt
6424            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6425            .await
6426            .unwrap();
6427        let edge = rt
6428            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6429            .await
6430            .unwrap();
6431        let edge_id: Uuid = edge.id.into();
6432
6433        let updated = rt
6434            .update_edge(
6435                &tok,
6436                edge_id,
6437                crate::curation::EdgePatch {
6438                    weight: Some(0.5),
6439                    ..Default::default()
6440                },
6441            )
6442            .await
6443            .unwrap();
6444        assert!((updated.weight - 0.5).abs() < 0.001);
6445    }
6446
6447    /// Regression test: `update_edge_symmetric_dml` previously stored
6448    /// `updated_at` via `chrono::Utc::now().timestamp()` (SECONDS) while every
6449    /// other `graph_edges` write path (`edge_upsert_statement`,
6450    /// `edge_soft_delete_statement`) uses `timestamp_micros()`: a genuine
6451    /// pre-existing bug, found while unifying this raw-SQL path with the
6452    /// atomic builder (which already used `timestamp_micros()` correctly)
6453    /// onto the shared `EDGE_SYMMETRIC_*_SQL` text. A seconds value misread as
6454    /// microseconds round-trips to a date a few minutes after the Unix epoch,
6455    /// not "now".
6456    #[tokio::test]
6457    async fn update_edge_symmetric_relation_stores_microsecond_updated_at() {
6458        let rt = rt();
6459        let tok = NamespaceToken::local();
6460        let a = rt
6461            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6462            .await
6463            .unwrap();
6464        let b = rt
6465            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6466            .await
6467            .unwrap();
6468        let edge = rt
6469            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
6470            .await
6471            .unwrap();
6472        let edge_id: Uuid = edge.id.into();
6473
6474        let before = chrono::Utc::now();
6475        let updated = rt
6476            .update_edge(
6477                &tok,
6478                edge_id,
6479                crate::curation::EdgePatch {
6480                    weight: Some(0.5),
6481                    ..Default::default()
6482                },
6483            )
6484            .await
6485            .unwrap();
6486
6487        let drift = (updated.updated_at - before).num_seconds().abs();
6488        assert!(
6489            drift < 60,
6490            "updated_at must round-trip as a recent timestamp (micros, not \
6491             seconds); got {:?}, expected within 60s of {:?}",
6492            updated.updated_at,
6493            before
6494        );
6495    }
6496
6497    #[tokio::test]
6498    async fn update_edge_changes_relation() {
6499        let rt = rt();
6500        let tok = NamespaceToken::local();
6501        let a = rt
6502            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6503            .await
6504            .unwrap();
6505        let b = rt
6506            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6507            .await
6508            .unwrap();
6509        let edge = rt
6510            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6511            .await
6512            .unwrap();
6513        let edge_id: Uuid = edge.id.into();
6514
6515        let updated = rt
6516            .update_edge(
6517                &tok,
6518                edge_id,
6519                crate::curation::EdgePatch {
6520                    relation: Some(EdgeRelation::VariantOf),
6521                    ..Default::default()
6522                },
6523            )
6524            .await
6525            .unwrap();
6526        assert_eq!(updated.relation, EdgeRelation::VariantOf);
6527    }
6528
6529    /// A symmetric-relation update whose canonical natural key collides
6530    /// with an existing edge must delete the requested (non-canonical)
6531    /// row and leave the surviving canonical row's attributes untouched
6532    /// (ADR-039 ON CONFLICT DO NOTHING) — the discarded edge's patched
6533    /// weight must never overwrite the survivor (khive#1213).
6534    #[tokio::test]
6535    async fn update_edge_symmetric_conflict_keeps_survivor_attributes() {
6536        let rt = rt();
6537        let tok = NamespaceToken::local();
6538        let a = rt
6539            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6540            .await
6541            .unwrap();
6542        let b = rt
6543            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6544            .await
6545            .unwrap();
6546
6547        let requested = rt
6548            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.2, None)
6549            .await
6550            .unwrap();
6551        let requested_id: Uuid = requested.id.into();
6552
6553        let canonical = rt
6554            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.6, None)
6555            .await
6556            .unwrap();
6557        let canonical_id: Uuid = canonical.id.into();
6558
6559        let updated = rt
6560            .update_edge(
6561                &tok,
6562                requested_id,
6563                crate::curation::EdgePatch {
6564                    relation: Some(EdgeRelation::CompetesWith),
6565                    weight: Some(0.9),
6566                    ..Default::default()
6567                },
6568            )
6569            .await
6570            .unwrap();
6571
6572        // The requested (non-canonical) row was absorbed into the survivor.
6573        assert_eq!(Uuid::from(updated.id), canonical_id);
6574        assert_eq!(
6575            updated.weight, 0.6,
6576            "survivor weight must not be overwritten by the discarded edge's patch"
6577        );
6578
6579        let requested_after = rt
6580            .get_edge_including_deleted(&tok, requested_id)
6581            .await
6582            .unwrap();
6583        assert!(
6584            requested_after.is_none(),
6585            "the non-canonical requested row must be deleted, not just tombstoned"
6586        );
6587    }
6588
6589    /// A soft-deleted surviving canonical row must not be resurrected by a
6590    /// conflicting symmetric-relation update (khive#1213).
6591    #[tokio::test]
6592    async fn update_edge_symmetric_conflict_does_not_resurrect_tombstoned_survivor() {
6593        let rt = rt();
6594        let tok = NamespaceToken::local();
6595        let a = rt
6596            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6597            .await
6598            .unwrap();
6599        let b = rt
6600            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6601            .await
6602            .unwrap();
6603
6604        let requested = rt
6605            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.2, None)
6606            .await
6607            .unwrap();
6608        let requested_id: Uuid = requested.id.into();
6609
6610        let canonical = rt
6611            .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 0.6, None)
6612            .await
6613            .unwrap();
6614        let canonical_id: Uuid = canonical.id.into();
6615        rt.delete_edge(&tok, canonical_id, false).await.unwrap();
6616
6617        rt.update_edge(
6618            &tok,
6619            requested_id,
6620            crate::curation::EdgePatch {
6621                relation: Some(EdgeRelation::CompetesWith),
6622                weight: Some(0.9),
6623                ..Default::default()
6624            },
6625        )
6626        .await
6627        .unwrap();
6628
6629        let requested_after = rt
6630            .get_edge_including_deleted(&tok, requested_id)
6631            .await
6632            .unwrap();
6633        assert!(
6634            requested_after.is_none(),
6635            "the non-canonical requested row must be deleted, not just tombstoned"
6636        );
6637
6638        let canonical_after = rt.get_edge(&tok, canonical_id).await.unwrap();
6639        assert!(
6640            canonical_after.is_none(),
6641            "a tombstoned survivor must not be resurrected by a conflicting update"
6642        );
6643    }
6644
6645    // ---- update_edge endpoint validation ----
6646
6647    // update_edge: note→entity annotates → set relation=Supersedes → InvalidInput (crossing).
6648    // Edge must NOT be mutated in the store.
6649    #[tokio::test]
6650    async fn update_edge_annotates_note_to_entity_set_supersedes_returns_invalid_input() {
6651        let rt = rt();
6652        let tok = NamespaceToken::local();
6653        let note = rt
6654            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
6655            .await
6656            .unwrap();
6657        let entity = rt
6658            .create_entity(&tok, "concept", None, "E", None, None, vec![])
6659            .await
6660            .unwrap();
6661        // Create a valid note→entity annotates edge.
6662        let edge = rt
6663            .link(&tok, note.id, entity.id, EdgeRelation::Annotates, 1.0, None)
6664            .await
6665            .unwrap();
6666        let edge_id: Uuid = edge.id.into();
6667
6668        // Attempt to change relation to Supersedes (crossing substrates → invalid).
6669        let result = rt
6670            .update_edge(
6671                &tok,
6672                edge_id,
6673                crate::curation::EdgePatch {
6674                    relation: Some(EdgeRelation::Supersedes),
6675                    ..Default::default()
6676                },
6677            )
6678            .await;
6679        assert!(
6680            matches!(result, Err(RuntimeError::InvalidInput(_))),
6681            "update to Supersedes on note→entity edge must return InvalidInput, got {result:?}"
6682        );
6683
6684        // Edge must NOT be mutated — re-fetch and verify relation unchanged.
6685        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
6686        assert_eq!(
6687            fetched.relation,
6688            EdgeRelation::Annotates,
6689            "edge relation must be unchanged after failed update"
6690        );
6691    }
6692
6693    // update_edge: entity→entity extends → set relation=Annotates → InvalidInput
6694    // (annotates source must be a note).
6695    #[tokio::test]
6696    async fn update_edge_entity_to_entity_set_annotates_returns_invalid_input() {
6697        let rt = rt();
6698        let tok = NamespaceToken::local();
6699        let a = rt
6700            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6701            .await
6702            .unwrap();
6703        let b = rt
6704            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6705            .await
6706            .unwrap();
6707        let edge = rt
6708            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6709            .await
6710            .unwrap();
6711        let edge_id: Uuid = edge.id.into();
6712
6713        let result = rt
6714            .update_edge(
6715                &tok,
6716                edge_id,
6717                crate::curation::EdgePatch {
6718                    relation: Some(EdgeRelation::Annotates),
6719                    ..Default::default()
6720                },
6721            )
6722            .await;
6723        assert!(
6724            matches!(result, Err(RuntimeError::InvalidInput(_))),
6725            "update to Annotates on entity→entity edge must return InvalidInput, got {result:?}"
6726        );
6727    }
6728
6729    // update_edge: entity→entity extends → set relation=Supersedes → Ok
6730    // (entity→entity is valid for supersedes).
6731    #[tokio::test]
6732    async fn update_edge_entity_to_entity_set_supersedes_succeeds() {
6733        let rt = rt();
6734        let tok = NamespaceToken::local();
6735        let a = rt
6736            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6737            .await
6738            .unwrap();
6739        let b = rt
6740            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6741            .await
6742            .unwrap();
6743        let edge = rt
6744            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6745            .await
6746            .unwrap();
6747        let edge_id: Uuid = edge.id.into();
6748
6749        let updated = rt
6750            .update_edge(
6751                &tok,
6752                edge_id,
6753                crate::curation::EdgePatch {
6754                    relation: Some(EdgeRelation::Supersedes),
6755                    ..Default::default()
6756                },
6757            )
6758            .await
6759            .unwrap();
6760        assert_eq!(updated.relation, EdgeRelation::Supersedes);
6761
6762        // Verify persisted.
6763        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
6764        assert_eq!(fetched.relation, EdgeRelation::Supersedes);
6765    }
6766
6767    // update_edge: weight-only (relation = None) → Ok, no validation, unchanged relation.
6768    #[tokio::test]
6769    async fn update_edge_weight_only_skips_validation() {
6770        let rt = rt();
6771        let tok = NamespaceToken::local();
6772        let a = rt
6773            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6774            .await
6775            .unwrap();
6776        let b = rt
6777            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6778            .await
6779            .unwrap();
6780        let edge = rt
6781            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6782            .await
6783            .unwrap();
6784        let edge_id: Uuid = edge.id.into();
6785
6786        let updated = rt
6787            .update_edge(
6788                &tok,
6789                edge_id,
6790                crate::curation::EdgePatch {
6791                    weight: Some(0.3),
6792                    ..Default::default()
6793                },
6794            )
6795            .await
6796            .unwrap();
6797        assert_eq!(updated.relation, EdgeRelation::Extends);
6798        assert!((updated.weight - 0.3).abs() < 0.001);
6799    }
6800
6801    // update_edge: entity→entity extends → set relation=VariantOf (same class) → Ok.
6802    #[tokio::test]
6803    async fn update_edge_same_class_relation_change_succeeds() {
6804        let rt = rt();
6805        let tok = NamespaceToken::local();
6806        let a = rt
6807            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6808            .await
6809            .unwrap();
6810        let b = rt
6811            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6812            .await
6813            .unwrap();
6814        let edge = rt
6815            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6816            .await
6817            .unwrap();
6818        let edge_id: Uuid = edge.id.into();
6819
6820        let updated = rt
6821            .update_edge(
6822                &tok,
6823                edge_id,
6824                crate::curation::EdgePatch {
6825                    relation: Some(EdgeRelation::VariantOf),
6826                    ..Default::default()
6827                },
6828            )
6829            .await
6830            .unwrap();
6831        assert_eq!(updated.relation, EdgeRelation::VariantOf);
6832    }
6833
6834    #[tokio::test]
6835    async fn list_edges_filters_by_relation() {
6836        let rt = rt();
6837        let tok = NamespaceToken::local();
6838        let a = rt
6839            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6840            .await
6841            .unwrap();
6842        let b = rt
6843            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6844            .await
6845            .unwrap();
6846        let c = rt
6847            .create_entity(&tok, "concept", None, "C", None, None, vec![])
6848            .await
6849            .unwrap();
6850
6851        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6852            .await
6853            .unwrap();
6854        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
6855            .await
6856            .unwrap();
6857
6858        let filter = EdgeListFilter {
6859            relations: vec![EdgeRelation::Extends],
6860            ..Default::default()
6861        };
6862        let edges = rt.list_edges(&tok, filter, 100, 0).await.unwrap();
6863        assert_eq!(edges.len(), 1);
6864        assert_eq!(edges[0].relation, EdgeRelation::Extends);
6865    }
6866
6867    #[tokio::test]
6868    async fn list_edges_filters_by_source() {
6869        let rt = rt();
6870        let tok = NamespaceToken::local();
6871        let a = rt
6872            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6873            .await
6874            .unwrap();
6875        let b = rt
6876            .create_entity(&tok, "concept", None, "B", None, None, vec![])
6877            .await
6878            .unwrap();
6879        let c = rt
6880            .create_entity(&tok, "concept", None, "C", None, None, vec![])
6881            .await
6882            .unwrap();
6883        let d = rt
6884            .create_entity(&tok, "concept", None, "D", None, None, vec![])
6885            .await
6886            .unwrap();
6887
6888        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
6889            .await
6890            .unwrap();
6891        rt.link(&tok, c.id, d.id, EdgeRelation::Extends, 1.0, None)
6892            .await
6893            .unwrap();
6894
6895        let filter = EdgeListFilter {
6896            source_id: Some(a.id),
6897            ..Default::default()
6898        };
6899        let edges = rt.list_edges(&tok, filter, 100, 0).await.unwrap();
6900        assert_eq!(edges.len(), 1);
6901        let src: Uuid = edges[0].source_id;
6902        assert_eq!(src, a.id);
6903    }
6904
6905    /// Regression: `offset` was hard-coded to 0 in `list_edges`, so every
6906    /// page returned the identical first rows. Pages must now tile the full
6907    /// matching set with no gaps or duplicates, and an out-of-range offset
6908    /// must return empty rather than page 1.
6909    #[tokio::test]
6910    async fn list_edges_offset_pages_through_full_set() {
6911        let rt = rt();
6912        let tok = NamespaceToken::local();
6913        let a = rt
6914            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6915            .await
6916            .unwrap();
6917        for i in 0..5 {
6918            let t = rt
6919                .create_entity(&tok, "concept", None, &format!("T{i}"), None, None, vec![])
6920                .await
6921                .unwrap();
6922            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
6923                .await
6924                .unwrap();
6925        }
6926
6927        let filter = EdgeListFilter {
6928            source_id: Some(a.id),
6929            relations: vec![EdgeRelation::Extends],
6930            ..Default::default()
6931        };
6932
6933        let page0 = rt.list_edges(&tok, filter.clone(), 2, 0).await.unwrap();
6934        let page1 = rt.list_edges(&tok, filter.clone(), 2, 2).await.unwrap();
6935        let page2 = rt.list_edges(&tok, filter.clone(), 2, 4).await.unwrap();
6936        assert_eq!(page0.len(), 2);
6937        assert_eq!(page1.len(), 2);
6938        assert_eq!(page2.len(), 1);
6939
6940        let ids = |p: &[Edge]| p.iter().map(|e| Uuid::from(e.id)).collect::<Vec<_>>();
6941        assert_ne!(ids(&page0), ids(&page1), "page 2 must differ from page 1");
6942
6943        let mut all_ids: Vec<Uuid> = ids(&page0)
6944            .into_iter()
6945            .chain(ids(&page1))
6946            .chain(ids(&page2))
6947            .collect();
6948        all_ids.sort();
6949        all_ids.dedup();
6950        assert_eq!(all_ids.len(), 5, "pages must tile the full edge set");
6951
6952        let empty = rt.list_edges(&tok, filter.clone(), 2, 100).await.unwrap();
6953        assert!(
6954            empty.is_empty(),
6955            "offset past the end must return empty, not page 1"
6956        );
6957    }
6958
6959    /// `list_edges_after` seeks via a durable insertion sequence instead of
6960    /// paging through OFFSET, so cost does not grow with walk depth.
6961    #[tokio::test]
6962    async fn list_edges_after_keyset_tiles_full_set() {
6963        let rt = rt();
6964        let tok = NamespaceToken::local();
6965        let a = rt
6966            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6967            .await
6968            .unwrap();
6969        for i in 0..5 {
6970            let t = rt
6971                .create_entity(&tok, "concept", None, &format!("K{i}"), None, None, vec![])
6972                .await
6973                .unwrap();
6974            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
6975                .await
6976                .unwrap();
6977        }
6978
6979        let filter = EdgeListFilter {
6980            source_id: Some(a.id),
6981            relations: vec![EdgeRelation::Extends],
6982            ..Default::default()
6983        };
6984
6985        let mut seen = Vec::new();
6986        let mut cursor: Option<Uuid> = None;
6987        for _ in 0..20 {
6988            let (page, next) = rt
6989                .list_edges_after(&tok, filter.clone(), cursor, 2)
6990                .await
6991                .unwrap();
6992            if page.is_empty() {
6993                break;
6994            }
6995            seen.extend(page.iter().map(|e| Uuid::from(e.id)));
6996            if next.is_none() {
6997                break;
6998            }
6999            cursor = next;
7000        }
7001        seen.sort();
7002        seen.dedup();
7003        assert_eq!(seen.len(), 5, "keyset walk must tile the full edge set");
7004
7005        // With no intervening writes, repeating the same cursor returns the
7006        // same insertion-sequence page.
7007        let (first_a, next_a) = rt
7008            .list_edges_after(&tok, filter.clone(), None, 2)
7009            .await
7010            .unwrap();
7011        let (first_b, next_b) = rt
7012            .list_edges_after(&tok, filter.clone(), None, 2)
7013            .await
7014            .unwrap();
7015        assert_eq!(
7016            first_a.iter().map(|e| e.id.0).collect::<Vec<_>>(),
7017            first_b.iter().map(|e| e.id.0).collect::<Vec<_>>(),
7018        );
7019        assert_eq!(next_a, next_b);
7020    }
7021
7022    #[tokio::test]
7023    async fn list_entities_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
7024        let rt = rt();
7025        let tok = NamespaceToken::local();
7026        let ids = [
7027            Uuid::parse_str("f0000000-0000-4000-8000-000000000011").unwrap(),
7028            Uuid::parse_str("f0000000-0000-4000-8000-000000000012").unwrap(),
7029            Uuid::parse_str("f0000000-0000-4000-8000-000000000013").unwrap(),
7030        ];
7031        let store = rt.entities(&tok).unwrap();
7032        for (index, id) in ids.into_iter().enumerate() {
7033            let mut entity = Entity::new("local", "concept", format!("Entity{index}"));
7034            entity.id = id;
7035            entity.created_at = 1_000_000;
7036            entity.updated_at = 1_000_000;
7037            store.upsert_entity(entity).await.unwrap();
7038        }
7039
7040        let (first, next) = rt
7041            .list_entities_after(&tok, None, None, &[], None, 2)
7042            .await
7043            .unwrap();
7044        assert_eq!(
7045            first.iter().map(|entity| entity.id).collect::<Vec<_>>(),
7046            ids[..2]
7047        );
7048        let cursor = next.expect("one original entity remains after page one");
7049
7050        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000011").unwrap();
7051        assert!(low_id < cursor);
7052        let mut inserted = Entity::new("local", "concept", "InsertedEntity");
7053        inserted.id = low_id;
7054        inserted.created_at = 1_000_000;
7055        inserted.updated_at = 1_000_000;
7056        store.upsert_entity(inserted).await.unwrap();
7057
7058        let (second, final_cursor) = rt
7059            .list_entities_after(&tok, None, None, &[], Some(cursor), 2)
7060            .await
7061            .unwrap();
7062        assert_eq!(
7063            second.iter().map(|entity| entity.id).collect::<Vec<_>>(),
7064            vec![ids[2], low_id]
7065        );
7066        assert_eq!(final_cursor, None);
7067    }
7068
7069    #[tokio::test]
7070    async fn list_notes_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
7071        let rt = rt();
7072        let tok = NamespaceToken::local();
7073        let ids = [
7074            Uuid::parse_str("f0000000-0000-4000-8000-000000000021").unwrap(),
7075            Uuid::parse_str("f0000000-0000-4000-8000-000000000022").unwrap(),
7076            Uuid::parse_str("f0000000-0000-4000-8000-000000000023").unwrap(),
7077        ];
7078        let store = rt.notes(&tok).unwrap();
7079        for (index, id) in ids.into_iter().enumerate() {
7080            let mut note = Note::new("local", "observation", format!("Note {index}"));
7081            note.id = id;
7082            note.created_at = 1_000_000;
7083            note.updated_at = 1_000_000;
7084            store.upsert_note(note).await.unwrap();
7085        }
7086
7087        let (first, next) = rt.list_notes_after(&tok, None, None, 2).await.unwrap();
7088        assert_eq!(
7089            first.iter().map(|note| note.id).collect::<Vec<_>>(),
7090            ids[..2]
7091        );
7092        let cursor = next.expect("one original note remains after page one");
7093
7094        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000021").unwrap();
7095        assert!(low_id < cursor);
7096        let mut inserted = Note::new("local", "observation", "Inserted note");
7097        inserted.id = low_id;
7098        inserted.created_at = 1_000_000;
7099        inserted.updated_at = 1_000_000;
7100        store.upsert_note(inserted).await.unwrap();
7101
7102        let (second, final_cursor) = rt
7103            .list_notes_after(&tok, None, Some(cursor), 2)
7104            .await
7105            .unwrap();
7106        assert_eq!(
7107            second.iter().map(|note| note.id).collect::<Vec<_>>(),
7108            vec![ids[2], low_id]
7109        );
7110        assert_eq!(final_cursor, None);
7111    }
7112
7113    #[tokio::test]
7114    async fn list_edges_after_same_timestamp_lower_uuid_insert_is_not_skipped() {
7115        let rt = rt();
7116        let tok = NamespaceToken::local();
7117        let source = rt
7118            .create_entity(&tok, "concept", None, "CursorSource", None, None, vec![])
7119            .await
7120            .unwrap();
7121        let mut targets = Vec::new();
7122        for index in 0..4 {
7123            targets.push(
7124                rt.create_entity(
7125                    &tok,
7126                    "concept",
7127                    None,
7128                    &format!("CursorTarget{index}"),
7129                    None,
7130                    None,
7131                    vec![],
7132                )
7133                .await
7134                .unwrap(),
7135            );
7136        }
7137
7138        let ids = [
7139            Uuid::parse_str("f0000000-0000-4000-8000-000000000001").unwrap(),
7140            Uuid::parse_str("f0000000-0000-4000-8000-000000000002").unwrap(),
7141            Uuid::parse_str("f0000000-0000-4000-8000-000000000003").unwrap(),
7142        ];
7143        let graph = rt.graph(&tok).unwrap();
7144        let created_at = chrono::DateTime::<chrono::Utc>::from_timestamp_micros(1_000_000).unwrap();
7145        for (index, id) in ids.into_iter().enumerate() {
7146            graph
7147                .upsert_edge(Edge {
7148                    id: id.into(),
7149                    namespace: "local".into(),
7150                    source_id: source.id,
7151                    target_id: targets[index].id,
7152                    relation: EdgeRelation::Extends,
7153                    weight: 1.0,
7154                    created_at,
7155                    updated_at: created_at,
7156                    deleted_at: None,
7157                    metadata: None,
7158                    target_backend: None,
7159                })
7160                .await
7161                .unwrap();
7162        }
7163
7164        let filter = EdgeListFilter {
7165            source_id: Some(source.id),
7166            relations: vec![EdgeRelation::Extends],
7167            ..Default::default()
7168        };
7169        let (first, next) = rt
7170            .list_edges_after(&tok, filter.clone(), None, 2)
7171            .await
7172            .unwrap();
7173        assert_eq!(
7174            first.iter().map(|edge| edge.id.0).collect::<Vec<_>>(),
7175            ids[..2]
7176        );
7177        let cursor = next.expect("one original edge remains after page one");
7178
7179        // The later insert has the same wall-clock microsecond and sorts before
7180        // the cursor UUID. Its database-assigned sequence still places it after
7181        // the issued boundary.
7182        let low_id = Uuid::parse_str("00000000-0000-4000-8000-000000000001").unwrap();
7183        assert!(low_id < cursor);
7184        graph
7185            .upsert_edge(Edge {
7186                id: low_id.into(),
7187                namespace: "local".into(),
7188                source_id: source.id,
7189                target_id: targets[3].id,
7190                relation: EdgeRelation::Extends,
7191                weight: 1.0,
7192                created_at,
7193                updated_at: created_at,
7194                deleted_at: None,
7195                metadata: None,
7196                target_backend: None,
7197            })
7198            .await
7199            .unwrap();
7200
7201        let (second, final_cursor) = rt
7202            .list_edges_after(&tok, filter, Some(cursor), 2)
7203            .await
7204            .unwrap();
7205        assert_eq!(
7206            second.iter().map(|edge| edge.id.0).collect::<Vec<_>>(),
7207            vec![ids[2], low_id]
7208        );
7209        assert_eq!(final_cursor, None);
7210    }
7211
7212    #[tokio::test]
7213    async fn list_entity_cursor_survives_soft_delete_and_rejects_hard_delete_or_hidden_scope() {
7214        let rt = rt();
7215        let local = NamespaceToken::local();
7216        for index in 0..3 {
7217            rt.create_entity(
7218                &local,
7219                "concept",
7220                None,
7221                &format!("CursorLifecycle{index}"),
7222                None,
7223                None,
7224                vec![],
7225            )
7226            .await
7227            .unwrap();
7228        }
7229
7230        let (_, next) = rt
7231            .list_entities_after(&local, None, None, &[], None, 2)
7232            .await
7233            .unwrap();
7234        let cursor = next.expect("three entities require a second page");
7235        let store = rt.entities(&local).unwrap();
7236        assert!(store.delete_entity(cursor, DeleteMode::Soft).await.unwrap());
7237
7238        let (remaining, next) = rt
7239            .list_entities_after(&local, None, None, &[], Some(cursor), 2)
7240            .await
7241            .expect("a soft-deleted cursor must retain its sequence boundary");
7242        assert_eq!(remaining.len(), 1);
7243        assert_eq!(next, None);
7244
7245        assert!(store.delete_entity(cursor, DeleteMode::Hard).await.unwrap());
7246        let hard_deleted = rt
7247            .list_entities_after(&local, None, None, &[], Some(cursor), 2)
7248            .await;
7249        assert!(
7250            matches!(hard_deleted, Err(RuntimeError::NotFound(_))),
7251            "a hard-deleted cursor must fail explicitly: {hard_deleted:?}"
7252        );
7253
7254        let hidden_ns = Namespace::parse("cursor-hidden").unwrap();
7255        let hidden_token = NamespaceToken::for_namespace(hidden_ns);
7256        let hidden = rt
7257            .create_entity(
7258                &hidden_token,
7259                "concept",
7260                None,
7261                "HiddenCursor",
7262                None,
7263                None,
7264                vec![],
7265            )
7266            .await
7267            .unwrap();
7268        let out_of_scope = rt
7269            .list_entities_after(&local, None, None, &[], Some(hidden.id), 2)
7270            .await;
7271        assert!(
7272            matches!(out_of_scope, Err(RuntimeError::NotFound(_))),
7273            "an out-of-scope cursor must not reveal or resume from the hidden row: {out_of_scope:?}"
7274        );
7275    }
7276
7277    #[tokio::test]
7278    async fn list_edges_after_single_namespace_exact_final_page_has_no_next_after() {
7279        let rt = rt();
7280        let tok = NamespaceToken::local();
7281        let a = rt
7282            .create_entity(&tok, "concept", None, "SingleCursorA", None, None, vec![])
7283            .await
7284            .unwrap();
7285        for i in 0..4 {
7286            let t = rt
7287                .create_entity(
7288                    &tok,
7289                    "concept",
7290                    None,
7291                    &format!("SingleCursorT{i}"),
7292                    None,
7293                    None,
7294                    vec![],
7295                )
7296                .await
7297                .unwrap();
7298            rt.link(&tok, a.id, t.id, EdgeRelation::Extends, 1.0, None)
7299                .await
7300                .unwrap();
7301        }
7302
7303        let filter = EdgeListFilter {
7304            source_id: Some(a.id),
7305            relations: vec![EdgeRelation::Extends],
7306            ..Default::default()
7307        };
7308
7309        let (page1, next1) = rt
7310            .list_edges_after(&tok, filter.clone(), None, 2)
7311            .await
7312            .unwrap();
7313        assert_eq!(page1.len(), 2);
7314        let cursor = next1.expect("first page must report a cursor when two rows remain");
7315
7316        let (page2, next2) = rt
7317            .list_edges_after(&tok, filter, Some(cursor), 2)
7318            .await
7319            .unwrap();
7320        assert_eq!(page2.len(), 2);
7321        assert_eq!(
7322            next2, None,
7323            "an exact-size final single-namespace page must not report a cursor"
7324        );
7325    }
7326
7327    #[tokio::test]
7328    async fn list_edges_after_multi_namespace_exact_final_page_has_no_next_after() {
7329        let rt = rt();
7330        let ns_a = Namespace::parse("cursor-ns-a").unwrap();
7331        let ns_b = Namespace::parse("cursor-ns-b").unwrap();
7332        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
7333        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
7334        let visible = NamespaceToken::mint_with_visibility(ns_a, vec![ns_b], ActorRef::anonymous());
7335
7336        for (tok, prefix) in [(&tok_a, "A"), (&tok_b, "B")] {
7337            let source = rt
7338                .create_entity(
7339                    tok,
7340                    "concept",
7341                    None,
7342                    &format!("MultiCursor{prefix}Source"),
7343                    None,
7344                    None,
7345                    vec![],
7346                )
7347                .await
7348                .unwrap();
7349            for i in 0..2 {
7350                let target = rt
7351                    .create_entity(
7352                        tok,
7353                        "concept",
7354                        None,
7355                        &format!("MultiCursor{prefix}Target{i}"),
7356                        None,
7357                        None,
7358                        vec![],
7359                    )
7360                    .await
7361                    .unwrap();
7362                rt.link(tok, source.id, target.id, EdgeRelation::Extends, 1.0, None)
7363                    .await
7364                    .unwrap();
7365            }
7366        }
7367
7368        let filter = EdgeListFilter {
7369            relations: vec![EdgeRelation::Extends],
7370            ..Default::default()
7371        };
7372        let (page1, next1) = rt
7373            .list_edges_after(&visible, filter.clone(), None, 2)
7374            .await
7375            .unwrap();
7376        assert_eq!(page1.len(), 2);
7377        let cursor = next1.expect("first merged page must report a cursor when rows remain");
7378
7379        let (page2, next2) = rt
7380            .list_edges_after(&visible, filter, Some(cursor), 2)
7381            .await
7382            .unwrap();
7383        assert_eq!(page2.len(), 2);
7384        assert_eq!(
7385            next2, None,
7386            "an exact-size final multi-namespace page must not report a cursor"
7387        );
7388    }
7389
7390    /// `stats()` should be able to report a per-relation breakdown so
7391    /// auditors know the true population per relation before sampling.
7392    #[tokio::test]
7393    async fn count_edges_by_relation_matches_fixtures() {
7394        let rt = rt();
7395        let tok = NamespaceToken::local();
7396        let a = rt
7397            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7398            .await
7399            .unwrap();
7400        let b = rt
7401            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7402            .await
7403            .unwrap();
7404        let c = rt
7405            .create_entity(&tok, "concept", None, "C", None, None, vec![])
7406            .await
7407            .unwrap();
7408
7409        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7410            .await
7411            .unwrap();
7412        rt.link(&tok, a.id, c.id, EdgeRelation::Extends, 1.0, None)
7413            .await
7414            .unwrap();
7415        rt.link(&tok, b.id, c.id, EdgeRelation::Enables, 1.0, None)
7416            .await
7417            .unwrap();
7418
7419        let counts = rt.count_edges_by_relation(&tok).await.unwrap();
7420        assert_eq!(counts.get("extends").copied(), Some(2));
7421        assert_eq!(counts.get("enables").copied(), Some(1));
7422    }
7423
7424    #[tokio::test]
7425    async fn delete_edge_removes_from_storage() {
7426        let rt = rt();
7427        let tok = NamespaceToken::local();
7428        let a = rt
7429            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7430            .await
7431            .unwrap();
7432        let b = rt
7433            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7434            .await
7435            .unwrap();
7436        let edge = rt
7437            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7438            .await
7439            .unwrap();
7440        let edge_id: Uuid = edge.id.into();
7441
7442        let deleted = rt.delete_edge(&tok, edge_id, true).await.unwrap();
7443        assert!(deleted);
7444
7445        let fetched = rt.get_edge(&tok, edge_id).await.unwrap();
7446        assert!(fetched.is_none(), "edge should be gone after delete");
7447    }
7448
7449    #[tokio::test]
7450    async fn count_edges_matches_filter() {
7451        let rt = rt();
7452        let tok = NamespaceToken::local();
7453        let a = rt
7454            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7455            .await
7456            .unwrap();
7457        let b = rt
7458            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7459            .await
7460            .unwrap();
7461        let c = rt
7462            .create_entity(&tok, "concept", None, "C", None, None, vec![])
7463            .await
7464            .unwrap();
7465
7466        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7467            .await
7468            .unwrap();
7469        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
7470            .await
7471            .unwrap();
7472
7473        let all = rt
7474            .count_edges(&tok, EdgeListFilter::default())
7475            .await
7476            .unwrap();
7477        assert_eq!(all, 2);
7478
7479        let just_extends = rt
7480            .count_edges(
7481                &tok,
7482                EdgeListFilter {
7483                    relations: vec![EdgeRelation::Extends],
7484                    ..Default::default()
7485                },
7486            )
7487            .await
7488            .unwrap();
7489        assert_eq!(just_extends, 1);
7490    }
7491
7492    // ---- substrate_exists_in_ns must use get_edge_visible ----
7493
7494    /// An edge owned by a visible (non-primary) namespace must be found by
7495    /// `substrate_exists_in_ns` and therefore usable as a graph root in
7496    /// `neighbors` and `traverse`.
7497    #[tokio::test]
7498    async fn edge_in_visible_namespace_reachable_as_graph_root() {
7499        let rt = rt();
7500        let ns_a = Namespace::parse("vis-edge-a").unwrap();
7501        let ns_b = Namespace::parse("vis-edge-b").unwrap();
7502
7503        // Create two entities and an edge in namespace B.
7504        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
7505        let src = rt
7506            .create_entity(&tok_b, "concept", None, "SrcB", None, None, vec![])
7507            .await
7508            .unwrap();
7509        let tgt = rt
7510            .create_entity(&tok_b, "concept", None, "TgtB", None, None, vec![])
7511            .await
7512            .unwrap();
7513        let edge = rt
7514            .link(&tok_b, src.id, tgt.id, EdgeRelation::Extends, 1.0, None)
7515            .await
7516            .unwrap();
7517
7518        // Namespace A with B in its visible set should be able to get the
7519        // edge and use it as a traverse root.
7520        let tok_a_vis = rt
7521            .authorize_with_visibility(ns_a.clone(), vec![ns_b.clone()])
7522            .unwrap();
7523
7524        // Direct get of the edge must succeed (visible namespace).
7525        let got = rt.get_edge_visible(&tok_a_vis, edge.id.0).await.unwrap();
7526        assert!(
7527            got.is_some(),
7528            "edge in visible namespace must be retrievable via get_edge_visible"
7529        );
7530
7531        // neighbors/traverse use substrate_exists_in_ns which now calls
7532        // get_edge_visible — they must not return empty for a visible-ns edge root.
7533        let neighbors = rt
7534            .neighbors(&tok_a_vis, src.id, Direction::Out, Some(16), None)
7535            .await
7536            .unwrap();
7537        assert!(
7538            neighbors.iter().any(|h| h.node_id == tgt.id),
7539            "neighbors of visible-ns node must include its visible-ns neighbor; got: {neighbors:?}"
7540        );
7541    }
7542
7543    // By-ID ops do not enforce namespace isolation. Shared-brain OSS model:
7544    // UUID is globally unique; get/update/delete find the record regardless
7545    // of caller's token namespace.
7546    #[tokio::test]
7547    async fn get_entity_cross_namespace_no_longer_denied() {
7548        let rt = rt();
7549        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
7550        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
7551        let entity = rt
7552            .create_entity(&ns_a, "concept", None, "Alpha", None, None, vec![])
7553            .await
7554            .unwrap();
7555
7556        // Same namespace: still works.
7557        let found = rt.get_entity(&ns_a, entity.id).await;
7558        assert!(found.is_ok(), "same-namespace get must succeed");
7559
7560        // Different namespace: now also returns the entity (shared brain).
7561        let cross = rt.get_entity(&ns_b, entity.id).await;
7562        assert!(
7563            cross.is_ok(),
7564            "cross-namespace get must succeed in shared-brain OSS (ADR-007 rule 2)"
7565        );
7566        assert_eq!(cross.unwrap().id, entity.id);
7567    }
7568
7569    #[tokio::test]
7570    async fn delete_entity_cross_namespace_no_longer_denied() {
7571        let rt = rt();
7572        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
7573        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
7574        let entity = rt
7575            .create_entity(&ns_a, "concept", None, "Beta", None, None, vec![])
7576            .await
7577            .unwrap();
7578
7579        // Cross-namespace delete now succeeds (shared brain).
7580        let cross_ns_result = rt.delete_entity(&ns_b, entity.id, true).await;
7581        assert!(
7582            cross_ns_result.is_ok(),
7583            "cross-namespace delete must succeed in shared-brain OSS; got {:?}",
7584            cross_ns_result
7585        );
7586        assert!(cross_ns_result.unwrap(), "delete must return true");
7587
7588        // Entity is gone — even from the original namespace.
7589        let gone = rt.get_entity(&ns_a, entity.id).await;
7590        assert!(gone.is_err(), "entity must be gone after delete");
7591    }
7592
7593    // ---- Note annotation tests ----
7594
7595    #[tokio::test]
7596    async fn create_note_indexes_into_fts5() {
7597        let rt = rt();
7598        let tok = NamespaceToken::local();
7599        let note = rt
7600            .create_note(
7601                &tok,
7602                "observation",
7603                None,
7604                "FlashAttention reduces memory by using tiling",
7605                Some(0.8),
7606                None,
7607                vec![],
7608            )
7609            .await
7610            .unwrap();
7611
7612        // FTS5 should have indexed the note content.
7613        let ns = tok.namespace().as_str().to_string();
7614        let hits = rt
7615            .text_for_notes(&tok)
7616            .unwrap()
7617            .search(khive_storage::types::TextSearchRequest {
7618                query: "FlashAttention".to_string(),
7619                mode: khive_storage::types::TextQueryMode::Plain,
7620                filter: Some(khive_storage::types::TextFilter {
7621                    namespaces: vec![ns],
7622                    ..Default::default()
7623                }),
7624                top_k: 10,
7625                snippet_chars: 100,
7626            })
7627            .await
7628            .unwrap();
7629
7630        assert!(
7631            hits.iter().any(|h| h.subject_id == note.id),
7632            "note should be indexed in FTS5 after create"
7633        );
7634    }
7635
7636    /// #916: `@` used to reach SQLite FTS5's bareword parser raw and error
7637    /// (`sanitize_fts5_query` did not strip it), surfacing as
7638    /// `RuntimeError::InvalidInput` per #569's fail-loud policy.
7639    /// `sanitize_fts5_token_group`'s bareword-safety gate now routes it
7640    /// through the quoted-phrase alternative instead, so `search_notes`
7641    /// succeeds and finds the seeded content.
7642    #[tokio::test]
7643    async fn search_notes_with_residual_fts5_char_now_sanitized() {
7644        let rt = rt();
7645        let tok = NamespaceToken::local();
7646        rt.create_note(
7647            &tok,
7648            "observation",
7649            None,
7650            "use foo@bar to chain calls",
7651            Some(0.5),
7652            None,
7653            vec![],
7654        )
7655        .await
7656        .unwrap();
7657
7658        let result = rt
7659            .search_notes(&tok, "foo@bar", None, 10, None, false, &[], None)
7660            .await;
7661
7662        let hits = result.unwrap_or_else(|e| {
7663            panic!("#916 search_notes must not fail on an '@'-bearing query, got: {e:?}")
7664        });
7665        assert!(
7666            !hits.is_empty(),
7667            "#916 '@'-bearing query must still find the seeded 'foo@bar' content via the \
7668             quoted-phrase alternative"
7669        );
7670    }
7671
7672    /// The `search_notes` FTS fail-open arm must only degrade genuine FTS5
7673    /// parser syntax errors. A non-parser `StorageError`: e.g. a pool
7674    /// exhaustion or connection timeout on the text-search backend — is not a
7675    /// bad query and must propagate as `Err`, not be silently swallowed into
7676    /// an empty (falsely "successful") result set. `search_notes`,
7677    /// `hybrid_search`, `hybrid_search_with_strategy`, and
7678    /// `collect_recall_text_hits` all share the same `is_fts5_syntax_error()`
7679    /// gate on `StorageError`, so this case generalizes to all four call sites.
7680    #[tokio::test]
7681    async fn search_notes_propagates_non_parser_fts_error() {
7682        let rt = rt();
7683        let tok = NamespaceToken::local();
7684        rt.create_note(
7685            &tok,
7686            "observation",
7687            None,
7688            "FlashAttention reduces memory by using tiling",
7689            Some(0.8),
7690            None,
7691            vec![],
7692        )
7693        .await
7694        .unwrap();
7695
7696        let ns = tok.namespace().as_str().to_string();
7697        arm_fts_search_fail(&ns);
7698
7699        let result = rt
7700            .search_notes(&tok, "FlashAttention", None, 10, None, false, &[], None)
7701            .await;
7702
7703        assert!(
7704            result.is_err(),
7705            "search_notes must propagate a non-parser FTS StorageError (Timeout) \
7706             as Err, not silently degrade it to an empty result, got: {:?}",
7707            result.ok()
7708        );
7709        assert!(
7710            matches!(
7711                result.unwrap_err(),
7712                RuntimeError::Storage(khive_storage::StorageError::Timeout { .. })
7713            ),
7714            "propagated error must be the injected StorageError::Timeout, unwrapped \
7715             through RuntimeError::Storage"
7716        );
7717    }
7718
7719    #[tokio::test]
7720    async fn create_note_with_properties() {
7721        let rt = rt();
7722        let tok = NamespaceToken::local();
7723        let props = serde_json::json!({"source": "arxiv:2205.14135"});
7724        let note = rt
7725            .create_note(
7726                &tok,
7727                "insight",
7728                None,
7729                "FlashAttention is IO-aware",
7730                Some(0.9),
7731                Some(props.clone()),
7732                vec![],
7733            )
7734            .await
7735            .unwrap();
7736
7737        assert_eq!(note.properties.as_ref().unwrap(), &props);
7738    }
7739
7740    #[tokio::test]
7741    async fn create_note_creates_annotates_edges() {
7742        let rt = rt();
7743        let tok = NamespaceToken::local();
7744        let entity = rt
7745            .create_entity(&tok, "concept", None, "FlashAttention", None, None, vec![])
7746            .await
7747            .unwrap();
7748
7749        let note = rt
7750            .create_note(
7751                &tok,
7752                "observation",
7753                None,
7754                "FlashAttention uses SRAM tiling for memory efficiency",
7755                Some(0.9),
7756                None,
7757                vec![entity.id],
7758            )
7759            .await
7760            .unwrap();
7761
7762        // The note should have an outbound `annotates` edge to the entity.
7763        let out_neighbors = rt
7764            .neighbors(
7765                &tok,
7766                note.id,
7767                Direction::Out,
7768                None,
7769                Some(vec![EdgeRelation::Annotates]),
7770            )
7771            .await
7772            .unwrap();
7773        assert_eq!(out_neighbors.len(), 1);
7774        assert_eq!(out_neighbors[0].node_id, entity.id);
7775        assert_eq!(out_neighbors[0].relation, EdgeRelation::Annotates);
7776
7777        // The entity should have an inbound `annotates` edge from the note.
7778        let in_neighbors = rt
7779            .neighbors(
7780                &tok,
7781                entity.id,
7782                Direction::In,
7783                None,
7784                Some(vec![EdgeRelation::Annotates]),
7785            )
7786            .await
7787            .unwrap();
7788        assert_eq!(in_neighbors.len(), 1);
7789        assert_eq!(in_neighbors[0].node_id, note.id);
7790    }
7791
7792    #[tokio::test]
7793    async fn neighbors_without_relation_filter_returns_all() {
7794        let rt = rt();
7795        let tok = NamespaceToken::local();
7796        let a = rt
7797            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7798            .await
7799            .unwrap();
7800        let b = rt
7801            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7802            .await
7803            .unwrap();
7804        let c = rt
7805            .create_entity(&tok, "concept", None, "C", None, None, vec![])
7806            .await
7807            .unwrap();
7808
7809        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7810            .await
7811            .unwrap();
7812        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
7813            .await
7814            .unwrap();
7815
7816        let all = rt
7817            .neighbors(&tok, a.id, Direction::Out, None, None)
7818            .await
7819            .unwrap();
7820        assert_eq!(all.len(), 2);
7821    }
7822
7823    #[tokio::test]
7824    async fn neighbors_with_relation_filter_returns_subset() {
7825        let rt = rt();
7826        let tok = NamespaceToken::local();
7827        let a = rt
7828            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7829            .await
7830            .unwrap();
7831        let b = rt
7832            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7833            .await
7834            .unwrap();
7835        let c = rt
7836            .create_entity(&tok, "concept", None, "C", None, None, vec![])
7837            .await
7838            .unwrap();
7839
7840        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7841            .await
7842            .unwrap();
7843        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
7844            .await
7845            .unwrap();
7846
7847        let filtered = rt
7848            .neighbors(
7849                &tok,
7850                a.id,
7851                Direction::Out,
7852                None,
7853                Some(vec![EdgeRelation::Extends]),
7854            )
7855            .await
7856            .unwrap();
7857        assert_eq!(filtered.len(), 1);
7858        assert_eq!(filtered[0].node_id, b.id);
7859        assert_eq!(filtered[0].relation, EdgeRelation::Extends);
7860    }
7861
7862    /// Self-loop direction parity:
7863    /// `neighbors_with_query_directed`'s post-merge dedup must not collapse a
7864    /// self-loop edge's Out row and In row into one — they share `(node_id,
7865    /// edge_id)` but are opposite directions, matching what a separate `Out`
7866    /// call plus a separate `In` call would return for the same edge. The
7867    /// self-loop edge is inserted directly through the graph store (`link()`
7868    /// rejects source_id == target_id) to exercise the merge/dedup path.
7869    #[tokio::test]
7870    async fn neighbors_with_query_directed_preserves_self_loop_direction_parity() {
7871        let rt = rt();
7872        let tok = NamespaceToken::local();
7873        let centre = rt
7874            .create_entity(&tok, "concept", None, "Centre", None, None, vec![])
7875            .await
7876            .unwrap();
7877
7878        let now = chrono::Utc::now();
7879        rt.graph(&tok)
7880            .unwrap()
7881            .upsert_edge(Edge {
7882                id: LinkId::from(Uuid::new_v4()),
7883                namespace: "local".to_string(),
7884                source_id: centre.id,
7885                target_id: centre.id,
7886                relation: EdgeRelation::Extends,
7887                weight: 0.7,
7888                created_at: now,
7889                updated_at: now,
7890                deleted_at: None,
7891                metadata: None,
7892                target_backend: None,
7893            })
7894            .await
7895            .unwrap();
7896
7897        let directed = rt
7898            .neighbors_with_query_directed(
7899                &tok,
7900                centre.id,
7901                NeighborQuery {
7902                    direction: Direction::Both,
7903                    relations: None,
7904                    limit: None,
7905                    min_weight: None,
7906                },
7907            )
7908            .await
7909            .unwrap();
7910
7911        assert_eq!(
7912            directed.len(),
7913            2,
7914            "a self-loop edge must produce both an Out hit and an In hit, not one collapsed hit"
7915        );
7916        let directions: Vec<Direction> = directed.iter().map(|(_, d)| d.clone()).collect();
7917        assert!(
7918            directions.contains(&Direction::Out),
7919            "self-loop must retain its Out-tagged hit"
7920        );
7921        assert!(
7922            directions.contains(&Direction::In),
7923            "self-loop must retain its In-tagged hit"
7924        );
7925    }
7926
7927    #[tokio::test]
7928    async fn search_notes_returns_relevant_note() {
7929        let rt = rt();
7930        let tok = NamespaceToken::local();
7931        rt.create_note(
7932            &tok,
7933            "observation",
7934            None,
7935            "GQA reduces KV cache memory for large models",
7936            Some(0.8),
7937            None,
7938            vec![],
7939        )
7940        .await
7941        .unwrap();
7942
7943        let results = rt
7944            .search_notes(&tok, "GQA KV cache", None, 10, None, false, &[], None)
7945            .await
7946            .unwrap();
7947
7948        assert!(!results.is_empty(), "search should return the indexed note");
7949        let hit = &results[0];
7950        assert!(
7951            hit.title.is_some(),
7952            "note hit title should be populated (falls back to content)"
7953        );
7954        assert!(
7955            hit.snippet.is_some(),
7956            "note hit snippet should be populated"
7957        );
7958    }
7959
7960    #[tokio::test]
7961    async fn search_notes_excludes_soft_deleted() {
7962        let rt = rt();
7963        let tok = NamespaceToken::local();
7964        let note = rt
7965            .create_note(
7966                &tok,
7967                "observation",
7968                None,
7969                "RoPE positional encoding rotary embeddings",
7970                Some(0.7),
7971                None,
7972                vec![],
7973            )
7974            .await
7975            .unwrap();
7976
7977        // Soft-delete the note.
7978        rt.notes(&tok)
7979            .unwrap()
7980            .delete_note(note.id, DeleteMode::Soft)
7981            .await
7982            .unwrap();
7983
7984        let results = rt
7985            .search_notes(
7986                &tok,
7987                "RoPE rotary positional",
7988                None,
7989                10,
7990                None,
7991                false,
7992                &[],
7993                None,
7994            )
7995            .await
7996            .unwrap();
7997
7998        assert!(
7999            results.iter().all(|h| h.note_id != note.id),
8000            "soft-deleted note should be excluded from search"
8001        );
8002    }
8003
8004    // ---- predicate pushdown before truncation (note branch) ----
8005
8006    /// Regression: notes store tags inside `properties["tags"]`: there is no
8007    /// separate tags column. Without pushdown, the tag filter is applied after
8008    /// `hits.truncate(limit)`, so a tag-matching note ranked beyond `limit` in
8009    /// the raw RRF fusion is silently dropped.
8010    ///
8011    /// Scenario: `limit=1`, tags_any=["note-target-tag"]. Two notes are inserted:
8012    ///   - decoy: high FTS rank (repeats query terms), NO target tag.
8013    ///   - target: lower FTS rank, HAS "note-target-tag" in `properties["tags"]`.
8014    ///
8015    /// Without pushdown: decoy occupies the slot, target is dropped.
8016    /// With pushdown: decoy is excluded in the alive-note loop, target survives, returned.
8017    #[tokio::test]
8018    async fn search_notes_tag_filter_pushed_before_truncation() {
8019        let rt = rt();
8020        let tok = NamespaceToken::local();
8021
8022        // Decoy note: repeats query tokens → higher FTS rank. No target tag.
8023        rt.create_note(
8024            &tok,
8025            "observation",
8026            None,
8027            "kappa lambda mu note decoy kappa lambda mu note decoy kappa lambda mu",
8028            Some(0.5),
8029            Some(serde_json::json!({"tags": ["other-note-tag"]})),
8030            vec![],
8031        )
8032        .await
8033        .unwrap();
8034
8035        // Target note: fewer query tokens → lower FTS rank. Has the target tag.
8036        let target = rt
8037            .create_note(
8038                &tok,
8039                "observation",
8040                None,
8041                "kappa lambda mu note target",
8042                Some(0.5),
8043                Some(serde_json::json!({"tags": ["note-target-tag"]})),
8044                vec![],
8045            )
8046            .await
8047            .unwrap();
8048
8049        // With limit=1 and tags_any, the fix must return the target note despite the
8050        // decoy ranking higher in raw FTS.
8051        let hits = rt
8052            .search_notes(
8053                &tok,
8054                "kappa lambda mu note",
8055                None,
8056                1,
8057                None,
8058                false,
8059                &["note-target-tag".to_string()],
8060                None,
8061            )
8062            .await
8063            .unwrap();
8064
8065        assert_eq!(
8066            hits.len(),
8067            1,
8068            "exactly one hit expected (tag-matching note)"
8069        );
8070        assert_eq!(
8071            hits[0].note_id, target.id,
8072            "tag-filtered note must be returned even when ranked below limit in raw fusion"
8073        );
8074    }
8075
8076    /// Regression: without pushdown, the properties filter is applied after truncation; a matching
8077    /// note ranked beyond `limit` is silently dropped.
8078    ///
8079    /// Scenario: `limit=1`, properties_filter={{"source": "target"}}. Two notes:
8080    ///   - decoy: high FTS rank, properties {{"source": "other"}}.
8081    ///   - target: lower FTS rank, properties {{"source": "target"}}.
8082    #[tokio::test]
8083    async fn search_notes_props_filter_pushed_before_truncation() {
8084        let rt = rt();
8085        let tok = NamespaceToken::local();
8086
8087        rt.create_note(
8088            &tok,
8089            "observation",
8090            None,
8091            "nu xi omicron note decoy nu xi omicron note decoy nu xi omicron",
8092            Some(0.5),
8093            Some(serde_json::json!({"source": "other"})),
8094            vec![],
8095        )
8096        .await
8097        .unwrap();
8098
8099        let target = rt
8100            .create_note(
8101                &tok,
8102                "observation",
8103                None,
8104                "nu xi omicron note target",
8105                Some(0.5),
8106                Some(serde_json::json!({"source": "target"})),
8107                vec![],
8108            )
8109            .await
8110            .unwrap();
8111
8112        let filter = serde_json::json!({"source": "target"});
8113        let hits = rt
8114            .search_notes(
8115                &tok,
8116                "nu xi omicron note",
8117                None,
8118                1,
8119                None,
8120                false,
8121                &[],
8122                Some(&filter),
8123            )
8124            .await
8125            .unwrap();
8126
8127        assert_eq!(
8128            hits.len(),
8129            1,
8130            "exactly one hit expected (properties-matching note)"
8131        );
8132        assert_eq!(
8133            hits[0].note_id, target.id,
8134            "properties-filtered note must be returned even when ranked below limit"
8135        );
8136    }
8137
8138    #[tokio::test]
8139    async fn resolve_returns_entity() {
8140        let rt = rt();
8141        let tok = NamespaceToken::local();
8142        let entity = rt
8143            .create_entity(&tok, "concept", None, "LoRA", None, None, vec![])
8144            .await
8145            .unwrap();
8146
8147        let resolved = rt.resolve(&tok, entity.id).await.unwrap();
8148        match resolved {
8149            Some(Resolved::Entity(e)) => assert_eq!(e.id, entity.id),
8150            other => panic!("expected Resolved::Entity, got {:?}", other),
8151        }
8152    }
8153
8154    #[tokio::test]
8155    async fn resolve_returns_note() {
8156        let rt = rt();
8157        let tok = NamespaceToken::local();
8158        let note = rt
8159            .create_note(
8160                &tok,
8161                "observation",
8162                None,
8163                "LoRA fine-tunes LLMs with low-rank adapters",
8164                Some(0.85),
8165                None,
8166                vec![],
8167            )
8168            .await
8169            .unwrap();
8170
8171        let resolved = rt.resolve(&tok, note.id).await.unwrap();
8172        match resolved {
8173            Some(Resolved::Note(n)) => assert_eq!(n.id, note.id),
8174            other => panic!("expected Resolved::Note, got {:?}", other),
8175        }
8176    }
8177
8178    #[tokio::test]
8179    async fn resolve_returns_none_for_unknown_uuid() {
8180        let rt = rt();
8181        let tok = NamespaceToken::local();
8182        let unknown = Uuid::new_v4();
8183        let resolved = rt.resolve(&tok, unknown).await.unwrap();
8184        assert!(resolved.is_none(), "unknown UUID should resolve to None");
8185    }
8186
8187    #[tokio::test]
8188    async fn resolve_prefix_finds_entity_in_own_namespace() {
8189        let rt = rt();
8190        let tok = NamespaceToken::local();
8191        let entity = rt
8192            .create_entity(&tok, "concept", None, "PrefixTest", None, None, vec![])
8193            .await
8194            .unwrap();
8195        let prefix = &entity.id.to_string()[..8];
8196
8197        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
8198        assert_eq!(resolved, Some(entity.id));
8199    }
8200
8201    #[test]
8202    fn hex_prefix_to_uuid_pattern_inserts_hyphens_at_canonical_boundaries() {
8203        let full = "aabbccdd112240008000000000000ab1";
8204        let cases: &[(usize, &str)] = &[
8205            (1, "a"),
8206            (7, "aabbccd"),
8207            (8, "aabbccdd"),
8208            (9, "aabbccdd-1"),
8209            (12, "aabbccdd-1122"),
8210            (13, "aabbccdd-1122-4"),
8211            (16, "aabbccdd-1122-4000"),
8212            (18, "aabbccdd-1122-4000-80"),
8213            (20, "aabbccdd-1122-4000-8000"),
8214            (23, "aabbccdd-1122-4000-8000-000"),
8215            (24, "aabbccdd-1122-4000-8000-0000"),
8216            (28, "aabbccdd-1122-4000-8000-00000000"),
8217            (31, "aabbccdd-1122-4000-8000-000000000ab"),
8218        ];
8219        for (len, expected) in cases {
8220            let input = &full[..*len];
8221            assert_eq!(
8222                hex_prefix_to_uuid_pattern(input),
8223                *expected,
8224                "len={len} input={input:?}"
8225            );
8226        }
8227    }
8228
8229    #[test]
8230    fn hex_prefix_to_uuid_pattern_full_32_char_matches_canonical_uuid() {
8231        let compact = "aabbccdd112240008000000000000ab1";
8232        let compact32 = &compact[..32];
8233        assert_eq!(
8234            hex_prefix_to_uuid_pattern(compact32),
8235            "aabbccdd-1122-4000-8000-000000000ab1"
8236        );
8237    }
8238
8239    /// Input longer than 32 hex chars is NOT truncated: the extra chars land
8240    /// past the canonical 12-char final
8241    /// segment with no further hyphen, so the pattern can never match a real
8242    /// (36-char) stored `id`, instead of silently truncating down to a
8243    /// pattern that matches the valid 32-char UUID.
8244    #[test]
8245    fn hex_prefix_to_uuid_pattern_overlong_input_is_not_truncated() {
8246        let compact32 = "aabbccdd112240008000000000000ab1";
8247        let overlong = format!("{compact32}extrahex");
8248        let pattern = hex_prefix_to_uuid_pattern(&overlong);
8249        assert_eq!(
8250            pattern, "aabbccdd-1122-4000-8000-000000000ab1extrahex",
8251            "overlong input must keep its extra chars, not truncate to the valid UUID"
8252        );
8253        assert_ne!(
8254            pattern, "aabbccdd-1122-4000-8000-000000000ab1",
8255            "overlong pattern must not collapse to the canonical 36-char UUID form"
8256        );
8257    }
8258
8259    #[test]
8260    fn hex_prefix_to_uuid_pattern_passes_through_hyphenated_input() {
8261        let hyphenated = "aabbccdd-1122-4000-8000-000000000ab1";
8262        assert_eq!(hex_prefix_to_uuid_pattern(hyphenated), hyphenated);
8263
8264        let partial = "aabbccdd-11";
8265        assert_eq!(hex_prefix_to_uuid_pattern(partial), partial);
8266    }
8267
8268    #[tokio::test]
8269    async fn resolve_prefix_compact_9_to_31_char_matches() {
8270        let rt = rt();
8271        let tok = NamespaceToken::local();
8272        let entity = rt
8273            .create_entity(
8274                &tok,
8275                "concept",
8276                None,
8277                "CompactPrefixTest",
8278                None,
8279                None,
8280                vec![],
8281            )
8282            .await
8283            .unwrap();
8284        let compact = entity.id.simple().to_string();
8285
8286        for len in [9, 12, 16, 20, 24, 28, 31] {
8287            let prefix = &compact[..len];
8288            let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
8289            assert_eq!(
8290                resolved,
8291                Some(entity.id),
8292                "compact prefix of len {len} should resolve"
8293            );
8294        }
8295    }
8296
8297    #[tokio::test]
8298    async fn resolve_prefix_compact_full_32_char_matches() {
8299        let rt = rt();
8300        let tok = NamespaceToken::local();
8301        let entity = rt
8302            .create_entity(&tok, "concept", None, "Full32Test", None, None, vec![])
8303            .await
8304            .unwrap();
8305        let compact = entity.id.simple().to_string();
8306        assert_eq!(compact.len(), 32);
8307
8308        let resolved = rt.resolve_prefix(&tok, &compact).await.unwrap();
8309        assert_eq!(resolved, Some(entity.id));
8310    }
8311
8312    /// A valid 32-char compact id with extra trailing hex chars appended must
8313    /// fail to resolve, not silently resolve to the valid entity via truncation.
8314    #[tokio::test]
8315    async fn resolve_prefix_rejects_overlong_all_hex_input() {
8316        let rt = rt();
8317        let tok = NamespaceToken::local();
8318        let entity = rt
8319            .create_entity(&tok, "concept", None, "OverlongTest", None, None, vec![])
8320            .await
8321            .unwrap();
8322        let compact = entity.id.simple().to_string();
8323        assert_eq!(compact.len(), 32);
8324
8325        let overlong = format!("{compact}ab");
8326        let resolved = rt.resolve_prefix(&tok, &overlong).await.unwrap();
8327        assert_eq!(
8328            resolved, None,
8329            "a 32-char id plus extra hex chars must not resolve to the valid entity"
8330        );
8331    }
8332
8333    /// The `resolve_prefix*` boundary rejects
8334    /// non-hex/non-hyphen input (e.g. LIKE wildcards `%`/`_`) instead of
8335    /// letting it reach the bound `LIKE` pattern unfiltered — covers callers
8336    /// (like khive-pack-git/src/ingest.rs) that resolve raw input without
8337    /// their own all-hex gate.
8338    #[tokio::test]
8339    async fn resolve_prefix_rejects_like_wildcard_input() {
8340        let rt = rt();
8341        let tok = NamespaceToken::local();
8342        let entity = rt
8343            .create_entity(&tok, "concept", None, "WildcardTest", None, None, vec![])
8344            .await
8345            .unwrap();
8346        let compact = entity.id.simple().to_string();
8347        // A caller that forgot to hex-gate might pass a `%`-bearing string
8348        // straight through, hoping to broaden a scan; the resolver boundary
8349        // must reject it instead of running it as a wildcard LIKE.
8350        let wildcard_prefix = format!("{}%", &compact[..8]);
8351
8352        let resolved = rt.resolve_prefix(&tok, &wildcard_prefix).await.unwrap();
8353        assert_eq!(
8354            resolved, None,
8355            "prefix containing a LIKE wildcard must be rejected, not resolved"
8356        );
8357    }
8358
8359    #[tokio::test]
8360    async fn resolve_prefix_boundary_at_hyphen_positions() {
8361        let rt = rt();
8362        let tok = NamespaceToken::local();
8363        let entity = rt
8364            .create_entity(&tok, "concept", None, "BoundaryTest", None, None, vec![])
8365            .await
8366            .unwrap();
8367        let compact = entity.id.simple().to_string();
8368
8369        for len in [8, 12, 16, 20, 24] {
8370            let prefix = &compact[..len];
8371            let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
8372            assert_eq!(
8373                resolved,
8374                Some(entity.id),
8375                "boundary prefix of len {len} should resolve"
8376            );
8377        }
8378    }
8379
8380    #[tokio::test]
8381    async fn resolve_prefix_ambiguous_still_detected_after_normalization() {
8382        use khive_storage::entity::Entity;
8383
8384        let rt = rt();
8385        let tok = NamespaceToken::local();
8386        let id_a = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000001").unwrap();
8387        let id_b = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000002").unwrap();
8388
8389        let mut entity_a = Entity::new("local", "concept", "AmbigCompactA");
8390        entity_a.id = id_a;
8391        let mut entity_b = Entity::new("local", "concept", "AmbigCompactB");
8392        entity_b.id = id_b;
8393
8394        let store = rt.entities(&tok).unwrap();
8395        store.upsert_entity(entity_a).await.unwrap();
8396        store.upsert_entity(entity_b).await.unwrap();
8397
8398        // Shared 20-char compact prefix (past the first hyphen boundary).
8399        let shared_compact = &id_a.simple().to_string()[..20];
8400        let err = rt.resolve_prefix(&tok, shared_compact).await.unwrap_err();
8401        assert!(
8402            matches!(
8403                err,
8404                RuntimeError::AmbiguousPrefix { ref matches, .. } if matches.len() == 2
8405            ),
8406            "shared compact prefix must still return AmbiguousPrefix; got {err:?}"
8407        );
8408    }
8409
8410    #[tokio::test]
8411    async fn resolve_prefix_invisible_across_namespaces() {
8412        let rt = rt();
8413        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8414        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8415        let entity = rt
8416            .create_entity(&ns_a, "concept", None, "Invisible", None, None, vec![])
8417            .await
8418            .unwrap();
8419        let prefix = &entity.id.to_string()[..8];
8420
8421        // From ns_b, the entity in ns_a should not be visible.
8422        let resolved = rt.resolve_prefix(&ns_b, prefix).await.unwrap();
8423        assert_eq!(resolved, None);
8424    }
8425
8426    #[tokio::test]
8427    async fn resolve_prefix_ambiguous_same_namespace() {
8428        use khive_storage::entity::Entity;
8429
8430        let rt = rt();
8431        let tok = NamespaceToken::local();
8432        // Two entities with UUIDs sharing the same 8-char prefix "aabbccdd".
8433        let id_a = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000001").unwrap();
8434        let id_b = Uuid::parse_str("aabbccdd-2222-4000-8000-000000000002").unwrap();
8435
8436        let mut entity_a = Entity::new("local", "concept", "AmbigA");
8437        entity_a.id = id_a;
8438        let mut entity_b = Entity::new("local", "concept", "AmbigB");
8439        entity_b.id = id_b;
8440
8441        let store = rt.entities(&tok).unwrap();
8442        store.upsert_entity(entity_a).await.unwrap();
8443        store.upsert_entity(entity_b).await.unwrap();
8444
8445        let err = rt.resolve_prefix(&tok, "aabbccdd").await.unwrap_err();
8446        assert!(
8447            matches!(
8448                err,
8449                RuntimeError::AmbiguousPrefix { ref prefix, ref matches }
8450                    if prefix == "aabbccdd" && matches.len() == 2
8451            ),
8452            "shared 8-char prefix must return AmbiguousPrefix; got {err:?}"
8453        );
8454    }
8455
8456    /// A single UUID legitimately present in TWO scanned tables (entities and
8457    /// notes here) must resolve cleanly to that one UUID, not a false
8458    /// `AmbiguousPrefix` naming the same UUID twice: without cross-table
8459    /// dedup, `matches.len()` becomes 2 for a single record.
8460    #[tokio::test]
8461    async fn resolve_prefix_cross_table_duplicate_uuid_resolves_cleanly() {
8462        use khive_storage::entity::Entity;
8463
8464        let rt = rt();
8465        let tok = NamespaceToken::local();
8466        let shared_id = Uuid::parse_str("ccddeeff-1111-4000-8000-000000000001").unwrap();
8467
8468        let mut entity = Entity::new("local", "concept", "Nvk749Entity");
8469        entity.id = shared_id;
8470        rt.entities(&tok)
8471            .unwrap()
8472            .upsert_entity(entity)
8473            .await
8474            .unwrap();
8475
8476        let mut note = Note::new("local", "observation", "nvk749 note with the same id");
8477        note.id = shared_id;
8478        rt.notes(&tok).unwrap().upsert_note(note).await.unwrap();
8479
8480        let resolved = rt
8481            .resolve_prefix(&tok, "ccddeeff")
8482            .await
8483            .expect("#749: a UUID present in two tables must not be reported as ambiguous");
8484        assert_eq!(
8485            resolved,
8486            Some(shared_id),
8487            "#749: cross-table duplicate must resolve to the single shared UUID"
8488        );
8489    }
8490
8491    /// The early-exit inside the per-table scan loop (`if matches.len()
8492    /// > 1 { break }`) must also operate on DEDUPED state — otherwise a
8493    /// cross-table duplicate could still short-circuit the scan before a
8494    /// later table contributes the SAME UUID again, which would have masked
8495    /// the bug rather than exercising it. This drives the duplicate through
8496    /// the earliest two tables scanned (entities, notes) so the early-exit
8497    /// path is the one under test, not a post-loop dedup applied too late.
8498    #[tokio::test]
8499    async fn resolve_prefix_early_exit_uses_deduped_match_count() {
8500        use khive_storage::entity::Entity;
8501
8502        let rt = rt();
8503        let tok = NamespaceToken::local();
8504        let shared_id = Uuid::parse_str("ddeeff11-2222-4000-8000-000000000002").unwrap();
8505
8506        // entities and notes are the first two tables scanned inside
8507        // resolve_prefix_inner — the same UUID in both must not trip the
8508        // mid-scan `matches.len() > 1` break as if two distinct UUIDs had
8509        // been found.
8510        let mut entity = Entity::new("local", "concept", "Nvk749bEntity");
8511        entity.id = shared_id;
8512        rt.entities(&tok)
8513            .unwrap()
8514            .upsert_entity(entity)
8515            .await
8516            .unwrap();
8517
8518        let mut note = Note::new("local", "observation", "nvk749b note with the same id");
8519        note.id = shared_id;
8520        rt.notes(&tok).unwrap().upsert_note(note).await.unwrap();
8521
8522        let resolved = rt
8523            .resolve_prefix(&tok, "ddeeff11")
8524            .await
8525            .expect("#749: deduped early-exit must not falsely report ambiguity");
8526        assert_eq!(resolved, Some(shared_id));
8527    }
8528
8529    // ---- Event resolution tests ----
8530    //
8531    // resolve_prefix and handle_get already include events; these tests are
8532    // regression coverage confirming event UUIDs are resolvable and that get()
8533    // returns kind="event".
8534
8535    #[tokio::test]
8536    async fn resolve_finds_event_by_full_uuid() {
8537        use khive_storage::Event;
8538        use khive_types::{EventKind, SubstrateKind};
8539
8540        let rt = rt();
8541        let tok = NamespaceToken::local();
8542        let ns = tok.namespace().as_str();
8543        let event = Event::new(
8544            ns,
8545            "test_verb",
8546            EventKind::Audit,
8547            SubstrateKind::Entity,
8548            "actor",
8549        );
8550        let event_id = event.id;
8551        rt.events(&tok).unwrap().append_event(event).await.unwrap();
8552
8553        let resolved = rt.resolve(&tok, event_id).await.unwrap();
8554        assert!(
8555            matches!(resolved, Some(Resolved::Event(_))),
8556            "event UUID must resolve to Resolved::Event, got {resolved:?}"
8557        );
8558    }
8559
8560    #[tokio::test]
8561    async fn resolve_prefix_finds_event() {
8562        use khive_storage::Event;
8563        use khive_types::{EventKind, SubstrateKind};
8564
8565        let rt = rt();
8566        let tok = NamespaceToken::local();
8567        let ns = tok.namespace().as_str();
8568        let event = Event::new(
8569            ns,
8570            "test_verb",
8571            EventKind::Audit,
8572            SubstrateKind::Entity,
8573            "actor",
8574        );
8575        let event_id = event.id;
8576        rt.events(&tok).unwrap().append_event(event).await.unwrap();
8577
8578        let prefix = &event_id.to_string()[..8];
8579        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
8580        assert_eq!(
8581            resolved,
8582            Some(event_id),
8583            "resolve_prefix must return event UUID for 8-char prefix"
8584        );
8585    }
8586
8587    // ---- Referential integrity tests ----
8588
8589    #[tokio::test]
8590    async fn link_phantom_source_returns_not_found() {
8591        let rt = rt();
8592        let tok = NamespaceToken::local();
8593        let b = rt
8594            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8595            .await
8596            .unwrap();
8597        let phantom = Uuid::new_v4();
8598
8599        let result = rt
8600            .link(&tok, phantom, b.id, EdgeRelation::Extends, 1.0, None)
8601            .await;
8602        match result {
8603            Err(RuntimeError::NotFound(msg)) => {
8604                assert!(
8605                    msg.contains("source"),
8606                    "error message must name 'source': {msg}"
8607                );
8608            }
8609            other => panic!("expected NotFound for phantom source, got {other:?}"),
8610        }
8611    }
8612
8613    #[tokio::test]
8614    async fn link_phantom_target_returns_not_found() {
8615        let rt = rt();
8616        let tok = NamespaceToken::local();
8617        let a = rt
8618            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8619            .await
8620            .unwrap();
8621        let phantom = Uuid::new_v4();
8622
8623        let result = rt
8624            .link(&tok, a.id, phantom, EdgeRelation::Extends, 1.0, None)
8625            .await;
8626        match result {
8627            Err(RuntimeError::NotFound(msg)) => {
8628                assert!(
8629                    msg.contains("target"),
8630                    "error message must name 'target': {msg}"
8631                );
8632            }
8633            other => panic!("expected NotFound for phantom target, got {other:?}"),
8634        }
8635    }
8636
8637    #[tokio::test]
8638    async fn link_real_entities_succeeds() {
8639        let rt = rt();
8640        let tok = NamespaceToken::local();
8641        let a = rt
8642            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8643            .await
8644            .unwrap();
8645        let b = rt
8646            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8647            .await
8648            .unwrap();
8649
8650        let edge = rt
8651            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
8652            .await
8653            .unwrap();
8654        assert_eq!(edge.source_id, a.id);
8655        assert_eq!(edge.target_id, b.id);
8656        assert_eq!(edge.relation, EdgeRelation::Extends);
8657    }
8658
8659    // ---- commit-time endpoint guard vs concurrent hard-delete ----
8660
8661    /// Deterministic form of the regression, exercised directly at the
8662    /// write step `link` performs after prepare-time validation: build the
8663    /// exact `Edge` `link` would build, delete the target the way a
8664    /// concurrent racer would, and confirm the guarded write refuses it.
8665    #[tokio::test]
8666    async fn link_write_time_guard_blocks_dangling_edge_after_target_vanishes() {
8667        let rt = rt();
8668        let tok = NamespaceToken::local();
8669        let a = rt
8670            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8671            .await
8672            .unwrap();
8673        let x = rt
8674            .create_entity(&tok, "concept", None, "X", None, None, vec![])
8675            .await
8676            .unwrap();
8677
8678        rt.validate_edge_relation_endpoints(&tok, a.id, x.id, EdgeRelation::Extends)
8679            .await
8680            .expect("prepare-time validation must pass while X is live");
8681
8682        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
8683
8684        let now = chrono::Utc::now();
8685        let edge = Edge {
8686            id: LinkId::from(Uuid::new_v4()),
8687            namespace: tok.namespace().as_str().to_string(),
8688            source_id: a.id,
8689            target_id: x.id,
8690            relation: EdgeRelation::Extends,
8691            weight: 1.0,
8692            created_at: now,
8693            updated_at: now,
8694            deleted_at: None,
8695            metadata: None,
8696            target_backend: None,
8697        };
8698        let outcome = rt
8699            .graph(&tok)
8700            .unwrap()
8701            .upsert_edge_guarded(edge)
8702            .await
8703            .unwrap();
8704        match outcome {
8705            khive_storage::GuardedWriteOutcome::Refused(missing) => {
8706                assert!(missing.target, "target must be reported missing");
8707            }
8708            other => panic!(
8709                "guarded write must refuse an edge whose target vanished before commit, got {other:?}"
8710            ),
8711        }
8712
8713        let edges = rt
8714            .list_edges(
8715                &tok,
8716                crate::curation::EdgeListFilter {
8717                    source_id: Some(a.id),
8718                    target_id: Some(x.id),
8719                    relations: vec![EdgeRelation::Extends],
8720                    ..Default::default()
8721                },
8722                10,
8723                0,
8724            )
8725            .await
8726            .unwrap();
8727        assert!(
8728            edges.is_empty(),
8729            "no dangling edge may be persisted after the guarded write refused it"
8730        );
8731    }
8732
8733    #[tokio::test]
8734    async fn link_many_writes_nothing_when_one_target_vanishes_before_write() {
8735        let rt = rt();
8736        let tok = NamespaceToken::local();
8737        let a = rt
8738            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8739            .await
8740            .unwrap();
8741        let b = rt
8742            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8743            .await
8744            .unwrap();
8745        let x = rt
8746            .create_entity(&tok, "concept", None, "X", None, None, vec![])
8747            .await
8748            .unwrap();
8749
8750        let specs = vec![
8751            LinkSpec {
8752                namespace: None,
8753                source_id: a.id,
8754                target_id: x.id,
8755                relation: EdgeRelation::Extends,
8756                weight: 1.0,
8757                metadata: None,
8758            },
8759            LinkSpec {
8760                namespace: None,
8761                source_id: a.id,
8762                target_id: b.id,
8763                relation: EdgeRelation::Extends,
8764                weight: 1.0,
8765                metadata: None,
8766            },
8767        ];
8768
8769        // Both specs validate fine at build_edge time (X and B both live).
8770        let mut edges = Vec::with_capacity(specs.len());
8771        for spec in &specs {
8772            edges.push(rt.build_edge(&tok, spec).await.unwrap());
8773        }
8774
8775        // X vanishes before the batched write — mirrors a concurrent
8776        // hard-delete landing between per-spec validation and link_many's
8777        // single guarded batch write.
8778        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
8779
8780        let outcome = rt
8781            .graph(&tok)
8782            .unwrap()
8783            .upsert_edges_guarded(edges)
8784            .await
8785            .unwrap();
8786        assert_eq!(
8787            outcome.summary.affected, 0,
8788            "no edge from the batch may be persisted when any endpoint vanished"
8789        );
8790        assert!(
8791            outcome.refused.is_some(),
8792            "refused batch entry must be reported"
8793        );
8794
8795        let edges = rt
8796            .list_edges(
8797                &tok,
8798                crate::curation::EdgeListFilter {
8799                    source_id: Some(a.id),
8800                    relations: vec![EdgeRelation::Extends],
8801                    ..Default::default()
8802                },
8803                10,
8804                0,
8805            )
8806            .await
8807            .unwrap();
8808        assert!(
8809            edges.is_empty(),
8810            "link_many's guarded batch must be all-or-nothing: the live A-B edge \
8811             must not have been persisted alongside the doomed A-X edge"
8812        );
8813    }
8814
8815    // ---- hard-delete row + incident-edge purge is ONE transaction ----
8816    //
8817    // Six tests below cover both orderings (write-then-delete, and a
8818    // concurrent write raced against delete via `tokio::join!`) across all
8819    // three hard-delete paths that cascade-purge incident edges: entity,
8820    // note, and edge-as-node. No sleeps — the "concurrent" tests assert an
8821    // invariant that must hold for EITHER interleaving the async scheduler
8822    // picks, rather than forcing one specific interleaving, so they are
8823    // deterministic (never flaky) without a barrier.
8824
8825    fn raw_edge(source_id: Uuid, target_id: Uuid, ns: &str) -> Edge {
8826        let now = chrono::Utc::now();
8827        Edge {
8828            id: LinkId::from(Uuid::new_v4()),
8829            namespace: ns.to_string(),
8830            source_id,
8831            target_id,
8832            relation: EdgeRelation::Extends,
8833            weight: 1.0,
8834            created_at: now,
8835            updated_at: now,
8836            deleted_at: None,
8837            metadata: None,
8838            target_backend: None,
8839        }
8840    }
8841
8842    async fn assert_no_edges_touch(rt: &KhiveRuntime, tok: &NamespaceToken, node_id: Uuid) {
8843        let as_source = rt
8844            .list_edges(
8845                tok,
8846                crate::curation::EdgeListFilter {
8847                    source_id: Some(node_id),
8848                    ..Default::default()
8849                },
8850                10,
8851                0,
8852            )
8853            .await
8854            .unwrap();
8855        let as_target = rt
8856            .list_edges(
8857                tok,
8858                crate::curation::EdgeListFilter {
8859                    target_id: Some(node_id),
8860                    ..Default::default()
8861                },
8862                10,
8863                0,
8864            )
8865            .await
8866            .unwrap();
8867        assert!(
8868            as_source.is_empty() && as_target.is_empty(),
8869            "no edge may reference hard-deleted node {node_id}: source-side={as_source:?} \
8870             target-side={as_target:?}"
8871        );
8872    }
8873
8874    #[tokio::test]
8875    async fn hard_delete_entity_purges_edge_written_before_delete() {
8876        let rt = rt();
8877        let tok = NamespaceToken::local();
8878        let a = rt
8879            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8880            .await
8881            .unwrap();
8882        let x = rt
8883            .create_entity(&tok, "concept", None, "X", None, None, vec![])
8884            .await
8885            .unwrap();
8886
8887        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
8888        assert_eq!(
8889            rt.graph(&tok)
8890                .unwrap()
8891                .upsert_edge_guarded(edge)
8892                .await
8893                .unwrap(),
8894            khive_storage::GuardedWriteOutcome::Written
8895        );
8896
8897        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
8898        assert_no_edges_touch(&rt, &tok, x.id).await;
8899    }
8900
8901    #[tokio::test]
8902    async fn hard_delete_entity_concurrent_with_guarded_write_never_leaves_dangling_edge() {
8903        let rt = std::sync::Arc::new(rt());
8904        let tok = NamespaceToken::local();
8905        let a = rt
8906            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8907            .await
8908            .unwrap();
8909        let x = rt
8910            .create_entity(&tok, "concept", None, "X", None, None, vec![])
8911            .await
8912            .unwrap();
8913
8914        let delete_rt = std::sync::Arc::clone(&rt);
8915        let delete_tok = tok.clone();
8916        let delete_task =
8917            tokio::spawn(async move { delete_rt.delete_entity(&delete_tok, x.id, true).await });
8918
8919        let write_rt = std::sync::Arc::clone(&rt);
8920        let write_tok = tok.clone();
8921        let ns = tok.namespace().as_str().to_string();
8922        let write_task = tokio::spawn(async move {
8923            let edge = raw_edge(a.id, x.id, &ns);
8924            write_rt
8925                .graph(&write_tok)
8926                .unwrap()
8927                .upsert_edge_guarded(edge)
8928                .await
8929        });
8930
8931        let (deleted, _written) = tokio::join!(delete_task, write_task);
8932        deleted.unwrap().unwrap();
8933        assert_no_edges_touch(&rt, &tok, x.id).await;
8934    }
8935
8936    #[tokio::test]
8937    async fn hard_delete_note_purges_edge_written_before_delete() {
8938        let rt = rt();
8939        let tok = NamespaceToken::local();
8940        let a = rt
8941            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8942            .await
8943            .unwrap();
8944        let n = rt
8945            .create_note(
8946                &tok,
8947                "observation",
8948                None,
8949                "note content",
8950                None,
8951                None,
8952                vec![],
8953            )
8954            .await
8955            .unwrap();
8956
8957        let edge = raw_edge(a.id, n.id, tok.namespace().as_str());
8958        assert_eq!(
8959            rt.graph(&tok)
8960                .unwrap()
8961                .upsert_edge_guarded(edge)
8962                .await
8963                .unwrap(),
8964            khive_storage::GuardedWriteOutcome::Written
8965        );
8966
8967        assert!(rt.delete_note(&tok, n.id, true).await.unwrap());
8968        assert_no_edges_touch(&rt, &tok, n.id).await;
8969    }
8970
8971    #[tokio::test]
8972    async fn hard_delete_note_concurrent_with_guarded_write_never_leaves_dangling_edge() {
8973        let rt = std::sync::Arc::new(rt());
8974        let tok = NamespaceToken::local();
8975        let a = rt
8976            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8977            .await
8978            .unwrap();
8979        let n = rt
8980            .create_note(
8981                &tok,
8982                "observation",
8983                None,
8984                "note content",
8985                None,
8986                None,
8987                vec![],
8988            )
8989            .await
8990            .unwrap();
8991
8992        let delete_rt = std::sync::Arc::clone(&rt);
8993        let delete_tok = tok.clone();
8994        let note_id = n.id;
8995        let delete_task =
8996            tokio::spawn(async move { delete_rt.delete_note(&delete_tok, note_id, true).await });
8997
8998        let write_rt = std::sync::Arc::clone(&rt);
8999        let write_tok = tok.clone();
9000        let ns = tok.namespace().as_str().to_string();
9001        let write_task = tokio::spawn(async move {
9002            let edge = raw_edge(a.id, note_id, &ns);
9003            write_rt
9004                .graph(&write_tok)
9005                .unwrap()
9006                .upsert_edge_guarded(edge)
9007                .await
9008        });
9009
9010        let (deleted, _written) = tokio::join!(delete_task, write_task);
9011        deleted.unwrap().unwrap();
9012        assert_no_edges_touch(&rt, &tok, note_id).await;
9013    }
9014
9015    #[tokio::test]
9016    async fn hard_delete_edge_endpoint_purges_annotating_edge_written_before_delete() {
9017        let rt = rt();
9018        let tok = NamespaceToken::local();
9019        let a = rt
9020            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9021            .await
9022            .unwrap();
9023        let b = rt
9024            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9025            .await
9026            .unwrap();
9027        let n = rt
9028            .create_note(
9029                &tok,
9030                "observation",
9031                None,
9032                "note content",
9033                None,
9034                None,
9035                vec![],
9036            )
9037            .await
9038            .unwrap();
9039        let base_edge = rt
9040            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
9041            .await
9042            .unwrap();
9043        let base_edge_id = Uuid::from(base_edge.id);
9044
9045        // An edge whose TARGET is another edge — the "edge-as-node" case
9046        // `delete_edge`'s cascade must sweep.
9047        let annotating = raw_edge(n.id, base_edge_id, tok.namespace().as_str());
9048        assert_eq!(
9049            rt.graph(&tok)
9050                .unwrap()
9051                .upsert_edge_guarded(annotating)
9052                .await
9053                .unwrap(),
9054            khive_storage::GuardedWriteOutcome::Written
9055        );
9056
9057        assert!(rt.delete_edge(&tok, base_edge_id, true).await.unwrap());
9058        assert_no_edges_touch(&rt, &tok, base_edge_id).await;
9059    }
9060
9061    #[tokio::test]
9062    async fn hard_delete_edge_endpoint_concurrent_with_guarded_write_never_leaves_dangling_edge() {
9063        let rt = std::sync::Arc::new(rt());
9064        let tok = NamespaceToken::local();
9065        let a = rt
9066            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9067            .await
9068            .unwrap();
9069        let b = rt
9070            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9071            .await
9072            .unwrap();
9073        let n = rt
9074            .create_note(
9075                &tok,
9076                "observation",
9077                None,
9078                "note content",
9079                None,
9080                None,
9081                vec![],
9082            )
9083            .await
9084            .unwrap();
9085        let base_edge = rt
9086            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
9087            .await
9088            .unwrap();
9089        let base_edge_id = Uuid::from(base_edge.id);
9090
9091        let delete_rt = std::sync::Arc::clone(&rt);
9092        let delete_tok = tok.clone();
9093        let delete_task =
9094            tokio::spawn(
9095                async move { delete_rt.delete_edge(&delete_tok, base_edge_id, true).await },
9096            );
9097
9098        let write_rt = std::sync::Arc::clone(&rt);
9099        let write_tok = tok.clone();
9100        let ns = tok.namespace().as_str().to_string();
9101        let write_task = tokio::spawn(async move {
9102            let edge = raw_edge(n.id, base_edge_id, &ns);
9103            write_rt
9104                .graph(&write_tok)
9105                .unwrap()
9106                .upsert_edge_guarded(edge)
9107                .await
9108        });
9109
9110        let (deleted, _written) = tokio::join!(delete_task, write_task);
9111        deleted.unwrap().unwrap();
9112        assert_no_edges_touch(&rt, &tok, base_edge_id).await;
9113    }
9114
9115    // ---- file-backed, both write-queue configs ----
9116    //
9117    // The six tests above run against `KhiveRuntime::memory()` and race
9118    // delete against the guarded write via `tokio::join!` with no explicit
9119    // ordering control, so the scheduler could run them fully sequentially
9120    // on one thread without ever exercising real interleaving, and neither
9121    // the file-backed storage path nor `write_queue_enabled: true`
9122    // (`KHIVE_WRITE_QUEUE=1`, the `WriterTask`-routed write path in
9123    // `SqlGraphStore`) is covered at all. The four tests below close both
9124    // gaps: file-backed databases, one run with the writer queue off
9125    // (default) and one with it on, each provably forcing the guarded write
9126    // to land on one specific side of the delete — fully committed before
9127    // the delete starts (swept by the delete's cascade) and attempted only
9128    // after the delete has already committed (refused by the guard) — via
9129    // plain `.await` sequencing rather than a race whose outcome the test
9130    // does not control.
9131
9132    fn file_backed_runtime(
9133        dir: &tempfile::TempDir,
9134        name: &str,
9135        write_queue_enabled: bool,
9136    ) -> KhiveRuntime {
9137        let path = dir.path().join(name);
9138        if write_queue_enabled {
9139            std::env::set_var("KHIVE_WRITE_QUEUE", "1");
9140        } else {
9141            std::env::remove_var("KHIVE_WRITE_QUEUE");
9142        }
9143        let rt = KhiveRuntime::new(crate::config::RuntimeConfig {
9144            db_path: Some(path),
9145            packs: vec!["kg".to_string()],
9146            brain_profile: None,
9147            actor_id: None,
9148            ..crate::config::RuntimeConfig::no_embeddings()
9149        })
9150        .unwrap();
9151        std::env::remove_var("KHIVE_WRITE_QUEUE");
9152        rt
9153    }
9154
9155    async fn assert_guarded_write_committed_before_delete_is_swept(rt: &KhiveRuntime) {
9156        let tok = NamespaceToken::local();
9157        let a = rt
9158            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9159            .await
9160            .unwrap();
9161        let x = rt
9162            .create_entity(&tok, "concept", None, "X", None, None, vec![])
9163            .await
9164            .unwrap();
9165
9166        // Write lands fully committed while X is still live — squarely
9167        // inside the window before the delete's cascade runs.
9168        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
9169        assert_eq!(
9170            rt.graph(&tok)
9171                .unwrap()
9172                .upsert_edge_guarded(edge)
9173                .await
9174                .unwrap(),
9175            khive_storage::GuardedWriteOutcome::Written,
9176            "write must succeed while both endpoints are still live"
9177        );
9178
9179        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
9180        assert_no_edges_touch(rt, &tok, x.id).await;
9181    }
9182
9183    async fn assert_guarded_write_attempted_after_delete_is_refused(rt: &KhiveRuntime) {
9184        let tok = NamespaceToken::local();
9185        let a = rt
9186            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9187            .await
9188            .unwrap();
9189        let x = rt
9190            .create_entity(&tok, "concept", None, "X", None, None, vec![])
9191            .await
9192            .unwrap();
9193
9194        // The delete's transaction has fully committed before the guarded
9195        // write is even attempted — squarely after the window has closed.
9196        assert!(rt.delete_entity(&tok, x.id, true).await.unwrap());
9197
9198        let edge = raw_edge(a.id, x.id, tok.namespace().as_str());
9199        let outcome = rt
9200            .graph(&tok)
9201            .unwrap()
9202            .upsert_edge_guarded(edge)
9203            .await
9204            .unwrap();
9205        match outcome {
9206            khive_storage::GuardedWriteOutcome::Refused(missing) => {
9207                assert!(
9208                    missing.target,
9209                    "target must be reported missing once the delete has committed"
9210                );
9211                assert!(!missing.source, "source was never deleted");
9212            }
9213            other => panic!(
9214                "guarded write attempted after the delete committed must be refused, got {other:?}"
9215            ),
9216        }
9217        assert_no_edges_touch(rt, &tok, x.id).await;
9218    }
9219
9220    #[tokio::test]
9221    #[serial_test::serial(khive_write_queue_env)]
9222    async fn guarded_write_before_delete_swept_file_backed_write_queue_off() {
9223        let dir = tempfile::tempdir().unwrap();
9224        let rt = file_backed_runtime(&dir, "guard_before_off.db", false);
9225        assert_guarded_write_committed_before_delete_is_swept(&rt).await;
9226    }
9227
9228    #[tokio::test]
9229    #[serial_test::serial(khive_write_queue_env)]
9230    async fn guarded_write_after_delete_refused_file_backed_write_queue_off() {
9231        let dir = tempfile::tempdir().unwrap();
9232        let rt = file_backed_runtime(&dir, "guard_after_off.db", false);
9233        assert_guarded_write_attempted_after_delete_is_refused(&rt).await;
9234    }
9235
9236    #[tokio::test]
9237    #[serial_test::serial(khive_write_queue_env)]
9238    async fn guarded_write_before_delete_swept_file_backed_write_queue_on() {
9239        let dir = tempfile::tempdir().unwrap();
9240        let rt = file_backed_runtime(&dir, "guard_before_on.db", true);
9241        assert_guarded_write_committed_before_delete_is_swept(&rt).await;
9242    }
9243
9244    #[tokio::test]
9245    #[serial_test::serial(khive_write_queue_env)]
9246    async fn guarded_write_after_delete_refused_file_backed_write_queue_on() {
9247        let dir = tempfile::tempdir().unwrap();
9248        let rt = file_backed_runtime(&dir, "guard_after_on.db", true);
9249        assert_guarded_write_attempted_after_delete_is_refused(&rt).await;
9250    }
9251
9252    #[tokio::test]
9253    async fn create_note_annotates_phantom_returns_not_found() {
9254        let rt = rt();
9255        let tok = NamespaceToken::local();
9256        let phantom = Uuid::new_v4();
9257
9258        let result = rt
9259            .create_note(
9260                &tok,
9261                "observation",
9262                None,
9263                "some content",
9264                Some(0.5),
9265                None,
9266                vec![phantom],
9267            )
9268            .await;
9269        assert!(
9270            matches!(result, Err(RuntimeError::NotFound(_))),
9271            "annotates with phantom uuid must return NotFound, got {result:?}"
9272        );
9273    }
9274
9275    #[tokio::test]
9276    async fn create_note_annotates_real_entity_succeeds() {
9277        let rt = rt();
9278        let tok = NamespaceToken::local();
9279        let entity = rt
9280            .create_entity(&tok, "concept", None, "RealTarget", None, None, vec![])
9281            .await
9282            .unwrap();
9283
9284        let note = rt
9285            .create_note(
9286                &tok,
9287                "observation",
9288                None,
9289                "content",
9290                Some(0.5),
9291                None,
9292                vec![entity.id],
9293            )
9294            .await
9295            .unwrap();
9296
9297        let neighbors = rt
9298            .neighbors(
9299                &tok,
9300                note.id,
9301                Direction::Out,
9302                None,
9303                Some(vec![EdgeRelation::Annotates]),
9304            )
9305            .await
9306            .unwrap();
9307        assert_eq!(neighbors.len(), 1);
9308        assert_eq!(neighbors[0].node_id, entity.id);
9309    }
9310
9311    // Atomicity: multi-target annotates golden path — all edges created, note present.
9312    #[tokio::test]
9313    async fn create_note_multi_annotates_creates_all_edges() {
9314        let rt = rt();
9315        let tok = NamespaceToken::local();
9316        let t1 = rt
9317            .create_entity(&tok, "concept", None, "Target1", None, None, vec![])
9318            .await
9319            .unwrap();
9320        let t2 = rt
9321            .create_entity(&tok, "concept", None, "Target2", None, None, vec![])
9322            .await
9323            .unwrap();
9324
9325        let note = rt
9326            .create_note(
9327                &tok,
9328                "observation",
9329                None,
9330                "content",
9331                Some(0.5),
9332                None,
9333                vec![t1.id, t2.id],
9334            )
9335            .await
9336            .unwrap();
9337
9338        let neighbors = rt
9339            .neighbors(
9340                &tok,
9341                note.id,
9342                Direction::Out,
9343                None,
9344                Some(vec![EdgeRelation::Annotates]),
9345            )
9346            .await
9347            .unwrap();
9348        assert_eq!(
9349            neighbors.len(),
9350            2,
9351            "multi-annotates note must have exactly 2 outbound annotates edges"
9352        );
9353        let target_ids: Vec<Uuid> = neighbors.iter().map(|n| n.node_id).collect();
9354        assert!(target_ids.contains(&t1.id));
9355        assert!(target_ids.contains(&t2.id));
9356    }
9357
9358    /// The atomic-apply post-commit renderer for a
9359    /// symmetric-edge update resolves the surviving row's store by the CALLER's
9360    /// token but must filter by the record's OWN namespace, passed explicitly —
9361    /// never by re-deriving it from whichever token happened to select the store
9362    /// (`self.graph(token)` scopes by `token.namespace()`, and by-ID edge updates
9363    /// are namespace-agnostic, so a caller in one namespace can legitimately
9364    /// commit an update against an edge recorded in another). This proves the
9365    /// `namespace` parameter — not the `token` argument — decides which row the
9366    /// natural-key lookup finds, at the level that is otherwise an
9367    /// acceptable substitute for a full cross-namespace atomic-apply test.
9368    #[tokio::test]
9369    async fn get_edge_by_natural_key_including_deleted_honors_explicit_namespace_not_token() {
9370        let rt = rt();
9371        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
9372        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
9373
9374        let a = rt
9375            .create_entity(&ns_b, "concept", None, "A", None, None, vec![])
9376            .await
9377            .unwrap();
9378        let b = rt
9379            .create_entity(&ns_b, "concept", None, "B", None, None, vec![])
9380            .await
9381            .unwrap();
9382        let edge = rt
9383            .link(&ns_b, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
9384            .await
9385            .unwrap();
9386        let (canon_src, canon_tgt) =
9387            canonical_edge_endpoints(EdgeRelation::CompetesWith, a.id, b.id);
9388
9389        // Caller token is ns-a (an unrelated namespace); passing "ns-b" explicitly
9390        // must still find the edge recorded there.
9391        let found = rt
9392            .get_edge_by_natural_key_including_deleted(
9393                &ns_a,
9394                "ns-b",
9395                canon_src,
9396                canon_tgt,
9397                EdgeRelation::CompetesWith,
9398            )
9399            .await
9400            .unwrap();
9401        assert_eq!(
9402            found.map(|e| Uuid::from(e.id)),
9403            Some(Uuid::from(edge.id)),
9404            "must find the edge by its own namespace regardless of the caller's token"
9405        );
9406
9407        // Passing the caller token's OWN namespace ("ns-a") as the explicit filter
9408        // must NOT find it — proves the lookup is keyed on the `namespace` argument,
9409        // not silently re-scoped to whatever namespace the token carries.
9410        let not_found = rt
9411            .get_edge_by_natural_key_including_deleted(
9412                &ns_a,
9413                "ns-a",
9414                canon_src,
9415                canon_tgt,
9416                EdgeRelation::CompetesWith,
9417            )
9418            .await
9419            .unwrap();
9420        assert!(
9421            not_found.is_none(),
9422            "must not find an edge recorded in a different namespace than the one queried"
9423        );
9424    }
9425
9426    /// `link` endpoint existence is a by-ID check and therefore namespace-agnostic:
9427    /// a target living in a different namespace than the caller must still
9428    /// resolve, exactly as `get()` would.
9429    #[tokio::test]
9430    async fn link_target_in_different_namespace_succeeds() {
9431        let rt = rt();
9432        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
9433        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
9434        let a = rt
9435            .create_entity(&ns_a, "concept", None, "A", None, None, vec![])
9436            .await
9437            .unwrap();
9438        let b = rt
9439            .create_entity(&ns_b, "concept", None, "B", None, None, vec![])
9440            .await
9441            .unwrap();
9442
9443        // Linking from ns-a: target b lives in ns-b — by-ID resolution finds it anyway.
9444        let result = rt
9445            .link(&ns_a, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9446            .await;
9447        assert!(
9448            result.is_ok(),
9449            "target in a different namespace than the caller must resolve (#631), got {result:?}"
9450        );
9451    }
9452
9453    #[tokio::test]
9454    async fn link_phantom_self_loop_returns_invalid_input() {
9455        let rt = rt();
9456        let tok = NamespaceToken::local();
9457        let phantom = Uuid::new_v4();
9458
9459        let result = rt
9460            .link(&tok, phantom, phantom, EdgeRelation::Extends, 1.0, None)
9461            .await;
9462        match result {
9463            Err(RuntimeError::InvalidInput(msg)) => {
9464                assert!(
9465                    msg.contains("self-loop"),
9466                    "self-loop must be rejected with self-loop message: {msg}"
9467                );
9468            }
9469            other => panic!("expected InvalidInput for self-loop, got {other:?}"),
9470        }
9471    }
9472
9473    // ---- edge target coverage + atomicity ----
9474
9475    #[tokio::test]
9476    async fn link_note_to_edge_annotates_succeeds() {
9477        let rt = rt();
9478        let tok = NamespaceToken::local();
9479        let a = rt
9480            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9481            .await
9482            .unwrap();
9483        let b = rt
9484            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9485            .await
9486            .unwrap();
9487        // Create a real edge between a and b, capture its UUID.
9488        let edge = rt
9489            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9490            .await
9491            .unwrap();
9492        let edge_uuid: Uuid = edge.id.into();
9493
9494        // Create a note and annotate the edge itself (edge is a valid substrate target for annotates).
9495        let note = rt
9496            .create_note(
9497                &tok,
9498                "observation",
9499                None,
9500                "edge note",
9501                Some(0.5),
9502                None,
9503                vec![],
9504            )
9505            .await
9506            .unwrap();
9507
9508        let result = rt
9509            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
9510            .await;
9511        assert!(
9512            result.is_ok(),
9513            "note→edge Annotates must succeed, got {result:?}"
9514        );
9515    }
9516    /// #803: `neighbors(edge_id, direction=In, relations=[Annotates])` must
9517    /// find the annotating note — the storage-layer `graph_edges` query
9518    /// filters on `target_id = node_id` with no substrate-type check, so an
9519    /// edge id works as a neighbor-query node the same as an entity or note
9520    /// id. This is the runtime capability `get(edge_id)`'s new `annotations`
9521    /// field (khive-pack-kg) builds on.
9522    #[tokio::test]
9523    async fn neighbors_edge_id_finds_annotating_note() {
9524        let rt = rt();
9525        let tok = NamespaceToken::local();
9526        let a = rt
9527            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9528            .await
9529            .unwrap();
9530        let b = rt
9531            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9532            .await
9533            .unwrap();
9534        let edge = rt
9535            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9536            .await
9537            .unwrap();
9538        let edge_uuid: Uuid = edge.id.into();
9539
9540        let note = rt
9541            .create_note(
9542                &tok,
9543                "observation",
9544                None,
9545                "edge note",
9546                Some(0.5),
9547                None,
9548                vec![edge_uuid],
9549            )
9550            .await
9551            .unwrap();
9552
9553        let neighbors = rt
9554            .neighbors(
9555                &tok,
9556                edge_uuid,
9557                Direction::In,
9558                None,
9559                Some(vec![EdgeRelation::Annotates]),
9560            )
9561            .await
9562            .unwrap();
9563        assert_eq!(neighbors.len(), 1, "expected annotating note to show up");
9564        assert_eq!(neighbors[0].node_id, note.id);
9565    }
9566
9567    #[tokio::test]
9568    async fn create_note_annotates_real_edge_succeeds() {
9569        let rt = rt();
9570        let tok = NamespaceToken::local();
9571        let a = rt
9572            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9573            .await
9574            .unwrap();
9575        let b = rt
9576            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9577            .await
9578            .unwrap();
9579        let edge = rt
9580            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9581            .await
9582            .unwrap();
9583        let edge_uuid: Uuid = edge.id.into();
9584
9585        let note = rt
9586            .create_note(
9587                &tok,
9588                "observation",
9589                None,
9590                "annotating an edge",
9591                Some(0.5),
9592                None,
9593                vec![edge_uuid],
9594            )
9595            .await
9596            .unwrap();
9597
9598        let neighbors = rt
9599            .neighbors(
9600                &tok,
9601                note.id,
9602                Direction::Out,
9603                None,
9604                Some(vec![EdgeRelation::Annotates]),
9605            )
9606            .await
9607            .unwrap();
9608        assert_eq!(neighbors.len(), 1);
9609        assert_eq!(neighbors[0].node_id, edge_uuid);
9610    }
9611
9612    #[tokio::test]
9613    async fn create_note_annotates_phantom_is_atomic_no_note_persisted() {
9614        let rt = rt();
9615        let tok = NamespaceToken::local();
9616        let phantom = Uuid::new_v4();
9617
9618        let before_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();
9619
9620        let result = rt
9621            .create_note(
9622                &tok,
9623                "observation",
9624                None,
9625                "should not persist",
9626                Some(0.5),
9627                None,
9628                vec![phantom],
9629            )
9630            .await;
9631        assert!(
9632            matches!(result, Err(RuntimeError::NotFound(_))),
9633            "phantom annotates target must return NotFound, got {result:?}"
9634        );
9635
9636        // Atomicity: the note row must NOT have been written.
9637        let after_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();
9638        assert_eq!(
9639            before_count, after_count,
9640            "failed create_note must not persist any note row (atomicity)"
9641        );
9642
9643        // FTS must not contain the content either.
9644        let search_hits = rt
9645            .search_notes(&tok, "should not persist", None, 10, None, false, &[], None)
9646            .await
9647            .unwrap();
9648        assert!(
9649            search_hits.is_empty(),
9650            "failed create_note must not index into FTS (atomicity)"
9651        );
9652        // Vector-store row: only written when an embedding model is configured; the rt()
9653        // harness has none, so no vector assertion is needed here.
9654    }
9655
9656    // ---- relation-aware endpoint contract ----
9657
9658    // Test #2: entity→entity with non-annotates rejects an edge UUID as target.
9659    #[tokio::test]
9660    async fn link_entity_to_edge_uuid_non_annotates_returns_invalid_input() {
9661        let rt = rt();
9662        let tok = NamespaceToken::local();
9663        let a = rt
9664            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9665            .await
9666            .unwrap();
9667        let b = rt
9668            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9669            .await
9670            .unwrap();
9671        // Create a real edge; capture its UUID as the bad target.
9672        let edge = rt
9673            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9674            .await
9675            .unwrap();
9676        let edge_uuid: Uuid = edge.id.into();
9677
9678        let result = rt
9679            .link(&tok, a.id, edge_uuid, EdgeRelation::Extends, 1.0, None)
9680            .await;
9681        match result {
9682            Err(RuntimeError::InvalidInput(msg)) => {
9683                assert!(
9684                    msg.contains("target"),
9685                    "error message must name 'target': {msg}"
9686                );
9687            }
9688            other => {
9689                panic!("expected InvalidInput for edge-uuid target with Extends, got {other:?}")
9690            }
9691        }
9692    }
9693
9694    // Test #3: non-annotates rejects a note UUID as source.
9695    #[tokio::test]
9696    async fn link_note_as_source_non_annotates_returns_invalid_input() {
9697        let rt = rt();
9698        let tok = NamespaceToken::local();
9699        let note = rt
9700            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
9701            .await
9702            .unwrap();
9703        let entity = rt
9704            .create_entity(&tok, "concept", None, "E", None, None, vec![])
9705            .await
9706            .unwrap();
9707
9708        let result = rt
9709            .link(&tok, note.id, entity.id, EdgeRelation::DependsOn, 1.0, None)
9710            .await;
9711        match result {
9712            Err(RuntimeError::InvalidInput(msg)) => {
9713                assert!(
9714                    msg.contains("source"),
9715                    "error message must name 'source': {msg}"
9716                );
9717            }
9718            other => panic!("expected InvalidInput for note source with DependsOn, got {other:?}"),
9719        }
9720    }
9721
9722    // Test #4: annotates rejects entity as source (source must be a note).
9723    #[tokio::test]
9724    async fn link_entity_as_annotates_source_returns_invalid_input() {
9725        let rt = rt();
9726        let tok = NamespaceToken::local();
9727        let a = rt
9728            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9729            .await
9730            .unwrap();
9731        let b = rt
9732            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9733            .await
9734            .unwrap();
9735
9736        let result = rt
9737            .link(&tok, a.id, b.id, EdgeRelation::Annotates, 1.0, None)
9738            .await;
9739        match result {
9740            Err(RuntimeError::InvalidInput(msg)) => {
9741                assert!(
9742                    msg.contains("source") && msg.contains("note"),
9743                    "error must say source must be a note: {msg}"
9744                );
9745            }
9746            other => {
9747                panic!("expected InvalidInput for entity source with Annotates, got {other:?}")
9748            }
9749        }
9750    }
9751
9752    #[tokio::test]
9753    async fn link_edge_as_annotates_source_returns_invalid_input() {
9754        let rt = rt();
9755        let tok = NamespaceToken::local();
9756        let a = rt
9757            .create_entity(&tok, "concept", None, "A", None, None, vec![])
9758            .await
9759            .unwrap();
9760        let b = rt
9761            .create_entity(&tok, "concept", None, "B", None, None, vec![])
9762            .await
9763            .unwrap();
9764        let edge = rt
9765            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
9766            .await
9767            .unwrap();
9768        let edge_uuid: Uuid = edge.id.into();
9769
9770        // An existing edge used as an annotates source: wrong kind, not absent.
9771        let result = rt
9772            .link(&tok, edge_uuid, a.id, EdgeRelation::Annotates, 1.0, None)
9773            .await;
9774        match result {
9775            Err(RuntimeError::InvalidInput(msg)) => {
9776                assert!(
9777                    msg.contains("source") && msg.contains("note"),
9778                    "edge-as-annotates-source must report wrong kind, not NotFound: {msg}"
9779                );
9780            }
9781            other => panic!("expected InvalidInput for edge source with Annotates, got {other:?}"),
9782        }
9783    }
9784
9785    // Test #5: note→event with annotates succeeds (event is a valid annotates target).
9786    #[tokio::test]
9787    async fn link_note_to_event_annotates_succeeds() {
9788        use khive_storage::Event;
9789        use khive_types::{EventKind, SubstrateKind};
9790
9791        let rt = rt();
9792        let tok = NamespaceToken::local();
9793        let note = rt
9794            .create_note(
9795                &tok,
9796                "observation",
9797                None,
9798                "observing an event",
9799                Some(0.6),
9800                None,
9801                vec![],
9802            )
9803            .await
9804            .unwrap();
9805
9806        // Build an event directly via the store (no runtime create_event exists).
9807        let ns = tok.namespace().as_str();
9808        let event = Event::new(
9809            ns,
9810            "test_verb",
9811            EventKind::Audit,
9812            SubstrateKind::Entity,
9813            "test_actor",
9814        );
9815        let event_id = event.id;
9816        rt.events(&tok).unwrap().append_event(event).await.unwrap();
9817
9818        let result = rt
9819            .link(&tok, note.id, event_id, EdgeRelation::Annotates, 1.0, None)
9820            .await;
9821        assert!(
9822            result.is_ok(),
9823            "note→event Annotates must succeed, got {result:?}"
9824        );
9825    }
9826
9827    // Test #6: create_note with event as annotates target succeeds.
9828    #[tokio::test]
9829    async fn create_note_annotates_event_succeeds() {
9830        use khive_storage::Event;
9831        use khive_types::{EventKind, SubstrateKind};
9832
9833        let rt = rt();
9834        let tok = NamespaceToken::local();
9835        let ns = tok.namespace().as_str();
9836        let event = Event::new(
9837            ns,
9838            "test_verb",
9839            EventKind::Audit,
9840            SubstrateKind::Entity,
9841            "test_actor",
9842        );
9843        let event_id = event.id;
9844        rt.events(&tok).unwrap().append_event(event).await.unwrap();
9845
9846        let result = rt
9847            .create_note(
9848                &tok,
9849                "observation",
9850                None,
9851                "note annotating an event",
9852                Some(0.5),
9853                None,
9854                vec![event_id],
9855            )
9856            .await;
9857        assert!(
9858            result.is_ok(),
9859            "create_note with event annotates target must succeed, got {result:?}"
9860        );
9861        // Verify the annotates edge was created.
9862        let note = result.unwrap();
9863        let neighbors = rt
9864            .neighbors(
9865                &tok,
9866                note.id,
9867                Direction::Out,
9868                None,
9869                Some(vec![EdgeRelation::Annotates]),
9870            )
9871            .await
9872            .unwrap();
9873        assert_eq!(neighbors.len(), 1);
9874        assert_eq!(neighbors[0].node_id, event_id);
9875    }
9876
9877    // ---- supersedes same-substrate contract ----
9878
9879    // Headline regression: note→note supersedes must succeed (was wrongly rejected before this fix).
9880    #[tokio::test]
9881    async fn link_supersedes_note_to_note_succeeds() {
9882        let rt = rt();
9883        let tok = NamespaceToken::local();
9884        let old_note = rt
9885            .create_note(
9886                &tok,
9887                "observation",
9888                None,
9889                "old observation",
9890                Some(0.7),
9891                None,
9892                vec![],
9893            )
9894            .await
9895            .unwrap();
9896        let new_note = rt
9897            .create_note(
9898                &tok,
9899                "observation",
9900                None,
9901                "revised observation superseding the old one",
9902                Some(0.9),
9903                None,
9904                vec![],
9905            )
9906            .await
9907            .unwrap();
9908
9909        let result = rt
9910            .link(
9911                &tok,
9912                new_note.id,
9913                old_note.id,
9914                EdgeRelation::Supersedes,
9915                1.0,
9916                None,
9917            )
9918            .await;
9919        assert!(
9920            result.is_ok(),
9921            "note→note Supersedes must succeed (note supersession), got {result:?}"
9922        );
9923    }
9924
9925    #[tokio::test]
9926    async fn link_supersedes_entity_to_entity_succeeds() {
9927        let rt = rt();
9928        let tok = NamespaceToken::local();
9929        let old_entity = rt
9930            .create_entity(&tok, "concept", None, "OldConcept", None, None, vec![])
9931            .await
9932            .unwrap();
9933        let new_entity = rt
9934            .create_entity(&tok, "concept", None, "NewConcept", None, None, vec![])
9935            .await
9936            .unwrap();
9937
9938        let result = rt
9939            .link(
9940                &tok,
9941                new_entity.id,
9942                old_entity.id,
9943                EdgeRelation::Supersedes,
9944                1.0,
9945                None,
9946            )
9947            .await;
9948        assert!(
9949            result.is_ok(),
9950            "entity→entity Supersedes must succeed, got {result:?}"
9951        );
9952    }
9953
9954    #[tokio::test]
9955    async fn link_supersedes_note_to_entity_returns_invalid_input() {
9956        let rt = rt();
9957        let tok = NamespaceToken::local();
9958        let note = rt
9959            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
9960            .await
9961            .unwrap();
9962        let entity = rt
9963            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
9964            .await
9965            .unwrap();
9966
9967        let result = rt
9968            .link(
9969                &tok,
9970                note.id,
9971                entity.id,
9972                EdgeRelation::Supersedes,
9973                1.0,
9974                None,
9975            )
9976            .await;
9977        match result {
9978            Err(RuntimeError::InvalidInput(msg)) => {
9979                assert!(
9980                    msg.contains("same substrate") || msg.contains("same-substrate"),
9981                    "error must name the same-substrate rule: {msg}"
9982                );
9983            }
9984            other => panic!(
9985                "expected InvalidInput for note→entity Supersedes (cross-substrate), got {other:?}"
9986            ),
9987        }
9988    }
9989
9990    #[tokio::test]
9991    async fn link_supersedes_entity_to_note_returns_invalid_input() {
9992        let rt = rt();
9993        let tok = NamespaceToken::local();
9994        let entity = rt
9995            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
9996            .await
9997            .unwrap();
9998        let note = rt
9999            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
10000            .await
10001            .unwrap();
10002
10003        let result = rt
10004            .link(
10005                &tok,
10006                entity.id,
10007                note.id,
10008                EdgeRelation::Supersedes,
10009                1.0,
10010                None,
10011            )
10012            .await;
10013        match result {
10014            Err(RuntimeError::InvalidInput(msg)) => {
10015                assert!(
10016                    msg.contains("same substrate") || msg.contains("same-substrate"),
10017                    "error must name the same-substrate rule: {msg}"
10018                );
10019            }
10020            other => panic!(
10021                "expected InvalidInput for entity→note Supersedes (cross-substrate), got {other:?}"
10022            ),
10023        }
10024    }
10025
10026    #[tokio::test]
10027    async fn link_supersedes_event_source_returns_invalid_input() {
10028        use khive_storage::Event;
10029        use khive_types::{EventKind, SubstrateKind};
10030
10031        let rt = rt();
10032        let tok = NamespaceToken::local();
10033        let ns = tok.namespace().as_str();
10034        let event = Event::new(
10035            ns,
10036            "test_verb",
10037            EventKind::Audit,
10038            SubstrateKind::Entity,
10039            "test_actor",
10040        );
10041        let event_id = event.id;
10042        rt.events(&tok).unwrap().append_event(event).await.unwrap();
10043
10044        let entity = rt
10045            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
10046            .await
10047            .unwrap();
10048
10049        let result = rt
10050            .link(
10051                &tok,
10052                event_id,
10053                entity.id,
10054                EdgeRelation::Supersedes,
10055                1.0,
10056                None,
10057            )
10058            .await;
10059        match result {
10060            Err(RuntimeError::InvalidInput(msg)) => {
10061                assert!(msg.contains("event"), "error must mention 'event': {msg}");
10062            }
10063            other => {
10064                panic!("expected InvalidInput for event source with Supersedes, got {other:?}")
10065            }
10066        }
10067    }
10068
10069    #[tokio::test]
10070    async fn link_supersedes_event_target_returns_invalid_input() {
10071        use khive_storage::Event;
10072        use khive_types::{EventKind, SubstrateKind};
10073
10074        let rt = rt();
10075        let tok = NamespaceToken::local();
10076        let ns = tok.namespace().as_str();
10077        let event = Event::new(
10078            ns,
10079            "test_verb",
10080            EventKind::Audit,
10081            SubstrateKind::Entity,
10082            "test_actor",
10083        );
10084        let event_id = event.id;
10085        rt.events(&tok).unwrap().append_event(event).await.unwrap();
10086
10087        let entity = rt
10088            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
10089            .await
10090            .unwrap();
10091
10092        let result = rt
10093            .link(
10094                &tok,
10095                entity.id,
10096                event_id,
10097                EdgeRelation::Supersedes,
10098                1.0,
10099                None,
10100            )
10101            .await;
10102        match result {
10103            Err(RuntimeError::InvalidInput(msg)) => {
10104                assert!(msg.contains("event"), "error must mention 'event': {msg}");
10105            }
10106            other => {
10107                panic!("expected InvalidInput for event target with Supersedes, got {other:?}")
10108            }
10109        }
10110    }
10111
10112    #[tokio::test]
10113    async fn link_supersedes_edge_source_returns_invalid_input() {
10114        let rt = rt();
10115        let tok = NamespaceToken::local();
10116        let a = rt
10117            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10118            .await
10119            .unwrap();
10120        let b = rt
10121            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10122            .await
10123            .unwrap();
10124        let edge = rt
10125            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10126            .await
10127            .unwrap();
10128        let edge_uuid: Uuid = edge.id.into();
10129
10130        let result = rt
10131            .link(&tok, edge_uuid, a.id, EdgeRelation::Supersedes, 1.0, None)
10132            .await;
10133        match result {
10134            Err(RuntimeError::InvalidInput(msg)) => {
10135                assert!(msg.contains("source"), "error must name 'source': {msg}");
10136            }
10137            other => {
10138                panic!("expected InvalidInput for edge-uuid source with Supersedes, got {other:?}")
10139            }
10140        }
10141    }
10142
10143    #[tokio::test]
10144    async fn link_supersedes_edge_target_returns_invalid_input() {
10145        let rt = rt();
10146        let tok = NamespaceToken::local();
10147        let a = rt
10148            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10149            .await
10150            .unwrap();
10151        let b = rt
10152            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10153            .await
10154            .unwrap();
10155        let edge = rt
10156            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10157            .await
10158            .unwrap();
10159        let edge_uuid: Uuid = edge.id.into();
10160
10161        let result = rt
10162            .link(&tok, a.id, edge_uuid, EdgeRelation::Supersedes, 1.0, None)
10163            .await;
10164        match result {
10165            Err(RuntimeError::InvalidInput(msg)) => {
10166                assert!(msg.contains("target"), "error must name 'target': {msg}");
10167            }
10168            other => {
10169                panic!("expected InvalidInput for edge-uuid target with Supersedes, got {other:?}")
10170            }
10171        }
10172    }
10173
10174    #[tokio::test]
10175    async fn link_supersedes_phantom_source_returns_not_found() {
10176        let rt = rt();
10177        let tok = NamespaceToken::local();
10178        let note = rt
10179            .create_note(
10180                &tok,
10181                "observation",
10182                None,
10183                "existing note",
10184                Some(0.5),
10185                None,
10186                vec![],
10187            )
10188            .await
10189            .unwrap();
10190        let phantom = Uuid::new_v4();
10191
10192        let result = rt
10193            .link(&tok, phantom, note.id, EdgeRelation::Supersedes, 1.0, None)
10194            .await;
10195        match result {
10196            Err(RuntimeError::NotFound(msg)) => {
10197                assert!(msg.contains("source"), "error must name 'source': {msg}");
10198            }
10199            other => panic!("expected NotFound for phantom source with Supersedes, got {other:?}"),
10200        }
10201    }
10202
10203    #[tokio::test]
10204    async fn link_supersedes_phantom_target_returns_not_found() {
10205        let rt = rt();
10206        let tok = NamespaceToken::local();
10207        let note = rt
10208            .create_note(
10209                &tok,
10210                "observation",
10211                None,
10212                "existing note",
10213                Some(0.5),
10214                None,
10215                vec![],
10216            )
10217            .await
10218            .unwrap();
10219        let phantom = Uuid::new_v4();
10220
10221        let result = rt
10222            .link(&tok, note.id, phantom, EdgeRelation::Supersedes, 1.0, None)
10223            .await;
10224        match result {
10225            Err(RuntimeError::NotFound(msg)) => {
10226                assert!(msg.contains("target"), "error must name 'target': {msg}");
10227            }
10228            other => panic!("expected NotFound for phantom target with Supersedes, got {other:?}"),
10229        }
10230    }
10231
10232    /// The canonical `remember | supersedes` chain: a `supersedes` source note living
10233    /// in a different namespace than the caller must still resolve as a by-ID endpoint.
10234    #[tokio::test]
10235    async fn link_supersedes_cross_namespace_source_succeeds() {
10236        let rt = rt();
10237        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
10238        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
10239        let note_a = rt
10240            .create_note(
10241                &ns_a,
10242                "observation",
10243                None,
10244                "note in ns-a",
10245                Some(0.5),
10246                None,
10247                vec![],
10248            )
10249            .await
10250            .unwrap();
10251        let note_b = rt
10252            .create_note(
10253                &ns_b,
10254                "observation",
10255                None,
10256                "note in ns-b",
10257                Some(0.5),
10258                None,
10259                vec![],
10260            )
10261            .await
10262            .unwrap();
10263
10264        // From ns-a perspective, note_b is in a different namespace — by-ID resolution
10265        // finds it anyway.
10266        let result = rt
10267            .link(
10268                &ns_a,
10269                note_b.id,
10270                note_a.id,
10271                EdgeRelation::Supersedes,
10272                1.0,
10273                None,
10274            )
10275            .await;
10276        assert!(
10277            result.is_ok(),
10278            "cross-namespace supersedes source must resolve (#631), got {result:?}"
10279        );
10280    }
10281
10282    // Sanity: extends (non-annotates, non-supersedes) still requires entity→entity.
10283    #[tokio::test]
10284    async fn link_extends_note_source_still_returns_invalid_input() {
10285        let rt = rt();
10286        let tok = NamespaceToken::local();
10287        let note = rt
10288            .create_note(
10289                &tok,
10290                "observation",
10291                None,
10292                "a note that cannot be an extends source",
10293                Some(0.5),
10294                None,
10295                vec![],
10296            )
10297            .await
10298            .unwrap();
10299        let entity = rt
10300            .create_entity(&tok, "concept", None, "E", None, None, vec![])
10301            .await
10302            .unwrap();
10303
10304        let result = rt
10305            .link(&tok, note.id, entity.id, EdgeRelation::Extends, 1.0, None)
10306            .await;
10307        assert!(
10308            matches!(result, Err(RuntimeError::InvalidInput(_))),
10309            "note source with Extends must still return InvalidInput after this fix, got {result:?}"
10310        );
10311    }
10312
10313    // Sanity: annotates note→edge still succeeds (unchanged path not broken by this fix).
10314    #[tokio::test]
10315    async fn link_annotates_note_to_edge_still_succeeds_after_fix() {
10316        let rt = rt();
10317        let tok = NamespaceToken::local();
10318        let a = rt
10319            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10320            .await
10321            .unwrap();
10322        let b = rt
10323            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10324            .await
10325            .unwrap();
10326        let edge = rt
10327            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10328            .await
10329            .unwrap();
10330        let edge_uuid: Uuid = edge.id.into();
10331
10332        let note = rt
10333            .create_note(
10334                &tok,
10335                "observation",
10336                None,
10337                "annotating an edge",
10338                Some(0.5),
10339                None,
10340                vec![],
10341            )
10342            .await
10343            .unwrap();
10344
10345        let result = rt
10346            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
10347            .await;
10348        assert!(
10349            result.is_ok(),
10350            "note→edge Annotates must still succeed after supersedes fix, got {result:?}"
10351        );
10352    }
10353
10354    // ---- Compensation-path rollback (fix/annotates) ----
10355
10356    // The compensation branch in `create_note_inner` (operations.rs) rolls back
10357    // a partial write — note row + first edge + FTS + vector — when a subsequent
10358    // link call fails. The failure trigger is a storage error (e.g. I/O failure)
10359    // that cannot occur in the in-memory runtime; this test instead exercises the
10360    // exact cleanup operations that the compensation branch performs, starting from
10361    // a manually-constructed partial state, and verifies the post-cleanup invariants.
10362    //
10363    // What this covers: the cleanup sequence (delete_edge, delete_note hard, FTS
10364    // index clean) is correct and leaves the DB in a pristine state. What it does
10365    // not cover: the trigger condition (second link failure). Storage-error injection
10366    // would require a mock GraphStore, which is beyond the current test infrastructure.
10367    #[tokio::test]
10368    async fn create_note_multi_annotates_compensation_cleanup_restores_pristine_state() {
10369        let rt = rt();
10370        let tok = NamespaceToken::local();
10371        let t1 = rt
10372            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
10373            .await
10374            .unwrap();
10375
10376        // Construct the partial state that the compensation branch would encounter:
10377        // note persisted + first annotates edge created.
10378        let note = rt
10379            .create_note(
10380                &tok,
10381                "observation",
10382                None,
10383                "partial note",
10384                Some(0.5),
10385                None,
10386                vec![t1.id],
10387            )
10388            .await
10389            .unwrap();
10390
10391        // Confirm the partial state exists before compensation.
10392        let before_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
10393        assert_eq!(before_notes.len(), 1, "note must be present before cleanup");
10394        let before_edges = rt
10395            .neighbors(
10396                &tok,
10397                note.id,
10398                Direction::Out,
10399                None,
10400                Some(vec![EdgeRelation::Annotates]),
10401            )
10402            .await
10403            .unwrap();
10404        assert_eq!(
10405            before_edges.len(),
10406            1,
10407            "one annotates edge must exist before cleanup"
10408        );
10409        let edge_id: Uuid = before_edges[0].edge_id;
10410
10411        // Execute the same cleanup sequence that `create_note_inner`'s Err branch runs.
10412        rt.delete_edge(&tok, edge_id, true).await.unwrap();
10413        rt.delete_note(&tok, note.id, true /* hard */)
10414            .await
10415            .unwrap();
10416
10417        // Post-compensation invariants:
10418        let after_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
10419        assert!(
10420            after_notes.is_empty(),
10421            "compensation must remove the note row; got {after_notes:?}"
10422        );
10423        let search_hits = rt
10424            .search_notes(&tok, "partial note", None, 10, None, false, &[], None)
10425            .await
10426            .unwrap();
10427        assert!(
10428            search_hits.is_empty(),
10429            "compensation must clean the FTS index; got {search_hits:?}"
10430        );
10431        let after_edges = rt
10432            .neighbors(&tok, note.id, Direction::Out, None, None)
10433            .await
10434            .unwrap();
10435        assert!(
10436            after_edges.is_empty(),
10437            "compensation must remove all partial edges; got {after_edges:?}"
10438        );
10439    }
10440
10441    // ---- Hard-delete cascade for note and edge annotation targets (fix/annotates) ----
10442
10443    // annotates is note → ANYTHING (entity, note, edge, event);
10444    // targets may be entity, edge, event, or note.
10445    // Hard-deleting any of those targets must cascade incident annotates edges.
10446    // Soft deletes leave edges (data-vs-view rule).
10447
10448    #[tokio::test]
10449    async fn annotated_entity_hard_delete_cascades_annotate_edge() {
10450        let rt = rt();
10451        let tok = NamespaceToken::local();
10452        let entity = rt
10453            .create_entity(&tok, "concept", None, "E", None, None, vec![])
10454            .await
10455            .unwrap();
10456        let note = rt
10457            .create_note(
10458                &tok,
10459                "observation",
10460                None,
10461                "note about entity",
10462                Some(0.5),
10463                None,
10464                vec![entity.id],
10465            )
10466            .await
10467            .unwrap();
10468
10469        // Confirm edge exists before delete.
10470        let before = rt
10471            .neighbors(
10472                &tok,
10473                note.id,
10474                Direction::Out,
10475                None,
10476                Some(vec![EdgeRelation::Annotates]),
10477            )
10478            .await
10479            .unwrap();
10480        assert_eq!(
10481            before.len(),
10482            1,
10483            "annotates edge must exist before entity delete"
10484        );
10485
10486        // Hard delete the entity.
10487        let deleted = rt.delete_entity(&tok, entity.id, true).await.unwrap();
10488        assert!(deleted, "entity hard delete must return true");
10489
10490        // Annotates edge must be gone.
10491        let after = rt
10492            .neighbors(
10493                &tok,
10494                note.id,
10495                Direction::Out,
10496                None,
10497                Some(vec![EdgeRelation::Annotates]),
10498            )
10499            .await
10500            .unwrap();
10501        assert!(
10502            after.is_empty(),
10503            "annotates edge must be cascaded on entity hard delete; got {after:?}"
10504        );
10505    }
10506
10507    #[tokio::test]
10508    async fn annotated_note_hard_delete_cascades_annotate_edge() {
10509        let rt = rt();
10510        let tok = NamespaceToken::local();
10511        // note_target is the thing being annotated (a note itself).
10512        let note_target = rt
10513            .create_note(
10514                &tok,
10515                "observation",
10516                None,
10517                "target note",
10518                Some(0.5),
10519                None,
10520                vec![],
10521            )
10522            .await
10523            .unwrap();
10524        // note_source annotates note_target.
10525        let note_source = rt
10526            .create_note(
10527                &tok,
10528                "insight",
10529                None,
10530                "annotation",
10531                Some(0.5),
10532                None,
10533                vec![note_target.id],
10534            )
10535            .await
10536            .unwrap();
10537
10538        let before = rt
10539            .neighbors(
10540                &tok,
10541                note_source.id,
10542                Direction::Out,
10543                None,
10544                Some(vec![EdgeRelation::Annotates]),
10545            )
10546            .await
10547            .unwrap();
10548        assert_eq!(
10549            before.len(),
10550            1,
10551            "annotates edge must exist before note delete"
10552        );
10553
10554        // Hard delete the annotation TARGET note.
10555        let deleted = rt.delete_note(&tok, note_target.id, true).await.unwrap();
10556        assert!(deleted, "note hard delete must return true");
10557
10558        // The annotates edge targeting note_target must be gone.
10559        let after = rt
10560            .neighbors(
10561                &tok,
10562                note_source.id,
10563                Direction::Out,
10564                None,
10565                Some(vec![EdgeRelation::Annotates]),
10566            )
10567            .await
10568            .unwrap();
10569        assert!(
10570            after.is_empty(),
10571            "annotates edge must be cascaded on note-target hard delete; got {after:?}"
10572        );
10573    }
10574
10575    #[tokio::test]
10576    async fn annotated_edge_delete_cascades_annotate_edge() {
10577        let rt = rt();
10578        let tok = NamespaceToken::local();
10579        let a = rt
10580            .create_entity(&tok, "concept", None, "A", None, None, vec![])
10581            .await
10582            .unwrap();
10583        let b = rt
10584            .create_entity(&tok, "concept", None, "B", None, None, vec![])
10585            .await
10586            .unwrap();
10587        // Create an edge to annotate.
10588        let base_edge = rt
10589            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
10590            .await
10591            .unwrap();
10592        let base_edge_uuid: Uuid = base_edge.id.into();
10593
10594        // Create a note that annotates the edge.
10595        let note = rt
10596            .create_note(
10597                &tok,
10598                "observation",
10599                None,
10600                "note about edge",
10601                Some(0.5),
10602                None,
10603                vec![base_edge_uuid],
10604            )
10605            .await
10606            .unwrap();
10607
10608        let before = rt
10609            .neighbors(
10610                &tok,
10611                note.id,
10612                Direction::Out,
10613                None,
10614                Some(vec![EdgeRelation::Annotates]),
10615            )
10616            .await
10617            .unwrap();
10618        assert_eq!(
10619            before.len(),
10620            1,
10621            "annotates edge must exist before base edge delete"
10622        );
10623
10624        // Delete the base edge.
10625        let deleted = rt.delete_edge(&tok, base_edge_uuid, true).await.unwrap();
10626        assert!(deleted, "edge delete must return true");
10627
10628        // The annotates edge targeting base_edge must be gone.
10629        let after = rt
10630            .neighbors(
10631                &tok,
10632                note.id,
10633                Direction::Out,
10634                None,
10635                Some(vec![EdgeRelation::Annotates]),
10636            )
10637            .await
10638            .unwrap();
10639        assert!(
10640            after.is_empty(),
10641            "annotates edge must be cascaded on base edge delete; got {after:?}"
10642        );
10643    }
10644
10645    #[tokio::test]
10646    async fn mixed_multi_annotates_partial_target_hard_delete_leaves_remaining_edges() {
10647        let rt = rt();
10648        let tok = NamespaceToken::local();
10649        let t1 = rt
10650            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
10651            .await
10652            .unwrap();
10653        let t2 = rt
10654            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
10655            .await
10656            .unwrap();
10657
10658        // Note annotates both t1 and t2.
10659        let note = rt
10660            .create_note(
10661                &tok,
10662                "observation",
10663                None,
10664                "multi-target note",
10665                Some(0.5),
10666                None,
10667                vec![t1.id, t2.id],
10668            )
10669            .await
10670            .unwrap();
10671
10672        let before = rt
10673            .neighbors(
10674                &tok,
10675                note.id,
10676                Direction::Out,
10677                None,
10678                Some(vec![EdgeRelation::Annotates]),
10679            )
10680            .await
10681            .unwrap();
10682        assert_eq!(
10683            before.len(),
10684            2,
10685            "must have 2 annotates edges before any delete"
10686        );
10687
10688        // Hard delete only t1.
10689        rt.delete_entity(&tok, t1.id, true).await.unwrap();
10690
10691        // Edge to t1 must be gone, edge to t2 must remain.
10692        let after = rt
10693            .neighbors(
10694                &tok,
10695                note.id,
10696                Direction::Out,
10697                None,
10698                Some(vec![EdgeRelation::Annotates]),
10699            )
10700            .await
10701            .unwrap();
10702        assert_eq!(
10703            after.len(),
10704            1,
10705            "only the edge to t1 must be cascaded; t2 edge must remain"
10706        );
10707        assert_eq!(
10708            after[0].node_id, t2.id,
10709            "remaining annotates edge must point to t2"
10710        );
10711    }
10712
10713    #[tokio::test]
10714    async fn annotated_note_soft_delete_preserves_annotate_edge() {
10715        let rt = rt();
10716        let tok = NamespaceToken::local();
10717        let note_target = rt
10718            .create_note(&tok, "observation", None, "target", Some(0.5), None, vec![])
10719            .await
10720            .unwrap();
10721        let note_source = rt
10722            .create_note(
10723                &tok,
10724                "insight",
10725                None,
10726                "annotation",
10727                Some(0.5),
10728                None,
10729                vec![note_target.id],
10730            )
10731            .await
10732            .unwrap();
10733
10734        let before = rt
10735            .neighbors(
10736                &tok,
10737                note_source.id,
10738                Direction::Out,
10739                None,
10740                Some(vec![EdgeRelation::Annotates]),
10741            )
10742            .await
10743            .unwrap();
10744        assert_eq!(before.len(), 1);
10745        let edge_id = before[0].edge_id;
10746
10747        // Soft delete must NOT cascade edges (data-vs-view principle).
10748        let deleted = rt.delete_note(&tok, note_target.id, false).await.unwrap();
10749        assert!(deleted, "soft delete must return true");
10750
10751        // The edge itself must survive the soft delete — checked at the
10752        // storage/edge layer directly (`get_edge`), not through `neighbors()`.
10753        // `neighbors()` is a VIEW query and correctly screens
10754        // out soft-deleted note targets — so it no longer surfaces this edge
10755        // once note_target is soft-deleted, even though the edge row itself
10756        // is untouched (data-vs-view principle: the edge is data, what
10757        // `neighbors()` shows is a view decision).
10758        let edge_after = rt.get_edge(&tok, edge_id).await.unwrap();
10759        assert!(
10760            edge_after.is_some(),
10761            "soft delete must NOT cascade edges; get_edge returned None"
10762        );
10763
10764        let after = rt
10765            .neighbors(
10766                &tok,
10767                note_source.id,
10768                Direction::Out,
10769                None,
10770                Some(vec![EdgeRelation::Annotates]),
10771            )
10772            .await
10773            .unwrap();
10774        assert_eq!(
10775            after.len(),
10776            0,
10777            "#748: neighbors() must screen out the soft-deleted note target; got {after:?}"
10778        );
10779    }
10780
10781    // ---- delete_edge public-API safety ----
10782
10783    // Passing an entity/note UUID to `delete_edge` must return Ok(false) with no
10784    // side effects — it must NOT delete inbound annotates edges targeting that record.
10785    // Without the get_edge guard, the old code would cascade inbound edges before
10786    // returning false.
10787    #[tokio::test]
10788    async fn delete_edge_non_edge_uuid_has_no_side_effects() {
10789        let rt = rt();
10790        let tok = NamespaceToken::local();
10791
10792        // Create an entity that has an inbound annotates edge.
10793        let entity = rt
10794            .create_entity(&tok, "concept", None, "Target", None, None, vec![])
10795            .await
10796            .unwrap();
10797        let note = rt
10798            .create_note(
10799                &tok,
10800                "observation",
10801                None,
10802                "annotates the entity",
10803                Some(0.5),
10804                None,
10805                vec![entity.id],
10806            )
10807            .await
10808            .unwrap();
10809
10810        // Confirm the annotates edge exists.
10811        let before = rt
10812            .neighbors(
10813                &tok,
10814                note.id,
10815                Direction::Out,
10816                None,
10817                Some(vec![EdgeRelation::Annotates]),
10818            )
10819            .await
10820            .unwrap();
10821        assert_eq!(before.len(), 1, "annotates edge must exist before test");
10822        let annotates_edge_id: Uuid = before[0].edge_id;
10823
10824        // Call delete_edge with the entity UUID (NOT an edge UUID).
10825        let result = rt.delete_edge(&tok, entity.id, true).await;
10826        assert!(
10827            result.is_ok(),
10828            "delete_edge must not error on a non-edge UUID"
10829        );
10830        assert!(
10831            !result.unwrap(),
10832            "delete_edge must return false for a non-edge UUID"
10833        );
10834
10835        // The inbound annotates edge to the entity must still exist — no side effects.
10836        let after = rt
10837            .neighbors(
10838                &tok,
10839                note.id,
10840                Direction::Out,
10841                None,
10842                Some(vec![EdgeRelation::Annotates]),
10843            )
10844            .await
10845            .unwrap();
10846        assert_eq!(
10847            after.len(),
10848            1,
10849            "delete_edge with a non-edge UUID must not touch inbound annotates edges"
10850        );
10851        assert_eq!(
10852            after[0].edge_id, annotates_edge_id,
10853            "the original annotates edge must be unchanged"
10854        );
10855    }
10856
10857    // ---- create_note compensation branch ----
10858
10859    // This test injects a deterministic failure on the second `link` call inside
10860    // `create_note_inner` (the one that would create the second annotates edge).
10861    // It verifies that the compensation branch is wired — i.e. this test would
10862    // fail if the `Err(e)` rollback arm at operations.rs were deleted.
10863    //
10864    // Injection mechanism: LINK_FAIL_AFTER thread-local (ops.rs, cfg(test) only).
10865    // Setting it to 2 forces the 2nd link call to return an error.  The counter is
10866    // reset to 0 once triggered, so no other test is affected.
10867    #[tokio::test]
10868    async fn create_note_multi_annotates_second_link_failure_rolls_back_partial_write() {
10869        let rt = rt();
10870        let tok = NamespaceToken::local();
10871        let t1 = rt
10872            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
10873            .await
10874            .unwrap();
10875        let t2 = rt
10876            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
10877            .await
10878            .unwrap();
10879
10880        // Arm the injection: fail on the 2nd link (link_idx+1 == 2).
10881        LINK_FAIL_AFTER.with(|cell| cell.set(2));
10882
10883        let result = rt
10884            .create_note(
10885                &tok,
10886                "observation",
10887                None,
10888                "rollback target",
10889                Some(0.5),
10890                None,
10891                vec![t1.id, t2.id],
10892            )
10893            .await;
10894
10895        // The call must fail with the injected error.
10896        assert!(
10897            result.is_err(),
10898            "create_note must propagate the injected link failure"
10899        );
10900        let err_msg = result.unwrap_err().to_string();
10901        assert!(
10902            err_msg.contains("injected link failure"),
10903            "error must carry injection message; got: {err_msg}"
10904        );
10905
10906        // Compensation must have removed the note row.
10907        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
10908        assert!(
10909            notes.is_empty(),
10910            "compensation must remove the note row; got {notes:?}"
10911        );
10912
10913        // FTS must have no hit for the content.
10914        let hits = rt
10915            .search_notes(&tok, "rollback target", None, 10, None, false, &[], None)
10916            .await
10917            .unwrap();
10918        assert!(
10919            hits.is_empty(),
10920            "compensation must clean FTS index; got {hits:?}"
10921        );
10922
10923        // No partial annotates edges must remain (first edge must have been deleted).
10924        let edges_from_t1 = rt
10925            .neighbors(
10926                &tok,
10927                t1.id,
10928                Direction::In,
10929                None,
10930                Some(vec![EdgeRelation::Annotates]),
10931            )
10932            .await
10933            .unwrap();
10934        let edges_from_t2 = rt
10935            .neighbors(
10936                &tok,
10937                t2.id,
10938                Direction::In,
10939                None,
10940                Some(vec![EdgeRelation::Annotates]),
10941            )
10942            .await
10943            .unwrap();
10944        assert!(
10945            edges_from_t1.is_empty(),
10946            "compensation must delete the first annotates edge; got {edges_from_t1:?}"
10947        );
10948        assert!(
10949            edges_from_t2.is_empty(),
10950            "no second annotates edge must exist; got {edges_from_t2:?}"
10951        );
10952    }
10953
10954    // Inject an FTS failure after the note row is committed and assert the note
10955    // row is removed (no stranded row). arm_fts_fail_scoped() arms the flag before
10956    // the call and it resets automatically after one trigger.
10957    #[tokio::test]
10958    async fn create_note_fts_failure_rolls_back_note_row() {
10959        let rt = rt();
10960        // Unique namespace: FTS_FAIL_NS is a namespace-keyed set, so a
10961        // concurrently running test arming a different namespace never evicts
10962        // this test's arm. The namespace still guards against a same-test
10963        // mismatch between the armed value and the note actually being created.
10964        let ns = Namespace::parse("fault-fts-rollback").unwrap();
10965        let tok = NamespaceToken::for_namespace(ns.clone());
10966
10967        let _arm = arm_fts_fail_scoped(ns.as_str());
10968
10969        let result = rt
10970            .create_note(
10971                &tok,
10972                "observation",
10973                None,
10974                "fts-fail rollback target",
10975                None,
10976                None,
10977                vec![],
10978            )
10979            .await;
10980
10981        assert!(
10982            result.is_err(),
10983            "create_note must propagate the injected FTS failure"
10984        );
10985        let err_msg = result.unwrap_err().to_string();
10986        assert!(
10987            err_msg.contains("injected FTS failure"),
10988            "error must carry injection message; got: {err_msg}"
10989        );
10990
10991        // Compensation must have removed the note row.
10992        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
10993        assert!(
10994            notes.is_empty(),
10995            "compensation must remove the note row after FTS failure; got {notes:?}"
10996        );
10997    }
10998
10999    // Arming FTS_FAIL_NS on one OS thread must still fire on a `create_note`
11000    // call that runs on a genuinely different OS thread. Arms here on the
11001    // test's own (tokio current-thread) task, then hands the triggering
11002    // `create_note` call to a `std::thread::spawn` worker running its own
11003    // single-threaded tokio runtime — a stronger guarantee of thread migration
11004    // than `tokio::spawn`, which may schedule the spawned task back onto the
11005    // same worker. Proves the process-wide, namespace-keyed `FTS_FAIL_NS` set
11006    // is thread-independent.
11007    #[tokio::test]
11008    async fn create_note_fts_failure_fires_across_os_threads() {
11009        let rt = std::sync::Arc::new(rt());
11010        let ns = Namespace::parse("fault-fts-rollback-cross-thread").unwrap();
11011        let tok = NamespaceToken::for_namespace(ns.clone());
11012
11013        let _arm = arm_fts_fail_scoped(ns.as_str());
11014
11015        let thread_rt = std::sync::Arc::clone(&rt);
11016        let thread_tok = tok.clone();
11017        let result = std::thread::spawn(move || {
11018            let worker = tokio::runtime::Builder::new_current_thread()
11019                .enable_all()
11020                .build()
11021                .expect("worker runtime must build");
11022            worker.block_on(thread_rt.create_note(
11023                &thread_tok,
11024                "observation",
11025                None,
11026                "fts-fail rollback target (cross-thread)",
11027                None,
11028                None,
11029                vec![],
11030            ))
11031        })
11032        .join()
11033        .expect("worker thread must not panic");
11034
11035        assert!(
11036            result.is_err(),
11037            "create_note on a different OS thread must still observe the injected FTS failure"
11038        );
11039        let err_msg = result.unwrap_err().to_string();
11040        assert!(
11041            err_msg.contains("injected FTS failure"),
11042            "error must carry injection message; got: {err_msg}"
11043        );
11044
11045        // Compensation must have removed the note row.
11046        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11047        assert!(
11048            notes.is_empty(),
11049            "compensation must remove the note row after FTS failure; got {notes:?}"
11050        );
11051    }
11052
11053    // Inject a vector insertion failure after note row + FTS commit and assert
11054    // both the note row and the FTS document are removed (no stranded rows).
11055    // Uses a unique namespace (see create_note_fts_failure_rolls_back_note_row)
11056    // so only this test consumes its VECTOR_FAIL_NS entry.
11057    // Since the single registered provider fires embed_document before the
11058    // injection check, the injection converts the successful embedding into an
11059    // error just before the VectorStore insert, then disarms.
11060    #[tokio::test]
11061    async fn create_note_vector_failure_rolls_back_note_row_and_fts() {
11062        const MODEL: &str = "test-vec-inject";
11063        const DIMS: usize = 4;
11064
11065        let rt = KhiveRuntime::memory().unwrap();
11066        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
11067        rt.register_embedder(provider);
11068
11069        let ns = Namespace::parse("fault-vec-rollback").unwrap();
11070        let tok = NamespaceToken::for_namespace(ns.clone());
11071
11072        let _arm = arm_vector_fail_scoped(ns.as_str());
11073
11074        let result = rt
11075            .create_note(
11076                &tok,
11077                "observation",
11078                None,
11079                "vec-fail rollback target",
11080                None,
11081                None,
11082                vec![],
11083            )
11084            .await;
11085
11086        assert!(
11087            result.is_err(),
11088            "create_note must propagate the injected vector failure"
11089        );
11090        let err_msg = result.unwrap_err().to_string();
11091        assert!(
11092            err_msg.contains("injected vector failure"),
11093            "error must carry injection message; got: {err_msg}"
11094        );
11095
11096        // Compensation must have removed the note row.
11097        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11098        assert!(
11099            notes.is_empty(),
11100            "compensation must remove note row after vector failure; got {notes:?}"
11101        );
11102    }
11103
11104    #[tokio::test]
11105    async fn vector_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other() {
11106        const MODEL: &str = "test-vec-inject-distinct-namespaces";
11107        const DIMS: usize = 4;
11108
11109        let rt_a = KhiveRuntime::memory().unwrap();
11110        let (provider_a, _counter_a) = ConstVecProvider::new(MODEL, DIMS);
11111        rt_a.register_embedder(provider_a);
11112        let ns_a = Namespace::parse("fault-vec-distinct-a").unwrap();
11113        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
11114
11115        let rt_b = KhiveRuntime::memory().unwrap();
11116        let (provider_b, _counter_b) = ConstVecProvider::new(MODEL, DIMS);
11117        rt_b.register_embedder(provider_b);
11118        let ns_b = Namespace::parse("fault-vec-distinct-b").unwrap();
11119        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
11120
11121        let _arm_a = arm_vector_fail_scoped(ns_a.as_str());
11122        let _arm_b = arm_vector_fail_scoped(ns_b.as_str());
11123
11124        let (result_a, result_b) = tokio::join!(
11125            rt_a.create_note(
11126                &tok_a,
11127                "observation",
11128                None,
11129                "vector failure target A",
11130                None,
11131                None,
11132                vec![],
11133            ),
11134            rt_b.create_note(
11135                &tok_b,
11136                "observation",
11137                None,
11138                "vector failure target B",
11139                None,
11140                None,
11141                vec![],
11142            ),
11143        );
11144
11145        assert!(
11146            result_a.is_err(),
11147            "namespace A must retain its pending vector failure injection"
11148        );
11149        assert!(
11150            result_b.is_err(),
11151            "namespace B must retain its pending vector failure injection"
11152        );
11153    }
11154
11155    // The `embedding_content` override must not bypass the same
11156    // FTS/vector compensation the plain `create_note` path already has —
11157    // both use `create_note_inner` underneath, but these tests exercise it
11158    // through `create_note_with_embedding_content` with a real Some(head)
11159    // override to prove the override path shares the identical rollback.
11160    #[tokio::test]
11161    async fn create_note_with_embedding_content_fts_failure_rolls_back_note_row() {
11162        let rt = rt();
11163        let ns = Namespace::parse("fault-fts-rollback-embedding-content").unwrap();
11164        let tok = NamespaceToken::for_namespace(ns.clone());
11165
11166        let _arm = arm_fts_fail_scoped(ns.as_str());
11167
11168        let full = "fts-fail rollback target with an embedding-content override";
11169        let head = &full[.."fts-fail rollback target".len()];
11170        let result = rt
11171            .create_note_with_embedding_content(
11172                &tok,
11173                "observation",
11174                None,
11175                full,
11176                Some(head),
11177                None,
11178                None,
11179                vec![],
11180            )
11181            .await;
11182
11183        assert!(
11184            result.is_err(),
11185            "create_note_with_embedding_content must propagate the injected FTS failure"
11186        );
11187        let err_msg = result.unwrap_err().to_string();
11188        assert!(
11189            err_msg.contains("injected FTS failure"),
11190            "error must carry injection message; got: {err_msg}"
11191        );
11192
11193        // Compensation must have removed the note row; a failed create must
11194        // never leave a stranded row behind just because it carried an
11195        // embedding_content override.
11196        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11197        assert!(
11198            notes.is_empty(),
11199            "compensation must remove the note row after FTS failure; got {notes:?}"
11200        );
11201    }
11202
11203    #[tokio::test]
11204    async fn create_note_with_embedding_content_vector_failure_rolls_back_note_row_and_fts() {
11205        const MODEL: &str = "test-vec-inject-embedding-content";
11206        const DIMS: usize = 4;
11207
11208        let rt = KhiveRuntime::memory().unwrap();
11209        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
11210        rt.register_embedder(provider);
11211
11212        let ns = Namespace::parse("fault-vec-rollback-embedding-content").unwrap();
11213        let tok = NamespaceToken::for_namespace(ns.clone());
11214
11215        let _arm = arm_vector_fail_scoped(ns.as_str());
11216
11217        let full = "vec-fail rollback target with an embedding-content override";
11218        let head = &full[.."vec-fail rollback target".len()];
11219        let result = rt
11220            .create_note_with_embedding_content(
11221                &tok,
11222                "observation",
11223                None,
11224                full,
11225                Some(head),
11226                None,
11227                None,
11228                vec![],
11229            )
11230            .await;
11231
11232        assert!(
11233            result.is_err(),
11234            "create_note_with_embedding_content must propagate the injected vector failure"
11235        );
11236        let err_msg = result.unwrap_err().to_string();
11237        assert!(
11238            err_msg.contains("injected vector failure"),
11239            "error must carry injection message; got: {err_msg}"
11240        );
11241
11242        // Compensation must have removed the note row: the ingest-layer
11243        // truncation counter only increments in the successful-create arm,
11244        // so a failed create — with or without an embedding_content override
11245        // — can never cause a spurious truncation count on the caller side.
11246        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
11247        assert!(
11248            notes.is_empty(),
11249            "compensation must remove note row after vector failure; got {notes:?}"
11250        );
11251    }
11252
11253    // ---- soft-delete index cleanup tests ----
11254
11255    #[tokio::test]
11256    async fn soft_delete_entity_removes_indexes() {
11257        let rt = rt();
11258        let tok = NamespaceToken::local();
11259        let entity = rt
11260            .create_entity(
11261                &tok,
11262                "concept",
11263                None,
11264                "QuantumEntanglement",
11265                Some("unique FTS term xzqjwv for soft delete test"),
11266                None,
11267                vec![],
11268            )
11269            .await
11270            .unwrap();
11271
11272        let ns = tok.namespace().as_str().to_string();
11273
11274        let before = rt
11275            .text(&tok)
11276            .unwrap()
11277            .search(TextSearchRequest {
11278                query: "xzqjwv".to_string(),
11279                mode: TextQueryMode::Plain,
11280                filter: Some(TextFilter {
11281                    namespaces: vec![ns.clone()],
11282                    ..Default::default()
11283                }),
11284                top_k: 10,
11285                snippet_chars: 100,
11286            })
11287            .await
11288            .unwrap();
11289        assert!(
11290            before.iter().any(|h| h.subject_id == entity.id),
11291            "entity must be in FTS before soft-delete"
11292        );
11293
11294        let deleted = rt.delete_entity(&tok, entity.id, false).await.unwrap();
11295        assert!(deleted, "soft delete must return true");
11296
11297        let after = rt
11298            .text(&tok)
11299            .unwrap()
11300            .search(TextSearchRequest {
11301                query: "xzqjwv".to_string(),
11302                mode: TextQueryMode::Plain,
11303                filter: Some(TextFilter {
11304                    namespaces: vec![ns],
11305                    ..Default::default()
11306                }),
11307                top_k: 10,
11308                snippet_chars: 100,
11309            })
11310            .await
11311            .unwrap();
11312        assert!(
11313            after.iter().all(|h| h.subject_id != entity.id),
11314            "soft-deleted entity must be removed from FTS index"
11315        );
11316    }
11317
11318    #[tokio::test]
11319    async fn soft_delete_note_removes_indexes() {
11320        let rt = rt();
11321        let tok = NamespaceToken::local();
11322        let note = rt
11323            .create_note(
11324                &tok,
11325                "observation",
11326                None,
11327                "SpectralDecomposition unique term yvwkqz for soft delete test",
11328                Some(0.7),
11329                None,
11330                vec![],
11331            )
11332            .await
11333            .unwrap();
11334
11335        let before = rt
11336            .search_notes(&tok, "yvwkqz", None, 10, None, false, &[], None)
11337            .await
11338            .unwrap();
11339        assert!(
11340            before.iter().any(|h| h.note_id == note.id),
11341            "note must be in FTS before soft-delete"
11342        );
11343
11344        let deleted = rt.delete_note(&tok, note.id, false).await.unwrap();
11345        assert!(deleted, "soft delete must return true");
11346
11347        let after = rt
11348            .search_notes(&tok, "yvwkqz", None, 10, None, false, &[], None)
11349            .await
11350            .unwrap();
11351        assert!(
11352            after.iter().all(|h| h.note_id != note.id),
11353            "soft-deleted note must be removed from FTS index"
11354        );
11355    }
11356
11357    // Base endpoint allowlist: unlisted triples must fail closed.
11358    // Document->Document Extends is not in the allowlist.
11359    #[tokio::test]
11360    async fn link_extends_document_to_document_returns_invalid_input() {
11361        let rt = rt();
11362        let tok = NamespaceToken::local();
11363        let d1 = rt
11364            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
11365            .await
11366            .unwrap();
11367        let d2 = rt
11368            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
11369            .await
11370            .unwrap();
11371        let result = rt
11372            .link(&tok, d1.id, d2.id, EdgeRelation::Extends, 1.0, None)
11373            .await;
11374        assert!(
11375            result.is_err(),
11376            "F010: document->document Extends must be rejected by the base allowlist; \
11377             current generic entity fallthrough incorrectly accepts it"
11378        );
11379    }
11380
11381    #[tokio::test]
11382    async fn link_illegal_entity_pair_names_loaded_legal_relations() {
11383        let rt = rt();
11384        let tok = NamespaceToken::local();
11385        rt.install_edge_rules(vec![EdgeEndpointRule {
11386            relation: EdgeRelation::DependsOn,
11387            source: EndpointKind::EntityOfKind("concept"),
11388            target: EndpointKind::EntityOfKind("project"),
11389        }]);
11390        let concept = rt
11391            .create_entity(&tok, "concept", None, "Concept", None, None, vec![])
11392            .await
11393            .unwrap();
11394        let project = rt
11395            .create_entity(&tok, "project", None, "Project", None, None, vec![])
11396            .await
11397            .unwrap();
11398
11399        let error = rt
11400            .link(
11401                &tok,
11402                concept.id,
11403                project.id,
11404                EdgeRelation::CompetesWith,
11405                1.0,
11406                None,
11407            )
11408            .await
11409            .expect_err("concept competes_with project must be rejected");
11410        let message = error.to_string();
11411        assert!(
11412            message.contains(
11413                "currently legal relations for concept -> project under the loaded endpoint rules: depends_on"
11414            ),
11415            "rejection must expose the exact loaded legal set; got: {message}"
11416        );
11417    }
11418
11419    #[test]
11420    fn cross_backend_legal_set_ignores_unenforced_annotates_pack_rule() {
11421        let rt = rt();
11422        rt.install_edge_rules(vec![EdgeEndpointRule {
11423            relation: EdgeRelation::Annotates,
11424            source: EndpointKind::EntityOfKind("concept"),
11425            target: EndpointKind::EntityOfKind("project"),
11426        }]);
11427        let source_id = Uuid::new_v4();
11428        let target_id = Uuid::new_v4();
11429        let source = Resolved::Entity(Entity::new("local", "concept", "Concept"));
11430        let target = Resolved::Entity(Entity::new("local", "project", "Project"));
11431
11432        rt.validate_link_endpoints_by_resolved(
11433            source_id,
11434            target_id,
11435            EdgeRelation::Annotates,
11436            Some(&source),
11437            Some(&target),
11438        )
11439        .expect_err(
11440            "an annotates pack rule cannot override the dedicated note-source validator branch",
11441        );
11442
11443        let error = rt
11444            .validate_link_endpoints_by_resolved(
11445                source_id,
11446                target_id,
11447                EdgeRelation::CompetesWith,
11448                Some(&source),
11449                Some(&target),
11450            )
11451            .expect_err("concept competes_with project must be rejected");
11452        let message = error.to_string();
11453        assert!(
11454            message.contains(
11455                "currently legal relations for concept -> project under the loaded endpoint rules: none"
11456            ),
11457            "an unenforced entity-source annotates pack rule must not be advertised; got: {message}"
11458        );
11459        assert!(
11460            !message.contains("endpoint rules: annotates"),
11461            "the rejection must not call annotates legal when the live validator rejects it; got: {message}"
11462        );
11463    }
11464
11465    // Happy path: Concept->Concept Extends is in the base allowlist and must succeed.
11466    #[tokio::test]
11467    async fn link_extends_concept_to_concept_succeeds() {
11468        let rt = rt();
11469        let tok = NamespaceToken::local();
11470        let a = rt
11471            .create_entity(&tok, "concept", None, "CA", None, None, vec![])
11472            .await
11473            .unwrap();
11474        let b = rt
11475            .create_entity(&tok, "concept", None, "CB", None, None, vec![])
11476            .await
11477            .unwrap();
11478        let result = rt
11479            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11480            .await;
11481        assert!(
11482            result.is_ok(),
11483            "F010: concept->concept Extends must be allowed (base allowlist)"
11484        );
11485    }
11486
11487    // CompetesWith is symmetric; reversed pair must deduplicate to one canonical row.
11488    #[tokio::test]
11489    async fn link_symmetric_relation_canonicalizes_endpoint_order() {
11490        use khive_storage::EdgeFilter;
11491        let rt = rt();
11492        let tok = NamespaceToken::local();
11493        let a = rt
11494            .create_entity(&tok, "concept", None, "ConceptP", None, None, vec![])
11495            .await
11496            .unwrap();
11497        let b = rt
11498            .create_entity(&tok, "concept", None, "ConceptQ", None, None, vec![])
11499            .await
11500            .unwrap();
11501        // Link A->B then B->A with the same symmetric relation.
11502        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
11503            .await
11504            .unwrap();
11505        rt.link(&tok, b.id, a.id, EdgeRelation::CompetesWith, 1.0, None)
11506            .await
11507            .unwrap();
11508        let count = rt
11509            .graph(&tok)
11510            .unwrap()
11511            .count_edges(EdgeFilter::default())
11512            .await
11513            .unwrap();
11514        assert_eq!(
11515            count,
11516            1,
11517            "F012: CompetesWith is symmetric; A->B and B->A must deduplicate to one canonical row; \
11518             found {count} rows (canonicalization not yet implemented)"
11519        );
11520    }
11521
11522    // Supersedes: positive tests for all 5 allowed entity kinds.
11523    #[tokio::test]
11524    async fn f010_supersedes_document_to_document_allowed() {
11525        let rt = rt();
11526        let tok = NamespaceToken::local();
11527        let a = rt
11528            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
11529            .await
11530            .unwrap();
11531        let b = rt
11532            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
11533            .await
11534            .unwrap();
11535        let result = rt
11536            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11537            .await;
11538        assert!(
11539            result.is_ok(),
11540            "document->document Supersedes must be allowed (allowlist), got {result:?}"
11541        );
11542    }
11543
11544    #[tokio::test]
11545    async fn f010_supersedes_artifact_to_artifact_allowed() {
11546        let rt = rt();
11547        let tok = NamespaceToken::local();
11548        let a = rt
11549            .create_entity(&tok, "artifact", None, "ArtA", None, None, vec![])
11550            .await
11551            .unwrap();
11552        let b = rt
11553            .create_entity(&tok, "artifact", None, "ArtB", None, None, vec![])
11554            .await
11555            .unwrap();
11556        let result = rt
11557            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11558            .await;
11559        assert!(
11560            result.is_ok(),
11561            "artifact->artifact Supersedes must be allowed (allowlist), got {result:?}"
11562        );
11563    }
11564
11565    #[tokio::test]
11566    async fn f010_supersedes_service_to_service_allowed() {
11567        let rt = rt();
11568        let tok = NamespaceToken::local();
11569        let a = rt
11570            .create_entity(&tok, "service", None, "SvcA", None, None, vec![])
11571            .await
11572            .unwrap();
11573        let b = rt
11574            .create_entity(&tok, "service", None, "SvcB", None, None, vec![])
11575            .await
11576            .unwrap();
11577        let result = rt
11578            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11579            .await;
11580        assert!(
11581            result.is_ok(),
11582            "service->service Supersedes must be allowed (allowlist), got {result:?}"
11583        );
11584    }
11585
11586    #[tokio::test]
11587    async fn f010_supersedes_dataset_to_dataset_allowed() {
11588        let rt = rt();
11589        let tok = NamespaceToken::local();
11590        let a = rt
11591            .create_entity(&tok, "dataset", None, "DataA", None, None, vec![])
11592            .await
11593            .unwrap();
11594        let b = rt
11595            .create_entity(&tok, "dataset", None, "DataB", None, None, vec![])
11596            .await
11597            .unwrap();
11598        let result = rt
11599            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11600            .await;
11601        assert!(
11602            result.is_ok(),
11603            "dataset->dataset Supersedes must be allowed (allowlist), got {result:?}"
11604        );
11605    }
11606
11607    // Supersedes: negative tests for rejected entity kinds.
11608    #[tokio::test]
11609    async fn f010_supersedes_project_to_project_rejected() {
11610        let rt = rt();
11611        let tok = NamespaceToken::local();
11612        let a = rt
11613            .create_entity(&tok, "project", None, "ProjA", None, None, vec![])
11614            .await
11615            .unwrap();
11616        let b = rt
11617            .create_entity(&tok, "project", None, "ProjB", None, None, vec![])
11618            .await
11619            .unwrap();
11620        let result = rt
11621            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11622            .await;
11623        assert!(
11624            matches!(result, Err(RuntimeError::InvalidInput(_))),
11625            "project->project Supersedes must be rejected (not in allowlist), got {result:?}"
11626        );
11627    }
11628
11629    #[tokio::test]
11630    async fn f010_supersedes_person_to_person_rejected() {
11631        let rt = rt();
11632        let tok = NamespaceToken::local();
11633        let a = rt
11634            .create_entity(&tok, "person", None, "Alice", None, None, vec![])
11635            .await
11636            .unwrap();
11637        let b = rt
11638            .create_entity(&tok, "person", None, "Bob", None, None, vec![])
11639            .await
11640            .unwrap();
11641        let result = rt
11642            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11643            .await;
11644        assert!(
11645            matches!(result, Err(RuntimeError::InvalidInput(_))),
11646            "person->person Supersedes must be rejected (not in allowlist), got {result:?}"
11647        );
11648    }
11649
11650    #[tokio::test]
11651    async fn f010_supersedes_org_to_org_rejected() {
11652        let rt = rt();
11653        let tok = NamespaceToken::local();
11654        let a = rt
11655            .create_entity(&tok, "org", None, "OrgA", None, None, vec![])
11656            .await
11657            .unwrap();
11658        let b = rt
11659            .create_entity(&tok, "org", None, "OrgB", None, None, vec![])
11660            .await
11661            .unwrap();
11662        let result = rt
11663            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11664            .await;
11665        assert!(
11666            matches!(result, Err(RuntimeError::InvalidInput(_))),
11667            "org->org Supersedes must be rejected (not in allowlist), got {result:?}"
11668        );
11669    }
11670
11671    // Supersedes entity→entity: same kind (concept→concept) must be allowed.
11672    #[tokio::test]
11673    async fn f010_supersedes_same_kind_entity_allowed() {
11674        let rt = rt();
11675        let tok = NamespaceToken::local();
11676        let a = rt
11677            .create_entity(&tok, "concept", None, "OldV", None, None, vec![])
11678            .await
11679            .unwrap();
11680        let b = rt
11681            .create_entity(&tok, "concept", None, "NewV", None, None, vec![])
11682            .await
11683            .unwrap();
11684        let result = rt
11685            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
11686            .await;
11687        assert!(
11688            result.is_ok(),
11689            "concept->concept Supersedes must be allowed by the base allowlist, got {result:?}"
11690        );
11691    }
11692
11693    // target_backend invariant: all edges written through link() must have
11694    // target_backend = None because validate_edge_relation_endpoints already ensured the
11695    // target exists locally.
11696    #[tokio::test]
11697    async fn f161_link_always_writes_null_target_backend() {
11698        let rt = rt();
11699        let tok = NamespaceToken::local();
11700        let a = rt
11701            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11702            .await
11703            .unwrap();
11704        let b = rt
11705            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11706            .await
11707            .unwrap();
11708        let edge = rt
11709            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
11710            .await
11711            .unwrap();
11712        assert!(
11713            edge.target_backend.is_none(),
11714            "F161: target_backend must be None for locally-routed edges; got {:?}",
11715            edge.target_backend
11716        );
11717    }
11718
11719    // link_many must also write null target_backend for all local edges.
11720    #[tokio::test]
11721    async fn f161_link_many_always_writes_null_target_backend() {
11722        let rt = rt();
11723        let tok = NamespaceToken::local();
11724        let a = rt
11725            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11726            .await
11727            .unwrap();
11728        let b = rt
11729            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11730            .await
11731            .unwrap();
11732        let c = rt
11733            .create_entity(&tok, "concept", None, "C", None, None, vec![])
11734            .await
11735            .unwrap();
11736        let specs = vec![
11737            LinkSpec {
11738                namespace: None,
11739                source_id: a.id,
11740                target_id: b.id,
11741                relation: EdgeRelation::Extends,
11742                weight: 1.0,
11743                metadata: None,
11744            },
11745            LinkSpec {
11746                namespace: None,
11747                source_id: a.id,
11748                target_id: c.id,
11749                relation: EdgeRelation::Enables,
11750                weight: 1.0,
11751                metadata: None,
11752            },
11753        ];
11754        let edges = rt.link_many(&tok, specs).await.unwrap();
11755        for edge in &edges {
11756            assert!(
11757                edge.target_backend.is_none(),
11758                "F161: target_backend must be None for locally-routed edges in link_many; got {:?}",
11759                edge.target_backend
11760            );
11761        }
11762    }
11763
11764    // Symmetric relation neighbors: competes_with queried from the non-canonical
11765    // endpoint must still return results when direction=Out is requested.
11766    #[tokio::test]
11767    async fn f012_symmetric_neighbors_visible_from_both_endpoints() {
11768        let rt = rt();
11769        let tok = NamespaceToken::local();
11770        let a = rt
11771            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11772            .await
11773            .unwrap();
11774        let b = rt
11775            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11776            .await
11777            .unwrap();
11778        // Link A→B competes_with; if A.id > B.id the edge is stored as B→A (canonical).
11779        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
11780            .await
11781            .unwrap();
11782        // Both endpoints should see the edge regardless of direction=Out.
11783        let from_a = rt
11784            .neighbors(
11785                &tok,
11786                a.id,
11787                Direction::Out,
11788                None,
11789                Some(vec![EdgeRelation::CompetesWith]),
11790            )
11791            .await
11792            .unwrap();
11793        let from_b = rt
11794            .neighbors(
11795                &tok,
11796                b.id,
11797                Direction::Out,
11798                None,
11799                Some(vec![EdgeRelation::CompetesWith]),
11800            )
11801            .await
11802            .unwrap();
11803        assert_eq!(
11804            from_a.len(),
11805            1,
11806            "node A must see competes_with neighbor from Direction::Out (F012); got {from_a:?}"
11807        );
11808        assert_eq!(
11809            from_b.len(),
11810            1,
11811            "node B must see competes_with neighbor from Direction::Out (F012); got {from_b:?}"
11812        );
11813    }
11814
11815    // Fix 1: Supersedes entity→entity — cross-kind (concept→document) must be rejected.
11816    #[tokio::test]
11817    async fn f010_supersedes_cross_kind_entity_rejected() {
11818        let rt = rt();
11819        let tok = NamespaceToken::local();
11820        let concept = rt
11821            .create_entity(&tok, "concept", None, "MyConcept", None, None, vec![])
11822            .await
11823            .unwrap();
11824        let doc = rt
11825            .create_entity(&tok, "document", None, "MyDoc", None, None, vec![])
11826            .await
11827            .unwrap();
11828        let result = rt
11829            .link(
11830                &tok,
11831                concept.id,
11832                doc.id,
11833                EdgeRelation::Supersedes,
11834                1.0,
11835                None,
11836            )
11837            .await;
11838        assert!(
11839            matches!(result, Err(RuntimeError::InvalidInput(_))),
11840            "concept->document Supersedes must be rejected by the base allowlist, got {result:?}"
11841        );
11842    }
11843
11844    // Cross-namespace delete_note now succeeds (UUID v4 is globally unique,
11845    // no namespace isolation on by-ID ops).
11846    #[tokio::test]
11847    async fn delete_note_cross_namespace_succeeds() {
11848        let rt = rt();
11849        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
11850        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
11851        let note = rt
11852            .create_note(
11853                &ns_a,
11854                "observation",
11855                None,
11856                "note in ns-a",
11857                Some(0.8),
11858                None,
11859                vec![],
11860            )
11861            .await
11862            .unwrap();
11863
11864        // Delete from a different namespace must now SUCCEED.
11865        let result = rt.delete_note(&ns_b, note.id, false).await;
11866        assert!(
11867            result.unwrap(),
11868            "cross-namespace delete_note (soft) must return Ok(true)"
11869        );
11870
11871        // Note must be gone from ns-a storage after the cross-ns soft delete.
11872        let note_store = rt.notes(&ns_a).unwrap();
11873        let gone = note_store.get_note(note.id).await.unwrap();
11874        assert!(
11875            gone.is_none(),
11876            "note must be soft-deleted in its home namespace after cross-ns delete"
11877        );
11878
11879        // Hard-delete path: create a fresh note and hard-delete from foreign token.
11880        let note2 = rt
11881            .create_note(
11882                &ns_a,
11883                "observation",
11884                None,
11885                "note2 in ns-a",
11886                Some(0.5),
11887                None,
11888                vec![],
11889            )
11890            .await
11891            .unwrap();
11892        let hard_result = rt.delete_note(&ns_b, note2.id, true).await;
11893        assert!(
11894            hard_result.unwrap(),
11895            "cross-namespace hard delete_note must return Ok(true)"
11896        );
11897        let gone2 = rt
11898            .get_note_including_deleted(&ns_a, note2.id)
11899            .await
11900            .unwrap();
11901        assert!(
11902            gone2.is_none(),
11903            "hard-deleted note must not appear even in including_deleted query"
11904        );
11905    }
11906
11907    // Regression: parallel link_many calls with overlapping triples must
11908    // return the identical persisted edge ID, not locally-generated phantom IDs.
11909    //
11910    // Sequence:
11911    //   1. First link_many creates the A→B Extends edge (persisted with ID₁).
11912    //   2. Second link_many upserts the same triple (ON CONFLICT DO UPDATE keeps ID₁).
11913    //   3. Both callers must see ID₁ in their returned Vec<Edge>.
11914    #[tokio::test]
11915    async fn link_many_overlapping_triple_returns_persisted_ids() {
11916        let rt = rt();
11917        let tok = NamespaceToken::local();
11918        let a = rt
11919            .create_entity(&tok, "concept", None, "A", None, None, vec![])
11920            .await
11921            .unwrap();
11922        let b = rt
11923            .create_entity(&tok, "concept", None, "B", None, None, vec![])
11924            .await
11925            .unwrap();
11926
11927        let spec = || LinkSpec {
11928            namespace: None,
11929            source_id: a.id,
11930            target_id: b.id,
11931            relation: EdgeRelation::Extends,
11932            weight: 1.0,
11933            metadata: None,
11934        };
11935
11936        // First call — creates the edge.
11937        let first = rt.link_many(&tok, vec![spec()]).await.unwrap();
11938        assert_eq!(first.len(), 1);
11939        let persisted_id: Uuid = first[0].id.into();
11940
11941        // Second call — same natural-key triple; ON CONFLICT updates, preserving the
11942        // existing row ID. link_many must read back the row and return that same ID.
11943        let second = rt.link_many(&tok, vec![spec()]).await.unwrap();
11944        assert_eq!(second.len(), 1);
11945        let second_id: Uuid = second[0].id.into();
11946
11947        assert_eq!(
11948            persisted_id, second_id,
11949            "link_many with an existing triple must return the persisted row ID ({persisted_id}), \
11950             not a new phantom ID ({second_id})"
11951        );
11952
11953        // Confirm only one edge row exists in the graph store.
11954        let count = rt
11955            .count_edges(&tok, crate::curation::EdgeListFilter::default())
11956            .await
11957            .unwrap();
11958        assert_eq!(count, 1, "upsert must not duplicate the edge row");
11959    }
11960
11961    // ── create_many: batch entity creation ───────────────────────────────────
11962
11963    #[tokio::test]
11964    async fn create_many_persists_all_entities() {
11965        let rt = rt();
11966        let tok = NamespaceToken::local();
11967
11968        let specs: Vec<EntityCreateSpec> = (0..5)
11969            .map(|i| EntityCreateSpec {
11970                kind: "concept".into(),
11971                entity_type: None,
11972                name: format!("BulkConcept-{i}"),
11973                description: Some(format!("desc {i}")),
11974                properties: None,
11975                tags: vec!["bulk-test".into()],
11976            })
11977            .collect();
11978
11979        let entities = rt.create_many(&tok, specs).await.unwrap();
11980        assert_eq!(entities.len(), 5, "all 5 entities must be returned");
11981
11982        // Verify each one is retrievable from storage.
11983        for entity in &entities {
11984            let fetched = rt.get_entity(&tok, entity.id).await.unwrap();
11985            assert_eq!(fetched.id, entity.id);
11986        }
11987    }
11988
11989    #[tokio::test]
11990    async fn create_many_empty_name_rejects_atomically() {
11991        let rt = rt();
11992        let tok = NamespaceToken::local();
11993
11994        let specs = vec![
11995            EntityCreateSpec {
11996                kind: "concept".into(),
11997                entity_type: None,
11998                name: "ValidEntity".into(),
11999                description: None,
12000                properties: None,
12001                tags: vec![],
12002            },
12003            EntityCreateSpec {
12004                kind: "concept".into(),
12005                entity_type: None,
12006                name: "".into(), // invalid — triggers atomic rejection
12007                description: None,
12008                properties: None,
12009                tags: vec![],
12010            },
12011        ];
12012
12013        let result = rt.create_many(&tok, specs).await;
12014        assert!(
12015            matches!(result, Err(RuntimeError::InvalidInput(_))),
12016            "empty name must produce InvalidInput error"
12017        );
12018
12019        // Nothing must have been written — list_entities returns 0 items.
12020        let rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
12021        assert_eq!(
12022            rows.len(),
12023            0,
12024            "atomic rejection must leave storage unchanged"
12025        );
12026    }
12027
12028    // entity_type validated at runtime layer when validator is installed.
12029    #[tokio::test]
12030    async fn create_many_rejects_unknown_entity_type_when_validator_installed() {
12031        let rt = rt();
12032        let tok = NamespaceToken::local();
12033
12034        // Install a mock validator that only accepts "algorithm" for "concept".
12035        rt.install_entity_type_validator(Arc::new(|kind, entity_type| {
12036            let Some(raw) = entity_type else {
12037                return Ok(None);
12038            };
12039            if kind == "concept" && raw == "algorithm" {
12040                return Ok(Some("algorithm".to_string()));
12041            }
12042            Err(RuntimeError::InvalidInput(format!(
12043                "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
12044            )))
12045        }));
12046
12047        let bad_spec = vec![EntityCreateSpec {
12048            kind: "concept".into(),
12049            entity_type: Some("not_a_registered_type".into()),
12050            name: "ShouldNotLand".into(),
12051            description: None,
12052            properties: None,
12053            tags: vec![],
12054        }];
12055
12056        let result = rt.create_many(&tok, bad_spec).await;
12057        assert!(
12058            matches!(result, Err(RuntimeError::InvalidInput(_))),
12059            "unknown entity_type must be rejected by the runtime-layer validator; got {result:?}"
12060        );
12061
12062        // Zero rows written — validator fires before any storage call.
12063        let rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
12064        assert_eq!(
12065            rows.len(),
12066            0,
12067            "validator rejection must leave storage empty"
12068        );
12069    }
12070
12071    // Valid entity_type passes through and is normalised by the validator.
12072    #[tokio::test]
12073    async fn create_many_accepts_valid_entity_type_via_validator() {
12074        let rt = rt();
12075        let tok = NamespaceToken::local();
12076
12077        rt.install_entity_type_validator(Arc::new(|kind, entity_type| {
12078            let Some(raw) = entity_type else {
12079                return Ok(None);
12080            };
12081            if kind == "concept" && raw == "algorithm" {
12082                return Ok(Some("algorithm".to_string()));
12083            }
12084            Err(RuntimeError::InvalidInput(format!(
12085                "unknown entity_type {raw:?} for {kind:?}"
12086            )))
12087        }));
12088
12089        let specs = vec![EntityCreateSpec {
12090            kind: "concept".into(),
12091            entity_type: Some("algorithm".into()),
12092            name: "BubbleSort".into(),
12093            description: None,
12094            properties: None,
12095            tags: vec![],
12096        }];
12097
12098        let entities = rt.create_many(&tok, specs).await.unwrap();
12099        assert_eq!(entities.len(), 1, "valid entity_type must be accepted");
12100        assert_eq!(
12101            entities[0].entity_type.as_deref(),
12102            Some("algorithm"),
12103            "entity_type must be stored as returned by the validator"
12104        );
12105    }
12106
12107    // FTS failure in create_many rolls back both substrates.
12108    //
12109    // Arm `arm_fts_fail_many_scoped` before the call; the FTS phase returns an injected
12110    // error; the test asserts zero rows in both `entities` and `fts_entities`.
12111    #[tokio::test]
12112    async fn create_many_fts_failure_rolls_back_both_substrates() {
12113        // Use a unique namespace so only this test consumes its failure entry.
12114        let ns = format!("fts-fail-many-{}", uuid::Uuid::new_v4().as_simple());
12115        let rt = rt();
12116        let tok = NamespaceToken::for_namespace(Namespace::parse(&ns).unwrap());
12117
12118        let specs = vec![
12119            EntityCreateSpec {
12120                kind: "concept".into(),
12121                entity_type: None,
12122                name: "FtsRollbackA".into(),
12123                description: None,
12124                properties: None,
12125                tags: vec![],
12126            },
12127            EntityCreateSpec {
12128                kind: "concept".into(),
12129                entity_type: None,
12130                name: "FtsRollbackB".into(),
12131                description: None,
12132                properties: None,
12133                tags: vec![],
12134            },
12135        ];
12136
12137        let _arm = arm_fts_fail_many_scoped(&ns);
12138        let result = rt.create_many(&tok, specs).await;
12139
12140        assert!(
12141            result.is_err(),
12142            "create_many must return Err when FTS write fails"
12143        );
12144
12145        // Entity substrate must be empty — entity rows must have been rolled back.
12146        let entity_rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
12147        assert_eq!(
12148            entity_rows.len(),
12149            0,
12150            "entity rows must be rolled back on FTS failure; found {entity_rows:?}"
12151        );
12152
12153        // FTS substrate must be empty — no stale fts_entities rows.
12154        let fts = rt.text(&tok).unwrap();
12155        let fts_count = fts
12156            .count(TextFilter {
12157                ids: vec![],
12158                kinds: vec![],
12159                namespaces: vec![ns.clone()],
12160            })
12161            .await
12162            .unwrap();
12163        assert_eq!(
12164            fts_count, 0,
12165            "fts_entities must be empty after FTS-failure rollback; found {fts_count}"
12166        );
12167    }
12168
12169    #[tokio::test]
12170    async fn create_many_fts_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other(
12171    ) {
12172        let rt_a = rt();
12173        let ns_a = Namespace::parse("fts-fail-many-distinct-a").unwrap();
12174        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
12175        let rt_b = rt();
12176        let ns_b = Namespace::parse("fts-fail-many-distinct-b").unwrap();
12177        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
12178
12179        let _arm_a = arm_fts_fail_many_scoped(ns_a.as_str());
12180        let _arm_b = arm_fts_fail_many_scoped(ns_b.as_str());
12181
12182        let (result_a, result_b) = tokio::join!(
12183            rt_a.create_many(
12184                &tok_a,
12185                vec![EntityCreateSpec {
12186                    kind: "concept".into(),
12187                    entity_type: None,
12188                    name: "FtsFailureTargetA".into(),
12189                    description: None,
12190                    properties: None,
12191                    tags: vec![],
12192                }],
12193            ),
12194            rt_b.create_many(
12195                &tok_b,
12196                vec![EntityCreateSpec {
12197                    kind: "concept".into(),
12198                    entity_type: None,
12199                    name: "FtsFailureTargetB".into(),
12200                    description: None,
12201                    properties: None,
12202                    tags: vec![],
12203                }],
12204            ),
12205        );
12206
12207        assert!(
12208            result_a.is_err(),
12209            "namespace A must retain its pending create_many FTS failure injection"
12210        );
12211        assert!(
12212            result_b.is_err(),
12213            "namespace B must retain its pending create_many FTS failure injection"
12214        );
12215    }
12216
12217    // A failure after the first entity and FTS document have been written rolls
12218    // back both substrates for the entire batch. Injected via
12219    // `arm_fts_fail_many_partial_scoped`.
12220    #[tokio::test]
12221    async fn create_many_mid_batch_storage_failure_rolls_back_both_substrates() {
12222        let ns = format!("fts-fail-partial-{}", uuid::Uuid::new_v4().as_simple());
12223        let rt = rt();
12224        let tok = NamespaceToken::for_namespace(Namespace::parse(&ns).unwrap());
12225
12226        let specs = vec![
12227            EntityCreateSpec {
12228                kind: "concept".into(),
12229                entity_type: None,
12230                name: "PartialRollbackA".into(),
12231                description: None,
12232                properties: None,
12233                tags: vec![],
12234            },
12235            EntityCreateSpec {
12236                kind: "concept".into(),
12237                entity_type: None,
12238                name: "PartialRollbackB".into(),
12239                description: None,
12240                properties: None,
12241                tags: vec![],
12242            },
12243        ];
12244
12245        let _arm = arm_fts_fail_many_partial_scoped(&ns);
12246        let result = rt.create_many(&tok, specs).await;
12247
12248        assert!(
12249            result.is_err(),
12250            "create_many must return Err when an FTS write fails mid-batch"
12251        );
12252        let error = result.unwrap_err().to_string();
12253        assert!(
12254            error.contains("atomic batch rolled back at entity index 1"),
12255            "the failure must occur inside the atomic batch after one complete row; got: {error}"
12256        );
12257
12258        // Entity substrate must be empty — entity rows must have been rolled back.
12259        let entity_rows = rt.list_entities(&tok, None, None, 100, 0).await.unwrap();
12260        assert_eq!(
12261            entity_rows.len(),
12262            0,
12263            "entity rows must be empty after a mid-batch FTS failure; found {entity_rows:?}"
12264        );
12265
12266        // FTS substrate must be empty — no stale fts_entities rows.
12267        let fts = rt.text(&tok).unwrap();
12268        let fts_count = fts
12269            .count(TextFilter {
12270                ids: vec![],
12271                kinds: vec![],
12272                namespaces: vec![ns.clone()],
12273            })
12274            .await
12275            .unwrap();
12276        assert_eq!(
12277            fts_count, 0,
12278            "fts_entities must be empty after a mid-batch FTS failure; found {fts_count}"
12279        );
12280    }
12281
12282    #[tokio::test]
12283    async fn create_many_fts_partial_failure_injections_for_distinct_namespaces_do_not_overwrite_each_other(
12284    ) {
12285        let rt_a = rt();
12286        let ns_a = Namespace::parse("fts-fail-many-partial-distinct-a").unwrap();
12287        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
12288        let rt_b = rt();
12289        let ns_b = Namespace::parse("fts-fail-many-partial-distinct-b").unwrap();
12290        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
12291
12292        let _arm_a = arm_fts_fail_many_partial_scoped(ns_a.as_str());
12293        let _arm_b = arm_fts_fail_many_partial_scoped(ns_b.as_str());
12294
12295        let (result_a, result_b) = tokio::join!(
12296            rt_a.create_many(
12297                &tok_a,
12298                vec![EntityCreateSpec {
12299                    kind: "concept".into(),
12300                    entity_type: None,
12301                    name: "FtsPartialFailureTargetA".into(),
12302                    description: None,
12303                    properties: None,
12304                    tags: vec![],
12305                }],
12306            ),
12307            rt_b.create_many(
12308                &tok_b,
12309                vec![EntityCreateSpec {
12310                    kind: "concept".into(),
12311                    entity_type: None,
12312                    name: "FtsPartialFailureTargetB".into(),
12313                    description: None,
12314                    properties: None,
12315                    tags: vec![],
12316                }],
12317            ),
12318        );
12319
12320        assert!(
12321            result_a.is_err(),
12322            "namespace A must retain its pending create_many partial FTS failure injection"
12323        );
12324        assert!(
12325            result_b.is_err(),
12326            "namespace B must retain its pending create_many partial FTS failure injection"
12327        );
12328    }
12329
12330    // ── Cross-namespace get_edge now succeeds (UUID v4 is globally unique) ──
12331
12332    #[tokio::test]
12333    async fn get_edge_cross_namespace_succeeds() {
12334        let rt = rt();
12335        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
12336        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
12337
12338        let src = rt
12339            .create_entity(&ns_a, "concept", None, "Src", None, None, vec![])
12340            .await
12341            .unwrap();
12342        let tgt = rt
12343            .create_entity(&ns_a, "concept", None, "Tgt", None, None, vec![])
12344            .await
12345            .unwrap();
12346        let edge = rt
12347            .link(&ns_a, src.id, tgt.id, EdgeRelation::Extends, 1.0, None)
12348            .await
12349            .unwrap();
12350
12351        // Visible from own namespace.
12352        let own_ns = rt.get_edge(&ns_a, Uuid::from(edge.id)).await;
12353        assert!(
12354            own_ns.is_ok() && own_ns.unwrap().is_some(),
12355            "edge must be visible in its own namespace"
12356        );
12357
12358        // Foreign namespace must now SUCCEED: by-ID get is namespace-agnostic.
12359        let cross_ns = rt.get_edge(&ns_b, Uuid::from(edge.id)).await;
12360        assert!(
12361            matches!(cross_ns, Ok(Some(_))),
12362            "cross-namespace get_edge must return Ok(Some(_)) after PR-A1, got {cross_ns:?}"
12363        );
12364
12365        // Absent edge UUID still returns None regardless of token namespace.
12366        let absent = rt.get_edge(&ns_b, Uuid::new_v4()).await;
12367        assert!(
12368            matches!(absent, Ok(None)),
12369            "absent edge must return Ok(None), got {absent:?}"
12370        );
12371    }
12372
12373    // ── Traversal across namespace labels now succeeds ────────────────────────
12374    //
12375    // Previously, traverse with ns_b token + ns_a root was silently empty
12376    // because substrate_exists_in_ns → get_entity rejected cross-namespace lookups.
12377    // Now: get_entity finds any entity by UUID; traverse finds the root and
12378    // returns paths scoped to the graph store's namespace filter for ns_b.
12379    #[tokio::test]
12380    async fn traverse_cross_namespace_root_is_accepted() {
12381        use khive_storage::types::TraversalOptions;
12382
12383        let rt = rt();
12384        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
12385        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
12386
12387        let a = rt
12388            .create_entity(&ns_a, "concept", None, "A", None, None, vec![])
12389            .await
12390            .unwrap();
12391        rt.create_entity(&ns_a, "concept", None, "B", None, None, vec![])
12392            .await
12393            .unwrap();
12394        rt.link(&ns_a, a.id, a.id, EdgeRelation::Extends, 1.0, None)
12395            .await
12396            .ok(); // may conflict with self-loop check; we just need an entity
12397
12398        // substrate_exists_in_ns finds the ns_a root via get_entity
12399        // (UUID-global lookup). The traverse proceeds; no panic.
12400        let result = rt
12401            .traverse(
12402                &ns_b,
12403                TraversalRequest {
12404                    roots: vec![a.id],
12405                    options: TraversalOptions {
12406                        max_depth: 1,
12407                        direction: Direction::Out,
12408                        ..Default::default()
12409                    },
12410                    include_roots: true,
12411                    include_properties: false,
12412                    execution_budget: Default::default(),
12413                },
12414            )
12415            .await;
12416        assert!(result.is_ok(), "traverse must not error; got {:?}", result);
12417    }
12418
12419    // ── Single root visible in multiple namespaces must yield exactly one
12420    //    traversal object (see merge_traversal_paths_by_root) ─────────────
12421    #[tokio::test]
12422    async fn traverse_single_root_across_visible_namespaces_yields_one_path() {
12423        use khive_storage::types::TraversalOptions;
12424
12425        let rt = rt();
12426        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns").unwrap());
12427        let a = rt
12428            .create_entity(&owner, "concept", None, "A", None, None, vec![])
12429            .await
12430            .unwrap();
12431        let b = rt
12432            .create_entity(&owner, "concept", None, "B", None, None, vec![])
12433            .await
12434            .unwrap();
12435        rt.link(&owner, a.id, b.id, EdgeRelation::Extends, 1.0, None)
12436            .await
12437            .unwrap();
12438
12439        // Token whose primary namespace ("caller-ns") does not own the root,
12440        // but whose visible set also includes "owner-ns" (where the root and
12441        // its edge actually live) — the shape produced by pack.rs always
12442        // widening visibility to include `local`.
12443        let caller = NamespaceToken::mint_with_visibility(
12444            Namespace::parse("caller-ns").unwrap(),
12445            vec![Namespace::parse("owner-ns").unwrap()],
12446            ActorRef::anonymous(),
12447        );
12448        assert_eq!(caller.visible_namespaces().len(), 2);
12449
12450        let result = rt
12451            .traverse(
12452                &caller,
12453                TraversalRequest {
12454                    roots: vec![a.id],
12455                    options: TraversalOptions {
12456                        max_depth: 1,
12457                        direction: Direction::Out,
12458                        ..Default::default()
12459                    },
12460                    include_roots: true,
12461                    include_properties: false,
12462                    execution_budget: Default::default(),
12463                },
12464            )
12465            .await
12466            .unwrap();
12467
12468        assert_eq!(
12469            result.len(),
12470            1,
12471            "one root visible across 2 namespaces must yield exactly one \
12472             GraphPath, got {result:#?}"
12473        );
12474        assert_eq!(result[0].root_id, a.id);
12475        let node_ids: std::collections::HashSet<Uuid> =
12476            result[0].nodes.iter().map(|n| n.node_id).collect();
12477        assert!(node_ids.contains(&a.id));
12478        assert!(
12479            node_ids.contains(&b.id),
12480            "merged path must retain the neighbor discovered in the owning \
12481             namespace, got {result:#?}"
12482        );
12483    }
12484
12485    /// Namespace fan-out clones one request but must not clone a fresh work
12486    /// allowance. With one adjacency row in each visible namespace, a one-row
12487    /// shared budget admits the first and makes the later namespace fail the
12488    /// whole operation instead of returning a partial merged path.
12489    #[tokio::test]
12490    async fn traverse_visible_namespaces_share_one_work_budget() {
12491        use khive_storage::types::{TraversalExecutionBudget, TraversalOptions};
12492
12493        let rt = rt();
12494        let ns_a = Namespace::parse("traverse-budget-a").unwrap();
12495        let ns_b = Namespace::parse("traverse-budget-b").unwrap();
12496        let tok_a = NamespaceToken::for_namespace(ns_a.clone());
12497        let tok_b = NamespaceToken::for_namespace(ns_b.clone());
12498        let visible = NamespaceToken::mint_with_visibility(ns_a, vec![ns_b], ActorRef::anonymous());
12499
12500        let root = rt
12501            .create_entity(&tok_a, "concept", None, "BudgetRoot", None, None, vec![])
12502            .await
12503            .unwrap();
12504        let child_a = rt
12505            .create_entity(&tok_a, "concept", None, "BudgetChildA", None, None, vec![])
12506            .await
12507            .unwrap();
12508        let child_b = rt
12509            .create_entity(&tok_b, "concept", None, "BudgetChildB", None, None, vec![])
12510            .await
12511            .unwrap();
12512        rt.link(
12513            &tok_a,
12514            root.id,
12515            child_a.id,
12516            EdgeRelation::Extends,
12517            1.0,
12518            None,
12519        )
12520        .await
12521        .unwrap();
12522        rt.link(
12523            &tok_b,
12524            root.id,
12525            child_b.id,
12526            EdgeRelation::Extends,
12527            1.0,
12528            None,
12529        )
12530        .await
12531        .unwrap();
12532
12533        let result = rt
12534            .traverse(
12535                &visible,
12536                TraversalRequest {
12537                    roots: vec![root.id],
12538                    options: TraversalOptions {
12539                        max_depth: 1,
12540                        direction: Direction::Out,
12541                        relations: None,
12542                        min_weight: None,
12543                        limit: Some(2),
12544                    },
12545                    include_roots: false,
12546                    include_properties: false,
12547                    execution_budget: TraversalExecutionBudget::new(
12548                        1,
12549                        std::time::Duration::from_secs(5),
12550                    ),
12551                },
12552            )
12553            .await;
12554
12555        assert!(matches!(
12556            result,
12557            Err(RuntimeError::Storage(khive_storage::StorageError::InvalidInput {
12558                message,
12559                ..
12560            })) if message.contains("work budget exceeded after 1 adjacency rows")
12561        ));
12562    }
12563
12564    // ── Multi-root traverse: one object per distinct root, including a
12565    //    root supplied both as itself and as a duplicate re-resolution ────
12566    #[tokio::test]
12567    async fn traverse_multi_root_one_path_per_distinct_root() {
12568        use khive_storage::types::TraversalOptions;
12569
12570        let rt = rt();
12571        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns2").unwrap());
12572        let a = rt
12573            .create_entity(&owner, "concept", None, "A", None, None, vec![])
12574            .await
12575            .unwrap();
12576        let c = rt
12577            .create_entity(&owner, "concept", None, "C", None, None, vec![])
12578            .await
12579            .unwrap();
12580
12581        // `a` appears twice in the roots list — this is what the pack
12582        // handler produces when a caller passes the same root once as a
12583        // short prefix and once as the full UUID: both resolve to the same
12584        // `Uuid` value by the time the request reaches the runtime.
12585        let result = rt
12586            .traverse(
12587                &owner,
12588                TraversalRequest {
12589                    roots: vec![a.id, a.id, c.id],
12590                    options: TraversalOptions {
12591                        max_depth: 1,
12592                        direction: Direction::Out,
12593                        ..Default::default()
12594                    },
12595                    include_roots: true,
12596                    include_properties: false,
12597                    execution_budget: Default::default(),
12598                },
12599            )
12600            .await
12601            .unwrap();
12602
12603        let root_ids: Vec<Uuid> = result.iter().map(|p| p.root_id).collect();
12604        assert_eq!(
12605            root_ids.len(),
12606            2,
12607            "duplicate root value must not produce a duplicate GraphPath, got {result:#?}"
12608        );
12609        assert!(root_ids.contains(&a.id));
12610        assert!(root_ids.contains(&c.id));
12611    }
12612
12613    // ── Note-kind nodes reached via traversal must use the same enrichment
12614    //    shape as neighbors, without restoring per-namespace phantom paths ──
12615    #[tokio::test]
12616    async fn traverse_note_node_matches_neighbors_in_one_path() {
12617        use khive_storage::types::TraversalOptions;
12618
12619        let rt = rt();
12620        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns3").unwrap());
12621        let a = rt
12622            .create_entity(&owner, "concept", None, "A", None, None, vec![])
12623            .await
12624            .unwrap();
12625        let note = rt
12626            .create_note(
12627                &owner,
12628                "observation",
12629                Some("TraversalNote"),
12630                "note body",
12631                None,
12632                None,
12633                vec![a.id],
12634            )
12635            .await
12636            .unwrap();
12637
12638        let caller = NamespaceToken::mint_with_visibility(
12639            Namespace::parse("caller-ns3").unwrap(),
12640            vec![Namespace::parse("owner-ns3").unwrap()],
12641            ActorRef::anonymous(),
12642        );
12643        let neighbors = rt
12644            .neighbors(
12645                &caller,
12646                a.id,
12647                Direction::In,
12648                None,
12649                Some(vec![EdgeRelation::Annotates]),
12650            )
12651            .await
12652            .unwrap();
12653        let note_hit = neighbors
12654            .iter()
12655            .find(|hit| hit.node_id == note.id)
12656            .unwrap_or_else(|| panic!("note must be present in neighbors, got {neighbors:#?}"));
12657
12658        let result = rt
12659            .traverse(
12660                &caller,
12661                TraversalRequest {
12662                    roots: vec![a.id],
12663                    options: TraversalOptions {
12664                        max_depth: 1,
12665                        direction: Direction::In,
12666                        relations: Some(vec![EdgeRelation::Annotates]),
12667                        ..Default::default()
12668                    },
12669                    include_roots: false,
12670                    include_properties: false,
12671                    execution_budget: Default::default(),
12672                },
12673            )
12674            .await
12675            .unwrap();
12676
12677        assert_eq!(
12678            result.len(),
12679            1,
12680            "one requested root must yield one path across the caller and owner namespaces"
12681        );
12682        let note_node = result[0]
12683            .nodes
12684            .iter()
12685            .find(|n| n.node_id == note.id)
12686            .unwrap_or_else(|| panic!("note must be present in traversal nodes, got {result:#?}"));
12687        assert_eq!(note_node.name.as_deref(), note_hit.name.as_deref());
12688        assert_eq!(note_node.kind.as_deref(), note_hit.kind.as_deref());
12689        assert_eq!(note_node.name.as_deref(), Some("TraversalNote"));
12690        assert_eq!(note_node.kind.as_deref(), Some("observation"));
12691    }
12692
12693    // ── A nameless annotation note reached via traversal must fall back to
12694    //    the same `[kind]` placeholder that `neighbors` produces ──
12695    #[tokio::test]
12696    async fn traverse_nameless_note_falls_back_to_bracketed_kind() {
12697        use khive_storage::types::TraversalOptions;
12698
12699        let rt = rt();
12700        let owner = NamespaceToken::for_namespace(Namespace::parse("owner-ns4").unwrap());
12701        let a = rt
12702            .create_entity(&owner, "concept", None, "A", None, None, vec![])
12703            .await
12704            .unwrap();
12705        let note = rt
12706            .create_note(
12707                &owner,
12708                "observation",
12709                None,
12710                "note body",
12711                None,
12712                None,
12713                vec![a.id],
12714            )
12715            .await
12716            .unwrap();
12717
12718        let caller = NamespaceToken::mint_with_visibility(
12719            Namespace::parse("caller-ns4").unwrap(),
12720            vec![Namespace::parse("owner-ns4").unwrap()],
12721            ActorRef::anonymous(),
12722        );
12723        let neighbors = rt
12724            .neighbors(
12725                &caller,
12726                a.id,
12727                Direction::In,
12728                None,
12729                Some(vec![EdgeRelation::Annotates]),
12730            )
12731            .await
12732            .unwrap();
12733        let note_hit = neighbors
12734            .iter()
12735            .find(|hit| hit.node_id == note.id)
12736            .unwrap_or_else(|| panic!("note must be present in neighbors, got {neighbors:#?}"));
12737
12738        let result = rt
12739            .traverse(
12740                &caller,
12741                TraversalRequest {
12742                    roots: vec![a.id],
12743                    options: TraversalOptions {
12744                        max_depth: 1,
12745                        direction: Direction::In,
12746                        relations: Some(vec![EdgeRelation::Annotates]),
12747                        ..Default::default()
12748                    },
12749                    include_roots: false,
12750                    include_properties: false,
12751                    execution_budget: Default::default(),
12752                },
12753            )
12754            .await
12755            .unwrap();
12756
12757        let note_node = result[0]
12758            .nodes
12759            .iter()
12760            .find(|n| n.node_id == note.id)
12761            .unwrap_or_else(|| panic!("note must be present in traversal nodes, got {result:#?}"));
12762        assert_eq!(note_node.name.as_deref(), note_hit.name.as_deref());
12763        assert_eq!(note_node.kind.as_deref(), note_hit.kind.as_deref());
12764        assert_eq!(note_node.name.as_deref(), Some("[observation]"));
12765        assert_eq!(note_node.kind.as_deref(), Some("observation"));
12766    }
12767
12768    // ---- purge cascade must include already-soft-deleted edges ----
12769    //
12770    // Hard delete must cascade ALL incident edges synchronously. A cascade driven
12771    // through `neighbors()`, which filters `deleted_at IS NULL`, would let incident
12772    // edges that were already soft-deleted survive endpoint purge as dangling rows.
12773    // `purge_incident_edges` issues a single DELETE without a `deleted_at` guard.
12774
12775    /// Count ALL `graph_edges` rows for a given UUID (source OR target), including soft-deleted.
12776    async fn count_all_incident_edges(rt: &KhiveRuntime, node_id: Uuid, ns: &str) -> u64 {
12777        let mut reader = rt.sql().reader().await.expect("sql reader must open");
12778        let row = reader
12779            .query_scalar(SqlStatement {
12780                sql: "SELECT COUNT(*) FROM graph_edges \
12781                      WHERE namespace = ?1 AND (source_id = ?2 OR target_id = ?2)"
12782                    .into(),
12783                params: vec![
12784                    SqlValue::Text(ns.to_string()),
12785                    SqlValue::Text(node_id.to_string()),
12786                ],
12787                label: Some("count_all_incident_edges".into()),
12788            })
12789            .await
12790            .expect("count query must succeed");
12791        match row {
12792            Some(SqlValue::Integer(n)) => n as u64,
12793            _ => panic!("count must return an integer"),
12794        }
12795    }
12796
12797    async fn lineage_warning_events(
12798        rt: &KhiveRuntime,
12799        tok: &NamespaceToken,
12800        target_id: Uuid,
12801    ) -> Vec<Event> {
12802        rt.events(tok)
12803            .expect("event store")
12804            .query_events(
12805                EventFilter {
12806                    kinds: vec![EventKind::Audit],
12807                    ..Default::default()
12808                },
12809                PageRequest::default(),
12810            )
12811            .await
12812            .expect("query warning events")
12813            .items
12814            .into_iter()
12815            .filter(|event| event.target_id == Some(target_id))
12816            .collect()
12817    }
12818
12819    #[tokio::test]
12820    async fn hard_delete_emits_relation_specific_lineage_warnings_only() {
12821        let rt = rt();
12822        let tok = NamespaceToken::local();
12823        let doomed = rt
12824            .create_entity(&tok, "document", None, "doomed", None, None, vec![])
12825            .await
12826            .unwrap();
12827
12828        let provenance_source = rt
12829            .create_entity(&tok, "artifact", None, "source", None, None, vec![])
12830            .await
12831            .unwrap();
12832        rt.link(
12833            &tok,
12834            provenance_source.id,
12835            doomed.id,
12836            EdgeRelation::DerivedFrom,
12837            1.0,
12838            None,
12839        )
12840        .await
12841        .unwrap();
12842
12843        for (kind, name, relation) in [
12844            ("document", "old", EdgeRelation::Supersedes),
12845            ("document", "next", EdgeRelation::Precedes),
12846            ("concept", "supported", EdgeRelation::Supports),
12847            ("concept", "refuted", EdgeRelation::Refutes),
12848        ] {
12849            let target = rt
12850                .create_entity(&tok, kind, None, name, None, None, vec![])
12851                .await
12852                .unwrap();
12853            rt.link(&tok, doomed.id, target.id, relation, 1.0, None)
12854                .await
12855                .unwrap();
12856        }
12857        let unrelated = rt
12858            .create_entity(&tok, "concept", None, "unrelated", None, None, vec![])
12859            .await
12860            .unwrap();
12861        rt.link(
12862            &tok,
12863            unrelated.id,
12864            doomed.id,
12865            EdgeRelation::IntroducedBy,
12866            1.0,
12867            None,
12868        )
12869        .await
12870        .unwrap();
12871
12872        assert!(rt.delete_entity(&tok, doomed.id, false).await.unwrap());
12873        assert!(
12874            lineage_warning_events(&rt, &tok, doomed.id)
12875                .await
12876                .is_empty(),
12877            "soft delete must not emit cascade-loss warnings"
12878        );
12879
12880        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
12881        let warnings = lineage_warning_events(&rt, &tok, doomed.id).await;
12882        assert_eq!(warnings.len(), 5);
12883
12884        let mut actual = warnings
12885            .iter()
12886            .map(|event| {
12887                assert_eq!(event.substrate, SubstrateKind::Entity);
12888                assert_eq!(event.payload["severity"], "warning");
12889                assert_eq!(event.payload["deleted_id"], doomed.id.to_string());
12890                assert_eq!(event.payload["edge_count"], 1);
12891                assert_eq!(event.payload["edges"].as_array().unwrap().len(), 1);
12892                (
12893                    event.payload["relation"].as_str().unwrap().to_string(),
12894                    event.payload["warning"].as_str().unwrap().to_string(),
12895                )
12896            })
12897            .collect::<Vec<_>>();
12898        actual.sort();
12899        assert_eq!(
12900            actual,
12901            vec![
12902                ("derived_from".into(), "provenance_loss".into()),
12903                ("precedes".into(), "temporal_sequence_loss".into()),
12904                ("refutes".into(), "evidential_link_loss".into()),
12905                ("supersedes".into(), "replacement_lineage_loss".into()),
12906                ("supports".into(), "evidential_link_loss".into()),
12907            ]
12908        );
12909        assert!(warnings
12910            .iter()
12911            .all(|event| event.payload["relation"] != "introduced_by"));
12912    }
12913
12914    #[tokio::test]
12915    async fn hard_delete_lineage_warning_is_filterable_by_caller_actor() {
12916        let rt = rt();
12917        let tok = NamespaceToken::mint_authorized(
12918            Namespace::local(),
12919            ActorRef::new("agent", "lineage-deleter"),
12920        );
12921        let expected_actor = "agent:lineage-deleter";
12922        let doomed = rt
12923            .create_entity(&tok, "document", None, "actor-doomed", None, None, vec![])
12924            .await
12925            .unwrap();
12926        let source = rt
12927            .create_entity(&tok, "artifact", None, "actor-source", None, None, vec![])
12928            .await
12929            .unwrap();
12930        rt.link(
12931            &tok,
12932            source.id,
12933            doomed.id,
12934            EdgeRelation::DerivedFrom,
12935            1.0,
12936            None,
12937        )
12938        .await
12939        .unwrap();
12940
12941        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
12942
12943        let warnings = rt
12944            .events(&tok)
12945            .expect("event store")
12946            .query_events(
12947                EventFilter {
12948                    kinds: vec![EventKind::Audit],
12949                    actors: vec![expected_actor.to_string()],
12950                    ..Default::default()
12951                },
12952                PageRequest::default(),
12953            )
12954            .await
12955            .expect("query actor-filtered warning events")
12956            .items
12957            .into_iter()
12958            .filter(|event| event.target_id == Some(doomed.id))
12959            .collect::<Vec<_>>();
12960        assert_eq!(warnings.len(), 1);
12961        assert_eq!(warnings[0].actor, expected_actor);
12962        assert_eq!(warnings[0].payload["relation"], "derived_from");
12963    }
12964
12965    #[tokio::test]
12966    async fn hard_delete_warns_for_tombstoned_protected_incident_edge() {
12967        let rt = rt();
12968        let tok = NamespaceToken::local();
12969        let doomed = rt
12970            .create_entity(
12971                &tok,
12972                "document",
12973                None,
12974                "tombstoned-edge-doomed",
12975                None,
12976                None,
12977                vec![],
12978            )
12979            .await
12980            .unwrap();
12981        let source = rt
12982            .create_entity(
12983                &tok,
12984                "artifact",
12985                None,
12986                "tombstoned-edge-source",
12987                None,
12988                None,
12989                vec![],
12990            )
12991            .await
12992            .unwrap();
12993        let edge = rt
12994            .link(
12995                &tok,
12996                source.id,
12997                doomed.id,
12998                EdgeRelation::DerivedFrom,
12999                1.0,
13000                None,
13001            )
13002            .await
13003            .unwrap();
13004        let edge_id = Uuid::from(edge.id);
13005        assert!(rt.delete_edge(&tok, edge_id, false).await.unwrap());
13006
13007        assert!(rt.delete_entity(&tok, doomed.id, true).await.unwrap());
13008
13009        let warnings = lineage_warning_events(&rt, &tok, doomed.id).await;
13010        assert_eq!(warnings.len(), 1);
13011        assert_eq!(warnings[0].payload["edge_count"], 1);
13012        let warned_edge = &warnings[0].payload["edges"].as_array().unwrap()[0];
13013        assert_eq!(warned_edge["id"], edge_id.to_string());
13014        assert!(
13015            warned_edge["deleted_at"].is_number(),
13016            "warning must preserve the edge's prior tombstone timestamp"
13017        );
13018        assert!(
13019            rt.get_edge_including_deleted(&tok, edge_id)
13020                .await
13021                .unwrap()
13022                .is_none(),
13023            "the warned tombstoned edge must still be physically cascaded"
13024        );
13025    }
13026
13027    #[tokio::test]
13028    async fn hard_delete_note_emits_evidential_lineage_warning() {
13029        let rt = rt();
13030        let tok = NamespaceToken::local();
13031        let evidence = rt
13032            .create_note(&tok, "observation", None, "evidence", None, None, vec![])
13033            .await
13034            .unwrap();
13035        let claim = rt
13036            .create_note(&tok, "insight", None, "claim", None, None, vec![])
13037            .await
13038            .unwrap();
13039        rt.link(
13040            &tok,
13041            evidence.id,
13042            claim.id,
13043            EdgeRelation::Supports,
13044            1.0,
13045            None,
13046        )
13047        .await
13048        .unwrap();
13049
13050        assert!(rt.delete_note(&tok, evidence.id, true).await.unwrap());
13051        let warnings = lineage_warning_events(&rt, &tok, evidence.id).await;
13052        assert_eq!(warnings.len(), 1);
13053        assert_eq!(warnings[0].substrate, SubstrateKind::Note);
13054        assert_eq!(warnings[0].payload["relation"], "supports");
13055        assert_eq!(warnings[0].payload["warning"], "evidential_link_loss");
13056    }
13057
13058    #[tokio::test]
13059    async fn lineage_warning_insert_failure_rolls_back_hard_delete_and_cascade() {
13060        let rt = rt();
13061        let tok = NamespaceToken::local();
13062        let doomed = rt
13063            .create_entity(&tok, "document", None, "doomed", None, None, vec![])
13064            .await
13065            .unwrap();
13066        let source = rt
13067            .create_entity(&tok, "artifact", None, "source", None, None, vec![])
13068            .await
13069            .unwrap();
13070        let edge = rt
13071            .link(
13072                &tok,
13073                source.id,
13074                doomed.id,
13075                EdgeRelation::DerivedFrom,
13076                1.0,
13077                None,
13078            )
13079            .await
13080            .unwrap();
13081
13082        let mut writer = rt.sql().writer().await.expect("sql writer");
13083        writer
13084            .execute_script(
13085                "CREATE TRIGGER reject_lineage_warning \
13086                 BEFORE INSERT ON events \
13087                 WHEN NEW.kind = 'audit' \
13088                   AND json_extract(NEW.payload, '$.severity') = 'warning' \
13089                 BEGIN \
13090                   SELECT RAISE(ABORT, 'injected lineage warning failure'); \
13091                 END;"
13092                    .into(),
13093            )
13094            .await
13095            .expect("install warning failure trigger");
13096        drop(writer);
13097
13098        let error = rt.delete_entity(&tok, doomed.id, true).await.unwrap_err();
13099        assert!(error
13100            .to_string()
13101            .contains("injected lineage warning failure"));
13102        assert!(
13103            rt.entities(&tok)
13104                .unwrap()
13105                .get_entity(doomed.id)
13106                .await
13107                .unwrap()
13108                .is_some(),
13109            "the endpoint row must roll back with the failed warning insert"
13110        );
13111        assert!(
13112            rt.get_edge(&tok, Uuid::from(edge.id))
13113                .await
13114                .unwrap()
13115                .is_some(),
13116            "the incident edge must roll back with the failed warning insert"
13117        );
13118    }
13119
13120    #[tokio::test]
13121    async fn hard_delete_entity_purges_already_soft_deleted_incident_edge() {
13122        let rt = rt();
13123        let tok = NamespaceToken::local();
13124        let ns = tok.namespace().to_string();
13125
13126        let a = rt
13127            .create_entity(&tok, "concept", None, "SrcA", None, None, vec![])
13128            .await
13129            .unwrap();
13130        let b = rt
13131            .create_entity(&tok, "concept", None, "TgtB", None, None, vec![])
13132            .await
13133            .unwrap();
13134
13135        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
13136            .await
13137            .unwrap();
13138
13139        // Soft-delete the edge — it is now invisible to `neighbors` but still in storage.
13140        let edge_hit = rt
13141            .neighbors(&tok, a.id, Direction::Out, None, None)
13142            .await
13143            .unwrap();
13144        assert_eq!(edge_hit.len(), 1, "edge must exist before soft-delete");
13145        let edge_uuid = edge_hit[0].edge_id;
13146        rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
13147
13148        // Confirm the edge is invisible to normal read paths but present in raw storage.
13149        let visible = rt
13150            .neighbors(&tok, a.id, Direction::Out, None, None)
13151            .await
13152            .unwrap();
13153        assert!(visible.is_empty(), "soft-deleted edge must be invisible");
13154        let raw_before = count_all_incident_edges(&rt, a.id, &ns).await;
13155        assert_eq!(
13156            raw_before, 1,
13157            "soft-deleted edge must still be a physical row"
13158        );
13159
13160        // Hard-delete (purge) the source entity — cascade must also remove the soft-deleted edge.
13161        rt.delete_entity(&tok, a.id, true).await.unwrap();
13162
13163        let raw_after = count_all_incident_edges(&rt, a.id, &ns).await;
13164        assert_eq!(
13165            raw_after, 0,
13166            "purge_incident_edges must physically remove soft-deleted edge rows (ADR-002)"
13167        );
13168    }
13169
13170    #[tokio::test]
13171    async fn hard_delete_note_purges_already_soft_deleted_incident_edge() {
13172        let rt = rt();
13173        let tok = NamespaceToken::local();
13174        let ns = tok.namespace().to_string();
13175
13176        let target = rt
13177            .create_note(
13178                &tok,
13179                "observation",
13180                None,
13181                "purge-cascade target note",
13182                Some(0.5),
13183                None,
13184                vec![],
13185            )
13186            .await
13187            .unwrap();
13188        let annotating = rt
13189            .create_note(
13190                &tok,
13191                "insight",
13192                None,
13193                "annotator note",
13194                Some(0.5),
13195                None,
13196                vec![target.id],
13197            )
13198            .await
13199            .unwrap();
13200
13201        // Soft-delete the annotates edge.
13202        let edge_hit = rt
13203            .neighbors(
13204                &tok,
13205                annotating.id,
13206                Direction::Out,
13207                None,
13208                Some(vec![EdgeRelation::Annotates]),
13209            )
13210            .await
13211            .unwrap();
13212        assert_eq!(edge_hit.len(), 1, "annotates edge must exist");
13213        let edge_uuid = edge_hit[0].edge_id;
13214        rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
13215
13216        let raw_before = count_all_incident_edges(&rt, target.id, &ns).await;
13217        assert_eq!(
13218            raw_before, 1,
13219            "soft-deleted edge must still be a physical row before note purge"
13220        );
13221
13222        // Hard-delete the target note — cascade must remove the soft-deleted edge row.
13223        rt.delete_note(&tok, target.id, true).await.unwrap();
13224
13225        let raw_after = count_all_incident_edges(&rt, target.id, &ns).await;
13226        assert_eq!(
13227            raw_after, 0,
13228            "purge_incident_edges must physically remove soft-deleted edge rows on note purge (ADR-002)"
13229        );
13230    }
13231
13232    // ---- cross-namespace entity hard-delete purges ALL incident edges ----
13233    //
13234    // `purge_incident_edges` must not scope its DELETE by `WHERE namespace = caller_ns`,
13235    // or a foreign-namespace entity's incident edges in ITS namespace would survive
13236    // the cascade as dangling rows.
13237
13238    /// Count ALL `graph_edges` rows for a given node UUID, across every namespace.
13239    async fn count_all_incident_edges_global(rt: &KhiveRuntime, node_id: Uuid) -> u64 {
13240        let mut reader = rt.sql().reader().await.expect("sql reader must open");
13241        let row = reader
13242            .query_scalar(SqlStatement {
13243                sql: "SELECT COUNT(*) FROM graph_edges WHERE source_id = ?1 OR target_id = ?1"
13244                    .into(),
13245                params: vec![SqlValue::Text(node_id.to_string())],
13246                label: Some("count_all_incident_edges_global".into()),
13247            })
13248            .await
13249            .expect("count query must succeed");
13250        match row {
13251            Some(SqlValue::Integer(n)) => n as u64,
13252            _ => panic!("count must return an integer"),
13253        }
13254    }
13255
13256    #[tokio::test]
13257    async fn cross_namespace_hard_delete_entity_purges_all_incident_edges() {
13258        // Entity lives in ns-owner. Edges live in ns-owner.
13259        // Delete is driven from ns-caller (a different namespace).
13260        // Assertion: after hard delete, no incident edges remain in ANY namespace.
13261        let rt = rt();
13262        let ns_owner = NamespaceToken::for_namespace(Namespace::parse("ns-owner").unwrap());
13263        let ns_caller = NamespaceToken::for_namespace(Namespace::parse("ns-caller").unwrap());
13264
13265        let entity = rt
13266            .create_entity(
13267                &ns_owner,
13268                "concept",
13269                None,
13270                "ForeignEntity",
13271                None,
13272                None,
13273                vec![],
13274            )
13275            .await
13276            .unwrap();
13277        let peer = rt
13278            .create_entity(&ns_owner, "concept", None, "Peer", None, None, vec![])
13279            .await
13280            .unwrap();
13281        // Create two incident edges in ns_owner. concept->Extends->concept is in the allowlist.
13282        rt.link(
13283            &ns_owner,
13284            entity.id,
13285            peer.id,
13286            EdgeRelation::Extends,
13287            1.0,
13288            None,
13289        )
13290        .await
13291        .unwrap();
13292        rt.link(
13293            &ns_owner,
13294            peer.id,
13295            entity.id,
13296            EdgeRelation::Extends,
13297            1.0,
13298            None,
13299        )
13300        .await
13301        .unwrap();
13302
13303        let before = count_all_incident_edges_global(&rt, entity.id).await;
13304        assert_eq!(before, 2, "two incident edges must exist before delete");
13305
13306        // Hard-delete entity from a DIFFERENT namespace token.
13307        let deleted = rt.delete_entity(&ns_caller, entity.id, true).await.unwrap();
13308        assert!(deleted, "cross-ns hard delete must return true");
13309
13310        // All incident edges must be gone regardless of namespace.
13311        let after = count_all_incident_edges_global(&rt, entity.id).await;
13312        assert_eq!(
13313            after, 0,
13314            "purge_incident_edges must remove all incident edges across namespaces (ADR-002, ADR-007)"
13315        );
13316    }
13317
13318    // ---- edge-ID hard-delete path ----
13319    //
13320    // Bug class: delete_edge drove the primary-edge guard through get_edge()
13321    // (live-only) and the cascade through neighbors() (live-only). Two reachable holes:
13322    // (a) soft-deleted primary edge cannot be hard-purged via its own ID;
13323    // (b) an already-soft-deleted annotates edge targeting a base edge survives that
13324    //     edge's hard delete as a dangling row with target_id = physically-gone edge id.
13325
13326    /// Count graph_edges rows matching the given edge ID, including soft-deleted rows.
13327    async fn count_edge_rows_by_id(rt: &KhiveRuntime, edge_id: Uuid, ns: &str) -> u64 {
13328        let mut reader = rt.sql().reader().await.expect("sql reader must open");
13329        let row = reader
13330            .query_scalar(SqlStatement {
13331                sql: "SELECT COUNT(*) FROM graph_edges WHERE namespace = ?1 AND id = ?2".into(),
13332                params: vec![
13333                    SqlValue::Text(ns.to_string()),
13334                    SqlValue::Text(edge_id.to_string()),
13335                ],
13336                label: Some("count_edge_rows_by_id".into()),
13337            })
13338            .await
13339            .expect("count query must succeed");
13340        match row {
13341            Some(SqlValue::Integer(n)) => n as u64,
13342            _ => panic!("count must return an integer"),
13343        }
13344    }
13345
13346    #[tokio::test]
13347    async fn hard_delete_edge_purges_already_soft_deleted_primary_edge() {
13348        let rt = rt();
13349        let tok = NamespaceToken::local();
13350        let ns = tok.namespace().to_string();
13351
13352        let a = rt
13353            .create_entity(&tok, "concept", None, "EA", None, None, vec![])
13354            .await
13355            .unwrap();
13356        let b = rt
13357            .create_entity(&tok, "concept", None, "EB", None, None, vec![])
13358            .await
13359            .unwrap();
13360
13361        let edge = rt
13362            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
13363            .await
13364            .unwrap();
13365        let edge_uuid: Uuid = edge.id.into();
13366
13367        // Soft-delete the edge first.
13368        let soft = rt.delete_edge(&tok, edge_uuid, false).await.unwrap();
13369        assert!(soft, "soft delete must succeed");
13370
13371        // Edge is now invisible to normal reads but still a physical row.
13372        assert!(
13373            rt.get_edge(&tok, edge_uuid).await.unwrap().is_none(),
13374            "soft-deleted edge must be invisible to get_edge"
13375        );
13376        assert_eq!(
13377            count_edge_rows_by_id(&rt, edge_uuid, &ns).await,
13378            1,
13379            "soft-deleted edge must still be a physical row"
13380        );
13381
13382        // Hard-delete (purge) via the edge ID — must succeed and remove the row.
13383        let purged = rt.delete_edge(&tok, edge_uuid, true).await.unwrap();
13384        assert!(
13385            purged,
13386            "hard delete of a soft-deleted edge must return true"
13387        );
13388
13389        assert_eq!(
13390            count_edge_rows_by_id(&rt, edge_uuid, &ns).await,
13391            0,
13392            "hard-delete must physically remove the soft-deleted edge row (ADR-002)"
13393        );
13394    }
13395
13396    #[tokio::test]
13397    async fn hard_delete_base_edge_purges_already_soft_deleted_annotates_edge() {
13398        let rt = rt();
13399        let tok = NamespaceToken::local();
13400        let ns = tok.namespace().to_string();
13401
13402        let a = rt
13403            .create_entity(&tok, "concept", None, "CA", None, None, vec![])
13404            .await
13405            .unwrap();
13406        let b = rt
13407            .create_entity(&tok, "concept", None, "CB", None, None, vec![])
13408            .await
13409            .unwrap();
13410
13411        // Create the base edge to be annotated.
13412        let base_edge = rt
13413            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
13414            .await
13415            .unwrap();
13416        let base_edge_uuid: Uuid = base_edge.id.into();
13417
13418        // Create a note that annotates the base edge.
13419        let note = rt
13420            .create_note(
13421                &tok,
13422                "observation",
13423                None,
13424                "note about base edge",
13425                Some(0.5),
13426                None,
13427                vec![base_edge_uuid],
13428            )
13429            .await
13430            .unwrap();
13431
13432        // Find the annotates edge.
13433        let ann_hits = rt
13434            .neighbors(
13435                &tok,
13436                note.id,
13437                Direction::Out,
13438                None,
13439                Some(vec![EdgeRelation::Annotates]),
13440            )
13441            .await
13442            .unwrap();
13443        assert_eq!(ann_hits.len(), 1, "annotates edge must exist");
13444        let ann_edge_uuid = ann_hits[0].edge_id;
13445
13446        // Soft-delete the annotates edge — now invisible but still a physical row.
13447        rt.delete_edge(&tok, ann_edge_uuid, false).await.unwrap();
13448        assert_eq!(
13449            count_edge_rows_by_id(&rt, ann_edge_uuid, &ns).await,
13450            1,
13451            "soft-deleted annotates edge must still be a physical row"
13452        );
13453
13454        // Hard-delete the base edge — cascade must also remove the soft-deleted annotates row.
13455        let purged = rt.delete_edge(&tok, base_edge_uuid, true).await.unwrap();
13456        assert!(purged, "hard delete of base edge must return true");
13457
13458        assert_eq!(
13459            count_edge_rows_by_id(&rt, ann_edge_uuid, &ns).await,
13460            0,
13461            "hard-delete of base edge must purge already-soft-deleted annotates edge row (ADR-002)"
13462        );
13463        assert_eq!(
13464            count_edge_rows_by_id(&rt, base_edge_uuid, &ns).await,
13465            0,
13466            "hard-delete must physically remove the base edge row"
13467        );
13468    }
13469
13470    // ---- entity create/update multi-model embed fan-out tests ----
13471
13472    // FTS failure after entity row commit rolls back the entity row.
13473    // Mirrors create_note_fts_failure_rolls_back_note_row but for entities.
13474    // Uses a unique namespace so this test's arm never fires for the wrong
13475    // write path, even under full-suite parallelism.
13476    #[tokio::test]
13477    async fn create_entity_fts_failure_rolls_back_entity_row() {
13478        let rt = KhiveRuntime::memory().unwrap();
13479        let ns = Namespace::parse("fault-entity-fts").unwrap();
13480        let tok = NamespaceToken::for_namespace(ns.clone());
13481
13482        let _arm = arm_fts_fail_scoped(ns.as_str());
13483
13484        let result = rt
13485            .create_entity(
13486                &tok,
13487                "concept",
13488                None,
13489                "fts-fail rollback target",
13490                None,
13491                None,
13492                vec![],
13493            )
13494            .await;
13495
13496        assert!(
13497            result.is_err(),
13498            "create_entity must propagate the injected FTS failure"
13499        );
13500        let err_msg = result.unwrap_err().to_string();
13501        assert!(
13502            err_msg.contains("injected FTS failure"),
13503            "error must carry injection message; got: {err_msg}"
13504        );
13505
13506        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
13507        assert!(
13508            entities.is_empty(),
13509            "compensation must remove the entity row after FTS failure; got {entities:?}"
13510        );
13511    }
13512
13513    #[tokio::test]
13514    async fn create_entity_fts_and_compensation_failures_report_partial_persistence() {
13515        let rt = KhiveRuntime::memory().unwrap();
13516        let ns = Namespace::parse("partial-persistence-fts").unwrap();
13517        let tok = NamespaceToken::for_namespace(ns.clone());
13518        let _fts_arm = arm_fts_fail_scoped(ns.as_str());
13519        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
13520
13521        let error = rt
13522            .create_entity(
13523                &tok,
13524                "concept",
13525                None,
13526                "FTS partial persistence",
13527                None,
13528                None,
13529                vec![],
13530            )
13531            .await
13532            .expect_err("FTS and compensation failures must fail create_entity");
13533        assert!(
13534            matches!(&error, RuntimeError::Khive(_)),
13535            "combined failures must use the structured wire error path"
13536        );
13537        let error_message = error.to_string();
13538        assert!(error_message.contains("injected FTS failure"));
13539        assert!(error_message.contains("injected compensation failure"));
13540        assert!(error_message.contains("partial persistence is possible"));
13541
13542        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
13543        assert_eq!(
13544            entities.len(),
13545            1,
13546            "the failed row cleanup must leave residue"
13547        );
13548        let record_id = entities[0].id;
13549        assert!(
13550            error_message.contains(&record_id.to_string()),
13551            "the error must identify the durable row that needs reconciliation"
13552        );
13553        assert!(
13554            rt.text(&tok)
13555                .unwrap()
13556                .get_document(ns.as_str(), record_id)
13557                .await
13558                .unwrap()
13559                .is_none(),
13560            "FTS cleanup must run even when the FTS upsert reports failure"
13561        );
13562    }
13563
13564    // Vector insert failure after entity row + FTS commit rolls back both.
13565    // Uses a unique namespace so only this test consumes its VECTOR_FAIL_NS entry.
13566    #[tokio::test]
13567    async fn create_entity_vector_failure_rolls_back_entity_row_and_fts() {
13568        const MODEL: &str = "test-entity-vec-inject";
13569        const DIMS: usize = 4;
13570
13571        let rt = KhiveRuntime::memory().unwrap();
13572        let (provider, _counter) = ConstVecProvider::new(MODEL, DIMS);
13573        rt.register_embedder(provider);
13574
13575        let ns = Namespace::parse("fault-entity-vec").unwrap();
13576        let tok = NamespaceToken::for_namespace(ns.clone());
13577
13578        let _arm = arm_vector_fail_scoped(ns.as_str());
13579
13580        let result = rt
13581            .create_entity(
13582                &tok,
13583                "concept",
13584                None,
13585                "vec-fail rollback target",
13586                Some("description so embed body is non-empty"),
13587                None,
13588                vec![],
13589            )
13590            .await;
13591
13592        assert!(
13593            result.is_err(),
13594            "create_entity must propagate the injected vector failure"
13595        );
13596        let err_msg = result.unwrap_err().to_string();
13597        assert!(
13598            err_msg.contains("injected vector failure"),
13599            "error must carry injection message; got: {err_msg}"
13600        );
13601
13602        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
13603        assert!(
13604            entities.is_empty(),
13605            "compensation must remove entity row after vector failure; got {entities:?}"
13606        );
13607
13608        // FTS document must also be removed.
13609        use khive_storage::types::{TextFilter, TextQueryMode, TextSearchRequest};
13610        let fts_hits = rt
13611            .text(&tok)
13612            .unwrap()
13613            .search(TextSearchRequest {
13614                query: "vec-fail rollback target".to_string(),
13615                mode: TextQueryMode::Plain,
13616                filter: Some(TextFilter {
13617                    namespaces: vec![ns.as_str().to_string()],
13618                    ..Default::default()
13619                }),
13620                top_k: 10,
13621                snippet_chars: 100,
13622            })
13623            .await
13624            .unwrap();
13625        assert!(
13626            fts_hits.is_empty(),
13627            "compensation must remove FTS document after vector failure; got {fts_hits:?}"
13628        );
13629    }
13630
13631    #[tokio::test]
13632    async fn create_entity_single_model_reports_primary_and_compensation_failures() {
13633        const MODEL: &str = "partial-persistence-single";
13634
13635        let rt = KhiveRuntime::memory().unwrap();
13636        let (provider, _counter) = ConstVecProvider::new(MODEL, 4);
13637        rt.register_embedder(provider);
13638
13639        let ns = Namespace::parse("partial-persistence-single").unwrap();
13640        let tok = NamespaceToken::for_namespace(ns.clone());
13641        let _vector_arm = arm_vector_fail_scoped(ns.as_str());
13642        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
13643
13644        let error = rt
13645            .create_entity(
13646                &tok,
13647                "concept",
13648                None,
13649                "single-model partial persistence",
13650                Some("the FTS document lands before the injected vector failure"),
13651                None,
13652                vec![],
13653            )
13654            .await
13655            .expect_err("vector and compensation failures must fail create_entity");
13656
13657        let error_message = error.to_string();
13658        assert!(error_message.contains("injected vector failure"));
13659        assert!(error_message.contains("injected compensation failure"));
13660        assert!(error_message.contains("partial persistence is possible"));
13661
13662        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
13663        assert_eq!(
13664            entities.len(),
13665            1,
13666            "the failed row cleanup must leave residue"
13667        );
13668        let record_id = entities[0].id;
13669        assert!(
13670            error_message.contains(&record_id.to_string()),
13671            "the caller-visible error must carry the recovery record ID"
13672        );
13673        assert!(
13674            rt.text(&tok)
13675                .unwrap()
13676                .get_document(ns.as_str(), record_id)
13677                .await
13678                .unwrap()
13679                .is_none(),
13680            "independent FTS compensation must still complete"
13681        );
13682        assert_eq!(
13683            rt.vectors_for_model(&tok, MODEL)
13684                .unwrap()
13685                .count()
13686                .await
13687                .unwrap(),
13688            0,
13689            "the failed model must be cleaned even though INSERT returned an error"
13690        );
13691    }
13692
13693    // Multi-model create_entity: second model's vector INSERT fails after the
13694    // first model's insert succeeds, triggering inserted_models rollback.
13695    // Uses arm_vector_fail_after(1) so the first insert passes and the second fails,
13696    // exercising the inserted_models compensation path in create_entity.
13697    // Thread-local VECTOR_FAIL_AFTER is per-thread isolated (current-thread tokio runtime),
13698    // so this test does not race with namespace-targeted VECTOR_FAIL_NS tests.
13699    #[tokio::test]
13700    async fn create_entity_multi_model_second_vector_failure_rolls_back_all() {
13701        const DIMS: usize = 4;
13702
13703        let rt = KhiveRuntime::memory().unwrap();
13704        let (provider_a, _ca) = ConstVecProvider::new("model-a", DIMS);
13705        let (provider_b, _cb) = ConstVecProvider::new("model-b", DIMS);
13706        rt.register_embedder(provider_a);
13707        rt.register_embedder(provider_b);
13708
13709        let ns = Namespace::parse("fault-entity-multi").unwrap();
13710        let tok = NamespaceToken::for_namespace(ns.clone());
13711
13712        // Let the first vector insert succeed, fail on the second.
13713        arm_vector_fail_after(1);
13714
13715        let result = rt
13716            .create_entity(
13717                &tok,
13718                "concept",
13719                None,
13720                "multi-model rollback target",
13721                Some("description for embedding"),
13722                None,
13723                vec![],
13724            )
13725            .await;
13726
13727        assert!(
13728            result.is_err(),
13729            "create_entity must propagate the injected multi-model vector failure"
13730        );
13731
13732        let entities = rt.list_entities(&tok, None, None, 1000, 0).await.unwrap();
13733        assert!(
13734            entities.is_empty(),
13735            "compensation must remove entity row; got {entities:?}"
13736        );
13737
13738        // Both model-a and model-b vector stores must be empty for the entity id.
13739        // (The entity was never returned so we can't get its id from the result;
13740        // list_entities returning empty is the primary assertion. Additionally confirm
13741        // both stores have zero rows via a broad vector search.)
13742        use khive_storage::types::VectorSearchRequest;
13743        let query_vec = vec![1.0_f32; DIMS];
13744        let hits_a = rt
13745            .vectors_for_model(&tok, "model-a")
13746            .unwrap()
13747            .search(VectorSearchRequest {
13748                query_vectors: vec![query_vec.clone()],
13749                top_k: 100,
13750                namespace: Some(ns.as_str().to_string()),
13751                kind: Some(khive_types::SubstrateKind::Entity),
13752                embedding_model: Some("model-a".to_string()),
13753                filter: None,
13754                backend_hints: None,
13755            })
13756            .await
13757            .unwrap();
13758        assert!(
13759            hits_a.is_empty(),
13760            "model-a vector store must be empty after rollback; got {hits_a:?}"
13761        );
13762        let hits_b = rt
13763            .vectors_for_model(&tok, "model-b")
13764            .unwrap()
13765            .search(VectorSearchRequest {
13766                query_vectors: vec![query_vec],
13767                top_k: 100,
13768                namespace: Some(ns.as_str().to_string()),
13769                kind: Some(khive_types::SubstrateKind::Entity),
13770                embedding_model: Some("model-b".to_string()),
13771                filter: None,
13772                backend_hints: None,
13773            })
13774            .await
13775            .unwrap();
13776        assert!(
13777            hits_b.is_empty(),
13778            "model-b vector store must be empty after rollback; got {hits_b:?}"
13779        );
13780    }
13781
13782    #[tokio::test]
13783    async fn create_entity_multi_model_reports_cleanup_failure_and_removes_all_vectors() {
13784        let rt = KhiveRuntime::memory().unwrap();
13785        let (provider_a, _ca) = ConstVecProvider::new("partial-multi-a", 4);
13786        let (provider_b, _cb) = ConstVecProvider::new("partial-multi-b", 4);
13787        rt.register_embedder(provider_a);
13788        rt.register_embedder(provider_b);
13789
13790        let ns = Namespace::parse("partial-persistence-multi").unwrap();
13791        let tok = NamespaceToken::for_namespace(ns.clone());
13792        let _cleanup_arm = arm_entity_compensation_fail_scoped(ns.as_str());
13793        arm_vector_fail_after(1);
13794
13795        let error = rt
13796            .create_entity(
13797                &tok,
13798                "concept",
13799                None,
13800                "multi-model partial persistence",
13801                Some("the second model fails after the first vector lands"),
13802                None,
13803                vec![],
13804            )
13805            .await
13806            .expect_err("second vector and compensation failures must fail create_entity");
13807
13808        let error_message = error.to_string();
13809        assert!(
13810            error_message.contains("injected vector insert failure"),
13811            "primary cause must be retained: {error_message}"
13812        );
13813        assert!(error_message.contains("injected compensation failure"));
13814
13815        let entities = rt.list_entities(&tok, None, None, 10, 0).await.unwrap();
13816        assert_eq!(
13817            entities.len(),
13818            1,
13819            "the failed row cleanup must leave residue"
13820        );
13821        let record_id = entities[0].id;
13822        assert!(error_message.contains(&record_id.to_string()));
13823
13824        for model in ["partial-multi-a", "partial-multi-b"] {
13825            assert_eq!(
13826                rt.vectors_for_model(&tok, model)
13827                    .unwrap()
13828                    .count()
13829                    .await
13830                    .unwrap(),
13831                0,
13832                "compensation must clean both the successful and failed model ({model})"
13833            );
13834        }
13835        assert!(
13836            rt.text(&tok)
13837                .unwrap()
13838                .get_document(ns.as_str(), record_id)
13839                .await
13840                .unwrap()
13841                .is_none(),
13842            "FTS compensation must succeed even when row cleanup fails"
13843        );
13844    }
13845
13846    // ADR-103 Amendment 2 regression: multi-model create_entity spawns one
13847    // embed task per configured model via tokio::spawn. Task-locals do not
13848    // cross a spawn boundary, so each spawned task must re-enter the
13849    // dispatch's usage scope explicitly for its embed to be counted.
13850    #[tokio::test]
13851    async fn create_entity_multi_model_counts_all_executed_embeds() {
13852        const DIMS: usize = 4;
13853
13854        let rt = KhiveRuntime::memory().unwrap();
13855        let (provider_a, _ca) = ConstVecProvider::new("usage-entity-model-a", DIMS);
13856        let (provider_b, _cb) = ConstVecProvider::new("usage-entity-model-b", DIMS);
13857        rt.register_embedder(provider_a);
13858        rt.register_embedder(provider_b);
13859
13860        let ns = Namespace::parse("usage-entity-multi").unwrap();
13861        let tok = NamespaceToken::for_namespace(ns.clone());
13862
13863        let ctx = crate::usage::UsageContext::new();
13864        crate::usage::scope(ctx.clone(), async {
13865            rt.create_entity(
13866                &tok,
13867                "concept",
13868                None,
13869                "usage-counted entity",
13870                Some("description so embed body is non-empty"),
13871                None,
13872                vec![],
13873            )
13874            .await
13875        })
13876        .await
13877        .expect("create_entity must succeed");
13878
13879        let snap = ctx.snapshot();
13880        assert_eq!(
13881            snap["embed_calls"], 2,
13882            "both configured models' executed embeds must be counted; got {snap:?}"
13883        );
13884    }
13885
13886    // Same regression for the note create path's multi-model embed fan-out.
13887    #[tokio::test]
13888    async fn create_note_multi_model_counts_all_executed_embeds() {
13889        const DIMS: usize = 4;
13890
13891        let rt = KhiveRuntime::memory().unwrap();
13892        let (provider_a, _ca) = ConstVecProvider::new("usage-note-model-a", DIMS);
13893        let (provider_b, _cb) = ConstVecProvider::new("usage-note-model-b", DIMS);
13894        rt.register_embedder(provider_a);
13895        rt.register_embedder(provider_b);
13896
13897        let ns = Namespace::parse("usage-note-multi").unwrap();
13898        let tok = NamespaceToken::for_namespace(ns.clone());
13899
13900        let ctx = crate::usage::UsageContext::new();
13901        crate::usage::scope(ctx.clone(), async {
13902            rt.create_note(
13903                &tok,
13904                "observation",
13905                None,
13906                "usage-counted note body",
13907                None,
13908                None,
13909                vec![],
13910            )
13911            .await
13912        })
13913        .await
13914        .expect("create_note must succeed");
13915
13916        let snap = ctx.snapshot();
13917        assert_eq!(
13918            snap["embed_calls"], 2,
13919            "both configured models' executed embeds must be counted; got {snap:?}"
13920        );
13921    }
13922
13923    // Embed calls are counted when issued, so detached completion after a
13924    // sibling failure cannot change the response's usage snapshot.
13925    #[tokio::test]
13926    async fn create_entity_multi_model_error_keeps_issued_usage_stable() {
13927        const DIMS: usize = 4;
13928
13929        let rt = KhiveRuntime::memory().unwrap();
13930        rt.register_embedder(FailFastProvider::new("usage-entity-fail-fast"));
13931        rt.register_embedder(SlowVecProvider::new("usage-entity-slow", DIMS));
13932
13933        let ns = Namespace::parse("usage-entity-error-drain").unwrap();
13934        let tok = NamespaceToken::for_namespace(ns.clone());
13935
13936        let ctx = crate::usage::UsageContext::new();
13937        let result = crate::usage::scope(ctx.clone(), async {
13938            rt.create_entity(
13939                &tok,
13940                "concept",
13941                None,
13942                "usage-drain entity",
13943                Some("description so embed body is non-empty"),
13944                None,
13945                vec![],
13946            )
13947            .await
13948        })
13949        .await;
13950
13951        assert!(
13952            result.is_err(),
13953            "one model failing must fail the whole create_entity call"
13954        );
13955
13956        let snap_immediately_after = ctx.snapshot();
13957        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
13958        let snap_after_delay = ctx.snapshot();
13959
13960        assert_eq!(
13961            snap_immediately_after, snap_after_delay,
13962            "embed completion after create_entity returns must not change issued \
13963             usage; got immediately_after={snap_immediately_after:?} \
13964             after_delay={snap_after_delay:?}"
13965        );
13966    }
13967
13968    // Same regression for the note create path's multi-model embed fan-out.
13969    #[tokio::test]
13970    async fn create_note_multi_model_error_keeps_issued_usage_stable() {
13971        const DIMS: usize = 4;
13972
13973        let rt = KhiveRuntime::memory().unwrap();
13974        rt.register_embedder(FailFastProvider::new("usage-note-fail-fast"));
13975        rt.register_embedder(SlowVecProvider::new("usage-note-slow", DIMS));
13976
13977        let ns = Namespace::parse("usage-note-error-drain").unwrap();
13978        let tok = NamespaceToken::for_namespace(ns.clone());
13979
13980        let ctx = crate::usage::UsageContext::new();
13981        let result = crate::usage::scope(ctx.clone(), async {
13982            rt.create_note(
13983                &tok,
13984                "observation",
13985                None,
13986                "usage-drain note body",
13987                None,
13988                None,
13989                vec![],
13990            )
13991            .await
13992        })
13993        .await;
13994
13995        assert!(
13996            result.is_err(),
13997            "one model failing must fail the whole create_note call"
13998        );
13999
14000        let snap_immediately_after = ctx.snapshot();
14001        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
14002        let snap_after_delay = ctx.snapshot();
14003
14004        assert_eq!(
14005            snap_immediately_after, snap_after_delay,
14006            "embed completion after create_note returns must not change issued \
14007             usage; got immediately_after={snap_immediately_after:?} \
14008             after_delay={snap_after_delay:?}"
14009        );
14010    }
14011
14012    // A fast provider failure must not wait on a slow sibling: the drain
14013    // aborts remaining embed tasks on the first error instead of awaiting
14014    // them to completion. The sibling here parks until a release that never
14015    // fires, so under await-to-completion this call would never return —
14016    // a bounded prompt error return is only reachable through the abort path.
14017    #[tokio::test]
14018    async fn create_entity_fast_embed_failure_does_not_wait_for_hung_sibling() {
14019        const DIMS: usize = 4;
14020
14021        let rt = KhiveRuntime::memory().unwrap();
14022        rt.register_embedder(FailFastProvider::new("latency-fail-fast"));
14023        let (parked, _release, _entered) = ParkedVecProvider::new("latency-parked", DIMS);
14024        rt.register_embedder(parked);
14025
14026        let ns = Namespace::parse("usage-entity-latency").unwrap();
14027        let tok = NamespaceToken::for_namespace(ns.clone());
14028
14029        let started = std::time::Instant::now();
14030        // Outer timeout so a regression to await-to-completion FAILS this test
14031        // within the bound instead of hanging the suite on the parked sibling.
14032        let result = tokio::time::timeout(
14033            std::time::Duration::from_secs(60),
14034            rt.create_entity(
14035                &tok,
14036                "concept",
14037                None,
14038                "latency entity",
14039                Some("description so embed body is non-empty"),
14040                None,
14041                vec![],
14042            ),
14043        )
14044        .await
14045        .expect("create_entity must return within the timeout — a hang means the abort path regressed to await-to-completion");
14046        let elapsed = started.elapsed();
14047
14048        assert!(
14049            result.is_err(),
14050            "one model failing must fail the whole create_entity call"
14051        );
14052        assert!(
14053            elapsed < std::time::Duration::from_secs(5),
14054            "a fast embed failure must return without waiting on the hung \
14055             sibling (which parks forever); took {elapsed:?}"
14056        );
14057    }
14058
14059    #[test]
14060    fn create_entity_embed_failure_returns_under_single_worker_saturation() {
14061        let (blocking, controls) = BlockingVecProvider::new("latency-blocking", 4);
14062        let fail_after_entry = FailFastProvider::after_signal(
14063            "latency-fail-after-entry",
14064            Arc::clone(&controls.entered),
14065        );
14066        let (result_tx, result_rx) = std::sync::mpsc::sync_channel(1);
14067
14068        let runtime_thread = std::thread::spawn(move || {
14069            let runtime = tokio::runtime::Builder::new_multi_thread()
14070                .worker_threads(1)
14071                .enable_all()
14072                .build()
14073                .expect("single-worker runtime must build");
14074            let rt = KhiveRuntime::memory().unwrap();
14075            rt.register_embedder(blocking);
14076            rt.register_embedder(fail_after_entry);
14077            let tok =
14078                NamespaceToken::for_namespace(Namespace::parse("embed-failure-latency").unwrap());
14079            let result = runtime.block_on(rt.create_entity(
14080                &tok,
14081                "concept",
14082                None,
14083                "blocked sibling entity",
14084                None,
14085                None,
14086                vec![],
14087            ));
14088            result_tx
14089                .send(result.map_err(|error| error.to_string()))
14090                .expect("test receiver must remain connected");
14091        });
14092
14093        let result = result_rx.recv_timeout(std::time::Duration::from_secs(3));
14094
14095        let (released, wake) = &*controls.release;
14096        *released.lock().expect("release lock must not be poisoned") = true;
14097        wake.notify_all();
14098        runtime_thread
14099            .join()
14100            .expect("single-worker runtime thread must join after release");
14101
14102        let error = result
14103            .expect("embed failure must return while synchronous inference remains blocked")
14104            .expect_err("one failed model must fail entity creation");
14105        assert!(error.contains("injected embed failure"));
14106    }
14107
14108    // Issued-at-dispatch accounting: an embed call that was handed to the
14109    // provider must count toward embed_calls even if the task is aborted
14110    // while parked on the provider await — the increment sits before the
14111    // await, so cancellation cannot undercount issued work.
14112    #[tokio::test]
14113    async fn aborted_embed_task_still_counts_issued_embed_call() {
14114        const DIMS: usize = 4;
14115
14116        let rt = std::sync::Arc::new(KhiveRuntime::memory().unwrap());
14117        let (parked, _release, entered) = ParkedVecProvider::new("abort-count-parked", DIMS);
14118        rt.register_embedder(parked);
14119
14120        let ctx = crate::usage::UsageContext::new();
14121        let task = {
14122            let rt = std::sync::Arc::clone(&rt);
14123            let ctx = ctx.clone();
14124            tokio::spawn(crate::usage::scope(ctx, async move {
14125                rt.embed_document_with_model("abort-count-parked", "abort count body")
14126                    .await
14127            }))
14128        };
14129
14130        // Wait until the parked service's embed was entered — the dispatch
14131        // point (and its count) is strictly before that entry.
14132        entered.notified().await;
14133        task.abort();
14134        let joined = task.await;
14135        assert!(
14136            joined.is_err() && joined.unwrap_err().is_cancelled(),
14137            "task must end as cancelled by the abort"
14138        );
14139
14140        assert_eq!(
14141            ctx.snapshot()["embed_calls"],
14142            1,
14143            "an issued embed call must be counted even when the task is \
14144             aborted while parked on the provider await"
14145        );
14146    }
14147
14148    // Note search must count its FTS5 execution the same way entity
14149    // hybrid_search does (retrieval.rs:435) — the search_notes FTS leg was
14150    // silently uncounted.
14151    #[tokio::test]
14152    async fn search_notes_counts_one_fts_pass() {
14153        let rt = KhiveRuntime::memory().unwrap();
14154        let ns = Namespace::parse("usage-note-search").unwrap();
14155        let tok = NamespaceToken::for_namespace(ns.clone());
14156
14157        rt.create_note(
14158            &tok,
14159            "observation",
14160            None,
14161            "usage counted note search body",
14162            None,
14163            None,
14164            vec![],
14165        )
14166        .await
14167        .expect("create_note must succeed");
14168
14169        let ctx = crate::usage::UsageContext::new();
14170        crate::usage::scope(ctx.clone(), async {
14171            rt.search_notes(&tok, "usage counted", None, 10, None, false, &[], None)
14172                .await
14173        })
14174        .await
14175        .expect("search_notes must succeed");
14176
14177        let snap = ctx.snapshot();
14178        assert!(
14179            snap["fts_passes"].as_u64().unwrap_or(0) >= 1,
14180            "note search FTS execution must count fts_passes; got {snap:?}"
14181        );
14182    }
14183
14184    // update_entity fans out to ALL registered models.
14185    // After create + update with a changed description, both model-a and model-b
14186    // vector stores hold a row for the entity id.
14187    #[tokio::test]
14188    async fn update_entity_fans_out_to_all_registered_models() {
14189        const DIMS: usize = 4;
14190
14191        let rt = KhiveRuntime::memory().unwrap();
14192        let (provider_a, _ca) = ConstVecProvider::new("embed-a", DIMS);
14193        let (provider_b, _cb) = ConstVecProvider::new("embed-b", DIMS);
14194        rt.register_embedder(provider_a);
14195        rt.register_embedder(provider_b);
14196
14197        let ns = Namespace::parse("update-entity-fanout").unwrap();
14198        let tok = NamespaceToken::for_namespace(ns.clone());
14199
14200        let entity = rt
14201            .create_entity(
14202                &tok,
14203                "concept",
14204                None,
14205                "FanOutEntity",
14206                Some("initial description"),
14207                None,
14208                vec![],
14209            )
14210            .await
14211            .expect("create_entity must succeed");
14212
14213        use crate::curation::EntityPatch;
14214        let patch = EntityPatch {
14215            description: Some(Some("updated description after fan-out fix".to_string())),
14216            ..Default::default()
14217        };
14218        rt.update_entity(&tok, entity.id, patch)
14219            .await
14220            .expect("update_entity must succeed");
14221
14222        use khive_storage::types::VectorSearchRequest;
14223        let query_vec = vec![1.0_f32; DIMS];
14224
14225        let hits_a = rt
14226            .vectors_for_model(&tok, "embed-a")
14227            .unwrap()
14228            .search(VectorSearchRequest {
14229                query_vectors: vec![query_vec.clone()],
14230                top_k: 10,
14231                namespace: Some(ns.as_str().to_string()),
14232                kind: Some(khive_types::SubstrateKind::Entity),
14233                embedding_model: Some("embed-a".to_string()),
14234                filter: None,
14235                backend_hints: None,
14236            })
14237            .await
14238            .unwrap();
14239        assert!(
14240            hits_a.iter().any(|h| h.subject_id == entity.id),
14241            "embed-a must hold a vector for the entity after update; got {hits_a:?}"
14242        );
14243
14244        let hits_b = rt
14245            .vectors_for_model(&tok, "embed-b")
14246            .unwrap()
14247            .search(VectorSearchRequest {
14248                query_vectors: vec![query_vec],
14249                top_k: 10,
14250                namespace: Some(ns.as_str().to_string()),
14251                kind: Some(khive_types::SubstrateKind::Entity),
14252                embedding_model: Some("embed-b".to_string()),
14253                filter: None,
14254                backend_hints: None,
14255            })
14256            .await
14257            .unwrap();
14258        assert!(
14259            hits_b.iter().any(|h| h.subject_id == entity.id),
14260            "embed-b must hold a vector for the entity after update; got {hits_b:?}"
14261        );
14262    }
14263
14264    // update_note fans out to ALL registered models.
14265    // After create + update with changed content, both embed-a and embed-b
14266    // vector stores hold a row for the note id.
14267    #[tokio::test]
14268    async fn update_note_fans_out_to_all_registered_models() {
14269        const DIMS: usize = 4;
14270
14271        let rt = KhiveRuntime::memory().unwrap();
14272        let (provider_a, _ca) = ConstVecProvider::new("embed-a", DIMS);
14273        let (provider_b, _cb) = ConstVecProvider::new("embed-b", DIMS);
14274        rt.register_embedder(provider_a);
14275        rt.register_embedder(provider_b);
14276
14277        let ns = Namespace::parse("update-note-fanout").unwrap();
14278        let tok = NamespaceToken::for_namespace(ns.clone());
14279
14280        let note = rt
14281            .create_note(
14282                &tok,
14283                "observation",
14284                None,
14285                "initial note content for fan-out test",
14286                None,
14287                None,
14288                vec![],
14289            )
14290            .await
14291            .expect("create_note must succeed");
14292
14293        use crate::curation::NotePatch;
14294        let patch = NotePatch {
14295            content: Some("updated content after fan-out fix".to_string()),
14296            ..Default::default()
14297        };
14298        rt.update_note(&tok, note.id, patch)
14299            .await
14300            .expect("update_note must succeed");
14301
14302        use khive_storage::types::VectorSearchRequest;
14303        let query_vec = vec![1.0_f32; DIMS];
14304
14305        let hits_a = rt
14306            .vectors_for_model(&tok, "embed-a")
14307            .unwrap()
14308            .search(VectorSearchRequest {
14309                query_vectors: vec![query_vec.clone()],
14310                top_k: 10,
14311                namespace: Some(ns.as_str().to_string()),
14312                kind: Some(khive_types::SubstrateKind::Note),
14313                embedding_model: Some("embed-a".to_string()),
14314                filter: None,
14315                backend_hints: None,
14316            })
14317            .await
14318            .unwrap();
14319        assert!(
14320            hits_a.iter().any(|h| h.subject_id == note.id),
14321            "embed-a must hold a vector for the note after update; got {hits_a:?}"
14322        );
14323
14324        let hits_b = rt
14325            .vectors_for_model(&tok, "embed-b")
14326            .unwrap()
14327            .search(VectorSearchRequest {
14328                query_vectors: vec![query_vec],
14329                top_k: 10,
14330                namespace: Some(ns.as_str().to_string()),
14331                kind: Some(khive_types::SubstrateKind::Note),
14332                embedding_model: Some("embed-b".to_string()),
14333                filter: None,
14334                backend_hints: None,
14335            })
14336            .await
14337            .unwrap();
14338        assert!(
14339            hits_b.iter().any(|h| h.subject_id == note.id),
14340            "embed-b must hold a vector for the note after update; got {hits_b:?}"
14341        );
14342    }
14343
14344    // ── By-ID ops must not filter by namespace ──────────────────────────────
14345    //
14346    // A namespace-gated by-ID op on an entity stamped "foreign" from a "local"
14347    // token would return NotFound, causing gtd.complete / update blindness.
14348    // UUID is globally unique; by-ID ops find the record regardless of
14349    // which namespace the caller's token carries.
14350
14351    #[tokio::test]
14352    async fn get_entity_cross_namespace_succeeds() {
14353        let rt = rt();
14354        // Create under "lambda:leo".
14355        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
14356        let entity = rt
14357            .create_entity(&leo_tok, "concept", None, "Peer-Entity", None, None, vec![])
14358            .await
14359            .unwrap();
14360        assert_eq!(entity.namespace, "lambda:leo");
14361
14362        // Read from "local" — must succeed (no namespace gate on by-ID get).
14363        let local_tok = NamespaceToken::local();
14364        let fetched = rt.get_entity(&local_tok, entity.id).await;
14365        assert!(
14366            fetched.is_ok(),
14367            "get_entity from local token must find lambda:leo entity; got {:?}",
14368            fetched
14369        );
14370        assert_eq!(fetched.unwrap().id, entity.id);
14371    }
14372
14373    #[tokio::test]
14374    async fn update_entity_cross_namespace_succeeds() {
14375        let rt = rt();
14376        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
14377        let entity = rt
14378            .create_entity(
14379                &leo_tok,
14380                "concept",
14381                None,
14382                "Peer-Entity-Update",
14383                None,
14384                None,
14385                vec![],
14386            )
14387            .await
14388            .unwrap();
14389
14390        // Update from "local" token — must not error with NotFound.
14391        let local_tok = NamespaceToken::local();
14392        let patch = crate::curation::EntityPatch {
14393            name: Some("Peer-Entity-Updated".to_string()),
14394            ..Default::default()
14395        };
14396        let result = rt.update_entity(&local_tok, entity.id, patch).await;
14397        assert!(
14398            result.is_ok(),
14399            "update_entity from local token must succeed on lambda:leo entity; got {:?}",
14400            result
14401        );
14402        assert_eq!(result.unwrap().name, "Peer-Entity-Updated");
14403    }
14404
14405    #[tokio::test]
14406    async fn delete_entity_cross_namespace_succeeds() {
14407        let rt = rt();
14408        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
14409        let entity = rt
14410            .create_entity(
14411                &leo_tok,
14412                "concept",
14413                None,
14414                "Peer-Entity-Delete",
14415                None,
14416                None,
14417                vec![],
14418            )
14419            .await
14420            .unwrap();
14421
14422        // Delete from "local" token — must succeed.
14423        let local_tok = NamespaceToken::local();
14424        let deleted = rt.delete_entity(&local_tok, entity.id, false).await;
14425        assert!(
14426            deleted.is_ok(),
14427            "delete_entity from local token must succeed on lambda:leo entity; got {:?}",
14428            deleted
14429        );
14430        assert!(
14431            deleted.unwrap(),
14432            "delete must return true when entity existed"
14433        );
14434    }
14435
14436    #[tokio::test]
14437    async fn namespace_preserved_on_entity_after_cross_namespace_get() {
14438        let rt = rt();
14439        let leo_tok = NamespaceToken::for_namespace(Namespace::parse("lambda:leo").unwrap());
14440        let entity = rt
14441            .create_entity(
14442                &leo_tok,
14443                "concept",
14444                None,
14445                "NS-Preserved",
14446                None,
14447                None,
14448                vec![],
14449            )
14450            .await
14451            .unwrap();
14452
14453        // The namespace column on the fetched record must still say "lambda:leo".
14454        let local_tok = NamespaceToken::local();
14455        let fetched = rt.get_entity(&local_tok, entity.id).await.unwrap();
14456        assert_eq!(
14457            fetched.namespace, "lambda:leo",
14458            "namespace column must be preserved; not overwritten with caller's namespace"
14459        );
14460    }
14461
14462    // ── PackByIdResolver unit tests ──────────────────────────────────────────
14463
14464    use crate::pack::PackByIdResolver;
14465    use tokio::sync::Mutex as TokioMutex;
14466
14467    #[derive(Debug, Default)]
14468    struct MockResolverState {
14469        owned: Vec<Uuid>,
14470        deleted: Vec<Uuid>,
14471        delete_calls: Vec<(Uuid, bool)>,
14472    }
14473
14474    struct MockPackResolver(TokioMutex<MockResolverState>);
14475
14476    impl MockPackResolver {
14477        fn new() -> Self {
14478            Self(TokioMutex::new(MockResolverState::default()))
14479        }
14480    }
14481
14482    #[async_trait::async_trait]
14483    impl crate::pack::PackByIdResolver for MockPackResolver {
14484        async fn resolve_by_id(&self, id: Uuid) -> Result<Option<Resolved>, RuntimeError> {
14485            let state = self.0.lock().await;
14486            if state.owned.contains(&id) && !state.deleted.contains(&id) {
14487                Ok(Some(Resolved::PackRecord {
14488                    pack: "mock".into(),
14489                    kind: "widget".into(),
14490                    data: serde_json::json!({ "id": id.to_string(), "name": "test-widget" }),
14491                }))
14492            } else {
14493                Ok(None)
14494            }
14495        }
14496
14497        async fn resolve_by_id_including_deleted(
14498            &self,
14499            id: Uuid,
14500        ) -> Result<Option<Resolved>, RuntimeError> {
14501            let state = self.0.lock().await;
14502            if state.owned.contains(&id) {
14503                Ok(Some(Resolved::PackRecord {
14504                    pack: "mock".into(),
14505                    kind: "widget".into(),
14506                    data: serde_json::json!({ "id": id.to_string(), "name": "test-widget" }),
14507                }))
14508            } else {
14509                Ok(None)
14510            }
14511        }
14512
14513        async fn delete_by_id(
14514            &self,
14515            id: Uuid,
14516            hard: bool,
14517        ) -> Result<serde_json::Value, RuntimeError> {
14518            let mut state = self.0.lock().await;
14519            if !state.owned.contains(&id) {
14520                return Err(RuntimeError::NotFound(format!(
14521                    "mock widget not found: {id}"
14522                )));
14523            }
14524            state.delete_calls.push((id, hard));
14525            if hard {
14526                state.owned.retain(|&x| x != id);
14527                state.deleted.retain(|&x| x != id);
14528            } else {
14529                state.deleted.push(id);
14530            }
14531            Ok(
14532                serde_json::json!({ "deleted": true, "id": id.to_string(), "kind": "widget", "hard": hard }),
14533            )
14534        }
14535    }
14536
14537    fn registry_with_mock_resolver(
14538        rt: KhiveRuntime,
14539        resolver: Box<dyn crate::pack::PackByIdResolver>,
14540    ) -> crate::VerbRegistry {
14541        use crate::pack::{PackRuntime, VerbRegistryBuilder};
14542        use khive_types::{HandlerDef, VerbCategory, Visibility};
14543
14544        static MINIMAL_HANDLERS: &[HandlerDef] = &[HandlerDef {
14545            name: "minimal.noop",
14546            description: "noop",
14547            visibility: Visibility::Verb,
14548            category: VerbCategory::Commissive,
14549            params: &[],
14550        }];
14551
14552        struct MinimalPack;
14553        impl khive_types::Pack for MinimalPack {
14554            const NAME: &'static str = "minimal";
14555            const NOTE_KINDS: &'static [&'static str] = &[];
14556            const ENTITY_KINDS: &'static [&'static str] = &[];
14557            const HANDLERS: &'static [HandlerDef] = MINIMAL_HANDLERS;
14558        }
14559        #[async_trait::async_trait]
14560        impl PackRuntime for MinimalPack {
14561            fn name(&self) -> &str {
14562                "minimal"
14563            }
14564            fn note_kinds(&self) -> &'static [&'static str] {
14565                &[]
14566            }
14567            fn entity_kinds(&self) -> &'static [&'static str] {
14568                &[]
14569            }
14570            fn handlers(&self) -> &'static [HandlerDef] {
14571                MINIMAL_HANDLERS
14572            }
14573            async fn dispatch(
14574                &self,
14575                _verb: &str,
14576                _params: serde_json::Value,
14577                _registry: &crate::VerbRegistry,
14578                _token: &NamespaceToken,
14579            ) -> Result<serde_json::Value, RuntimeError> {
14580                Err(RuntimeError::InvalidInput("stub".into()))
14581            }
14582        }
14583
14584        let _ = rt;
14585        let mut builder = VerbRegistryBuilder::new();
14586        builder.register(MinimalPack);
14587        builder.register_resolver("mock", resolver);
14588        builder.build().expect("registry build failed")
14589    }
14590
14591    #[tokio::test]
14592    async fn pack_record_resolved_pair_returns_none() {
14593        let pr = Resolved::PackRecord {
14594            pack: "knowledge".into(),
14595            kind: "atom".into(),
14596            data: serde_json::json!({}),
14597        };
14598        assert!(
14599            resolved_pair(Some(&pr)).is_none(),
14600            "PackRecord must not be a valid edge endpoint"
14601        );
14602    }
14603
14604    #[test]
14605    fn resolved_pair_surfaces_entity_type() {
14606        let e = Resolved::Entity(
14607            Entity::new("mathlib", "concept", "Nat.add_comm").with_entity_type(Some("theorem")),
14608        );
14609        assert_eq!(
14610            resolved_pair(Some(&e)),
14611            Some(("entity", "concept", Some("theorem"))),
14612            "entity_type subtype must be surfaced alongside base kind"
14613        );
14614    }
14615
14616    #[test]
14617    fn endpoint_of_type_matches_subtype_not_base_kind() {
14618        // An entity whose base kind is "concept" and subtype is "theorem".
14619        let kind = "concept";
14620        let et = Some("theorem");
14621
14622        // EntityOfType matches only when BOTH base kind and subtype match.
14623        assert!(endpoint_matches(
14624            &EndpointKind::EntityOfType {
14625                kind: "concept",
14626                entity_type: "theorem",
14627            },
14628            "entity",
14629            kind,
14630            et
14631        ));
14632        assert!(!endpoint_matches(
14633            &EndpointKind::EntityOfType {
14634                kind: "concept",
14635                entity_type: "definition",
14636            },
14637            "entity",
14638            kind,
14639            et
14640        ));
14641
14642        // The silently-inert trap: EntityOfKind sees only the BASE
14643        // kind, so EntityOfKind("theorem") never matches a concept/theorem.
14644        assert!(!endpoint_matches(
14645            &EndpointKind::EntityOfKind("theorem"),
14646            "entity",
14647            kind,
14648            et
14649        ));
14650        // EntityOfKind still matches the base kind.
14651        assert!(endpoint_matches(
14652            &EndpointKind::EntityOfKind("concept"),
14653            "entity",
14654            kind,
14655            et
14656        ));
14657
14658        // EntityOfType rejects non-entity substrates and entities with no subtype.
14659        assert!(!endpoint_matches(
14660            &EndpointKind::EntityOfType {
14661                kind: "concept",
14662                entity_type: "theorem",
14663            },
14664            "note",
14665            "task",
14666            None
14667        ));
14668        assert!(!endpoint_matches(
14669            &EndpointKind::EntityOfType {
14670                kind: "concept",
14671                entity_type: "theorem",
14672            },
14673            "entity",
14674            kind,
14675            None
14676        ));
14677    }
14678
14679    #[test]
14680    fn endpoint_of_type_requires_base_kind_match() {
14681        // Regression: an entity with entity_type="theorem" but base kind != "concept"
14682        // must NOT match a formal concept rule. This was the exact bypass:
14683        // before the fix, EntityOfType("theorem") ignored the base kind entirely.
14684        let wrong_base_kind = "project"; // not "concept"
14685        let et = Some("theorem");
14686
14687        // The formal rule requires kind="concept". A "project" entity with
14688        // entity_type="theorem" must not match — even though the subtype string
14689        // matches — because the base kind differs.
14690        assert!(
14691            !endpoint_matches(
14692                &EndpointKind::EntityOfType {
14693                    kind: "concept",
14694                    entity_type: "theorem",
14695                },
14696                "entity",
14697                wrong_base_kind,
14698                et
14699            ),
14700            "EntityOfType must reject an entity whose base kind != rule.kind \
14701             even when entity_type matches — the pre-fix bug admitted this"
14702        );
14703
14704        // The correct concept entity with the same subtype still matches.
14705        assert!(endpoint_matches(
14706            &EndpointKind::EntityOfType {
14707                kind: "concept",
14708                entity_type: "theorem",
14709            },
14710            "entity",
14711            "concept",
14712            et
14713        ));
14714    }
14715
14716    #[tokio::test]
14717    async fn registry_resolvers_accessor_returns_registered() {
14718        let resolver = Box::new(MockPackResolver::new());
14719        let registry = registry_with_mock_resolver(rt(), resolver);
14720        assert_eq!(registry.resolvers().len(), 1);
14721        assert_eq!(registry.resolvers()[0].0, "mock");
14722    }
14723
14724    #[tokio::test]
14725    async fn mock_resolver_resolve_by_id_returns_pack_record() {
14726        let id = Uuid::new_v4();
14727        let resolver: Box<dyn PackByIdResolver> = Box::new(MockPackResolver::new());
14728        // We need interior access — downcast first, then use via trait.
14729        let inner = MockPackResolver::new();
14730        inner.0.lock().await.owned.push(id);
14731        let result: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
14732        match result.unwrap() {
14733            Some(Resolved::PackRecord { pack, kind, data }) => {
14734                assert_eq!(pack, "mock");
14735                assert_eq!(kind, "widget");
14736                assert_eq!(data["id"].as_str().unwrap(), id.to_string());
14737            }
14738            other => panic!("expected PackRecord, got {:?}", other),
14739        }
14740        let _ = resolver;
14741    }
14742
14743    #[tokio::test]
14744    async fn mock_resolver_resolve_unknown_uuid_returns_none() {
14745        let inner = MockPackResolver::new();
14746        let id = Uuid::new_v4();
14747        let result: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
14748        assert!(result.unwrap().is_none());
14749    }
14750
14751    #[tokio::test]
14752    async fn mock_resolver_delete_soft_records_call() {
14753        let id = Uuid::new_v4();
14754        let inner = MockPackResolver::new();
14755        inner.0.lock().await.owned.push(id);
14756
14757        let result: Result<serde_json::Value, RuntimeError> = inner.delete_by_id(id, false).await;
14758        let result = result.unwrap();
14759        assert_eq!(result["deleted"], serde_json::json!(true));
14760        assert_eq!(result["hard"], serde_json::json!(false));
14761
14762        // After soft-delete: resolve_by_id returns None, but including_deleted returns Some.
14763        let live: Result<Option<Resolved>, RuntimeError> = inner.resolve_by_id(id).await;
14764        assert!(live.unwrap().is_none());
14765        let incl: Result<Option<Resolved>, RuntimeError> =
14766            inner.resolve_by_id_including_deleted(id).await;
14767        assert!(incl.unwrap().is_some());
14768    }
14769
14770    #[tokio::test]
14771    async fn mock_resolver_delete_hard_removes_record() {
14772        let id = Uuid::new_v4();
14773        let inner = MockPackResolver::new();
14774        inner.0.lock().await.owned.push(id);
14775
14776        let result: Result<serde_json::Value, RuntimeError> = inner.delete_by_id(id, true).await;
14777        assert_eq!(result.unwrap()["hard"], serde_json::json!(true));
14778
14779        // After hard-delete: neither probe finds the record.
14780        let incl: Result<Option<Resolved>, RuntimeError> =
14781            inner.resolve_by_id_including_deleted(id).await;
14782        assert!(incl.unwrap().is_none());
14783    }
14784
14785    #[tokio::test]
14786    async fn pack_record_not_valid_context_entity() {
14787        // Validates the GTD handler arm compiles and returns InvalidInput.
14788        // We exercise the match logic directly by constructing a PackRecord Resolved.
14789        let pr = Resolved::PackRecord {
14790            pack: "knowledge".into(),
14791            kind: "atom".into(),
14792            data: serde_json::json!({}),
14793        };
14794        // The match in GTD handlers.rs now handles PackRecord → InvalidInput.
14795        // We can verify the enum variant is reachable.
14796        assert!(matches!(pr, Resolved::PackRecord { .. }));
14797    }
14798
14799    // ── Batched enrich_neighbor_hits / enrich_path_nodes ────────────────────
14800
14801    fn neighbor_hit(node_id: Uuid) -> NeighborHit {
14802        NeighborHit {
14803            node_id,
14804            edge_id: Uuid::new_v4(),
14805            relation: EdgeRelation::Extends,
14806            weight: 1.0,
14807            name: None,
14808            kind: None,
14809            entity_type: None,
14810        }
14811    }
14812
14813    fn path_node(node_id: Uuid, depth: usize) -> PathNode {
14814        PathNode {
14815            node_id,
14816            via_edge: None,
14817            depth,
14818            name: None,
14819            kind: None,
14820            properties: None,
14821            weight: 0.0,
14822        }
14823    }
14824
14825    /// merge_traversal_paths_by_root: three namespaces each contribute the
14826    /// same root plus 2 distinct non-root nodes (each namespace already at
14827    /// its own `limit`, matching the per-namespace SQL-layer cap). The
14828    /// union across namespaces is 6 distinct non-root nodes; the merge must
14829    /// re-enforce `limit` on that union rather than passing it through.
14830    #[test]
14831    fn merge_traversal_paths_reenforces_limit_across_namespaces() {
14832        let root = Uuid::new_v4();
14833        let path_for = |n: usize| GraphPath {
14834            root_id: root,
14835            nodes: (0..n).map(|_| path_node(Uuid::new_v4(), 1)).collect(),
14836            total_weight: 1.0,
14837        };
14838
14839        let paths = vec![path_for(2), path_for(2), path_for(2)];
14840        let merged = merge_traversal_paths_by_root(paths, Some(2));
14841
14842        assert_eq!(merged.len(), 1);
14843        assert_eq!(
14844            merged[0].nodes.len(),
14845            2,
14846            "merge must re-enforce limit=2 on the unioned nodes, got {:?}",
14847            merged[0].nodes
14848        );
14849    }
14850
14851    /// merge_traversal_paths_by_root: a node reachable at different depths
14852    /// via two namespaces must report its shallowest depth and the
14853    /// `via_edge` that produced that depth, and the merged node order must
14854    /// be BFS (ascending depth) rather than the concatenation order of the
14855    /// per-namespace inputs.
14856    #[test]
14857    fn merge_traversal_paths_keeps_shortest_depth_and_bfs_order() {
14858        let root = Uuid::new_v4();
14859        let shared = Uuid::new_v4();
14860        let far_node = Uuid::new_v4();
14861        let deep_edge = Uuid::new_v4();
14862        let shallow_edge = Uuid::new_v4();
14863
14864        // Namespace processed first: an unrelated node at depth 1, and the
14865        // shared node reached the long way, at depth 4.
14866        let ns_first = GraphPath {
14867            root_id: root,
14868            nodes: vec![
14869                path_node(far_node, 1),
14870                PathNode {
14871                    node_id: shared,
14872                    via_edge: Some(deep_edge),
14873                    depth: 4,
14874                    name: None,
14875                    kind: None,
14876                    properties: None,
14877                    weight: 0.0,
14878                },
14879            ],
14880            total_weight: 1.0,
14881        };
14882        // Namespace processed second: the same shared node, reached at depth 2.
14883        let ns_second = GraphPath {
14884            root_id: root,
14885            nodes: vec![PathNode {
14886                node_id: shared,
14887                via_edge: Some(shallow_edge),
14888                depth: 2,
14889                name: None,
14890                kind: None,
14891                properties: None,
14892                weight: 0.0,
14893            }],
14894            total_weight: 1.0,
14895        };
14896
14897        let merged = merge_traversal_paths_by_root(vec![ns_first, ns_second], None);
14898
14899        assert_eq!(merged.len(), 1);
14900        let nodes = &merged[0].nodes;
14901        assert!(
14902            nodes.windows(2).all(|w| w[0].depth <= w[1].depth),
14903            "merged nodes must be in BFS (ascending depth) order, got {:?}",
14904            nodes
14905                .iter()
14906                .map(|n| (n.node_id, n.depth))
14907                .collect::<Vec<_>>()
14908        );
14909        let shared_node = nodes
14910            .iter()
14911            .find(|n| n.node_id == shared)
14912            .expect("shared node must survive the merge");
14913        assert_eq!(
14914            shared_node.depth, 2,
14915            "shared node must report its shortest depth across namespaces"
14916        );
14917        assert_eq!(
14918            shared_node.via_edge,
14919            Some(shallow_edge),
14920            "shared node must carry the via_edge that produced the shortest path"
14921        );
14922    }
14923
14924    /// merge_traversal_paths_by_root: `total_weight` must describe the nodes
14925    /// the caller is actually handed. The heaviest node here sits deepest, so
14926    /// re-applying `limit` to the merged union drops it — and the reported
14927    /// weight has to drop with it rather than keep quoting a node that was
14928    /// screened out.
14929    #[test]
14930    fn merge_traversal_paths_total_weight_drops_with_the_node_it_described() {
14931        let root = Uuid::new_v4();
14932        let weighted = |depth: usize, weight: f64| PathNode {
14933            node_id: Uuid::new_v4(),
14934            via_edge: None,
14935            depth,
14936            name: None,
14937            kind: None,
14938            properties: None,
14939            weight,
14940        };
14941
14942        let path = GraphPath {
14943            root_id: root,
14944            nodes: vec![weighted(1, 0.5), weighted(1, 0.4), weighted(2, 9.0)],
14945            total_weight: 9.0,
14946        };
14947
14948        let merged = merge_traversal_paths_by_root(vec![path], Some(2));
14949
14950        assert_eq!(merged.len(), 1);
14951        assert_eq!(
14952            merged[0].nodes.len(),
14953            2,
14954            "limit=2 must drop the depth-2 node"
14955        );
14956        assert_eq!(
14957            merged[0].total_weight, 0.5,
14958            "total_weight must be the max over surviving nodes, not the 9.0 \
14959             carried by the node the limit removed"
14960        );
14961    }
14962
14963    /// enrich_neighbor_hits: entity hit resolved, note hit resolved with
14964    /// name-fallback to "[kind]", bogus UUID left as None.  Order preserved.
14965    #[tokio::test]
14966    async fn enrich_neighbor_hits_batch_entity_note_and_bogus() {
14967        let rt = rt();
14968        let tok = NamespaceToken::local();
14969
14970        // Create an entity neighbor.
14971        let entity = rt
14972            .create_entity(&tok, "concept", None, "MyEntity", None, None, vec![])
14973            .await
14974            .unwrap();
14975
14976        // Nameless note — name falls back to "[observation]".
14977        let note = rt
14978            .create_note(&tok, "observation", None, "body", Some(0.5), None, vec![])
14979            .await
14980            .unwrap();
14981
14982        let bogus_id = Uuid::new_v4();
14983
14984        let mut hits = vec![
14985            neighbor_hit(entity.id),
14986            neighbor_hit(note.id),
14987            neighbor_hit(bogus_id),
14988        ];
14989
14990        rt.enrich_neighbor_hits(&tok, &mut hits).await;
14991
14992        assert_eq!(hits[0].name.as_deref(), Some("MyEntity"));
14993        assert_eq!(hits[0].kind.as_deref(), Some("concept"));
14994
14995        assert_eq!(hits[1].name.as_deref(), Some("[observation]"));
14996        assert_eq!(hits[1].kind.as_deref(), Some("observation"));
14997
14998        assert!(hits[2].name.is_none());
14999        assert!(hits[2].kind.is_none());
15000    }
15001
15002    /// enrich_neighbor_hits: note with a non-empty name uses the actual name.
15003    #[tokio::test]
15004    async fn enrich_neighbor_hits_note_with_name_uses_name() {
15005        let rt = rt();
15006        let tok = NamespaceToken::local();
15007
15008        let note = rt
15009            .create_note(
15010                &tok,
15011                "insight",
15012                Some("NoteTitle"),
15013                "body",
15014                Some(0.5),
15015                None,
15016                vec![],
15017            )
15018            .await
15019            .unwrap();
15020
15021        let mut hits = vec![neighbor_hit(note.id)];
15022        rt.enrich_neighbor_hits(&tok, &mut hits).await;
15023
15024        assert_eq!(hits[0].name.as_deref(), Some("NoteTitle"));
15025        assert_eq!(hits[0].kind.as_deref(), Some("insight"));
15026    }
15027
15028    /// enrich_path_nodes: two paths sharing a repeated node_id; each node
15029    /// enriched from a single batch; unresolved node stays None.
15030    #[tokio::test]
15031    async fn enrich_path_nodes_batch_dedup_and_unresolved() {
15032        let rt = rt();
15033        let tok = NamespaceToken::local();
15034
15035        let ea = rt
15036            .create_entity(&tok, "concept", None, "Alpha", None, None, vec![])
15037            .await
15038            .unwrap();
15039        let eb = rt
15040            .create_entity(&tok, "document", None, "Beta", None, None, vec![])
15041            .await
15042            .unwrap();
15043        let bogus_id = Uuid::new_v4();
15044
15045        // Path 1: ea → eb → bogus  |  Path 2: eb → ea  (shared nodes, reversed)
15046        let mut paths = vec![
15047            GraphPath {
15048                root_id: ea.id,
15049                nodes: vec![
15050                    path_node(ea.id, 0),
15051                    path_node(eb.id, 1),
15052                    path_node(bogus_id, 2),
15053                ],
15054                total_weight: 1.0,
15055            },
15056            GraphPath {
15057                root_id: eb.id,
15058                nodes: vec![path_node(eb.id, 0), path_node(ea.id, 1)],
15059                total_weight: 1.0,
15060            },
15061        ];
15062
15063        rt.enrich_path_nodes(&tok, &mut paths, false).await;
15064
15065        assert_eq!(paths[0].nodes[0].name.as_deref(), Some("Alpha"));
15066        assert_eq!(paths[0].nodes[0].kind.as_deref(), Some("concept"));
15067        assert_eq!(paths[0].nodes[1].name.as_deref(), Some("Beta"));
15068        assert_eq!(paths[0].nodes[1].kind.as_deref(), Some("document"));
15069        assert!(paths[0].nodes[2].name.is_none());
15070        assert!(paths[0].nodes[2].kind.is_none());
15071
15072        // Shared nodes resolve from the same HashMap — order within each path is preserved.
15073        assert_eq!(paths[1].nodes[0].name.as_deref(), Some("Beta"));
15074        assert_eq!(paths[1].nodes[0].kind.as_deref(), Some("document"));
15075        assert_eq!(paths[1].nodes[1].name.as_deref(), Some("Alpha"));
15076        assert_eq!(paths[1].nodes[1].kind.as_deref(), Some("concept"));
15077    }
15078
15079    /// enrich_neighbor_hits and enrich_path_nodes must resolve entities whose
15080    /// namespace is in the token's extra-visible set (not only the primary).
15081    ///
15082    /// Regression: the old `get_entities_by_ids`
15083    /// call left `filter.namespaces` unset, which collapses to
15084    /// `namespace = primary` in `build_entity_where`.  Graph expansion already
15085    /// crosses visible namespaces, so enrichment must match that scope.
15086    #[tokio::test]
15087    async fn enrich_resolves_entities_in_extra_visible_namespace() {
15088        let rt = KhiveRuntime::memory().unwrap();
15089
15090        let ns_a = Namespace::parse("enrich-ns-a").unwrap();
15091        let ns_b = Namespace::parse("enrich-ns-b").unwrap();
15092
15093        let tok_b = rt.authorize(ns_b.clone()).unwrap();
15094
15095        // Entity lives in ns-b.
15096        let entity_b = rt
15097            .create_entity(&tok_b, "concept", None, "EntityInB", None, None, vec![])
15098            .await
15099            .unwrap();
15100        assert_eq!(entity_b.namespace, "enrich-ns-b");
15101
15102        // Token whose primary is ns-a but ns-b is in the visible set.
15103        let vis_tok = rt
15104            .authorize_with_visibility(ns_a.clone(), vec![ns_b.clone()])
15105            .unwrap();
15106
15107        // ── neighbor hits ──────────────────────────────────────────────────
15108        let mut hits = vec![neighbor_hit(entity_b.id)];
15109        rt.enrich_neighbor_hits(&vis_tok, &mut hits).await;
15110
15111        assert_eq!(
15112            hits[0].name.as_deref(),
15113            Some("EntityInB"),
15114            "entity in extra-visible ns must be enriched by enrich_neighbor_hits"
15115        );
15116        assert_eq!(hits[0].kind.as_deref(), Some("concept"));
15117
15118        // ── path nodes ─────────────────────────────────────────────────────
15119        let mut paths = vec![GraphPath {
15120            root_id: entity_b.id,
15121            nodes: vec![path_node(entity_b.id, 0)],
15122            total_weight: 1.0,
15123        }];
15124        rt.enrich_path_nodes(&vis_tok, &mut paths, false).await;
15125
15126        assert_eq!(
15127            paths[0].nodes[0].name.as_deref(),
15128            Some("EntityInB"),
15129            "entity in extra-visible ns must be enriched by enrich_path_nodes"
15130        );
15131        assert_eq!(paths[0].nodes[0].kind.as_deref(), Some("concept"));
15132    }
15133
15134    /// enrich_neighbor_hits populates entity_type from the already-fetched entity
15135    /// batch when the entity has a non-null entity_type.  Entities without one and
15136    /// note nodes leave entity_type as None.
15137    #[tokio::test]
15138    async fn enrich_neighbor_hits_populates_entity_type() {
15139        let rt = rt();
15140        let tok = NamespaceToken::local();
15141
15142        let props = serde_json::json!({"domain": "attention"});
15143        let entity = rt
15144            .create_entity(
15145                &tok,
15146                "concept",
15147                Some("algorithm"),
15148                "FlashAttn",
15149                None,
15150                Some(props),
15151                vec![],
15152            )
15153            .await
15154            .unwrap();
15155
15156        let entity_no_type = rt
15157            .create_entity(&tok, "concept", None, "PlainConcept", None, None, vec![])
15158            .await
15159            .unwrap();
15160
15161        let mut hits = vec![neighbor_hit(entity.id), neighbor_hit(entity_no_type.id)];
15162        rt.enrich_neighbor_hits(&tok, &mut hits).await;
15163
15164        assert_eq!(hits[0].entity_type.as_deref(), Some("algorithm"));
15165        assert!(
15166            hits[1].entity_type.is_none(),
15167            "entity without entity_type must leave the field as None"
15168        );
15169    }
15170
15171    /// enrich_path_nodes populates properties from the already-fetched entity
15172    /// batch when the entity has a non-null properties blob.  Entities without
15173    /// properties leave the field as None.
15174    #[tokio::test]
15175    async fn enrich_path_nodes_populates_properties() {
15176        let rt = rt();
15177        let tok = NamespaceToken::local();
15178
15179        let props = serde_json::json!({"year": 2024, "venue": "NeurIPS"});
15180        let entity_with_props = rt
15181            .create_entity(
15182                &tok,
15183                "document",
15184                None,
15185                "AttentionPaper",
15186                None,
15187                Some(props.clone()),
15188                vec![],
15189            )
15190            .await
15191            .unwrap();
15192
15193        let entity_no_props = rt
15194            .create_entity(&tok, "concept", None, "BareConceptNode", None, None, vec![])
15195            .await
15196            .unwrap();
15197
15198        let mut paths = vec![GraphPath {
15199            root_id: entity_with_props.id,
15200            nodes: vec![
15201                path_node(entity_with_props.id, 0),
15202                path_node(entity_no_props.id, 1),
15203            ],
15204            total_weight: 1.0,
15205        }];
15206
15207        rt.enrich_path_nodes(&tok, &mut paths, true).await;
15208
15209        assert_eq!(
15210            paths[0].nodes[0].properties.as_ref(),
15211            Some(&props),
15212            "properties must be filled when entity has a non-null properties blob"
15213        );
15214        assert!(
15215            paths[0].nodes[1].properties.is_none(),
15216            "entity without properties must leave the field as None"
15217        );
15218    }
15219
15220    /// The runtime enforces the public root cap before doing any root-existence
15221    /// lookups or handing work to storage.
15222    #[tokio::test]
15223    async fn traverse_rejects_root_count_above_public_cap_before_lookup() {
15224        use khive_storage::types::{TraversalOptions, MAX_TRAVERSAL_ROOTS};
15225
15226        let rt = rt();
15227        let tok = NamespaceToken::local();
15228        let err = rt
15229            .traverse(
15230                &tok,
15231                TraversalRequest {
15232                    roots: (0..=MAX_TRAVERSAL_ROOTS)
15233                        .map(|_| uuid::Uuid::new_v4())
15234                        .collect(),
15235                    options: TraversalOptions {
15236                        max_depth: 1,
15237                        direction: Direction::Out,
15238                        relations: None,
15239                        min_weight: None,
15240                        limit: None,
15241                    },
15242                    include_roots: false,
15243                    include_properties: false,
15244                    execution_budget: Default::default(),
15245                },
15246            )
15247            .await
15248            .unwrap_err();
15249
15250        assert!(matches!(
15251            err,
15252            RuntimeError::InvalidInput(message)
15253                if message.contains("roots must contain at most 100 entries")
15254        ));
15255    }
15256
15257    // ── Additive EDGE_RULES composition: pack EntityOfType rules must not shadow
15258    // the base EntityOfKind contract for the same relation. ──────────────────────
15259    //
15260    // When a pack contributes EntityOfType rules for a relation (e.g. variant_of:
15261    // goal -> theorem and goal -> definition), the base contract's EntityOfKind
15262    // rule for the same relation (concept -> concept) must still fire for entities
15263    // whose base kind is "concept" but whose EntityOfType pair is not in any pack rule.
15264    //
15265    // Specifically: a goal entity resolves to base kind "concept". A goal -> goal
15266    // variant_of edge has no matching pack rule (goal -> goal is not declared), so
15267    // pack_rule_allows returns false. The validator then extracts the base kind
15268    // ("concept") and checks base_entity_rule_allows, which returns true.
15269    // The edge is therefore allowed: additive composition holds.
15270
15271    #[test]
15272    fn pack_entity_of_type_rules_do_not_shadow_base_entity_of_kind_rule() {
15273        // Formal-style EntityOfType rules for variant_of: goal -> theorem, goal -> definition.
15274        // goal -> goal is deliberately absent — that case must fall through to the base rule.
15275        let pack_rules: Vec<EdgeEndpointRule> = vec![
15276            EdgeEndpointRule {
15277                relation: EdgeRelation::VariantOf,
15278                source: EndpointKind::EntityOfType {
15279                    kind: "concept",
15280                    entity_type: "goal",
15281                },
15282                target: EndpointKind::EntityOfType {
15283                    kind: "concept",
15284                    entity_type: "theorem",
15285                },
15286            },
15287            EdgeEndpointRule {
15288                relation: EdgeRelation::VariantOf,
15289                source: EndpointKind::EntityOfType {
15290                    kind: "concept",
15291                    entity_type: "goal",
15292                },
15293                target: EndpointKind::EntityOfType {
15294                    kind: "concept",
15295                    entity_type: "definition",
15296                },
15297            },
15298        ];
15299
15300        let goal_a =
15301            Resolved::Entity(Entity::new("local", "concept", "G-a").with_entity_type(Some("goal")));
15302        let goal_b =
15303            Resolved::Entity(Entity::new("local", "concept", "G-b").with_entity_type(Some("goal")));
15304
15305        // Pack rules do not cover goal -> goal, so pack_rule_allows must return false.
15306        assert!(
15307            !pack_rule_allows(
15308                &pack_rules,
15309                EdgeRelation::VariantOf,
15310                Some(&goal_a),
15311                Some(&goal_b)
15312            ),
15313            "pack rules must not cover goal->goal variant_of (no such rule declared)"
15314        );
15315
15316        // The base contract allows concept -> concept for variant_of.
15317        // A goal entity's base kind is "concept", so this must return true.
15318        assert!(
15319            base_entity_rule_allows("concept", EdgeRelation::VariantOf, "concept"),
15320            "base contract must allow concept->concept variant_of regardless of pack EntityOfType rules"
15321        );
15322    }
15323
15324    // Integration path: pack EntityOfType rules installed on the runtime must not
15325    // block a goal->goal variant_of link that the base contract already permits.
15326    // Exercises validate_edge_relation_endpoints lines 1173-1223:
15327    //   pack miss -> extract e.kind ("concept") -> base_entity_rule_allows -> Ok.
15328    #[tokio::test]
15329    async fn link_variant_of_goal_to_goal_allowed_when_pack_has_entity_of_type_rules() {
15330        let rt = rt();
15331        let tok = NamespaceToken::local();
15332
15333        // Install formal-style EntityOfType rules for variant_of (goal -> theorem/definition).
15334        // goal -> goal is absent so the base concept->concept rule must carry this case.
15335        rt.install_edge_rules(vec![
15336            EdgeEndpointRule {
15337                relation: EdgeRelation::VariantOf,
15338                source: EndpointKind::EntityOfType {
15339                    kind: "concept",
15340                    entity_type: "goal",
15341                },
15342                target: EndpointKind::EntityOfType {
15343                    kind: "concept",
15344                    entity_type: "theorem",
15345                },
15346            },
15347            EdgeEndpointRule {
15348                relation: EdgeRelation::VariantOf,
15349                source: EndpointKind::EntityOfType {
15350                    kind: "concept",
15351                    entity_type: "goal",
15352                },
15353                target: EndpointKind::EntityOfType {
15354                    kind: "concept",
15355                    entity_type: "definition",
15356                },
15357            },
15358        ]);
15359
15360        let a = rt
15361            .create_entity(
15362                &tok,
15363                "concept",
15364                Some("goal"),
15365                "Goal Alpha",
15366                None,
15367                None,
15368                vec![],
15369            )
15370            .await
15371            .unwrap();
15372        let b = rt
15373            .create_entity(
15374                &tok,
15375                "concept",
15376                Some("goal"),
15377                "Goal Beta",
15378                None,
15379                None,
15380                vec![],
15381            )
15382            .await
15383            .unwrap();
15384
15385        // Neither endpoint matches any pack rule (no goal->goal rule).
15386        // The base concept->concept rule must fire and allow the edge.
15387        let result = rt
15388            .link(&tok, a.id, b.id, EdgeRelation::VariantOf, 1.0, None)
15389            .await;
15390        assert!(
15391            result.is_ok(),
15392            "goal->goal variant_of must be allowed via the base concept->concept rule \
15393             even when EntityOfType rules for variant_of are installed; got {result:?}"
15394        );
15395
15396        // Fail-closed check: additive rules must not make validation fail-open.
15397        // A goal(concept) -> project variant_of edge has no matching pack rule
15398        // (project is not in the installed variant_of rules) and no matching base
15399        // rule (no (concept, VariantOf, project) row). It must be rejected.
15400        let p = rt
15401            .create_entity(&tok, "project", None, "Proj", None, None, vec![])
15402            .await
15403            .unwrap();
15404        let bad = rt
15405            .link(&tok, a.id, p.id, EdgeRelation::VariantOf, 1.0, None)
15406            .await;
15407        assert!(
15408            bad.is_err(),
15409            "additive pack rules must not make validation fail-open; \
15410             goal(concept)->project variant_of must be rejected (pack miss + base miss); \
15411             got {bad:?}"
15412        );
15413    }
15414
15415    // Load-bearing positive: a pack EntityOfType rule adds an endpoint the base contract
15416    // does not cover. The base contract has no (concept, DependsOn, concept) row (the
15417    // DependsOn rows are project/service/artifact only). A theorem->definition DependsOn
15418    // edge can therefore ONLY pass through the pack rule, proving the union is load-bearing.
15419    #[tokio::test]
15420    async fn link_depends_on_theorem_to_definition_allowed_only_via_pack_rule() {
15421        let rt = rt();
15422        let tok = NamespaceToken::local();
15423
15424        // Confirm the base contract does NOT allow concept->concept DependsOn.
15425        // (Documented here so the assertion below is not a tautology.)
15426        assert!(
15427            !base_entity_rule_allows("concept", EdgeRelation::DependsOn, "concept"),
15428            "base contract must not allow concept->concept DependsOn; \
15429             test would be vacuous if this precondition fails"
15430        );
15431
15432        // Install a single EntityOfType rule: theorem depends_on definition.
15433        // With no rules, the link would be rejected by the base contract.
15434        // With this rule, it must be accepted via the pack path (lines 1173-1179).
15435        rt.install_edge_rules(vec![EdgeEndpointRule {
15436            relation: EdgeRelation::DependsOn,
15437            source: EndpointKind::EntityOfType {
15438                kind: "concept",
15439                entity_type: "theorem",
15440            },
15441            target: EndpointKind::EntityOfType {
15442                kind: "concept",
15443                entity_type: "definition",
15444            },
15445        }]);
15446
15447        let thm = rt
15448            .create_entity(&tok, "concept", Some("theorem"), "T1", None, None, vec![])
15449            .await
15450            .unwrap();
15451        let def = rt
15452            .create_entity(
15453                &tok,
15454                "concept",
15455                Some("definition"),
15456                "D1",
15457                None,
15458                None,
15459                vec![],
15460            )
15461            .await
15462            .unwrap();
15463
15464        // This can only pass through the pack rule — the base contract rejects it.
15465        let result = rt
15466            .link(&tok, thm.id, def.id, EdgeRelation::DependsOn, 1.0, None)
15467            .await;
15468        assert!(
15469            result.is_ok(),
15470            "theorem->definition DependsOn must be allowed by the installed pack rule; \
15471             the base contract has no concept->concept DependsOn row; got {result:?}"
15472        );
15473    }
15474
15475    // ── Provenance endpoint pairs ────────────────────────────────────────────
15476    // Four base endpoint pairs: document->person and document->org (document
15477    // authorship), concept->org (concept origination by an org), and
15478    // document->document (normative document dependency). Positive links for
15479    // each pair, plus a direction-matters negative guard.
15480
15481    #[tokio::test]
15482    async fn link_document_introduced_by_person_allowed() {
15483        let rt = rt();
15484        let tok = NamespaceToken::local();
15485
15486        let doc = rt
15487            .create_entity(&tok, "document", None, "Paper", None, None, vec![])
15488            .await
15489            .unwrap();
15490        let author = rt
15491            .create_entity(&tok, "person", None, "Author", None, None, vec![])
15492            .await
15493            .unwrap();
15494
15495        let result = rt
15496            .link(
15497                &tok,
15498                doc.id,
15499                author.id,
15500                EdgeRelation::IntroducedBy,
15501                1.0,
15502                None,
15503            )
15504            .await;
15505        assert!(
15506            result.is_ok(),
15507            "document->person introduced_by must be allowed by the ADR-002 \
15508             endpoint amendment; got {result:?}"
15509        );
15510    }
15511
15512    #[tokio::test]
15513    async fn link_document_introduced_by_org_allowed() {
15514        let rt = rt();
15515        let tok = NamespaceToken::local();
15516
15517        let doc = rt
15518            .create_entity(&tok, "document", None, "Whitepaper", None, None, vec![])
15519            .await
15520            .unwrap();
15521        let org = rt
15522            .create_entity(&tok, "org", None, "Publisher", None, None, vec![])
15523            .await
15524            .unwrap();
15525
15526        let result = rt
15527            .link(&tok, doc.id, org.id, EdgeRelation::IntroducedBy, 1.0, None)
15528            .await;
15529        assert!(
15530            result.is_ok(),
15531            "document->org introduced_by must be allowed by the ADR-002 \
15532             endpoint amendment; got {result:?}"
15533        );
15534    }
15535
15536    #[tokio::test]
15537    async fn link_concept_introduced_by_org_allowed() {
15538        let rt = rt();
15539        let tok = NamespaceToken::local();
15540
15541        let concept = rt
15542            .create_entity(&tok, "concept", None, "Architecture", None, None, vec![])
15543            .await
15544            .unwrap();
15545        let org = rt
15546            .create_entity(&tok, "org", None, "Originator", None, None, vec![])
15547            .await
15548            .unwrap();
15549
15550        let result = rt
15551            .link(
15552                &tok,
15553                concept.id,
15554                org.id,
15555                EdgeRelation::IntroducedBy,
15556                1.0,
15557                None,
15558            )
15559            .await;
15560        assert!(
15561            result.is_ok(),
15562            "concept->org introduced_by must be allowed by the ADR-002 \
15563             endpoint amendment; got {result:?}"
15564        );
15565    }
15566
15567    #[tokio::test]
15568    async fn link_document_depends_on_document_allowed() {
15569        let rt = rt();
15570        let tok = NamespaceToken::local();
15571
15572        let doc_a = rt
15573            .create_entity(&tok, "document", None, "Spec A", None, None, vec![])
15574            .await
15575            .unwrap();
15576        let doc_b = rt
15577            .create_entity(&tok, "document", None, "Spec B", None, None, vec![])
15578            .await
15579            .unwrap();
15580
15581        let result = rt
15582            .link(&tok, doc_a.id, doc_b.id, EdgeRelation::DependsOn, 1.0, None)
15583            .await;
15584        assert!(
15585            result.is_ok(),
15586            "document->document depends_on must be allowed by the ADR-002 \
15587             endpoint amendment; got {result:?}"
15588        );
15589        let edge = result.unwrap();
15590        let dk = edge
15591            .metadata
15592            .as_ref()
15593            .and_then(|m| m.get("dependency_kind"))
15594            .and_then(|v| v.as_str());
15595        assert_eq!(
15596            dk,
15597            Some("normative"),
15598            "document->document depends_on must infer dependency_kind=normative"
15599        );
15600    }
15601
15602    #[tokio::test]
15603    async fn link_org_introduced_by_document_rejected_direction_matters() {
15604        let rt = rt();
15605        let tok = NamespaceToken::local();
15606
15607        let org = rt
15608            .create_entity(&tok, "org", None, "Publisher", None, None, vec![])
15609            .await
15610            .unwrap();
15611        let doc = rt
15612            .create_entity(&tok, "document", None, "Paper", None, None, vec![])
15613            .await
15614            .unwrap();
15615
15616        // The amendment adds document->org, not org->document. Direction matters:
15617        // an org is not "introduced by" a document it published.
15618        let result = rt
15619            .link(&tok, org.id, doc.id, EdgeRelation::IntroducedBy, 1.0, None)
15620            .await;
15621        assert!(
15622            result.is_err(),
15623            "org->document introduced_by must remain rejected; only \
15624             document->org is permitted, not the reverse; got {result:?}"
15625        );
15626    }
15627
15628    // ── create_note_with_embedding_content ──────────────────────────────────
15629
15630    /// Like `ConstVecService`/`ConstVecProvider` above, but records every text
15631    /// it is asked to embed so a test can assert exactly what reached the
15632    /// "provider" — used to verify the effective embed text is the capped
15633    /// override, not the full note content.
15634    struct CapturingVecService {
15635        dims: usize,
15636        captured: Arc<std::sync::Mutex<Vec<String>>>,
15637    }
15638
15639    #[async_trait]
15640    impl EmbeddingService for CapturingVecService {
15641        async fn embed(
15642            &self,
15643            texts: &[String],
15644            _model: EmbeddingModel,
15645        ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
15646            for text in texts {
15647                if text.len() > MAX_TEXT_CHARS {
15648                    return Err(EmbedError::TextTooLong {
15649                        length: text.len(),
15650                        max: MAX_TEXT_CHARS,
15651                    });
15652                }
15653            }
15654            self.captured.lock().unwrap().extend(texts.iter().cloned());
15655            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
15656        }
15657
15658        fn supports_model(&self, _model: EmbeddingModel) -> bool {
15659            true
15660        }
15661
15662        fn name(&self) -> &'static str {
15663            "capturing-vec"
15664        }
15665    }
15666
15667    struct CapturingVecProvider {
15668        provider_name: String,
15669        dims: usize,
15670        captured: Arc<std::sync::Mutex<Vec<String>>>,
15671    }
15672
15673    #[async_trait]
15674    impl EmbedderProvider for CapturingVecProvider {
15675        fn name(&self) -> &str {
15676            &self.provider_name
15677        }
15678
15679        fn dimensions(&self) -> usize {
15680            self.dims
15681        }
15682
15683        async fn build(&self) -> crate::error::RuntimeResult<Arc<dyn EmbeddingService>> {
15684            Ok(Arc::new(CapturingVecService {
15685                dims: self.dims,
15686                captured: Arc::clone(&self.captured),
15687            }))
15688        }
15689    }
15690
15691    #[tokio::test]
15692    async fn create_bounds_embedding_input_without_truncating_stored_content() {
15693        let rt = rt();
15694        let tok = NamespaceToken::local();
15695        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
15696        rt.register_embedder(CapturingVecProvider {
15697            provider_name: "strict-length-test".into(),
15698            dims: 4,
15699            captured: Arc::clone(&captured),
15700        });
15701
15702        let content = format!("{}\u{1f980}tail", "a".repeat(MAX_TEXT_CHARS - 1));
15703        let note = rt
15704            .create_note(&tok, "observation", None, &content, None, None, vec![])
15705            .await
15706            .expect("over-length note create must succeed");
15707        let fetched = rt
15708            .notes(&tok)
15709            .unwrap()
15710            .get_note(note.id)
15711            .await
15712            .unwrap()
15713            .expect("created note must be retrievable");
15714        assert_eq!(fetched.content, content, "stored content must remain full");
15715
15716        let embedded = captured.lock().unwrap().clone();
15717        assert_eq!(embedded.len(), 1);
15718        assert_eq!(embedded[0].len(), MAX_TEXT_CHARS - 1);
15719        assert!(embedded[0].is_char_boundary(embedded[0].len()));
15720        assert!(!embedded[0].contains('\u{1f980}'));
15721
15722        let vector_info = rt
15723            .vectors_for_model(&tok, "strict-length-test")
15724            .expect("vector store")
15725            .info()
15726            .await
15727            .expect("vector info");
15728        assert_eq!(vector_info.dimensions, 4);
15729        assert_eq!(vector_info.entry_count, 1);
15730
15731        captured.lock().unwrap().clear();
15732        rt.reindex_note(&tok, &fetched)
15733            .await
15734            .expect("reindex must bound the same stored content");
15735        assert_eq!(captured.lock().unwrap()[0].len(), MAX_TEXT_CHARS - 1);
15736
15737        captured.lock().unwrap().clear();
15738        rt.embed_document_batch_with_model("strict-length-test", std::slice::from_ref(&content))
15739            .await
15740            .expect("batch reindex seam must bound stored content");
15741        assert_eq!(captured.lock().unwrap()[0].len(), MAX_TEXT_CHARS - 1);
15742
15743        let normal = "normal byte-identical embedding input";
15744        rt.create_note(&tok, "observation", None, normal, None, None, vec![])
15745            .await
15746            .expect("normal note create must succeed");
15747        assert_eq!(captured.lock().unwrap().last().unwrap(), normal);
15748
15749        let long_description = format!("{}\u{1f980}tail", "b".repeat(MAX_TEXT_CHARS));
15750        rt.create_entity(
15751            &tok,
15752            "concept",
15753            None,
15754            "entity",
15755            Some(&long_description),
15756            None,
15757            vec![],
15758        )
15759        .await
15760        .expect("over-length entity create must succeed");
15761    }
15762
15763    #[tokio::test]
15764    async fn create_note_with_embedding_content_none_matches_create_note() {
15765        let rt = rt();
15766        let tok = NamespaceToken::local();
15767        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
15768        rt.register_embedder(CapturingVecProvider {
15769            provider_name: "capturing-vec".into(),
15770            dims: 4,
15771            captured: Arc::clone(&captured),
15772        });
15773
15774        let note = rt
15775            .create_note_with_embedding_content(
15776                &tok,
15777                "observation",
15778                None,
15779                "full content, no override",
15780                None,
15781                None,
15782                None,
15783                vec![],
15784            )
15785            .await
15786            .expect("create with None override must behave like create_note");
15787        assert_eq!(note.content, "full content, no override");
15788        let seen = captured.lock().unwrap().clone();
15789        assert_eq!(
15790            seen,
15791            vec!["full content, no override".to_string()],
15792            "with no override the embedder must see the full content"
15793        );
15794    }
15795
15796    #[tokio::test]
15797    async fn create_note_with_embedding_content_embeds_capped_override_and_stores_full_content() {
15798        let rt = rt();
15799        let tok = NamespaceToken::local();
15800        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
15801        rt.register_embedder(CapturingVecProvider {
15802            provider_name: "capturing-vec".into(),
15803            dims: 4,
15804            captured: Arc::clone(&captured),
15805        });
15806
15807        let full = "head-term and then a very long tail-term that exceeds any cap";
15808        let head = &full[.."head-term and then a very long".len()];
15809
15810        let note = rt
15811            .create_note_with_embedding_content(
15812                &tok,
15813                "observation",
15814                None,
15815                full,
15816                Some(head),
15817                None,
15818                None,
15819                vec![],
15820            )
15821            .await
15822            .expect("proper-prefix override must be accepted");
15823        assert_eq!(note.content, full, "stored content must be the full text");
15824
15825        let seen = captured.lock().unwrap().clone();
15826        assert_eq!(
15827            seen,
15828            vec![head.to_string()],
15829            "embedder must see only the capped override"
15830        );
15831    }
15832
15833    #[tokio::test]
15834    async fn create_note_with_embedding_content_fans_out_identical_override_to_multiple_models() {
15835        let rt = rt();
15836        let tok = NamespaceToken::local();
15837        let captured_a = Arc::new(std::sync::Mutex::new(Vec::new()));
15838        let captured_b = Arc::new(std::sync::Mutex::new(Vec::new()));
15839        rt.register_embedder(CapturingVecProvider {
15840            provider_name: "capturing-vec-a".into(),
15841            dims: 4,
15842            captured: Arc::clone(&captured_a),
15843        });
15844        rt.register_embedder(CapturingVecProvider {
15845            provider_name: "capturing-vec-b".into(),
15846            dims: 4,
15847            captured: Arc::clone(&captured_b),
15848        });
15849
15850        let full = "head-only-embedded plus a long discarded tail";
15851        let head = &full[.."head-only-embedded".len()];
15852
15853        rt.create_note_with_embedding_content(
15854            &tok,
15855            "observation",
15856            None,
15857            full,
15858            Some(head),
15859            None,
15860            None,
15861            vec![],
15862        )
15863        .await
15864        .expect("create ok");
15865
15866        assert_eq!(
15867            captured_a.lock().unwrap().clone(),
15868            vec![head.to_string()],
15869            "model A must receive the identical capped override"
15870        );
15871        assert_eq!(
15872            captured_b.lock().unwrap().clone(),
15873            vec![head.to_string()],
15874            "model B must receive the identical capped override"
15875        );
15876
15877        // Both models actually persisted a vector row for the note (not just
15878        // an embed call that was discarded before insertion).
15879        let vs_a = rt
15880            .vectors_for_model(&tok, "capturing-vec-a")
15881            .expect("vector store for model A");
15882        assert_eq!(
15883            vs_a.count().await.expect("vector count A"),
15884            1,
15885            "model A must have exactly one vector row for the note"
15886        );
15887        let vs_b = rt
15888            .vectors_for_model(&tok, "capturing-vec-b")
15889            .expect("vector store for model B");
15890        assert_eq!(
15891            vs_b.count().await.expect("vector count B"),
15892            1,
15893            "model B must have exactly one vector row for the note"
15894        );
15895    }
15896
15897    #[tokio::test]
15898    async fn create_note_with_embedding_content_rejects_empty_override() {
15899        let rt = rt();
15900        let tok = NamespaceToken::local();
15901
15902        let err = rt
15903            .create_note_with_embedding_content(
15904                &tok,
15905                "observation",
15906                None,
15907                "some content",
15908                Some(""),
15909                None,
15910                None,
15911                vec![],
15912            )
15913            .await
15914            .expect_err("empty override must be rejected");
15915        assert!(matches!(err, RuntimeError::InvalidInput(_)));
15916    }
15917
15918    #[tokio::test]
15919    async fn create_note_with_embedding_content_rejects_non_prefix_override() {
15920        let rt = rt();
15921        let tok = NamespaceToken::local();
15922
15923        let err = rt
15924            .create_note_with_embedding_content(
15925                &tok,
15926                "observation",
15927                None,
15928                "the actual content",
15929                Some("an unrelated string"),
15930                None,
15931                None,
15932                vec![],
15933            )
15934            .await
15935            .expect_err("non-prefix override must be rejected");
15936        assert!(matches!(err, RuntimeError::InvalidInput(ref m) if m.contains("prefix")));
15937    }
15938
15939    #[tokio::test]
15940    async fn create_note_with_embedding_content_rejects_equal_length_override() {
15941        let rt = rt();
15942        let tok = NamespaceToken::local();
15943
15944        // Same length and same text as `content` is not a *proper* prefix.
15945        let err = rt
15946            .create_note_with_embedding_content(
15947                &tok,
15948                "observation",
15949                None,
15950                "identical text",
15951                Some("identical text"),
15952                None,
15953                None,
15954                vec![],
15955            )
15956            .await
15957            .expect_err("an equal-length override must be rejected as not a proper prefix");
15958        assert!(matches!(err, RuntimeError::InvalidInput(ref m) if m.contains("prefix")));
15959    }
15960
15961    #[tokio::test]
15962    async fn create_note_with_embedding_content_rejects_secret_bearing_override() {
15963        let rt = rt();
15964        let tok = NamespaceToken::local();
15965
15966        let token_span = "ghp_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
15967        let content = format!("{token_span} plus extra trailing content beyond the override");
15968        let embedding_content = format!("{token_span} plus extra");
15969
15970        let err = rt
15971            .create_note_with_embedding_content(
15972                &tok,
15973                "observation",
15974                None,
15975                &content,
15976                Some(&embedding_content),
15977                None,
15978                None,
15979                vec![],
15980            )
15981            .await
15982            .expect_err("a credential-shaped override must fail the secret gate");
15983        assert!(
15984            matches!(err, RuntimeError::SecretDetected(_)),
15985            "expected SecretDetected, got {err:?}"
15986        );
15987
15988        // Fail-closed: no note survives the rejected create.
15989        let count = rt
15990            .notes(&tok)
15991            .unwrap()
15992            .count_notes(tok.namespace().as_str(), None)
15993            .await
15994            .unwrap();
15995        assert_eq!(count, 0, "a rejected create must leave no note behind");
15996    }
15997}