Skip to main content

khive_runtime/
curation.rs

1// Licensed under the Apache License, Version 2.0.
2
3// FILE SIZE JUSTIFICATION: curation.rs holds entity/note/edge patch types alongside
4// their update and merge implementations. The implementations share private helpers
5// (merge_properties, namespace checks, dedup policy) that need pub(crate) access to
6// runtime internals. Inline tests cover merge semantics that require direct access to
7// those helpers. Split plan: extract patch types into `curation/patch.rs` and merge
8// logic into `curation/merge.rs` once the dedup policy API stabilises.
9//! Curation operations: entity update/merge and edge-list filter type.
10
11use std::collections::{HashMap, HashSet, VecDeque};
12
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use uuid::Uuid;
16
17use khive_db::SqliteError;
18use khive_storage::note::Note;
19use khive_storage::types::{EdgeFilter, TextDocument};
20use khive_storage::{EdgeRelation, Entity, SubstrateKind};
21use khive_types::{Details, EdgeEndpointRule, EventKind, KhiveError};
22use rusqlite::OptionalExtension;
23
24use crate::error::{RuntimeError, RuntimeResult};
25use crate::operations::{base_entity_rule_allows, canonical_edge_endpoints, endpoint_matches};
26use crate::runtime::{KhiveRuntime, NamespaceToken};
27
28/// Test-only pause point at the read/write boundary of a guarded
29/// read-modify-write, so a race between two concurrent callers of the same
30/// PRODUCTION entry point (not the underlying store primitive) can be
31/// reproduced deterministically instead of relying on scheduler luck or
32/// sleeps. A no-op unless the calling task runs inside
33/// `AFTER_READ_BARRIER.scope(...)`; production code never establishes that
34/// scope, so `pause_after_read` costs nothing outside these regression
35/// tests, and it does not exist at all in non-test builds.
36#[cfg(test)]
37pub(crate) mod race_seam {
38    use std::sync::Arc;
39    use tokio::sync::Barrier;
40
41    tokio::task_local! {
42        pub(crate) static AFTER_READ_BARRIER: Arc<Barrier>;
43    }
44
45    pub(crate) async fn pause_after_read() {
46        if let Ok(barrier) = AFTER_READ_BARRIER.try_with(Arc::clone) {
47            barrier.wait().await;
48        }
49    }
50}
51
52pub(crate) fn stale_note_snapshot_error(id: Uuid) -> RuntimeError {
53    RuntimeError::Khive(KhiveError::conflict(format!(
54        "note {id} changed concurrently after it was read; retry with fresh state"
55    )))
56}
57
58pub(crate) fn stale_entity_snapshot_error(id: Uuid) -> RuntimeError {
59    RuntimeError::Khive(KhiveError::conflict(format!(
60        "entity {id} changed concurrently after it was read; retry with fresh state"
61    )))
62}
63
64pub(crate) fn stale_edge_snapshot_error(id: Uuid) -> RuntimeError {
65    RuntimeError::Khive(KhiveError::conflict(format!(
66        "edge {id} changed concurrently after it was read; retry with fresh state"
67    )))
68}
69
70/// Immutable embedding-registry view for one logical write.
71///
72/// Document byte budgets are derived from the model name at the embedding seam,
73/// so retaining the exact name set keeps merge cleanup, table preparation, and
74/// survivor reindexing on one plan during concurrent registration.
75#[derive(Clone, Debug, Default)]
76struct EmbeddingModelPlan {
77    model_names: Vec<String>,
78}
79
80impl EmbeddingModelPlan {
81    fn capture(runtime: &KhiveRuntime) -> Self {
82        Self {
83            model_names: runtime.registered_embedding_model_names(),
84        }
85    }
86
87    fn is_empty(&self) -> bool {
88        self.model_names.is_empty()
89    }
90
91    fn model_names(&self) -> &[String] {
92        &self.model_names
93    }
94
95    fn vector_tables(&self) -> Vec<String> {
96        self.model_names
97            .iter()
98            .map(|name| format!("vec_{}", crate::config::sanitize_key(name)))
99            .collect()
100    }
101}
102
103// ---------------------------------------------------------------------------
104// Public types
105// ---------------------------------------------------------------------------
106
107/// Patch for `update_entity`. Only `Some(_)` fields are applied; `None` means "leave unchanged".
108///
109/// For `description`:
110/// - `None` (outer) — leave the current description as-is
111/// - `Some(None)` — clear the description (set to NULL)
112/// - `Some(Some(s))` — set the description to `s`
113///
114/// For `properties` (deep-merge semantics):
115/// - `None` — leave properties as-is
116/// - `Some(value)` — deep-merge `value` into existing properties. Keys present in
117///   the patch overwrite existing keys; keys absent from the patch are preserved.
118///   Removing a key requires explicit replacement of the parent object (or a future
119///   `unset`/`null-marker` extension).
120///
121/// For `tags` — replace semantics: `Some(vec)` sets tags to exactly `vec`. To add
122/// a tag without losing existing tags, read the entity first, push the new tag,
123/// and pass the full list back.
124///
125/// For `entity_type` — ADR-014 tri-state: `None` leaves the current type
126/// unchanged, `Some(None)` explicitly clears it, and `Some(Some(value))`
127/// validates and normalizes `value` through the installed entity-type
128/// registry.
129#[derive(Clone, Debug, Default)]
130pub struct EntityPatch {
131    pub name: Option<String>,
132    pub description: Option<Option<String>>,
133    pub properties: Option<Value>,
134    pub tags: Option<Vec<String>>,
135    pub entity_type: Option<Option<String>>,
136}
137
138/// Policy used when deduplicating two entities.
139#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
140#[serde(rename_all = "snake_case")]
141pub enum EntityDedupMergePolicy {
142    /// `into` values win on conflict. Tags are unioned. Properties from `from` fill in
143    /// keys that `into` doesn't have. This is the default.
144    #[default]
145    PreferInto,
146    /// `from` values win on conflict.
147    PreferFrom,
148    /// Deep-merge: object properties merge recursively. Scalar conflicts go to `into`.
149    Union,
150}
151
152/// Safety-floor guard that refused an explicit entity merge.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub enum EntityMergeGuard {
155    EntityKind,
156    NameSimilarity,
157    ProjectCompatibility,
158}
159
160impl EntityMergeGuard {
161    pub fn as_str(self) -> &'static str {
162        match self {
163            Self::EntityKind => "entity_kind",
164            Self::NameSimilarity => "name_similarity",
165            Self::ProjectCompatibility => "project_compatibility",
166        }
167    }
168}
169
170/// Validate the non-forced entity-merge safety floor.
171pub fn validate_entity_merge_floor(into: &Entity, from: &Entity) -> Result<(), EntityMergeGuard> {
172    if into.kind != from.kind {
173        return Err(EntityMergeGuard::EntityKind);
174    }
175    if !names_are_similar(&into.name, &from.name) {
176        return Err(EntityMergeGuard::NameSimilarity);
177    }
178    if projects_are_disjoint(into, from) {
179        return Err(EntityMergeGuard::ProjectCompatibility);
180    }
181    Ok(())
182}
183
184/// Convert a safety-floor refusal into the merge verb's structured conflict contract.
185pub fn entity_merge_guard_error(guard: EntityMergeGuard) -> RuntimeError {
186    RuntimeError::Khive(
187        KhiveError::conflict(format!(
188            "entity merge refused by {} guard; use force=true only when the caller accepts responsibility",
189            guard.as_str()
190        ))
191        .with_details(Details::new([
192            ("guard", guard.as_str()),
193            ("override", "force=true"),
194        ])),
195    )
196}
197
198fn names_are_similar(left: &str, right: &str) -> bool {
199    let left = normalize_name(left);
200    let right = normalize_name(right);
201    if left.is_empty() || right.is_empty() {
202        return false;
203    }
204    if left == right {
205        return true;
206    }
207
208    let shorter_len = left.chars().count().min(right.chars().count());
209    if shorter_len >= 3 && (left.starts_with(&right) || right.starts_with(&left)) {
210        return true;
211    }
212
213    let left_trigrams = trigrams(&left);
214    let right_trigrams = trigrams(&right);
215    if left_trigrams.is_empty() || right_trigrams.is_empty() {
216        return false;
217    }
218    let overlap = left_trigrams.intersection(&right_trigrams).count();
219    overlap.saturating_mul(4) >= left_trigrams.len().saturating_add(right_trigrams.len())
220}
221
222fn normalize_name(name: &str) -> String {
223    let mut normalized = String::with_capacity(name.len());
224    let mut pending_space = false;
225    for ch in name.chars().flat_map(char::to_lowercase) {
226        if ch.is_whitespace() {
227            pending_space = !normalized.is_empty();
228        } else {
229            if pending_space {
230                normalized.push(' ');
231                pending_space = false;
232            }
233            normalized.push(ch);
234        }
235    }
236    normalized
237}
238
239fn trigrams(value: &str) -> HashSet<[char; 3]> {
240    let chars: Vec<char> = value.chars().collect();
241    chars
242        .windows(3)
243        .map(|window| [window[0], window[1], window[2]])
244        .collect()
245}
246
247fn projects_are_disjoint(into: &Entity, from: &Entity) -> bool {
248    let Some(into_projects) = into
249        .properties
250        .as_ref()
251        .and_then(|properties| properties.get("projects"))
252        .and_then(Value::as_array)
253    else {
254        return false;
255    };
256    let Some(from_projects) = from
257        .properties
258        .as_ref()
259        .and_then(|properties| properties.get("projects"))
260        .and_then(Value::as_array)
261    else {
262        return false;
263    };
264    if into_projects.is_empty() || from_projects.is_empty() {
265        return false;
266    }
267
268    let (indexed, candidates) = if into_projects.len() <= from_projects.len() {
269        (into_projects, from_projects)
270    } else {
271        (from_projects, into_projects)
272    };
273    let mut indexed_strings = HashSet::new();
274    let mut indexed_values = HashSet::new();
275    for value in indexed {
276        if let Some(value) = value.as_str() {
277            indexed_strings.insert(normalize_project_string(value));
278        } else {
279            indexed_values.insert(value.clone());
280        }
281    }
282    !candidates.iter().any(|candidate| {
283        if let Some(candidate) = candidate.as_str() {
284            indexed_strings.contains(&normalize_project_string(candidate))
285        } else {
286            indexed_values.contains(candidate)
287        }
288    })
289}
290
291fn normalize_project_string(value: &str) -> String {
292    value.trim().to_ascii_lowercase()
293}
294
295/// Strategy for merging note content when two notes are combined.
296#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
297#[serde(rename_all = "snake_case")]
298pub enum ContentMergeStrategy {
299    #[default]
300    Append,
301    PreferInto,
302    PreferFrom,
303}
304
305/// Result returned by `merge_entity` / `merge_note`.
306#[derive(Clone, Debug, Serialize, Deserialize)]
307pub struct MergeSummary {
308    pub kept_id: Uuid,
309    pub removed_id: Uuid,
310    pub edges_rewired: usize,
311    /// Incident edges dropped instead of rewired because the rewired
312    /// `(source, relation, target)` triple would violate the pack endpoint
313    /// contract `link` enforces (khive#1216) — consistent with the existing
314    /// dangling-endpoint skip behavior, never silently rewired into a
315    /// contract-violating edge.
316    #[serde(default)]
317    pub edges_contract_skipped: usize,
318    /// Full preimages for natural-key edge conflicts resolved by this merge.
319    /// Each entry names the surviving row, the dropped duplicate, and every
320    /// incident edge cascaded with it so the destructive step is reversible.
321    #[serde(default)]
322    pub edge_conflict_preimages: Vec<MergeEdgeConflictPreimage>,
323    pub properties_merged: usize,
324    pub tags_unioned: usize,
325    pub content_appended: bool,
326    pub dry_run: bool,
327    /// Rows and bytes this merge materialized against the per-transaction
328    /// budget, alongside the limits it was admitted under. Enforcement already
329    /// happened inside the transaction; this is the observed usage.
330    #[serde(default)]
331    pub tx_budget: MergeTxBudgetReport,
332    /// Actual embedding-input truncation observed while reindexing the survivor.
333    #[serde(skip)]
334    pub embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
335}
336
337/// Complete stored state of an edge removed while resolving a merge conflict.
338///
339/// Timestamps use the storage layer's microsecond representation. `relation`
340/// remains a string so a legacy row predating the closed relation enum can
341/// still be captured without making an otherwise valid merge fail.
342#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
343pub struct MergeEdgePreimage {
344    pub id: Uuid,
345    pub namespace: String,
346    pub source_id: Uuid,
347    pub target_id: Uuid,
348    pub relation: String,
349    pub weight: f64,
350    pub created_at: i64,
351    pub updated_at: i64,
352    pub deleted_at: Option<i64>,
353    pub target_backend: Option<String>,
354    pub metadata: Option<Value>,
355}
356
357/// One natural-key collision resolved by a direct entity or note merge.
358#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
359pub struct MergeEdgeConflictPreimage {
360    pub surviving_edge_id: Uuid,
361    pub dropped_edge: MergeEdgePreimage,
362    /// Edges removed by the hard-delete cascade because they referenced the
363    /// dropped edge as a node. Under the accepted endpoint contract these are
364    /// `annotates` edges, including already-soft-deleted rows.
365    #[serde(default, skip_serializing_if = "Vec::is_empty")]
366    pub incident_edge_preimages: Vec<MergeEdgePreimage>,
367}
368
369/// Default per-transaction row cap for a direct entity/note merge. Every row
370/// materialized into Rust inside the merge transaction counts: the two merge
371/// records, incident edges, endpoint-contract resolutions, and conflict
372/// cascade rows. Far above any legitimate single-record merge, while bounding
373/// the writer hold and heap of a hub-node merge (`traverse` bounds its shared
374/// read expansion at 100k rows; a merge holds the writer, so it is tighter).
375const MERGE_TX_MAX_ROWS: usize = 50_000;
376
377/// Default per-transaction aggregate byte cap across the same materialized
378/// state (variable-length payloads: descriptions/content, properties, tags,
379/// edge metadata, fanout table names).
380const MERGE_TX_MAX_BYTES: usize = 32 * 1024 * 1024;
381
382/// Hard materialization limits for one merge transaction.
383///
384/// Enforced on the writer connection inside the merge's own `BEGIN IMMEDIATE`
385/// transaction, so the counted rows are exactly the rows the merge operates
386/// on — a pre-flight count on another connection could be outgrown between
387/// the count and the merge. Exceeding either limit rejects the merge with the
388/// observed counts before further state is materialized, and the transaction
389/// rolls back. Dry runs are budgeted identically: the preview performs the
390/// same reads and carries the same materialization hazard.
391#[derive(Clone, Copy, Debug)]
392pub struct MergeTxLimits {
393    pub max_rows: usize,
394    pub max_bytes: usize,
395}
396
397impl Default for MergeTxLimits {
398    fn default() -> Self {
399        Self {
400            max_rows: MERGE_TX_MAX_ROWS,
401            max_bytes: MERGE_TX_MAX_BYTES,
402        }
403    }
404}
405
406/// Observed budget usage for one merge transaction (see [`MergeTxLimits`]).
407#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
408pub struct MergeTxBudgetReport {
409    pub rows_charged: usize,
410    pub bytes_charged: usize,
411    pub max_rows: usize,
412    pub max_bytes: usize,
413}
414
415/// Running row/byte account for one merge transaction.
416struct MergeTxBudget {
417    limits: MergeTxLimits,
418    rows: usize,
419    bytes: usize,
420}
421
422impl MergeTxBudget {
423    fn new(limits: MergeTxLimits) -> Self {
424        Self {
425            limits,
426            rows: 0,
427            bytes: 0,
428        }
429    }
430
431    /// Add `rows`/`bytes` to the account; reject once either limit is passed.
432    /// Callers charge each unit of state *before* retaining it, so a rejected
433    /// merge never materializes more than one row past the cap.
434    fn charge(&mut self, rows: usize, bytes: usize, context: &str) -> Result<(), SqliteError> {
435        self.rows = self.rows.saturating_add(rows);
436        self.bytes = self.bytes.saturating_add(bytes);
437        if self.rows > self.limits.max_rows || self.bytes > self.limits.max_bytes {
438            return Err(SqliteError::InvalidData(format!(
439                "merge transaction budget exceeded while {context}: {} rows / {} bytes \
440                 materialized (limits {} rows / {} bytes); the merge was rejected before \
441                 materializing further state — curate the incident edges down or merge in \
442                 smaller steps",
443                self.rows, self.bytes, self.limits.max_rows, self.limits.max_bytes
444            )));
445        }
446        Ok(())
447    }
448
449    fn report(&self) -> MergeTxBudgetReport {
450        MergeTxBudgetReport {
451            rows_charged: self.rows,
452            bytes_charged: self.bytes,
453            max_rows: self.limits.max_rows,
454            max_bytes: self.limits.max_bytes,
455        }
456    }
457}
458
459/// Fixed overhead approximates the id/timestamp/weight columns; variable
460/// payloads are counted at their stored length.
461fn edge_row_budget_bytes(edge: &EdgeRow) -> usize {
462    96 + edge.namespace.len()
463        + edge.relation.len()
464        + edge.target_backend.as_deref().map_or(0, str::len)
465        + edge.metadata.as_deref().map_or(0, str::len)
466}
467
468/// Patch for `update_edge`. Only `Some(_)` fields are applied; `None` means "leave unchanged".
469///
470/// For `properties` — replacement semantics (not deep merge): `Some(value)` replaces
471/// the entire metadata object. `None` leaves metadata unchanged.
472#[derive(Clone, Debug, Default)]
473pub struct EdgePatch {
474    pub relation: Option<EdgeRelation>,
475    pub weight: Option<f64>,
476    pub properties: Option<Value>,
477}
478
479/// Patch for `update_note`. Only `Some(_)` fields are applied; `None` means "leave unchanged".
480///
481/// For `salience`/`decay_factor`:
482/// - `None` (outer) — leave unchanged
483/// - `Some(None)` — clear the value
484/// - `Some(Some(v))` — set to v
485#[derive(Clone, Debug, Default)]
486pub struct NotePatch {
487    pub name: Option<Option<String>>,
488    pub content: Option<String>,
489    pub salience: Option<Option<f64>>,
490    pub decay_factor: Option<Option<f64>>,
491    pub properties: Option<Value>,
492    pub(crate) kind_status: Option<String>,
493}
494
495impl NotePatch {
496    /// Construct a `NotePatch` from the public fields only.
497    /// Use this from external crates; `kind_status` is set to `None`.
498    pub fn new(
499        name: Option<Option<String>>,
500        content: Option<String>,
501        salience: Option<Option<f64>>,
502        decay_factor: Option<Option<f64>>,
503        properties: Option<Value>,
504    ) -> Self {
505        Self {
506            name,
507            content,
508            salience,
509            decay_factor,
510            properties,
511            kind_status: None,
512        }
513    }
514}
515
516/// Filter for `list_edges` / `count_edges`.
517#[derive(Clone, Debug, Default)]
518pub struct EdgeListFilter {
519    pub source_id: Option<Uuid>,
520    pub target_id: Option<Uuid>,
521    /// Empty = any relation.
522    pub relations: Vec<EdgeRelation>,
523    pub min_weight: Option<f64>,
524    pub max_weight: Option<f64>,
525}
526
527impl From<EdgeListFilter> for EdgeFilter {
528    fn from(f: EdgeListFilter) -> Self {
529        EdgeFilter {
530            source_ids: f.source_id.into_iter().collect(),
531            target_ids: f.target_id.into_iter().collect(),
532            relations: f.relations,
533            min_weight: f.min_weight,
534            max_weight: f.max_weight,
535            ..Default::default()
536        }
537    }
538}
539
540// ---------------------------------------------------------------------------
541// Private types
542// ---------------------------------------------------------------------------
543
544#[derive(Clone, Copy, Debug, PartialEq, Eq)]
545enum EntityMergeValidation {
546    LegacyKind,
547    SafetyFloor,
548    Forced,
549}
550
551#[derive(Debug)]
552enum EntityMergeRefusal {
553    LegacyKind {
554        into_id: Uuid,
555        into_kind: String,
556        from_id: Uuid,
557        from_kind: String,
558    },
559    SafetyFloor(EntityMergeGuard),
560}
561
562impl EntityMergeRefusal {
563    fn into_runtime_error(self) -> RuntimeError {
564        match self {
565            Self::LegacyKind {
566                into_id,
567                into_kind,
568                from_id,
569                from_kind,
570            } => RuntimeError::InvalidInput(format!(
571                "cannot merge entities of different kinds: into={into_id} ({into_kind}), \
572                 from={from_id} ({from_kind}); merge requires both entities to share the same kind"
573            )),
574            Self::SafetyFloor(guard) => entity_merge_guard_error(guard),
575        }
576    }
577}
578
579#[derive(Debug)]
580enum MergeEntitySqlError {
581    Sqlite(SqliteError),
582    Refusal(EntityMergeRefusal),
583}
584
585impl std::fmt::Display for MergeEntitySqlError {
586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587        match self {
588            Self::Sqlite(error) => std::fmt::Display::fmt(error, f),
589            Self::Refusal(_) => f.write_str("entity merge refused by transactional policy"),
590        }
591    }
592}
593
594impl std::error::Error for MergeEntitySqlError {}
595
596impl From<SqliteError> for MergeEntitySqlError {
597    fn from(error: SqliteError) -> Self {
598        Self::Sqlite(error)
599    }
600}
601
602impl From<rusqlite::Error> for MergeEntitySqlError {
603    fn from(error: rusqlite::Error) -> Self {
604        Self::Sqlite(SqliteError::Rusqlite(error))
605    }
606}
607
608fn map_merge_entity_storage_error(error: khive_storage::StorageError) -> RuntimeError {
609    match error {
610        khive_storage::StorageError::Driver {
611            capability,
612            operation,
613            source,
614        } => match source.downcast::<MergeEntitySqlError>() {
615            Ok(error) => match *error {
616                MergeEntitySqlError::Sqlite(error) => RuntimeError::Sqlite(error),
617                MergeEntitySqlError::Refusal(error) => error.into_runtime_error(),
618            },
619            Err(source) => RuntimeError::Storage(khive_storage::StorageError::Driver {
620                capability,
621                operation,
622                source,
623            }),
624        },
625        error => RuntimeError::Storage(error),
626    }
627}
628
629// REASON: EdgeRow fields are populated via rusqlite row mapping. The struct is fully
630// constructed even when not all fields are read back after construction. The complete
631// field mapping guards against column-order bugs when the schema changes.
632#[derive(Clone)]
633struct EdgeRow {
634    id: Uuid,
635    /// The edge's own attribution namespace (khive#1236) — may differ from the
636    /// merge's target namespace, since by-ID edge endpoints are namespace-agnostic
637    /// (ADR-007 Rev 6) and an edge is stamped with its *creator's* namespace, not
638    /// either endpoint's. All row-scoped SQL against this edge (conflict probe,
639    /// update, delete) must key off this field, never the merge's `namespace` arg.
640    namespace: String,
641    source_id: Uuid,
642    target_id: Uuid,
643    relation: String,
644    weight: f64,
645    created_at: i64,
646    updated_at: i64,
647    deleted_at: Option<i64>,
648    target_backend: Option<String>,
649    metadata: Option<String>,
650}
651
652fn edge_row_preimage(edge: &EdgeRow) -> Result<MergeEdgePreimage, SqliteError> {
653    let metadata = edge
654        .metadata
655        .as_deref()
656        .map(serde_json::from_str)
657        .transpose()
658        .map_err(|error| SqliteError::InvalidData(error.to_string()))?;
659    Ok(MergeEdgePreimage {
660        id: edge.id,
661        namespace: edge.namespace.clone(),
662        source_id: edge.source_id,
663        target_id: edge.target_id,
664        relation: edge.relation.clone(),
665        weight: edge.weight,
666        created_at: edge.created_at,
667        updated_at: edge.updated_at,
668        deleted_at: edge.deleted_at,
669        target_backend: edge.target_backend.clone(),
670        metadata,
671    })
672}
673
674/// Capture every row that the accepted hard-edge-delete cascade would remove
675/// when `root_edge_id` is purged. The traversal is recursive because an
676/// `annotates` edge may itself be an annotation target. Rows that also touch a
677/// merge participant use their transaction-start snapshot from `original_edges`
678/// so the preimage never reflects an earlier rewire in the same merge.
679fn collect_conflict_incident_edge_preimages(
680    conn: &rusqlite::Connection,
681    root_edge_id: Uuid,
682    original_edges: &HashMap<Uuid, EdgeRow>,
683    budget: &mut MergeTxBudget,
684) -> Result<Vec<MergeEdgePreimage>, SqliteError> {
685    let parse_id =
686        |s: String| Uuid::parse_str(&s).map_err(|e| SqliteError::InvalidData(e.to_string()));
687    let mut queue = VecDeque::from([root_edge_id]);
688    let mut seen = HashSet::from([root_edge_id]);
689    let mut preimages = Vec::new();
690
691    while let Some(target_edge_id) = queue.pop_front() {
692        let mut stmt = conn.prepare(
693            "SELECT id, namespace, source_id, target_id, relation, weight, created_at, \
694                    updated_at, deleted_at, target_backend, metadata \
695             FROM graph_edges WHERE source_id = ?1 OR target_id = ?1 ORDER BY id",
696        )?;
697        let mut rows = stmt.query(rusqlite::params![target_edge_id.to_string()])?;
698        while let Some(row) = rows.next()? {
699            let edge = EdgeRow {
700                id: parse_id(row.get(0)?)?,
701                namespace: row.get(1)?,
702                source_id: parse_id(row.get(2)?)?,
703                target_id: parse_id(row.get(3)?)?,
704                relation: row.get(4)?,
705                weight: row.get(5)?,
706                created_at: row.get(6)?,
707                updated_at: row.get(7)?,
708                deleted_at: row.get(8)?,
709                target_backend: row.get(9)?,
710                metadata: row.get(10)?,
711            };
712            budget.charge(
713                1,
714                edge_row_budget_bytes(&edge),
715                "collecting conflict cascade rows",
716            )?;
717            if !seen.insert(edge.id) {
718                continue;
719            }
720            let preimage = match original_edges.get(&edge.id) {
721                Some(original) => edge_row_preimage(original)?,
722                None => edge_row_preimage(&edge)?,
723            };
724            queue.push_back(edge.id);
725            preimages.push(preimage);
726        }
727    }
728
729    Ok(preimages)
730}
731
732fn delete_conflict_incident_edges(
733    conn: &rusqlite::Connection,
734    preimages: &[MergeEdgePreimage],
735) -> Result<(), SqliteError> {
736    for edge in preimages.iter().rev() {
737        conn.execute(
738            khive_db::stores::graph::EDGE_SYMMETRIC_DELETE_NONCANONICAL_SQL,
739            rusqlite::params![&edge.namespace, edge.id.to_string()],
740        )?;
741    }
742    Ok(())
743}
744
745/// Resolves the substrate (`"entity"` or `"note"`), kind, and entity_type (entities
746/// only) of an edge endpoint by id, namespace-agnostically — by-ID resolution is
747/// namespace-agnostic by design (ADR-007 Rev 6), and an edge's non-merging endpoint
748/// may live in any namespace. Returns `None` if `id` resolves to neither table
749/// (e.g. a hard-deleted or otherwise absent record); callers must treat that as
750/// "the endpoint contract cannot be evaluated" and drop the edge rather than
751/// silently allow it through.
752/// `(substrate, kind, entity_type)` for a resolved merge-edge endpoint.
753type MergeEdgeEndpointInfo = (&'static str, String, Option<String>);
754
755fn resolve_merge_edge_endpoint(
756    conn: &rusqlite::Connection,
757    id: Uuid,
758) -> Result<Option<MergeEdgeEndpointInfo>, SqliteError> {
759    let id_str = id.to_string();
760    if let Some((kind, entity_type)) = conn
761        .query_row(
762            "SELECT kind, entity_type FROM entities WHERE id = ?1",
763            rusqlite::params![&id_str],
764            |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?)),
765        )
766        .optional()
767        .map_err(SqliteError::Rusqlite)?
768    {
769        return Ok(Some(("entity", kind, entity_type)));
770    }
771    if let Some(kind) = conn
772        .query_row(
773            "SELECT kind FROM notes WHERE id = ?1",
774            rusqlite::params![&id_str],
775            |row| row.get::<_, String>(0),
776        )
777        .optional()
778        .map_err(SqliteError::Rusqlite)?
779    {
780        return Ok(Some(("note", kind, None)));
781    }
782    Ok(None)
783}
784
785/// [`resolve_merge_edge_endpoint`] with the resolved row charged against the
786/// merge transaction budget — endpoint resolution reads one row per non-merging
787/// endpoint, so a hub merge's contract checks are part of its materialization.
788fn resolve_merge_edge_endpoint_budgeted(
789    conn: &rusqlite::Connection,
790    id: Uuid,
791    budget: &mut MergeTxBudget,
792) -> Result<Option<MergeEdgeEndpointInfo>, SqliteError> {
793    let info = resolve_merge_edge_endpoint(conn, id)?;
794    if let Some((_, kind, entity_type)) = &info {
795        budget.charge(
796            1,
797            kind.len() + entity_type.as_deref().map_or(0, str::len),
798            "resolving rewire endpoint contracts",
799        )?;
800    }
801    Ok(info)
802}
803
804/// `true` if `(src_sub, src_kind, src_type) -[relation]-> (tgt_sub, tgt_kind, tgt_type)`
805/// is permitted under the base ADR-002 entity allowlist or a pack-declared
806/// `EdgeEndpointRule` — the exact same `endpoint_matches` semantics `link`'s
807/// `validate_edge_relation_endpoints` applies (khive-runtime/src/operations.rs),
808/// reused here rather than re-derived, per the #543/#621 lesson that a parallel
809/// matcher drifts out of sync with the validator.
810///
811/// `annotates` is exempt: its source-must-be-a-note constraint is enforced at
812/// edge creation and unchanged by rewiring (an entity merge only ever rewires
813/// its unfiltered target; a note merge rewiring the source substitutes another
814/// note), and its target may be any substrate. Callers short-circuit `annotates`
815/// before endpoint resolution — an annotates target may be an event or an edge,
816/// which `resolve_merge_edge_endpoint` cannot resolve; the exemption here is
817/// kept as defense in depth.
818// REASON: the two endpoints each need substrate/kind/entity_type independently —
819// collapsing them into a tuple/struct would obscure which side is which at call
820// sites that already pass them as separate locals.
821#[allow(clippy::too_many_arguments)]
822fn merge_rewire_endpoint_contract_allows(
823    pack_rules: &[EdgeEndpointRule],
824    relation: EdgeRelation,
825    src_sub: &str,
826    src_kind: &str,
827    src_type: Option<&str>,
828    tgt_sub: &str,
829    tgt_kind: &str,
830    tgt_type: Option<&str>,
831) -> bool {
832    if relation == EdgeRelation::Annotates {
833        return true;
834    }
835    // Same-substrate relations permit any note→note pair unconditionally,
836    // matching `validate_edge_relation_endpoints`'s `(Note, Note) => {}` arm.
837    if src_sub == "note" && tgt_sub == "note" && crate::pack::is_special_relation(relation) {
838        return true;
839    }
840    if src_sub == "entity"
841        && tgt_sub == "entity"
842        && base_entity_rule_allows(src_kind, relation, tgt_kind)
843    {
844        return true;
845    }
846    pack_rules.iter().any(|r| {
847        r.relation == relation
848            && endpoint_matches(&r.source, src_sub, src_kind, src_type)
849            && endpoint_matches(&r.target, tgt_sub, tgt_kind, tgt_type)
850    })
851}
852
853// ---------------------------------------------------------------------------
854// Implementation
855// ---------------------------------------------------------------------------
856
857impl KhiveRuntime {
858    /// Patch-style entity update.
859    ///
860    /// Only fields set to `Some(_)` are changed. Re-indexes FTS5 (and vectors if configured)
861    /// when `name`, `description`, or `entity_type` changes; skips re-indexing for
862    /// property/tag-only patches.
863    ///
864    /// Returns `RuntimeError::NotFound` if the entity does not exist or belongs to a different
865    /// namespace. Namespace isolation is enforced at the runtime layer.
866    /// Computes the patched `Entity`, `reindex_required`, and `changed_fields` without
867    /// writing anything, so both the normal write path and the atomic-prepare path
868    /// share one source of truth for what a patched entity looks like.
869    pub(crate) async fn prepare_update_entity(
870        &self,
871        token: &NamespaceToken,
872        id: Uuid,
873        patch: EntityPatch,
874    ) -> RuntimeResult<(Entity, bool, Vec<&'static str>, i64, Option<i64>)> {
875        crate::secret_gate::reject_reserved_secret_gate_property(patch.properties.as_ref())?;
876        if let Some(ref name) = patch.name {
877            crate::secret_gate::check(name)?;
878        }
879        if let Some(Some(ref desc)) = patch.description {
880            crate::secret_gate::check(desc)?;
881        }
882        if let Some(ref props) = patch.properties {
883            crate::secret_gate::check_json(props)?;
884        }
885        if let Some(ref tags) = patch.tags {
886            crate::secret_gate::check_tags(tags)?;
887        }
888        let store = self.entities(token)?;
889        let mut entity = store
890            .get_entity(id)
891            .await?
892            .ok_or_else(|| RuntimeError::NotFound(format!("entity {id}")))?;
893        let expected_updated_at = entity.updated_at;
894        let expected_deleted_at = entity.deleted_at;
895        #[cfg(test)]
896        race_seam::pause_after_read().await;
897
898        // ADR-014 tri-state: outer `None` = unchanged; `Some(None)` = explicit
899        // clear (no vocabulary validation — there is no value to validate);
900        // `Some(Some(raw))` = set, validated and normalized.
901        let validated_entity_type = match &patch.entity_type {
902            Some(None) => Some(None),
903            Some(Some(raw)) => Some(Some(
904                self.validate_entity_type_for_kind(&entity.kind, Some(raw))?
905                    .expect("set branch always yields a normalized value"),
906            )),
907            None => None,
908        };
909
910        let mut reindex_required = false;
911        let mut changed_fields: Vec<&'static str> = Vec::new();
912
913        if let Some(name) = patch.name {
914            reindex_required |= entity.name != name;
915            entity.name = name;
916            changed_fields.push("name");
917        }
918        if let Some(desc_patch) = patch.description {
919            reindex_required |= entity.description != desc_patch;
920            entity.description = desc_patch;
921            changed_fields.push("description");
922        }
923        if let Some(props) = patch.properties {
924            let (merged, _) = merge_properties(
925                &entity.properties,
926                &Some(props),
927                EntityDedupMergePolicy::PreferFrom,
928            );
929            entity.properties = merged;
930            changed_fields.push("properties");
931        }
932        if let Some(tags) = patch.tags {
933            entity.tags = tags;
934            changed_fields.push("tags");
935        }
936        if let Some(entity_type) = validated_entity_type {
937            reindex_required |= entity.entity_type != entity_type;
938            entity.entity_type = entity_type;
939            changed_fields.push("entity_type");
940        }
941
942        // `updated_at` is also the optimistic-concurrency revision for
943        // full-entity replacement. Make it strictly advance even when two
944        // operations land inside one clock microsecond. Saturation is not a
945        // valid fallback: reusing i64::MAX would make the CAS accept a write
946        // without advancing its revision.
947        let minimum_updated_at = expected_updated_at.checked_add(1).ok_or_else(|| {
948            RuntimeError::Internal(format!(
949                "entity {id} updated_at is already at i64::MAX and cannot advance"
950            ))
951        })?;
952        entity.updated_at = chrono::Utc::now()
953            .timestamp_micros()
954            .max(minimum_updated_at);
955        Ok((
956            entity,
957            reindex_required,
958            changed_fields,
959            expected_updated_at,
960            expected_deleted_at,
961        ))
962    }
963
964    pub async fn update_entity(
965        &self,
966        token: &NamespaceToken,
967        id: Uuid,
968        patch: EntityPatch,
969    ) -> RuntimeResult<Entity> {
970        Ok(self
971            .update_entity_with_embedding_report(token, id, patch)
972            .await?
973            .0)
974    }
975
976    pub async fn update_entity_with_embedding_report(
977        &self,
978        token: &NamespaceToken,
979        id: Uuid,
980        patch: EntityPatch,
981    ) -> RuntimeResult<(Entity, crate::retrieval::EmbeddingTruncationReport)> {
982        let (entity, reindex_required, changed_fields, expected_updated_at, expected_deleted_at) =
983            self.prepare_update_entity(token, id, patch).await?;
984
985        let store = self.entities(token)?;
986        let persisted = store
987            .replace_entity_if_unchanged(entity.clone(), expected_updated_at, expected_deleted_at)
988            .await?;
989        if !persisted {
990            return Err(stale_entity_snapshot_error(id));
991        }
992
993        let embedding_report = if reindex_required {
994            self.reindex_entity(token, &entity).await?
995        } else {
996            crate::retrieval::EmbeddingTruncationReport::default()
997        };
998
999        let event_store = self.events(token)?;
1000        let event = khive_storage::event::Event::new(
1001            entity.namespace.clone(),
1002            "update",
1003            EventKind::EntityUpdated,
1004            SubstrateKind::Entity,
1005            "",
1006        )
1007        .with_target(entity.id)
1008        .with_payload(serde_json::json!({
1009            "id": entity.id,
1010            "namespace": entity.namespace,
1011            "changed_fields": changed_fields,
1012        }));
1013        event_store.append_event(event).await.map_err(|e| {
1014            RuntimeError::Internal(format!("update_entity: event store write failed: {e}"))
1015        })?;
1016
1017        Ok((entity, embedding_report))
1018    }
1019
1020    /// Merge `from_id` into `into_id`.
1021    ///
1022    /// All edges incident to `from_id` are rewired to `into_id`. Self-loops that would
1023    /// result from the rewire are dropped. Properties and tags are merged per `strategy`.
1024    /// `from_id` is tombstoned with merge provenance and removed from indexes. Returns a summary.
1025    ///
1026    /// If `dry_run` is true, computes and returns the planned summary without mutating any rows.
1027    ///
1028    /// Atomic: all SQL (entity reads/writes, edge rewires, FTS updates, vec-index delete)
1029    /// runs on a single pool connection inside one `BEGIN IMMEDIATE` transaction via
1030    /// `merge_entity_sql`. If embedding vectors are configured, the vector re-insert for
1031    /// `into_id` is performed after the transaction (requires async embedding computation).
1032    pub async fn merge_entity(
1033        &self,
1034        token: &NamespaceToken,
1035        into_id: Uuid,
1036        from_id: Uuid,
1037        strategy: EntityDedupMergePolicy,
1038        content_strategy: ContentMergeStrategy,
1039        dry_run: bool,
1040    ) -> RuntimeResult<MergeSummary> {
1041        self.merge_entity_with_reason(
1042            token,
1043            into_id,
1044            from_id,
1045            strategy,
1046            content_strategy,
1047            dry_run,
1048            None,
1049        )
1050        .await
1051    }
1052
1053    /// Merge `from_id` into `into_id` and include an optional reason in the audit event.
1054    // REASON: these arguments mirror the merge verb's policy, content strategy,
1055    // dry-run, and audit-reason fields; a builder would only move that surface.
1056    #[allow(clippy::too_many_arguments)]
1057    pub async fn merge_entity_with_reason(
1058        &self,
1059        token: &NamespaceToken,
1060        into_id: Uuid,
1061        from_id: Uuid,
1062        strategy: EntityDedupMergePolicy,
1063        content_strategy: ContentMergeStrategy,
1064        dry_run: bool,
1065        reason: Option<String>,
1066    ) -> RuntimeResult<MergeSummary> {
1067        self.merge_entity_with_validation(
1068            token,
1069            into_id,
1070            from_id,
1071            strategy,
1072            content_strategy,
1073            dry_run,
1074            reason,
1075            EntityMergeValidation::LegacyKind,
1076        )
1077        .await
1078    }
1079
1080    /// Merge two entities with an explicit override for the entity safety floor.
1081    ///
1082    /// Non-forced calls enforce entity kind, name similarity, and project compatibility
1083    /// against the rows reread inside the merge transaction. Legacy merge methods retain
1084    /// their historical same-kind-only policy.
1085    /// A non-dry-run override is recorded as `force: true` in the merge event.
1086    // REASON: these arguments mirror the merge verb's policy, content strategy,
1087    // dry-run, audit-reason, and force fields; a builder would only move that surface.
1088    #[allow(clippy::too_many_arguments)]
1089    pub async fn merge_entity_with_reason_and_force(
1090        &self,
1091        token: &NamespaceToken,
1092        into_id: Uuid,
1093        from_id: Uuid,
1094        strategy: EntityDedupMergePolicy,
1095        content_strategy: ContentMergeStrategy,
1096        dry_run: bool,
1097        reason: Option<String>,
1098        force: bool,
1099    ) -> RuntimeResult<MergeSummary> {
1100        let validation = if force {
1101            EntityMergeValidation::Forced
1102        } else {
1103            EntityMergeValidation::SafetyFloor
1104        };
1105        self.merge_entity_with_validation(
1106            token,
1107            into_id,
1108            from_id,
1109            strategy,
1110            content_strategy,
1111            dry_run,
1112            reason,
1113            validation,
1114        )
1115        .await
1116    }
1117
1118    #[allow(clippy::too_many_arguments)]
1119    async fn merge_entity_with_validation(
1120        &self,
1121        token: &NamespaceToken,
1122        into_id: Uuid,
1123        from_id: Uuid,
1124        strategy: EntityDedupMergePolicy,
1125        content_strategy: ContentMergeStrategy,
1126        dry_run: bool,
1127        reason: Option<String>,
1128        validation: EntityMergeValidation,
1129    ) -> RuntimeResult<MergeSummary> {
1130        if let Some(reason) = reason.as_deref() {
1131            crate::secret_gate::check(reason)?;
1132        }
1133        if into_id == from_id {
1134            return Err(RuntimeError::InvalidInput(
1135                "cannot merge an entity into itself".into(),
1136            ));
1137        }
1138        let ns = token.namespace().as_str().to_owned();
1139        let fts_table = "fts_entities".to_string();
1140        // One immutable registry view governs transactional deletion, table
1141        // preparation, and survivor reindex. A late model belongs to a later
1142        // write/backfill rather than only one leg of this merge.
1143        let embedding_plan = EmbeddingModelPlan::capture(self);
1144        let vec_tables = embedding_plan.vector_tables();
1145        // Loaded once here (sync, cheap) so the rewire loop can evaluate the
1146        // endpoint contract without an async round-trip per edge (khive#1216).
1147        let pack_rules = self.pack_edge_rules();
1148
1149        // Ensure all required tables exist (idempotent DDL) before the transaction.
1150        let _ = self.entities(token)?;
1151        let _ = self.graph(token)?;
1152        let _ = self.text(token)?;
1153        // vectors_for_model (not the default-model-only self.vectors()) so
1154        // custom-only runtimes (no default embedding_model) still get DDL primed.
1155        for model_name in embedding_plan.model_names() {
1156            let _ = self.vectors_for_model(token, model_name)?;
1157        }
1158
1159        let pool = self.backend().pool_arc();
1160        // When the write queue is enabled, route this multi-statement merge through
1161        // the single-writer task instead of the pool's writer mutex. A lookup
1162        // failure degrades to the legacy mutex path rather than failing the merge.
1163        let writer_task = pool.writer_task_handle().ok().flatten();
1164
1165        let (mut summary, updated_entity) = if let Some(writer_task) = writer_task {
1166            writer_task
1167                .send(move |conn| {
1168                    merge_entity_sql(
1169                        conn,
1170                        ns,
1171                        fts_table,
1172                        vec_tables,
1173                        into_id,
1174                        from_id,
1175                        strategy,
1176                        content_strategy,
1177                        dry_run,
1178                        pack_rules,
1179                        validation,
1180                        MergeTxLimits::default(),
1181                    )
1182                    .map_err(|e| {
1183                        khive_storage::StorageError::driver(
1184                            khive_storage::StorageCapability::Entities,
1185                            "merge_entity",
1186                            e,
1187                        )
1188                    })
1189                })
1190                .await
1191                .map_err(map_merge_entity_storage_error)?
1192        } else {
1193            tokio::task::spawn_blocking(move || {
1194                let guard = pool.writer()?;
1195                let mut refusal = None;
1196                let result = guard.transaction(|conn| {
1197                    merge_entity_sql(
1198                        conn,
1199                        ns,
1200                        fts_table,
1201                        vec_tables,
1202                        into_id,
1203                        from_id,
1204                        strategy,
1205                        content_strategy,
1206                        dry_run,
1207                        pack_rules,
1208                        validation,
1209                        MergeTxLimits::default(),
1210                    )
1211                    .map_err(|error| match error {
1212                        MergeEntitySqlError::Sqlite(error) => error,
1213                        MergeEntitySqlError::Refusal(error) => {
1214                            refusal = Some(error);
1215                            SqliteError::InvalidData(
1216                                "entity merge refused by transactional policy".to_string(),
1217                            )
1218                        }
1219                    })
1220                });
1221                match refusal {
1222                    Some(error) => Err(error.into_runtime_error()),
1223                    None => result.map_err(RuntimeError::from),
1224                }
1225            })
1226            .await
1227            .map_err(|e| RuntimeError::Internal(e.to_string()))??
1228        };
1229
1230        // Emitted only after the transaction has committed, so the log write
1231        // never extends the writer hold the budget exists to bound.
1232        if !dry_run {
1233            tracing::info!(
1234                into_id = %summary.kept_id,
1235                from_id = %summary.removed_id,
1236                budget_rows = summary.tx_budget.rows_charged,
1237                budget_bytes = summary.tx_budget.bytes_charged,
1238                budget_max_rows = summary.tx_budget.max_rows,
1239                budget_max_bytes = summary.tx_budget.max_bytes,
1240                "merge_entity: transaction materialization budget"
1241            );
1242        }
1243
1244        // FTS and vec-deletes already committed inside the transaction above;
1245        // only the embedding re-insert needs an async step outside it.
1246        if !dry_run && !embedding_plan.is_empty() {
1247            summary.embedding_truncation = self
1248                .reindex_entity_with_plan(token, &updated_entity, &embedding_plan)
1249                .await?;
1250        }
1251
1252        // Dry-run is a read-only preview: it must not append a merge event.
1253        if !dry_run {
1254            let event_store = self.events(token)?;
1255            // Mirror the wire-level strategy spelling from MergeParams so consumers
1256            // can round-trip the policy string back into a request.
1257            let policy_str = match strategy {
1258                EntityDedupMergePolicy::PreferInto => "prefer_into",
1259                EntityDedupMergePolicy::PreferFrom => "prefer_from",
1260                EntityDedupMergePolicy::Union => "union",
1261            };
1262            let mut payload = serde_json::json!({
1263                "into_id": summary.kept_id,
1264                "from_id": summary.removed_id,
1265                "policy": policy_str,
1266                "content_strategy": format!("{:?}", content_strategy),
1267                "edges_rewired": summary.edges_rewired,
1268                "edges_contract_skipped": summary.edges_contract_skipped,
1269                "edge_conflict_preimages": &summary.edge_conflict_preimages,
1270            });
1271            if let Some(reason) = reason {
1272                payload["reason"] = serde_json::Value::String(reason);
1273            }
1274            if validation == EntityMergeValidation::Forced {
1275                payload["force"] = serde_json::Value::Bool(true);
1276            }
1277            let event = khive_storage::event::Event::new(
1278                updated_entity.namespace.clone(),
1279                "merge",
1280                EventKind::EntityMerged,
1281                SubstrateKind::Entity,
1282                "",
1283            )
1284            .with_target(summary.kept_id)
1285            .with_payload(payload);
1286            event_store.append_event(event).await.map_err(|e| {
1287                RuntimeError::Internal(format!("merge_entity: event store write failed: {e}"))
1288            })?;
1289        }
1290
1291        Ok(summary)
1292    }
1293
1294    // ---- Internal helpers ----
1295
1296    /// Re-upsert FTS5 document and vector(s) for the entity across all registered models.
1297    ///
1298    /// Uses `entity.namespace` — the authoritative namespace stored on the record — rather
1299    /// than the caller-supplied `namespace` parameter. This prevents a cross-namespace
1300    /// reindex from writing the search document into the wrong namespace's FTS index.
1301    ///
1302    /// Best-effort for vectors: if embedding or inserting for a particular model fails,
1303    /// logs a warning and continues to the next model. The FTS step is fail-closed
1304    /// (propagates error). Callers (update_entity, merge_entity) have already committed
1305    /// the entity row, so a partial embed miss leaves a stale vector rather than
1306    /// rolling back the update — acceptable because SqliteVecStore::insert is an upsert
1307    /// (the prior vector stays intact on failure, keeping the record searchable).
1308    pub(crate) async fn reindex_entity(
1309        &self,
1310        token: &NamespaceToken,
1311        entity: &Entity,
1312    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1313        let embedding_plan = EmbeddingModelPlan::capture(self);
1314        self.reindex_entity_with_plan(token, entity, &embedding_plan)
1315            .await
1316    }
1317
1318    async fn reindex_entity_with_plan(
1319        &self,
1320        token: &NamespaceToken,
1321        entity: &Entity,
1322        embedding_plan: &EmbeddingModelPlan,
1323    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1324        // Use entity.namespace (authoritative) rather than token.namespace().as_str() (caller claim).
1325        let ns = entity.namespace.clone();
1326        let doc = entity_fts_document(entity);
1327        let embed_body = doc.body.clone();
1328        self.text(token)?.upsert_document(doc).await?;
1329
1330        let mut report = crate::retrieval::EmbeddingTruncationReport::default();
1331        for model_name in embedding_plan.model_names() {
1332            match self
1333                .embed_document_with_model_outcome_for_token(token, model_name, &embed_body)
1334                .await
1335            {
1336                Ok(outcome) => {
1337                    report.observe(&outcome);
1338                    match self.vectors_for_model(token, model_name) {
1339                        Ok(vs) => {
1340                            if let Err(e) = vs
1341                                .insert(
1342                                    entity.id,
1343                                    SubstrateKind::Entity,
1344                                    &ns,
1345                                    "entity.body",
1346                                    vec![outcome.vector],
1347                                )
1348                                .await
1349                            {
1350                                tracing::warn!(
1351                                    model = model_name,
1352                                    id = %entity.id,
1353                                    "reindex_entity: vector insert failed, skipping model: {e}"
1354                                );
1355                            }
1356                        }
1357                        Err(e) => {
1358                            tracing::warn!(
1359                                model = model_name,
1360                                id = %entity.id,
1361                                "reindex_entity: could not access vector store for model, skipping: {e}"
1362                            );
1363                        }
1364                    }
1365                }
1366                Err(e) => {
1367                    tracing::warn!(
1368                        model = model_name,
1369                        id = %entity.id,
1370                        "reindex_entity: embed failed for model, skipping: {e}"
1371                    );
1372                }
1373            }
1374        }
1375
1376        Ok(report)
1377    }
1378
1379    /// Remove an entity from FTS5 and vector indexes across all registered models.
1380    pub(crate) async fn remove_from_indexes(
1381        &self,
1382        token: &NamespaceToken,
1383        id: Uuid,
1384    ) -> RuntimeResult<()> {
1385        let ns = token.namespace().as_str().to_owned();
1386        self.text(token)?.delete_document(&ns, id).await?;
1387        for model_name in self.registered_embedding_model_names() {
1388            self.vectors_for_model(token, &model_name)?
1389                .delete(id)
1390                .await?;
1391        }
1392        Ok(())
1393    }
1394
1395    /// Re-upsert FTS5 document and vector(s) for the note across all registered models.
1396    ///
1397    /// Best-effort for vectors: mirrors reindex_entity's warn-and-continue policy.
1398    pub(crate) async fn reindex_note(
1399        &self,
1400        token: &NamespaceToken,
1401        note: &khive_storage::note::Note,
1402    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1403        let embedding_plan = EmbeddingModelPlan::capture(self);
1404        self.reindex_note_with_plan(token, note, &embedding_plan)
1405            .await
1406    }
1407
1408    async fn reindex_note_with_plan(
1409        &self,
1410        token: &NamespaceToken,
1411        note: &khive_storage::note::Note,
1412        embedding_plan: &EmbeddingModelPlan,
1413    ) -> RuntimeResult<crate::retrieval::EmbeddingTruncationReport> {
1414        self.text_for_notes(token)?
1415            .upsert_document(note_fts_document(note))
1416            .await?;
1417
1418        let ns = note.namespace.clone();
1419        let mut report = crate::retrieval::EmbeddingTruncationReport::default();
1420        for model_name in embedding_plan.model_names() {
1421            match self
1422                .embed_document_with_model_outcome_for_token(
1423                    token,
1424                    model_name,
1425                    note_embedding_text_ref(note),
1426                )
1427                .await
1428            {
1429                Ok(outcome) => {
1430                    report.observe(&outcome);
1431                    match self.vectors_for_model(token, model_name) {
1432                        Ok(vs) => {
1433                            if let Err(e) = vs
1434                                .insert(
1435                                    note.id,
1436                                    SubstrateKind::Note,
1437                                    &ns,
1438                                    "note.content",
1439                                    vec![outcome.vector],
1440                                )
1441                                .await
1442                            {
1443                                tracing::warn!(
1444                                    model = model_name,
1445                                    id = %note.id,
1446                                    "reindex_note: vector insert failed, skipping model: {e}"
1447                                );
1448                            }
1449                        }
1450                        Err(e) => {
1451                            tracing::warn!(
1452                                model = model_name,
1453                                id = %note.id,
1454                                "reindex_note: could not access vector store for model, skipping: {e}"
1455                            );
1456                        }
1457                    }
1458                }
1459                Err(e) => {
1460                    tracing::warn!(
1461                        model = model_name,
1462                        id = %note.id,
1463                        "reindex_note: embed failed for model, skipping: {e}"
1464                    );
1465                }
1466            }
1467        }
1468        Ok(report)
1469    }
1470
1471    /// Apply a note patch to exactly the supplied read snapshot without
1472    /// fetching the row again. The caller must persist it through
1473    /// [`Self::update_note_from_snapshot_with_embedding_report`] or a write
1474    /// plan guarded by the snapshot's `updated_at`/`deleted_at` values.
1475    pub(crate) async fn prepare_update_note_from_snapshot(
1476        &self,
1477        _token: &NamespaceToken,
1478        mut note: khive_storage::note::Note,
1479        patch: NotePatch,
1480    ) -> RuntimeResult<(khive_storage::note::Note, bool)> {
1481        crate::secret_gate::reject_reserved_secret_gate_property(patch.properties.as_ref())?;
1482        if let Some(ref content) = patch.content {
1483            crate::secret_gate::check(content)?;
1484        }
1485        if let Some(Some(ref name)) = patch.name {
1486            crate::secret_gate::check(name)?;
1487        }
1488        if let Some(ref props) = patch.properties {
1489            crate::secret_gate::check_json(props)?;
1490        }
1491
1492        reject_pack_managed_schedule_mutation(&note, "update")?;
1493
1494        let mut text_changed = false;
1495
1496        if let Some(name_patch) = patch.name {
1497            text_changed |= note.name != name_patch;
1498            note.name = name_patch;
1499        }
1500        if let Some(content) = patch.content {
1501            text_changed |= note.content != content;
1502            note.content = content;
1503        }
1504        if let Some(salience_patch) = patch.salience {
1505            // Reject invalid salience rather than silently clamping caller input.
1506            if let Some(s) = salience_patch {
1507                if !s.is_finite() || !(0.0..=1.0).contains(&s) {
1508                    return Err(crate::RuntimeError::InvalidInput(format!(
1509                        "salience must be a finite value in [0.0, 1.0]; got {s}"
1510                    )));
1511                }
1512            }
1513            note.salience = salience_patch;
1514        }
1515        if let Some(decay_patch) = patch.decay_factor {
1516            // Reject invalid decay_factor rather than silently clamping caller input.
1517            if let Some(d) = decay_patch {
1518                if !d.is_finite() || d < 0.0 {
1519                    return Err(crate::RuntimeError::InvalidInput(format!(
1520                        "decay_factor must be a finite value >= 0.0; got {d}"
1521                    )));
1522                }
1523            }
1524            note.decay_factor = decay_patch;
1525        }
1526        if let Some(props) = patch.properties {
1527            // ADR-056 makes these three properties transport evidence owned
1528            // exclusively by `comm.ingest`. This check lives at the runtime
1529            // patch seam, not only in comm's shared-CRUD hook, because direct
1530            // Rust callers and atomic update preparation both arrive here
1531            // without dispatching that hook. Scope it to `message`: the same
1532            // JSON names remain ordinary caller metadata on every other kind.
1533            if note.kind == "message" {
1534                if !props.is_object() {
1535                    return Err(RuntimeError::InvalidInput(
1536                        "properties on a `message` note must be patched with an object: a \
1537                         non-object patch would replace the transport-owned quarantine and \
1538                         channel provenance established by `comm.ingest`"
1539                            .into(),
1540                    ));
1541                }
1542                if let Some(named) = message_transport_owned_property_named_in(&props) {
1543                    return Err(RuntimeError::InvalidInput(format!(
1544                        "`{named}` is transport-owned on a `message` note and cannot be patched; \
1545                         only `comm.ingest` may establish quarantine disposition and channel \
1546                         provenance"
1547                    )));
1548                }
1549            }
1550            // On a pack-owned note kind, the properties in
1551            // `OWNER_ESTABLISHED_PROPERTIES` are established by the owning pack
1552            // and read back by it to decide something structural — who wrote
1553            // the record and when, which author-side record it copies, which
1554            // conversation it belongs to. A caller cannot patch them here.
1555            // Only a patch that *names* one of them is refused, and naming is
1556            // the exact test: the merge below is `PreferFrom`, so a patch that
1557            // names an owned key would overwrite it while a patch that does
1558            // not name it leaves it intact. Every other key still merges
1559            // normally — arbitrary metadata on a pack-owned record (a
1560            // `blocked_on` note on a `task`) has no other write path and must
1561            // keep working.
1562            if self.is_pack_owned_note_kind(&note.kind) {
1563                // A non-object patch names nothing, so it slips past the
1564                // named-key check below and then takes `merge_json`'s
1565                // non-object `PreferFrom` arm, which replaces the whole
1566                // property object rather than merging into it — erasing
1567                // every owned key. Refused on every pack-owned kind, not only
1568                // rows that currently carry an owned key, so an identical
1569                // call cannot succeed or fail on state the caller cannot see.
1570                if !props.is_object() {
1571                    return Err(RuntimeError::InvalidInput(format!(
1572                        "properties on a `{}` note must be patched with an object: a non-object \
1573                         patch names no key, so it would replace the whole property object rather \
1574                         than merging into it. Pass an object containing the keys you intend to \
1575                         set.",
1576                        note.kind
1577                    )));
1578                }
1579                if let Some(named) = owner_established_property_named_in(&props) {
1580                    return Err(RuntimeError::InvalidInput(format!(
1581                        "`{named}` is not patchable on a `{}` note: the pack that owns this \
1582                         kind establishes it and reads it back — to decide how the record is \
1583                         attributed and grouped, or to reproduce it verbatim when the record \
1584                         is re-emitted — so it is written by the owner and immutable to a \
1585                         caller patch. Patch any other property key here, or omit \
1586                         `{named}` from this patch.",
1587                        note.kind
1588                    )));
1589                }
1590            }
1591            let (merged, _) = merge_properties(
1592                &note.properties,
1593                &Some(props),
1594                EntityDedupMergePolicy::PreferFrom,
1595            );
1596            note.properties = merged;
1597        }
1598        if let Some(status) = patch.kind_status {
1599            note.status = status;
1600        }
1601
1602        // `updated_at` is also the optimistic-concurrency revision for
1603        // full-note replacement. Make it strictly advance even when two
1604        // operations land inside one clock microsecond. Saturation is not a
1605        // valid fallback: reusing i64::MAX would make the CAS accept a write
1606        // without advancing its revision.
1607        let minimum_updated_at = note.updated_at.checked_add(1).ok_or_else(|| {
1608            RuntimeError::Internal(format!(
1609                "note {} updated_at is already at i64::MAX and cannot advance",
1610                note.id
1611            ))
1612        })?;
1613        note.updated_at = chrono::Utc::now()
1614            .timestamp_micros()
1615            .max(minimum_updated_at);
1616        Ok((note, text_changed))
1617    }
1618
1619    /// Patch-style note update.
1620    pub async fn update_note(
1621        &self,
1622        token: &NamespaceToken,
1623        id: Uuid,
1624        patch: NotePatch,
1625    ) -> RuntimeResult<khive_storage::note::Note> {
1626        Ok(self
1627            .update_note_with_embedding_report(token, id, patch)
1628            .await?
1629            .0)
1630    }
1631
1632    pub async fn update_note_with_embedding_report(
1633        &self,
1634        token: &NamespaceToken,
1635        id: Uuid,
1636        patch: NotePatch,
1637    ) -> RuntimeResult<(
1638        khive_storage::note::Note,
1639        crate::retrieval::EmbeddingTruncationReport,
1640    )> {
1641        let snapshot = self
1642            .notes(token)?
1643            .get_note(id)
1644            .await?
1645            .ok_or_else(|| RuntimeError::NotFound(format!("note {id}")))?;
1646        self.update_note_from_snapshot_with_embedding_report(token, snapshot, patch)
1647            .await
1648    }
1649
1650    /// Patch and persist one note from a caller-owned read snapshot.
1651    ///
1652    /// This is the canonical seam for kind hooks that normalize coupled
1653    /// fields from the current note. The same snapshot feeds normalization,
1654    /// patch application, and the compare-and-swap write; a concurrent note
1655    /// change therefore refuses the write instead of persisting derivations
1656    /// computed from stale state.
1657    pub async fn update_note_from_snapshot_with_embedding_report(
1658        &self,
1659        token: &NamespaceToken,
1660        snapshot: khive_storage::note::Note,
1661        patch: NotePatch,
1662    ) -> RuntimeResult<(
1663        khive_storage::note::Note,
1664        crate::retrieval::EmbeddingTruncationReport,
1665    )> {
1666        let expected_updated_at = snapshot.updated_at;
1667        let expected_deleted_at = snapshot.deleted_at;
1668        let id = snapshot.id;
1669        let store = self.notes(token)?;
1670        let current = store
1671            .get_note(id)
1672            .await?
1673            .ok_or_else(|| RuntimeError::NotFound(format!("note {id}")))?;
1674        if current != snapshot {
1675            return Err(stale_note_snapshot_error(id));
1676        }
1677        let (note, text_changed) = self
1678            .prepare_update_note_from_snapshot(token, snapshot, patch)
1679            .await?;
1680
1681        let persisted = store
1682            .replace_note_if_unchanged(note.clone(), expected_updated_at, expected_deleted_at)
1683            .await?;
1684        if !persisted {
1685            return Err(stale_note_snapshot_error(id));
1686        }
1687
1688        let embedding_report = if text_changed {
1689            let report = self.reindex_note(token, &note).await?;
1690            // Notify any pack-owned vector cache (e.g. a warm ANN index) that this
1691            // note's embedding changed, via a generic hook so khive-runtime/pack-kg
1692            // never take a dependency on the consuming pack. No-op if unregistered.
1693            self.fire_note_mutation_hook(&note.kind, note.id).await;
1694            report
1695        } else {
1696            crate::retrieval::EmbeddingTruncationReport::default()
1697        };
1698
1699        Ok((note, embedding_report))
1700    }
1701
1702    /// Claim `external_id` on an outbound `message` note through the
1703    /// ADR-124-sanctioned store-level one-key atomic path, bypassing the
1704    /// caller-facing owner-established-property refusal in
1705    /// [`Self::update_note`] (and its crate-internal prepare path). This is deliberately
1706    /// NOT exposed through any registered verb (ADR-124's stated bound): it is
1707    /// reachable only from pack/runtime code that owns outbox bookkeeping for
1708    /// the `message` note kind.
1709    ///
1710    /// Refuses (returns `Err`, never writes) unless the live row is a
1711    /// `message` note, `properties.direction == "outbound"`, and
1712    /// `properties.external_id` is currently absent or empty.
1713    pub async fn claim_outbound_message_external_id(
1714        &self,
1715        token: &NamespaceToken,
1716        id: Uuid,
1717        external_id: String,
1718    ) -> RuntimeResult<khive_storage::note::Note> {
1719        let store = self.notes(token)?;
1720        let note = store
1721            .get_note(id)
1722            .await?
1723            .ok_or_else(|| RuntimeError::NotFound(format!("note {id}")))?;
1724        if note.kind != "message" {
1725            return Err(RuntimeError::InvalidInput(format!(
1726                "external_id can only be claimed on a `message` note; note {id} is a `{}`",
1727                note.kind
1728            )));
1729        }
1730        let props = note.properties.as_ref().and_then(|v| v.as_object());
1731        let direction = props
1732            .and_then(|p| p.get("direction"))
1733            .and_then(|v| v.as_str());
1734        if direction != Some("outbound") {
1735            return Err(RuntimeError::InvalidInput(format!(
1736                "external_id can only be claimed on an outbound message note; note {id} has \
1737                 direction {:?}",
1738                direction
1739            )));
1740        }
1741        let existing = props
1742            .and_then(|p| p.get("external_id"))
1743            .and_then(|v| v.as_str());
1744        if existing.is_some_and(|v| !v.is_empty()) {
1745            return Err(RuntimeError::InvalidInput(format!(
1746                "note {id} already has an external_id claimed"
1747            )));
1748        }
1749        store
1750            .set_note_property(
1751                id,
1752                "external_id",
1753                Value::String(external_id),
1754                note.updated_at,
1755            )
1756            .await?;
1757        store
1758            .get_note(id)
1759            .await?
1760            .ok_or_else(|| RuntimeError::NotFound(format!("note {id}")))
1761    }
1762
1763    /// Merge `from_id` note into `into_id` note.
1764    ///
1765    /// Both notes must exist in the namespace and have the same `kind`. Content is merged
1766    /// per `content_strategy`. Properties are merged per `strategy`. `from_id` is
1767    /// tombstoned (status='deleted', deleted_at set). Returns a summary.
1768    ///
1769    /// If `dry_run` is true, computes and returns the planned summary without mutating
1770    /// any rows, edges, or indexes.
1771    pub async fn merge_note(
1772        &self,
1773        token: &NamespaceToken,
1774        into_id: Uuid,
1775        from_id: Uuid,
1776        strategy: EntityDedupMergePolicy,
1777        content_strategy: ContentMergeStrategy,
1778        dry_run: bool,
1779    ) -> RuntimeResult<MergeSummary> {
1780        self.merge_note_with_reason(
1781            token,
1782            into_id,
1783            from_id,
1784            strategy,
1785            content_strategy,
1786            dry_run,
1787            None,
1788        )
1789        .await
1790    }
1791
1792    /// Merge `from_id` note into `into_id` note and include an optional audit reason.
1793    // REASON: these arguments mirror the merge verb's policy, content strategy,
1794    // dry-run, and audit-reason fields; a builder would only move that surface.
1795    #[allow(clippy::too_many_arguments)]
1796    pub async fn merge_note_with_reason(
1797        &self,
1798        token: &NamespaceToken,
1799        into_id: Uuid,
1800        from_id: Uuid,
1801        strategy: EntityDedupMergePolicy,
1802        content_strategy: ContentMergeStrategy,
1803        dry_run: bool,
1804        reason: Option<String>,
1805    ) -> RuntimeResult<MergeSummary> {
1806        if let Some(reason) = reason.as_deref() {
1807            crate::secret_gate::check(reason)?;
1808        }
1809        if into_id == from_id {
1810            return Err(RuntimeError::InvalidInput(
1811                "cannot merge a note into itself".into(),
1812            ));
1813        }
1814        let ns = token.namespace().as_str().to_string();
1815        let fts_table = "fts_notes".to_string();
1816        // Keep deletion, table preparation, and survivor reindex on the same
1817        // immutable registry view; see the entity merge path above.
1818        let embedding_plan = EmbeddingModelPlan::capture(self);
1819        let vec_tables = embedding_plan.vector_tables();
1820        let pack_rules = self.pack_edge_rules();
1821
1822        let note_store = self.notes(token)?;
1823        let into_note = note_store
1824            .get_note(into_id)
1825            .await?
1826            .ok_or_else(|| RuntimeError::NotFound("not found in this namespace".into()))?;
1827        Self::ensure_namespace(&into_note.namespace, &ns)?;
1828
1829        let from_note = note_store
1830            .get_note(from_id)
1831            .await?
1832            .ok_or_else(|| RuntimeError::NotFound("not found in this namespace".into()))?;
1833        Self::ensure_namespace(&from_note.namespace, &ns)?;
1834
1835        reject_pack_managed_schedule_mutation(&into_note, "merge")?;
1836        reject_pack_managed_schedule_mutation(&from_note, "merge")?;
1837
1838        let _ = self.graph(token)?;
1839        let _ = self.text_for_notes(token)?;
1840        for model_name in embedding_plan.model_names() {
1841            let _ = self.vectors_for_model(token, model_name)?;
1842        }
1843
1844        // Resolved here, where the runtime's installed pack-kind list is in
1845        // reach; `merge_note_sql` runs on the writer connection with no runtime
1846        // handle. Both notes share a kind (checked inside), so the into-note's
1847        // kind decides for the merge.
1848        let preserve_owner_established = self.is_pack_owned_note_kind(&into_note.kind);
1849
1850        let pool = self.backend().pool_arc();
1851        let writer_task = pool.writer_task_handle().ok().flatten();
1852
1853        let (mut summary, updated_note) = if let Some(writer_task) = writer_task {
1854            writer_task
1855                .send(move |conn| {
1856                    merge_note_sql(
1857                        conn,
1858                        ns,
1859                        fts_table,
1860                        vec_tables,
1861                        into_id,
1862                        from_id,
1863                        strategy,
1864                        content_strategy,
1865                        dry_run,
1866                        pack_rules,
1867                        preserve_owner_established,
1868                        MergeTxLimits::default(),
1869                    )
1870                    .map_err(|e| {
1871                        khive_storage::StorageError::driver(
1872                            khive_storage::StorageCapability::Notes,
1873                            "merge_note",
1874                            e,
1875                        )
1876                    })
1877                })
1878                .await
1879                .map_err(RuntimeError::Storage)?
1880        } else {
1881            tokio::task::spawn_blocking(move || {
1882                let guard = pool.writer()?;
1883                guard.transaction(|conn| {
1884                    merge_note_sql(
1885                        conn,
1886                        ns,
1887                        fts_table,
1888                        vec_tables,
1889                        into_id,
1890                        from_id,
1891                        strategy,
1892                        content_strategy,
1893                        dry_run,
1894                        pack_rules,
1895                        preserve_owner_established,
1896                        MergeTxLimits::default(),
1897                    )
1898                })
1899            })
1900            .await
1901            .map_err(|e| RuntimeError::Internal(e.to_string()))??
1902        };
1903
1904        // Emitted only after the transaction has committed, so the log write
1905        // never extends the writer hold the budget exists to bound.
1906        if !dry_run {
1907            tracing::info!(
1908                into_id = %summary.kept_id,
1909                from_id = %summary.removed_id,
1910                budget_rows = summary.tx_budget.rows_charged,
1911                budget_bytes = summary.tx_budget.bytes_charged,
1912                budget_max_rows = summary.tx_budget.max_rows,
1913                budget_max_bytes = summary.tx_budget.max_bytes,
1914                "merge_note: transaction materialization budget"
1915            );
1916        }
1917
1918        if !dry_run && !embedding_plan.is_empty() {
1919            summary.embedding_truncation = self
1920                .reindex_note_with_plan(token, &updated_note, &embedding_plan)
1921                .await?;
1922            // A merge changes the same ANN corpus as update_note's text_changed
1923            // branch, so fire the same mutation hook regardless of which public
1924            // write path reached the corpus change.
1925            self.fire_note_mutation_hook(&updated_note.kind, updated_note.id)
1926                .await;
1927        }
1928
1929        // Dry-run is a read-only preview: it must not append a merge event.
1930        if !dry_run {
1931            let event_store = self.events(token)?;
1932            // Mirror the wire-level strategy spelling from MergeParams so consumers
1933            // can round-trip the policy string back into a request.
1934            let policy_str = match strategy {
1935                EntityDedupMergePolicy::PreferInto => "prefer_into",
1936                EntityDedupMergePolicy::PreferFrom => "prefer_from",
1937                EntityDedupMergePolicy::Union => "union",
1938            };
1939            let mut payload = serde_json::json!({
1940                "into_id": summary.kept_id,
1941                "from_id": summary.removed_id,
1942                "policy": policy_str,
1943                "content_strategy": format!("{:?}", content_strategy),
1944                "edges_rewired": summary.edges_rewired,
1945                "edges_contract_skipped": summary.edges_contract_skipped,
1946                "edge_conflict_preimages": &summary.edge_conflict_preimages,
1947            });
1948            if let Some(reason) = reason {
1949                payload["reason"] = serde_json::Value::String(reason);
1950            }
1951            let event = khive_storage::event::Event::new(
1952                updated_note.namespace.clone(),
1953                "merge",
1954                EventKind::NoteMerged,
1955                SubstrateKind::Note,
1956                "",
1957            )
1958            .with_target(summary.kept_id)
1959            .with_payload(payload);
1960            event_store.append_event(event).await.map_err(|e| {
1961                RuntimeError::Internal(format!("merge_note: event store write failed: {e}"))
1962            })?;
1963        }
1964
1965        Ok(summary)
1966    }
1967}
1968
1969/// Keep executable schedule intent behind the schedule pack's state-machine verbs.
1970///
1971/// `scheduled_event` notes carry both replay payloads and lifecycle state. Allowing
1972/// generic note update/merge to rewrite either would turn the immutable creator event
1973/// into a bearer credential for attacker-selected work: replay would attribute the
1974/// changed row to its original creator. Schedule's own transitions use its private
1975/// note-store CAS helpers and therefore do not pass through this generic curation seam.
1976fn reject_pack_managed_schedule_mutation(
1977    note: &khive_storage::note::Note,
1978    operation: &str,
1979) -> RuntimeResult<()> {
1980    if note.kind == "scheduled_event" {
1981        return Err(RuntimeError::InvalidInput(format!(
1982            "cannot {operation} a schedule-managed `scheduled_event` note through generic KG \
1983             mutation; use schedule.cancel or create a replacement schedule"
1984        )));
1985    }
1986    Ok(())
1987}
1988
1989// ---------------------------------------------------------------------------
1990// FTS document construction
1991// ---------------------------------------------------------------------------
1992
1993/// Build the canonical text embedded for an entity on create, update, merge,
1994/// and repair paths.
1995pub fn entity_embedding_text(entity: &Entity) -> String {
1996    match &entity.description {
1997        Some(description) if !description.is_empty() => {
1998            format!("{} {description}", entity.name)
1999        }
2000        _ => entity.name.clone(),
2001    }
2002}
2003
2004/// Build the canonical text embedded for a note when no explicit bounded
2005/// embedding prefix was supplied at creation time.
2006pub fn note_embedding_text(note: &Note) -> String {
2007    note_embedding_text_ref(note).to_owned()
2008}
2009
2010/// Borrow the canonical note embedding text for runtime paths that do not
2011/// require ownership.
2012pub(crate) fn note_embedding_text_ref(note: &Note) -> &str {
2013    &note.content
2014}
2015
2016/// Build the `TextDocument` for an entity. This is the single source of truth for
2017/// entity FTS document shape; all write paths (create, update, merge, reindex, backfill)
2018/// must go through this function so search parity is guaranteed.
2019///
2020/// Body rule: when the entity has a non-empty description, prepend the name
2021/// (`"<name> <description>"`). Otherwise the body is just the name. This
2022/// matches the FTS index contract: `title` and `body` are the ranked columns;
2023/// `tags`, `metadata`, and `namespace` are UNINDEXED.
2024///
2025/// `updated_at` is taken from the entity's own timestamp so that backfill and
2026/// reindex runs record the entity's actual mutation time rather than the
2027/// reindex execution time.
2028pub fn entity_fts_document(entity: &Entity) -> TextDocument {
2029    let updated_at =
2030        chrono::DateTime::from_timestamp_micros(entity.updated_at).unwrap_or_else(chrono::Utc::now);
2031    TextDocument {
2032        subject_id: entity.id,
2033        kind: SubstrateKind::Entity,
2034        title: Some(entity.name.clone()),
2035        body: entity_embedding_text(entity),
2036        tags: entity.tags.clone(),
2037        namespace: entity.namespace.clone(),
2038        metadata: entity.properties.clone(),
2039        updated_at,
2040    }
2041}
2042
2043/// Build the `TextDocument` for a note. This is the single source of truth for
2044/// note FTS document shape; all write paths (create, update, reindex) must go
2045/// through this function so recall parity is guaranteed. Changes here apply to
2046/// every caller automatically.
2047///
2048/// Body rule: when the note has a `name`, prepend it to the content
2049/// (`"<name> <content>"`). This matches the FTS index contract: title and body
2050/// both contribute to ranking, and the name is the most salient signal.
2051///
2052/// `updated_at` is taken from the note's own timestamp (not `Utc::now()`) so
2053/// that backfill and reindex runs record the note's actual mutation time rather
2054/// than the reindex execution time.
2055pub fn note_fts_document(note: &Note) -> TextDocument {
2056    let body = match &note.name {
2057        Some(n) => format!("{n} {}", note.content),
2058        None => note.content.clone(),
2059    };
2060    let updated_at =
2061        chrono::DateTime::from_timestamp_micros(note.updated_at).unwrap_or_else(chrono::Utc::now);
2062    TextDocument {
2063        subject_id: note.id,
2064        kind: SubstrateKind::Note,
2065        title: note.name.clone(),
2066        body,
2067        tags: vec![],
2068        namespace: note.namespace.clone(),
2069        metadata: note.properties.clone(),
2070        updated_at,
2071    }
2072}
2073
2074/// SQL-bind–ready scalars derived from [`note_fts_document`].
2075///
2076/// Used by `merge_note_sql` to guarantee that the raw SQL FTS INSERT stores
2077/// exactly what [`Fts5TextSearch::upsert_document`] would write, preventing
2078/// null/empty-string divergence on the `title` column for nameless notes.
2079pub(crate) struct NoteFtsScalars {
2080    /// Empty string when `note.name` is `None` — matches the `unwrap_or("")` in
2081    /// `Fts5TextSearch::upsert_document`.
2082    pub title: String,
2083    pub body: String,
2084    /// Always the JSON array `"[]"`.
2085    pub tags: String,
2086    /// Serialised `note.properties`, or `None` when properties are absent.
2087    pub metadata: Option<String>,
2088    /// `note.updated_at` converted to `DateTime<Utc>` timestamp_micros.
2089    pub updated_at_micros: i64,
2090}
2091
2092/// Derive [`NoteFtsScalars`] from a [`Note`].
2093///
2094/// All values match the encoding that [`Fts5TextSearch::upsert_document`]
2095/// applies when given the output of [`note_fts_document`].
2096pub(crate) fn note_fts_scalars(note: &Note) -> NoteFtsScalars {
2097    let doc = note_fts_document(note);
2098    NoteFtsScalars {
2099        title: doc.title.unwrap_or_default(),
2100        body: doc.body,
2101        tags: "[]".to_string(),
2102        metadata: doc
2103            .metadata
2104            .as_ref()
2105            .map(|v| serde_json::to_string(v).unwrap_or_default()),
2106        updated_at_micros: doc.updated_at.timestamp_micros(),
2107    }
2108}
2109
2110// ---------------------------------------------------------------------------
2111// Transactional merge SQL helpers
2112// ---------------------------------------------------------------------------
2113
2114/// Cheap SQL-side byte-length probe for one merge entity, evaluated BEFORE
2115/// [`read_merge_entity`] copies its columns into Rust `String`s and parses
2116/// `properties`/`tags` as JSON. `LENGTH()` still requires SQLite to touch the
2117/// stored bytes, but skips the Rust-side allocation and JSON parse — the
2118/// expensive part for an oversized record. Charging this probe against the
2119/// budget before the full read means an over-budget record is rejected
2120/// without ever being materialized or parsed inside the writer transaction.
2121/// Each column is wrapped in `CAST(... AS BLOB)` — plain `LENGTH(text)`
2122/// returns SQLite's *character* count for TEXT values, not the UTF-8 byte
2123/// count the budget is denominated in, so a multibyte (CJK/emoji) record
2124/// could under-report and pass a probe its true byte size exceeds. Casting
2125/// to BLOB forces `LENGTH()` to report octets instead.
2126/// A missing row probes as zero; `read_merge_entity`'s own "not found" error
2127/// fires on the subsequent full read and is unaffected by this probe.
2128fn probe_merge_entity_bytes(conn: &rusqlite::Connection, id: Uuid) -> Result<usize, SqliteError> {
2129    let id_str = id.to_string();
2130    let len: Option<i64> = conn
2131        .query_row(
2132            "SELECT LENGTH(CAST(name AS BLOB)) \
2133                    + COALESCE(LENGTH(CAST(description AS BLOB)), 0) \
2134                    + COALESCE(LENGTH(CAST(properties AS BLOB)), 0) \
2135                    + LENGTH(CAST(tags AS BLOB)) \
2136             FROM entities WHERE id = ?1 AND deleted_at IS NULL",
2137            rusqlite::params![id_str],
2138            |row| row.get(0),
2139        )
2140        .optional()
2141        .map_err(SqliteError::Rusqlite)?;
2142    Ok(128_usize.saturating_add(len.unwrap_or(0).max(0) as usize))
2143}
2144
2145/// Read one entity row by ID within a namespace, returning `SqliteError` on missing/wrong-ns.
2146fn read_merge_entity(
2147    conn: &rusqlite::Connection,
2148    id: Uuid,
2149    namespace: &str,
2150) -> Result<Entity, SqliteError> {
2151    let id_str = id.to_string();
2152    let mut stmt = conn.prepare(
2153        "SELECT id, namespace, kind, entity_type, name, description, properties, tags, \
2154         created_at, updated_at, deleted_at, merged_into, merge_event_id, \
2155         (SELECT a.content_ref FROM attachments AS a \
2156          WHERE a.record_uuid = entities.id AND a.substrate = 'entity' \
2157            AND a.role = 'content') AS content_ref \
2158         FROM entities WHERE id = ?1 AND deleted_at IS NULL",
2159    )?;
2160    let mut rows = stmt.query(rusqlite::params![id_str])?;
2161    let row = rows
2162        .next()?
2163        .ok_or_else(|| SqliteError::InvalidData(format!("entity {id} not found")))?;
2164
2165    let id_s: String = row.get(0)?;
2166    let ns: String = row.get(1)?;
2167    let kind: String = row.get(2)?;
2168    let entity_type: Option<String> = row.get(3)?;
2169    let name: String = row.get(4)?;
2170    let description: Option<String> = row.get(5)?;
2171    let properties_str: Option<String> = row.get(6)?;
2172    let tags_str: String = row.get(7)?;
2173    let created_at: i64 = row.get(8)?;
2174    let updated_at: i64 = row.get(9)?;
2175    let deleted_at: Option<i64> = row.get(10)?;
2176    let merged_into_str: Option<String> = row.get(11)?;
2177    let merge_event_id_str: Option<String> = row.get(12)?;
2178    let content_ref: Option<String> = row.get(13)?;
2179
2180    if ns != namespace {
2181        return Err(SqliteError::InvalidData(format!(
2182            "entity {id} belongs to namespace '{ns}', not '{namespace}'"
2183        )));
2184    }
2185
2186    let entity_id = Uuid::parse_str(&id_s).map_err(|e| SqliteError::InvalidData(e.to_string()))?;
2187    let properties: Option<Value> = properties_str
2188        .map(|s| {
2189            serde_json::from_str::<Value>(&s).map_err(|e| SqliteError::InvalidData(e.to_string()))
2190        })
2191        .transpose()?;
2192    let tags: Vec<String> =
2193        serde_json::from_str(&tags_str).map_err(|e| SqliteError::InvalidData(e.to_string()))?;
2194    let merged_into = merged_into_str
2195        .as_deref()
2196        .map(Uuid::parse_str)
2197        .transpose()
2198        .map_err(|e| SqliteError::InvalidData(e.to_string()))?;
2199    let merge_event_id = merge_event_id_str
2200        .as_deref()
2201        .map(Uuid::parse_str)
2202        .transpose()
2203        .map_err(|e| SqliteError::InvalidData(e.to_string()))?;
2204
2205    Ok(Entity {
2206        id: entity_id,
2207        namespace: ns,
2208        kind,
2209        entity_type,
2210        name,
2211        description,
2212        properties,
2213        tags,
2214        created_at,
2215        updated_at,
2216        deleted_at,
2217        merged_into,
2218        merge_event_id,
2219        content_ref,
2220    })
2221}
2222
2223/// All merge SQL on one connection inside an already-open `BEGIN IMMEDIATE` transaction.
2224///
2225/// Reads both entities, rewires/drops incident edges, merges entity fields, updates FTS,
2226/// deletes the `from` vec entry (if `vec_table` is Some), and tombstones `from` with merge
2227/// provenance.  Returns the updated `into` entity so the caller can do the async vec re-insert.
2228///
2229/// When `dry_run` is true, all reads and computations are performed but no writes are issued.
2230// REASON: merge requires both entity IDs, the namespace, FTS and vec table names, merge
2231// policy, and dry-run flag — all are load-bearing; reducing to a struct would obscure
2232// the sync/async boundary split that keeps this function off the async runtime.
2233#[allow(clippy::too_many_arguments)]
2234fn merge_entity_sql(
2235    conn: &rusqlite::Connection,
2236    namespace: String,
2237    fts_table: String,
2238    vec_tables: Vec<String>,
2239    into_id: Uuid,
2240    from_id: Uuid,
2241    strategy: EntityDedupMergePolicy,
2242    content_strategy: ContentMergeStrategy,
2243    dry_run: bool,
2244    pack_rules: Vec<EdgeEndpointRule>,
2245    validation: EntityMergeValidation,
2246    limits: MergeTxLimits,
2247) -> Result<(MergeSummary, Entity), MergeEntitySqlError> {
2248    let mut budget = MergeTxBudget::new(limits);
2249    // Config-scaled fanout (one FTS/vector delete per table, one contract rule
2250    // set per pack) is charged in bytes only: it is bounded by configuration,
2251    // not by graph shape, but belongs in the same account it amortizes over.
2252    budget.charge(
2253        0,
2254        vec_tables.iter().map(String::len).sum::<usize>()
2255            + pack_rules.len() * std::mem::size_of::<EdgeEndpointRule>(),
2256        "preparing pack and vector fanout",
2257    )?;
2258
2259    budget.charge(
2260        1,
2261        probe_merge_entity_bytes(conn, into_id)?,
2262        "reading merge records",
2263    )?;
2264    let into_entity = read_merge_entity(conn, into_id, &namespace)?;
2265    budget.charge(
2266        1,
2267        probe_merge_entity_bytes(conn, from_id)?,
2268        "reading merge records",
2269    )?;
2270    let from_entity = read_merge_entity(conn, from_id, &namespace)?;
2271
2272    match validation {
2273        EntityMergeValidation::LegacyKind if into_entity.kind != from_entity.kind => {
2274            return Err(MergeEntitySqlError::Refusal(
2275                EntityMergeRefusal::LegacyKind {
2276                    into_id,
2277                    into_kind: into_entity.kind,
2278                    from_id,
2279                    from_kind: from_entity.kind,
2280                },
2281            ));
2282        }
2283        EntityMergeValidation::SafetyFloor => {
2284            validate_entity_merge_floor(&into_entity, &from_entity).map_err(|guard| {
2285                MergeEntitySqlError::Refusal(EntityMergeRefusal::SafetyFloor(guard))
2286            })?;
2287        }
2288        EntityMergeValidation::LegacyKind | EntityMergeValidation::Forced => {}
2289    }
2290
2291    // --- Collect edges incident to from_id ---
2292    let parse_id =
2293        |s: String| Uuid::parse_str(&s).map_err(|e| SqliteError::InvalidData(e.to_string()));
2294
2295    let from_str = from_id.to_string();
2296
2297    // Namespace-agnostic (khive#1236): edge endpoints resolve by-ID regardless of
2298    // namespace (ADR-007 Rev 6), and `link` stamps an edge with its *creator's*
2299    // namespace, not either endpoint's — so an edge incident to `from_id` can live
2300    // in any namespace. Scoping this collection to the merge's own namespace missed
2301    // those edges entirely. Each row's own `namespace` column is carried through
2302    // (`EdgeRow::namespace`) and used for every subsequent SQL op against that row.
2303    let mut outbound: Vec<EdgeRow> = Vec::new();
2304    {
2305        let mut stmt = conn.prepare(
2306            "SELECT id, namespace, source_id, target_id, relation, weight, created_at, \
2307                    updated_at, deleted_at, target_backend, metadata \
2308             FROM graph_edges WHERE source_id = ?1",
2309        )?;
2310        let mut rows = stmt.query(rusqlite::params![&from_str])?;
2311        while let Some(row) = rows.next()? {
2312            let edge = EdgeRow {
2313                id: parse_id(row.get(0)?)?,
2314                namespace: row.get(1)?,
2315                source_id: parse_id(row.get(2)?)?,
2316                target_id: parse_id(row.get(3)?)?,
2317                relation: row.get(4)?,
2318                weight: row.get(5)?,
2319                created_at: row.get(6)?,
2320                updated_at: row.get(7)?,
2321                deleted_at: row.get(8)?,
2322                target_backend: row.get(9)?,
2323                metadata: row.get(10)?,
2324            };
2325            budget.charge(1, edge_row_budget_bytes(&edge), "collecting incident edges")?;
2326            outbound.push(edge);
2327        }
2328    }
2329
2330    let mut inbound: Vec<EdgeRow> = Vec::new();
2331    {
2332        let mut stmt = conn.prepare(
2333            "SELECT id, namespace, source_id, target_id, relation, weight, created_at, \
2334                    updated_at, deleted_at, target_backend, metadata \
2335             FROM graph_edges WHERE target_id = ?1",
2336        )?;
2337        let mut rows = stmt.query(rusqlite::params![&from_str])?;
2338        while let Some(row) = rows.next()? {
2339            let edge = EdgeRow {
2340                id: parse_id(row.get(0)?)?,
2341                namespace: row.get(1)?,
2342                source_id: parse_id(row.get(2)?)?,
2343                target_id: parse_id(row.get(3)?)?,
2344                relation: row.get(4)?,
2345                weight: row.get(5)?,
2346                created_at: row.get(6)?,
2347                updated_at: row.get(7)?,
2348                deleted_at: row.get(8)?,
2349                target_backend: row.get(9)?,
2350                metadata: row.get(10)?,
2351            };
2352            budget.charge(1, edge_row_budget_bytes(&edge), "collecting incident edges")?;
2353            inbound.push(edge);
2354        }
2355    }
2356
2357    // Deduplicate by edge ID (a self-edge from_id→from_id appears in both lists).
2358    let mut seen: HashSet<Uuid> = HashSet::new();
2359    let mut all_edges: Vec<EdgeRow> = Vec::new();
2360    for edge in outbound.into_iter().chain(inbound) {
2361        if seen.insert(edge.id) {
2362            all_edges.push(edge);
2363        }
2364    }
2365    let original_edges: HashMap<Uuid, EdgeRow> = all_edges
2366        .iter()
2367        .map(|edge| (edge.id, edge.clone()))
2368        .collect();
2369
2370    // --- Merge entity fields ---
2371    let (merged_props, properties_merged) =
2372        merge_properties(&into_entity.properties, &from_entity.properties, strategy);
2373    let merged_name = merge_string_field(&into_entity.name, &from_entity.name, strategy);
2374    let (merged_description, content_appended) = match content_strategy {
2375        ContentMergeStrategy::Append => {
2376            let into_desc = into_entity.description.as_deref().unwrap_or("");
2377            let from_desc = from_entity.description.as_deref().unwrap_or("");
2378            if from_desc.is_empty() {
2379                (into_entity.description.clone(), false)
2380            } else if into_desc.is_empty() {
2381                (from_entity.description.clone(), true)
2382            } else {
2383                (Some(format!("{}\n\n---\n\n{}", into_desc, from_desc)), true)
2384            }
2385        }
2386        // Description selection follows `content_strategy` directly — it is a
2387        // deliberate, independently-settable choice, not derived from the
2388        // entity-field `strategy` (properties/name/tags merge policy).
2389        ContentMergeStrategy::PreferInto => (into_entity.description.clone(), false),
2390        ContentMergeStrategy::PreferFrom => (from_entity.description.clone(), false),
2391    };
2392    let (merged_tags, tags_unioned) = union_tags(&into_entity.tags, &from_entity.tags);
2393
2394    let now = chrono::Utc::now().timestamp_micros();
2395    let into_str = into_id.to_string();
2396    let props_str = merged_props
2397        .as_ref()
2398        .map(|v| serde_json::to_string(v).unwrap_or_default());
2399    let tags_json = serde_json::to_string(&merged_tags).unwrap_or_else(|_| "[]".to_string());
2400
2401    // Writes are gated on `!dry_run` below, but the loop itself always runs so a
2402    // dry-run response reports a predictive `edges_rewired` count instead of zero.
2403    let mut rewired_edge_ids = HashSet::new();
2404    let mut edges_contract_skipped = 0usize;
2405    let mut edge_conflict_preimages = Vec::new();
2406    let mut conflict_deleted_edge_ids = HashSet::new();
2407    for edge in all_edges {
2408        if conflict_deleted_edge_ids.contains(&edge.id) {
2409            continue;
2410        }
2411        let raw_src = if edge.source_id == from_id {
2412            into_id
2413        } else {
2414            edge.source_id
2415        };
2416        let raw_tgt = if edge.target_id == from_id {
2417            into_id
2418        } else {
2419            edge.target_id
2420        };
2421        let relation_typed = edge.relation.parse::<EdgeRelation>().ok();
2422        // Symmetric relations must be stored with source_uuid < target_uuid.
2423        // Apply canonicalization so the conflict check and UPDATE both use the canonical form.
2424        let (new_src, new_tgt) = match relation_typed {
2425            Some(rel) => canonical_edge_endpoints(rel, raw_src, raw_tgt),
2426            None => (raw_src, raw_tgt),
2427        };
2428
2429        if new_src == new_tgt {
2430            if !dry_run {
2431                conn.execute(
2432                    "DELETE FROM graph_edges WHERE namespace = ?1 AND id = ?2",
2433                    rusqlite::params![&edge.namespace, edge.id.to_string()],
2434                )?;
2435            }
2436            continue;
2437        }
2438
2439        // Endpoint-contract check (khive#1216): the rewired triple must still pass
2440        // the same allowlist `link` enforces. `into_id` and `from_id` share `kind`
2441        // (enforced by the caller), but `entity_type` may differ between them, so a
2442        // pack rule scoped via `EntityOfType` can accept `from_id`'s edge yet reject
2443        // the post-rewrite pair against `into_id`. A violating edge is dropped and
2444        // counted, mirroring the existing dangling-endpoint skip behavior rather
2445        // than silently writing a contract-violating edge or aborting the merge.
2446        let contract_ok = match relation_typed {
2447            // `annotates` targets may be events or edges, which
2448            // `resolve_merge_edge_endpoint` cannot resolve — evaluate its
2449            // (unconditional) exemption before endpoint resolution so valid
2450            // annotates edges are not dropped as unresolvable.
2451            Some(EdgeRelation::Annotates) => true,
2452            Some(rel) => {
2453                let src_info = if new_src == into_id {
2454                    Some((
2455                        "entity",
2456                        into_entity.kind.clone(),
2457                        into_entity.entity_type.clone(),
2458                    ))
2459                } else {
2460                    resolve_merge_edge_endpoint_budgeted(conn, new_src, &mut budget)?
2461                };
2462                let tgt_info = if new_tgt == into_id {
2463                    Some((
2464                        "entity",
2465                        into_entity.kind.clone(),
2466                        into_entity.entity_type.clone(),
2467                    ))
2468                } else {
2469                    resolve_merge_edge_endpoint_budgeted(conn, new_tgt, &mut budget)?
2470                };
2471                match (src_info, tgt_info) {
2472                    (Some((src_sub, src_kind, src_type)), Some((tgt_sub, tgt_kind, tgt_type))) => {
2473                        merge_rewire_endpoint_contract_allows(
2474                            &pack_rules,
2475                            rel,
2476                            src_sub,
2477                            &src_kind,
2478                            src_type.as_deref(),
2479                            tgt_sub,
2480                            &tgt_kind,
2481                            tgt_type.as_deref(),
2482                        )
2483                    }
2484                    // An endpoint no longer resolves (e.g. concurrently hard-deleted)
2485                    // — cannot evaluate the contract, so drop rather than assume ok.
2486                    _ => false,
2487                }
2488            }
2489            // Relation string predates the closed EdgeRelation enum (pre-migration
2490            // data); leave existing behavior in place rather than guessing.
2491            None => true,
2492        };
2493        if !contract_ok {
2494            if !dry_run {
2495                conn.execute(
2496                    "DELETE FROM graph_edges WHERE namespace = ?1 AND id = ?2",
2497                    rusqlite::params![&edge.namespace, edge.id.to_string()],
2498                )?;
2499            }
2500            tracing::warn!(
2501                edge_id = %edge.id,
2502                source = %new_src,
2503                target = %new_tgt,
2504                relation = %edge.relation,
2505                "merge_entity: dropping rewired edge — endpoint contract violation post-merge"
2506            );
2507            edges_contract_skipped += 1;
2508            continue;
2509        }
2510
2511        let now_ts = chrono::Utc::now().timestamp_micros();
2512        // Preserve the original edge ID where possible so callers can still get()
2513        // it by the ID returned from link(): update in-place when there's no
2514        // conflict; when into_id already owns this (source,target,relation), the
2515        // incoming (from-side) duplicate is dropped and the existing into-edge is
2516        // left untouched (ADR-039 `ON CONFLICT ... DO NOTHING` semantics).
2517        // Check for a conflict: does into_id already have this natural key?
2518        let conflict_id: Option<String> = {
2519            let conflict_src = new_src.to_string();
2520            let conflict_tgt = new_tgt.to_string();
2521            conn.query_row(
2522                khive_db::stores::graph::EDGE_SYMMETRIC_CONFLICT_PROBE_SQL,
2523                rusqlite::params![
2524                    &edge.namespace,
2525                    &conflict_src,
2526                    &conflict_tgt,
2527                    &edge.relation,
2528                    edge.id.to_string(),
2529                ],
2530                |row| row.get(0),
2531            )
2532            .optional()
2533            .map_err(SqliteError::Rusqlite)?
2534        };
2535
2536        if let Some(conflict_id) = conflict_id {
2537            // A live or soft-deleted row already owns this natural key: drop the
2538            // incoming duplicate. The surviving row's weight/metadata/deleted_at
2539            // are never mutated or resurrected. Capture the duplicate and the
2540            // complete hard-delete cascade before removing either, so the audit
2541            // event contains enough state to restore every destroyed row.
2542            let surviving_edge_id = Uuid::parse_str(&conflict_id)
2543                .map_err(|error| SqliteError::InvalidData(error.to_string()))?;
2544            let incident_edge_preimages = collect_conflict_incident_edge_preimages(
2545                conn,
2546                edge.id,
2547                &original_edges,
2548                &mut budget,
2549            )?;
2550            for incident in &incident_edge_preimages {
2551                conflict_deleted_edge_ids.insert(incident.id);
2552                rewired_edge_ids.remove(&incident.id);
2553            }
2554            conflict_deleted_edge_ids.insert(edge.id);
2555            rewired_edge_ids.insert(edge.id);
2556
2557            if !dry_run {
2558                delete_conflict_incident_edges(conn, &incident_edge_preimages)?;
2559                conn.execute(
2560                    khive_db::stores::graph::EDGE_SYMMETRIC_DELETE_NONCANONICAL_SQL,
2561                    rusqlite::params![&edge.namespace, edge.id.to_string()],
2562                )?;
2563            }
2564            edge_conflict_preimages.push(MergeEdgeConflictPreimage {
2565                surviving_edge_id,
2566                dropped_edge: edge_row_preimage(&edge)?,
2567                incident_edge_preimages,
2568            });
2569        } else {
2570            if dry_run {
2571                rewired_edge_ids.insert(edge.id);
2572                continue;
2573            }
2574            let changed = conn.execute(
2575                "UPDATE graph_edges SET \
2576                     source_id = ?1, target_id = ?2, updated_at = ?3 \
2577                     WHERE namespace = ?4 AND id = ?5",
2578                rusqlite::params![
2579                    new_src.to_string(),
2580                    new_tgt.to_string(),
2581                    now_ts,
2582                    &edge.namespace,
2583                    edge.id.to_string(),
2584                ],
2585            )?;
2586            if changed > 0 {
2587                rewired_edge_ids.insert(edge.id);
2588            }
2589        }
2590    }
2591    let edges_rewired = rewired_edge_ids.len();
2592
2593    if !dry_run {
2594        // UPDATE only the merged fields — a full-row INSERT OR REPLACE silently
2595        // nulls any column missing from its list (entity_type and the former
2596        // entity-owned content_ref were lost this way; khive#1214). Attachments
2597        // now live in their own table and this targeted UPDATE leaves them alone.
2598        conn.execute(
2599            "UPDATE entities SET \
2600                 name = ?1, description = ?2, properties = ?3, tags = ?4, \
2601                 updated_at = ?5, merged_into = NULL, merge_event_id = NULL \
2602             WHERE namespace = ?6 AND id = ?7",
2603            rusqlite::params![
2604                &merged_name,
2605                &merged_description,
2606                &props_str,
2607                &tags_json,
2608                now,
2609                &namespace,
2610                &into_str,
2611            ],
2612        )?;
2613
2614        // Body formula mirrors entity_fts_document (the canonical constructor):
2615        // this path is sync/spawn_blocking so it can't call it directly, but
2616        // must stay field-identical.
2617        let fts_body = match &merged_description {
2618            Some(d) if !d.is_empty() => format!("{} {}", merged_name, d),
2619            _ => merged_name.clone(),
2620        };
2621        let kind_str = SubstrateKind::Entity.to_string();
2622
2623        conn.execute(
2624            &format!(
2625                "DELETE FROM {} WHERE namespace = ?1 AND subject_id = ?2",
2626                fts_table
2627            ),
2628            rusqlite::params![&namespace, &into_str],
2629        )?;
2630        conn.execute(
2631            &format!(
2632                "INSERT INTO {} \
2633                 (subject_id, kind, title, body, tags, namespace, metadata, updated_at) \
2634                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
2635                fts_table
2636            ),
2637            rusqlite::params![
2638                &into_str,
2639                &kind_str,
2640                &merged_name,
2641                &fts_body,
2642                &tags_json,
2643                &namespace,
2644                &props_str,
2645                now,
2646            ],
2647        )?;
2648
2649        conn.execute(
2650            &format!(
2651                "DELETE FROM {} WHERE namespace = ?1 AND subject_id = ?2",
2652                fts_table
2653            ),
2654            rusqlite::params![&namespace, &from_str],
2655        )?;
2656
2657        khive_db::stores::vectors::delete_subject_from_vector_tables(
2658            conn,
2659            &vec_tables,
2660            from_id,
2661            &namespace,
2662        )?;
2663
2664        let merge_event_id = Uuid::new_v4();
2665        conn.execute(
2666            "UPDATE entities \
2667             SET deleted_at = ?1, merged_into = ?2, merge_event_id = ?3, updated_at = ?1 \
2668             WHERE namespace = ?4 AND id = ?5 AND deleted_at IS NULL",
2669            rusqlite::params![
2670                now,
2671                into_str,
2672                merge_event_id.to_string(),
2673                &namespace,
2674                &from_str,
2675            ],
2676        )?;
2677    }
2678
2679    let updated_entity = Entity {
2680        id: into_id,
2681        namespace,
2682        kind: into_entity.kind,
2683        entity_type: into_entity.entity_type,
2684        name: merged_name,
2685        description: merged_description,
2686        properties: merged_props,
2687        tags: merged_tags,
2688        created_at: into_entity.created_at,
2689        updated_at: now,
2690        deleted_at: into_entity.deleted_at,
2691        merged_into: None,
2692        merge_event_id: None,
2693        content_ref: into_entity.content_ref,
2694    };
2695
2696    Ok((
2697        MergeSummary {
2698            kept_id: into_id,
2699            removed_id: from_id,
2700            edges_rewired,
2701            edges_contract_skipped,
2702            edge_conflict_preimages,
2703            properties_merged,
2704            tags_unioned,
2705            content_appended,
2706            dry_run,
2707            tx_budget: budget.report(),
2708            embedding_truncation: Default::default(),
2709        },
2710        updated_entity,
2711    ))
2712}
2713
2714// ---------------------------------------------------------------------------
2715// Note merge SQL helpers
2716// ---------------------------------------------------------------------------
2717
2718/// Cheap SQL-side byte-length probe for one merge note — see
2719/// [`probe_merge_entity_bytes`] for why this runs before
2720/// [`read_merge_note`]'s full column copy and JSON parse, and why each
2721/// column is cast to BLOB before `LENGTH()`.
2722fn probe_merge_note_bytes(conn: &rusqlite::Connection, id: Uuid) -> Result<usize, SqliteError> {
2723    let id_str = id.to_string();
2724    let len: Option<i64> = conn
2725        .query_row(
2726            "SELECT COALESCE(LENGTH(CAST(name AS BLOB)), 0) \
2727                    + LENGTH(CAST(content AS BLOB)) \
2728                    + COALESCE(LENGTH(CAST(properties AS BLOB)), 0) \
2729             FROM notes WHERE id = ?1 AND deleted_at IS NULL",
2730            rusqlite::params![id_str],
2731            |row| row.get(0),
2732        )
2733        .optional()
2734        .map_err(SqliteError::Rusqlite)?;
2735    Ok(128_usize.saturating_add(len.unwrap_or(0).max(0) as usize))
2736}
2737
2738/// Read one note row by ID within a namespace, returning `SqliteError` on missing/wrong-ns.
2739fn read_merge_note(
2740    conn: &rusqlite::Connection,
2741    id: Uuid,
2742    namespace: &str,
2743) -> Result<khive_storage::note::Note, SqliteError> {
2744    use khive_storage::note::Note;
2745    let id_str = id.to_string();
2746    let mut stmt = conn.prepare(
2747        "SELECT id, namespace, kind, status, name, content, salience, decay_factor, \
2748         expires_at, properties, created_at, updated_at, deleted_at \
2749         FROM notes WHERE id = ?1 AND deleted_at IS NULL",
2750    )?;
2751    let mut rows = stmt.query(rusqlite::params![id_str])?;
2752    let row = rows
2753        .next()?
2754        .ok_or_else(|| SqliteError::InvalidData(format!("note {id} not found")))?;
2755
2756    let id_s: String = row.get(0)?;
2757    let ns: String = row.get(1)?;
2758    let kind: String = row.get(2)?;
2759    let status: String = row.get(3)?;
2760    let name: Option<String> = row.get(4)?;
2761    let content: String = row.get(5)?;
2762    let salience: Option<f64> = row.get(6)?;
2763    let decay_factor: Option<f64> = row.get(7)?;
2764    let expires_at: Option<i64> = row.get(8)?;
2765    let properties_str: Option<String> = row.get(9)?;
2766    let created_at: i64 = row.get(10)?;
2767    let updated_at: i64 = row.get(11)?;
2768    let deleted_at: Option<i64> = row.get(12)?;
2769
2770    if ns != namespace {
2771        return Err(SqliteError::InvalidData(format!(
2772            "note {id} belongs to namespace '{ns}', not '{namespace}'"
2773        )));
2774    }
2775
2776    let note_id = Uuid::parse_str(&id_s).map_err(|e| SqliteError::InvalidData(e.to_string()))?;
2777    let properties: Option<serde_json::Value> = properties_str
2778        .map(|s| serde_json::from_str(&s).map_err(|e| SqliteError::InvalidData(e.to_string())))
2779        .transpose()?;
2780
2781    Ok(Note {
2782        id: note_id,
2783        namespace: ns,
2784        kind,
2785        status,
2786        name,
2787        content,
2788        salience,
2789        decay_factor,
2790        expires_at,
2791        properties,
2792        created_at,
2793        updated_at,
2794        deleted_at,
2795    })
2796}
2797
2798fn max_option_f64(a: Option<f64>, b: Option<f64>) -> Option<f64> {
2799    match (a, b) {
2800        (Some(x), Some(y)) => Some(x.max(y)),
2801        (Some(x), None) => Some(x),
2802        (None, Some(y)) => Some(y),
2803        (None, None) => None,
2804    }
2805}
2806
2807fn append_merge_history(props: Option<Value>, entry: Value) -> Result<Option<Value>, SqliteError> {
2808    use serde_json::{json, Map};
2809    let mut obj: Map<String, Value> = match props {
2810        Some(Value::Object(m)) => m,
2811        Some(other) => {
2812            let mut m = Map::new();
2813            m.insert("_value".into(), other);
2814            m
2815        }
2816        None => Map::new(),
2817    };
2818    let history = obj
2819        .entry("_merge_history".to_string())
2820        .or_insert_with(|| json!([]));
2821    if let Value::Array(arr) = history {
2822        arr.push(entry);
2823    }
2824    Ok(Some(Value::Object(obj)))
2825}
2826
2827/// All note merge SQL on one connection inside a `BEGIN IMMEDIATE` transaction.
2828///
2829/// Reads both notes (must have same `kind`), rewires/drops incident edges, merges content
2830/// per `content_strategy`, tombstones `from`. Returns the updated `into` note for async
2831/// re-embedding.
2832///
2833/// When `dry_run` is true, all reads and computations are performed but no writes are issued.
2834// REASON: note merge additionally requires a content_strategy parameter versus entity merge;
2835// same sync/async boundary rationale as merge_entity_sql applies here.
2836#[allow(clippy::too_many_arguments)]
2837fn merge_note_sql(
2838    conn: &rusqlite::Connection,
2839    namespace: String,
2840    fts_table: String,
2841    vec_tables: Vec<String>,
2842    into_id: Uuid,
2843    from_id: Uuid,
2844    strategy: EntityDedupMergePolicy,
2845    content_strategy: ContentMergeStrategy,
2846    dry_run: bool,
2847    pack_rules: Vec<EdgeEndpointRule>,
2848    preserve_owner_established: bool,
2849    limits: MergeTxLimits,
2850) -> Result<(MergeSummary, khive_storage::note::Note), SqliteError> {
2851    let mut budget = MergeTxBudget::new(limits);
2852    // Same accounting as `merge_entity_sql`: config-scaled fanout in bytes only.
2853    budget.charge(
2854        0,
2855        vec_tables.iter().map(String::len).sum::<usize>()
2856            + pack_rules.len() * std::mem::size_of::<EdgeEndpointRule>(),
2857        "preparing pack and vector fanout",
2858    )?;
2859
2860    budget.charge(
2861        1,
2862        probe_merge_note_bytes(conn, into_id)?,
2863        "reading merge records",
2864    )?;
2865    let into_note = read_merge_note(conn, into_id, &namespace)?;
2866    budget.charge(
2867        1,
2868        probe_merge_note_bytes(conn, from_id)?,
2869        "reading merge records",
2870    )?;
2871    let from_note = read_merge_note(conn, from_id, &namespace)?;
2872
2873    if into_note.kind != from_note.kind {
2874        return Err(SqliteError::InvalidData(format!(
2875            "cannot merge notes of different kinds: {} vs {}",
2876            into_note.kind, from_note.kind
2877        )));
2878    }
2879
2880    // A quarantined message participates in no merges, in either role. Folding
2881    // its content into an ordinary message would retain the body while the
2882    // marker restoration below drops the `quarantined` disposition — laundering
2883    // quarantined transport content into an unmarked record. Release is the
2884    // channel-ingest path's decision, never a side effect of curation.
2885    if into_note.kind == "message"
2886        && (message_is_quarantined(&into_note) || message_is_quarantined(&from_note))
2887    {
2888        return Err(SqliteError::InvalidData(
2889            "cannot merge a quarantined message: quarantine disposition is              transport-owned and must be released by the channel-ingest path              before the content can be folded into another record"
2890                .to_string(),
2891        ));
2892    }
2893
2894    let now = chrono::Utc::now().timestamp_micros();
2895    let into_str = into_id.to_string();
2896    let from_str = from_id.to_string();
2897
2898    // Collect edges incident to from_id.
2899    let parse_id =
2900        |s: String| Uuid::parse_str(&s).map_err(|e| SqliteError::InvalidData(e.to_string()));
2901
2902    // Namespace-agnostic (khive#1236): see the equivalent comment in
2903    // `merge_entity_sql` — edge endpoints resolve by-ID regardless of namespace.
2904    let mut outbound: Vec<EdgeRow> = Vec::new();
2905    {
2906        let mut stmt = conn.prepare(
2907            "SELECT id, namespace, source_id, target_id, relation, weight, created_at, updated_at, deleted_at, target_backend, metadata \
2908             FROM graph_edges WHERE source_id = ?1",
2909        )?;
2910        let mut rows = stmt.query(rusqlite::params![&from_str])?;
2911        while let Some(row) = rows.next()? {
2912            let edge = EdgeRow {
2913                id: parse_id(row.get(0)?)?,
2914                namespace: row.get(1)?,
2915                source_id: parse_id(row.get(2)?)?,
2916                target_id: parse_id(row.get(3)?)?,
2917                relation: row.get(4)?,
2918                weight: row.get(5)?,
2919                created_at: row.get(6)?,
2920                updated_at: row.get(7)?,
2921                deleted_at: row.get(8)?,
2922                target_backend: row.get(9)?,
2923                metadata: row.get(10)?,
2924            };
2925            budget.charge(1, edge_row_budget_bytes(&edge), "collecting incident edges")?;
2926            outbound.push(edge);
2927        }
2928    }
2929    let mut inbound: Vec<EdgeRow> = Vec::new();
2930    {
2931        let mut stmt = conn.prepare(
2932            "SELECT id, namespace, source_id, target_id, relation, weight, created_at, updated_at, deleted_at, target_backend, metadata \
2933             FROM graph_edges WHERE target_id = ?1",
2934        )?;
2935        let mut rows = stmt.query(rusqlite::params![&from_str])?;
2936        while let Some(row) = rows.next()? {
2937            let edge = EdgeRow {
2938                id: parse_id(row.get(0)?)?,
2939                namespace: row.get(1)?,
2940                source_id: parse_id(row.get(2)?)?,
2941                target_id: parse_id(row.get(3)?)?,
2942                relation: row.get(4)?,
2943                weight: row.get(5)?,
2944                created_at: row.get(6)?,
2945                updated_at: row.get(7)?,
2946                deleted_at: row.get(8)?,
2947                target_backend: row.get(9)?,
2948                metadata: row.get(10)?,
2949            };
2950            budget.charge(1, edge_row_budget_bytes(&edge), "collecting incident edges")?;
2951            inbound.push(edge);
2952        }
2953    }
2954    let mut seen: HashSet<Uuid> = HashSet::new();
2955    let mut all_edges: Vec<EdgeRow> = Vec::new();
2956    for edge in outbound.into_iter().chain(inbound) {
2957        if seen.insert(edge.id) {
2958            all_edges.push(edge);
2959        }
2960    }
2961    let original_edges: HashMap<Uuid, EdgeRow> = all_edges
2962        .iter()
2963        .map(|edge| (edge.id, edge.clone()))
2964        .collect();
2965
2966    // Merge note fields.
2967    let (merged_content, content_appended) = match content_strategy {
2968        ContentMergeStrategy::Append => {
2969            if from_note.content.is_empty() {
2970                (into_note.content.clone(), false)
2971            } else {
2972                (
2973                    format!("{}\n\n---\n\n{}", into_note.content, from_note.content),
2974                    true,
2975                )
2976            }
2977        }
2978        ContentMergeStrategy::PreferInto => (into_note.content.clone(), false),
2979        ContentMergeStrategy::PreferFrom => (from_note.content.clone(), false),
2980    };
2981
2982    let merged_name = match strategy {
2983        EntityDedupMergePolicy::PreferFrom => from_note.name.clone().or(into_note.name.clone()),
2984        _ => into_note.name.clone().or(from_note.name.clone()),
2985    };
2986
2987    let (mut merged_props, _) =
2988        merge_properties(&into_note.properties, &from_note.properties, strategy);
2989
2990    // A merge folds two records together; it does not transfer attribution.
2991    // On a pack-owned note kind the into-note's owned identity properties are
2992    // restored after the fold, under every strategy including `PreferFrom`, so
2993    // the surviving row still says who wrote it.
2994    if preserve_owner_established {
2995        preserve_owner_established_properties(&into_note.properties, &mut merged_props);
2996    }
2997    if into_note.kind == "message" {
2998        preserve_message_transport_properties(&into_note.properties, &mut merged_props);
2999    }
3000
3001    // Recomputed from the final retained properties rather than carried
3002    // forward from the fold's own count. The fold's count and post-
3003    // restoration reality diverge whenever an owner-established key holds a
3004    // nested object: `union` recurses into it and counts the absorbed
3005    // note's leaf as merged, but restoration then reverts the whole key,
3006    // and the fold's flat "keys contributed" number cannot express a
3007    // partial reversal of a nested contribution. Diffing the final object
3008    // against the into-note's pre-merge properties sidesteps that fold/
3009    // restoration coupling entirely.
3010    let properties_merged = count_new_property_keys(
3011        into_note.properties.as_ref(),
3012        merged_props.as_ref(),
3013        strategy,
3014    );
3015
3016    let merge_history_entry = serde_json::json!({
3017        "merged_from": from_id.to_string(),
3018        "merged_at": now,
3019        "strategy": format!("{:?}", strategy),
3020        "content_strategy": format!("{:?}", content_strategy),
3021    });
3022    let merged_props = append_merge_history(merged_props, merge_history_entry)?;
3023
3024    let merged_salience = max_option_f64(into_note.salience, from_note.salience);
3025    let merged_expires_at = match (into_note.expires_at, from_note.expires_at) {
3026        (Some(a), Some(b)) => Some(a.max(b)),
3027        (Some(a), None) => Some(a),
3028        (None, Some(b)) => Some(b),
3029        (None, None) => None,
3030    };
3031
3032    let props_str = merged_props
3033        .as_ref()
3034        .map(|v| serde_json::to_string(v).unwrap_or_default());
3035
3036    // The loop always runs so a dry-run reports a predictive `edges_rewired`
3037    // count instead of zero (mirrors the entity merge path).
3038    let mut rewired_edge_ids = HashSet::new();
3039    let mut edges_contract_skipped = 0usize;
3040    let mut edge_conflict_preimages = Vec::new();
3041    let mut conflict_deleted_edge_ids = HashSet::new();
3042    {
3043        for edge in all_edges {
3044            if conflict_deleted_edge_ids.contains(&edge.id) {
3045                continue;
3046            }
3047            let raw_src = if edge.source_id == from_id {
3048                into_id
3049            } else {
3050                edge.source_id
3051            };
3052            let raw_tgt = if edge.target_id == from_id {
3053                into_id
3054            } else {
3055                edge.target_id
3056            };
3057            let relation_typed = edge.relation.parse::<EdgeRelation>().ok();
3058            // Canonicalize symmetric relations before conflict check + UPDATE.
3059            let (new_src, new_tgt) = match relation_typed {
3060                Some(rel) => canonical_edge_endpoints(rel, raw_src, raw_tgt),
3061                None => (raw_src, raw_tgt),
3062            };
3063            if new_src == new_tgt {
3064                if !dry_run {
3065                    conn.execute(
3066                        "DELETE FROM graph_edges WHERE namespace = ?1 AND id = ?2",
3067                        rusqlite::params![&edge.namespace, edge.id.to_string()],
3068                    )?;
3069                }
3070                continue;
3071            }
3072
3073            // Endpoint-contract check (khive#1216/#1236): see the equivalent
3074            // block in `merge_entity_sql` for the full rationale. Here the
3075            // rewiring endpoint is a note (`into_id`'s kind, substrate "note"),
3076            // not an entity.
3077            let contract_ok = match relation_typed {
3078                // Same rationale as the entity-merge path: annotates targets may
3079                // be events or edges, unresolvable by substrate lookup — the
3080                // exemption must precede endpoint resolution.
3081                Some(EdgeRelation::Annotates) => true,
3082                Some(rel) => {
3083                    let src_info = if new_src == into_id {
3084                        Some(("note", into_note.kind.clone(), None))
3085                    } else {
3086                        resolve_merge_edge_endpoint_budgeted(conn, new_src, &mut budget)?
3087                    };
3088                    let tgt_info = if new_tgt == into_id {
3089                        Some(("note", into_note.kind.clone(), None))
3090                    } else {
3091                        resolve_merge_edge_endpoint_budgeted(conn, new_tgt, &mut budget)?
3092                    };
3093                    match (src_info, tgt_info) {
3094                        (
3095                            Some((src_sub, src_kind, src_type)),
3096                            Some((tgt_sub, tgt_kind, tgt_type)),
3097                        ) => merge_rewire_endpoint_contract_allows(
3098                            &pack_rules,
3099                            rel,
3100                            src_sub,
3101                            &src_kind,
3102                            src_type.as_deref(),
3103                            tgt_sub,
3104                            &tgt_kind,
3105                            tgt_type.as_deref(),
3106                        ),
3107                        _ => false,
3108                    }
3109                }
3110                None => true,
3111            };
3112            if !contract_ok {
3113                if !dry_run {
3114                    conn.execute(
3115                        "DELETE FROM graph_edges WHERE namespace = ?1 AND id = ?2",
3116                        rusqlite::params![&edge.namespace, edge.id.to_string()],
3117                    )?;
3118                }
3119                tracing::warn!(
3120                    edge_id = %edge.id,
3121                    source = %new_src,
3122                    target = %new_tgt,
3123                    relation = %edge.relation,
3124                    "merge_note: dropping rewired edge — endpoint contract violation post-merge"
3125                );
3126                edges_contract_skipped += 1;
3127                continue;
3128            }
3129
3130            let now_ts = chrono::Utc::now().timestamp_micros();
3131            let conflict_id: Option<String> = {
3132                let conflict_src = new_src.to_string();
3133                let conflict_tgt = new_tgt.to_string();
3134                conn.query_row(
3135                    khive_db::stores::graph::EDGE_SYMMETRIC_CONFLICT_PROBE_SQL,
3136                    rusqlite::params![
3137                        &edge.namespace,
3138                        &conflict_src,
3139                        &conflict_tgt,
3140                        &edge.relation,
3141                        edge.id.to_string(),
3142                    ],
3143                    |row| row.get(0),
3144                )
3145                .optional()
3146                .map_err(SqliteError::Rusqlite)?
3147            };
3148
3149            if let Some(conflict_id) = conflict_id {
3150                // A live or soft-deleted row already owns this natural key: drop
3151                // the incoming duplicate (ADR-039 `ON CONFLICT ... DO NOTHING`).
3152                // The surviving row's weight/metadata/deleted_at are never
3153                // mutated or resurrected. Match hard `delete_edge`: cascade
3154                // incident annotations, and preserve every removed row first.
3155                let surviving_edge_id = Uuid::parse_str(&conflict_id)
3156                    .map_err(|error| SqliteError::InvalidData(error.to_string()))?;
3157                let incident_edge_preimages = collect_conflict_incident_edge_preimages(
3158                    conn,
3159                    edge.id,
3160                    &original_edges,
3161                    &mut budget,
3162                )?;
3163                for incident in &incident_edge_preimages {
3164                    conflict_deleted_edge_ids.insert(incident.id);
3165                    rewired_edge_ids.remove(&incident.id);
3166                }
3167                conflict_deleted_edge_ids.insert(edge.id);
3168                rewired_edge_ids.insert(edge.id);
3169
3170                if !dry_run {
3171                    delete_conflict_incident_edges(conn, &incident_edge_preimages)?;
3172                    conn.execute(
3173                        khive_db::stores::graph::EDGE_SYMMETRIC_DELETE_NONCANONICAL_SQL,
3174                        rusqlite::params![&edge.namespace, edge.id.to_string()],
3175                    )?;
3176                }
3177                edge_conflict_preimages.push(MergeEdgeConflictPreimage {
3178                    surviving_edge_id,
3179                    dropped_edge: edge_row_preimage(&edge)?,
3180                    incident_edge_preimages,
3181                });
3182            } else {
3183                if dry_run {
3184                    rewired_edge_ids.insert(edge.id);
3185                    continue;
3186                }
3187                let changed = conn.execute(
3188                    "UPDATE graph_edges SET \
3189                     source_id = ?1, target_id = ?2, updated_at = ?3 \
3190                     WHERE namespace = ?4 AND id = ?5",
3191                    rusqlite::params![
3192                        new_src.to_string(),
3193                        new_tgt.to_string(),
3194                        now_ts,
3195                        &edge.namespace,
3196                        edge.id.to_string(),
3197                    ],
3198                )?;
3199                if changed > 0 {
3200                    rewired_edge_ids.insert(edge.id);
3201                }
3202            }
3203        }
3204    }
3205    let edges_rewired = rewired_edge_ids.len();
3206
3207    if !dry_run {
3208        conn.prepare_cached(khive_db::stores::note::NOTE_UPSERT_SQL)?
3209            .execute(rusqlite::params![
3210                &into_str,
3211                &namespace,
3212                &into_note.kind,
3213                &into_note.status,
3214                &merged_name,
3215                &merged_content,
3216                merged_salience,
3217                into_note.decay_factor,
3218                merged_expires_at,
3219                &props_str,
3220                into_note.created_at,
3221                now,
3222                into_note.deleted_at,
3223            ])?;
3224
3225        conn.execute(
3226            &format!(
3227                "DELETE FROM {} WHERE namespace = ?1 AND subject_id = ?2",
3228                fts_table
3229            ),
3230            rusqlite::params![&namespace, &into_str],
3231        )?;
3232        // Derive FTS scalars through the shared constructor so this raw SQL path
3233        // is field-identical to TextSearch::upsert_document: critically, `title`
3234        // is an empty string (not SQL NULL) for nameless notes, so get_document
3235        // round-trips None <-> "" correctly.
3236        let fts_merged = {
3237            let mut merged_note = Note::new(&namespace, &*into_note.kind, &*merged_content);
3238            merged_note.id = into_id;
3239            merged_note.name = merged_name.clone();
3240            merged_note.properties = merged_props.clone();
3241            merged_note.updated_at = now;
3242            note_fts_scalars(&merged_note)
3243        };
3244        conn.execute(
3245            &format!(
3246                "INSERT INTO {} \
3247                 (subject_id, kind, title, body, tags, namespace, metadata, updated_at) \
3248                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
3249                fts_table
3250            ),
3251            rusqlite::params![
3252                &into_str,
3253                SubstrateKind::Note.to_string(),
3254                &fts_merged.title,
3255                &fts_merged.body,
3256                &fts_merged.tags,
3257                &namespace,
3258                &fts_merged.metadata,
3259                fts_merged.updated_at_micros,
3260            ],
3261        )?;
3262
3263        conn.execute(
3264            &format!(
3265                "DELETE FROM {} WHERE namespace = ?1 AND subject_id = ?2",
3266                fts_table
3267            ),
3268            rusqlite::params![&namespace, &from_str],
3269        )?;
3270
3271        khive_db::stores::vectors::delete_subject_from_vector_tables(
3272            conn,
3273            &vec_tables,
3274            from_id,
3275            &namespace,
3276        )?;
3277
3278        conn.execute(
3279            "UPDATE notes SET status = 'deleted', deleted_at = ?1, updated_at = ?1 \
3280             WHERE namespace = ?2 AND id = ?3 AND deleted_at IS NULL",
3281            rusqlite::params![now, &namespace, &from_str],
3282        )?;
3283    }
3284
3285    let updated_note = khive_storage::note::Note {
3286        id: into_id,
3287        namespace: namespace.clone(),
3288        kind: into_note.kind.clone(),
3289        status: into_note.status.clone(),
3290        name: merged_name,
3291        content: merged_content,
3292        salience: merged_salience,
3293        decay_factor: into_note.decay_factor,
3294        expires_at: merged_expires_at,
3295        properties: merged_props,
3296        created_at: into_note.created_at,
3297        updated_at: now,
3298        deleted_at: into_note.deleted_at,
3299    };
3300
3301    Ok((
3302        MergeSummary {
3303            kept_id: into_id,
3304            removed_id: from_id,
3305            edges_rewired,
3306            edges_contract_skipped,
3307            edge_conflict_preimages,
3308            properties_merged,
3309            tags_unioned: 0,
3310            content_appended,
3311            dry_run,
3312            tx_budget: budget.report(),
3313            embedding_truncation: Default::default(),
3314        },
3315        updated_note,
3316    ))
3317}
3318
3319// ---------------------------------------------------------------------------
3320// Merge helpers (pure functions — easier to unit test)
3321// ---------------------------------------------------------------------------
3322
3323/// `pub(crate)` so `crate::atomic_prepare::prepare_merge` can reuse this exact
3324/// field-fold semantics for atomic/non-atomic parity.
3325pub(crate) fn merge_string_field(
3326    into: &str,
3327    from: &str,
3328    strategy: EntityDedupMergePolicy,
3329) -> String {
3330    match strategy {
3331        EntityDedupMergePolicy::PreferInto | EntityDedupMergePolicy::Union => into.to_string(),
3332        EntityDedupMergePolicy::PreferFrom => from.to_string(),
3333    }
3334}
3335
3336/// Property keys on a pack-owned note that the owning pack establishes and
3337/// then reads back to decide something structural about the record.
3338///
3339/// The test for membership is that both halves hold: the key is written
3340/// under the owner's authority rather than from caller input, AND its value
3341/// is read to decide identity, grouping, routing, lifecycle, visibility,
3342/// authorization, deduplication, or membership. `from_actor`, `direction` and
3343/// `sent_at` answer "who wrote this, in which direction, when"; `outbound_ref`
3344/// and `thread_id` answer "which record is this one's author-side original,
3345/// and which conversation does it belong to". `subject` is reproduced
3346/// verbatim when a record is re-emitted; `wire_message_id` and `external_id`
3347/// are the author-side citation and correlation key a reply is routed
3348/// against. The set is therefore not "keys that identify a party" — it is
3349/// "keys the owner established and later trusts".
3350///
3351/// Naming one of these in a caller-supplied `properties` patch is refused by
3352/// `update` on a pack-owned kind (see [`owner_established_property_named_in`]).
3353///
3354/// `to_actor` belongs here alongside `from_actor`: comm establishes it at
3355/// send time from the `to=` param, and `comm.read` trusts a present string
3356/// value to decide whether the caller is the addressee, failing open only
3357/// when the key is absent or non-string. A caller must not be able to
3358/// retarget a delivered message's addressee via a patch that names no other
3359/// currently-protected key.
3360///
3361/// Membership here governs writes to an EXISTING record only. Introducing one
3362/// of these keys at create time is a separate question and is not addressed
3363/// by this constant.
3364pub(crate) const OWNER_ESTABLISHED_PROPERTIES: &[&str] = &[
3365    "from_actor",
3366    "to_actor",
3367    "direction",
3368    "sent_at",
3369    "outbound_ref",
3370    "thread_id",
3371    "subject",
3372    "wire_message_id",
3373    "external_id",
3374];
3375
3376/// Transport evidence that only `comm.ingest` may establish on a `message`.
3377///
3378/// This list is deliberately separate from [`OWNER_ESTABLISHED_PROPERTIES`].
3379/// The latter applies to every pack-owned note kind; quarantine disposition
3380/// and channel attribution are message-only, and protecting these names on a
3381/// task, memory, or another pack-owned note would reserve ordinary metadata
3382/// outside ADR-056's scope.
3383pub(crate) const MESSAGE_TRANSPORT_OWNED_PROPERTIES: &[&str] =
3384    &["quarantined", "channel_kind", "channel_slug"];
3385
3386/// Whether a stored message note carries a live quarantine disposition.
3387///
3388/// The marker is written by transports as JSON `true` and by some channel
3389/// adapters as the string `"true"`; both spellings are live in stored data
3390/// (`comm.health` counts both). Any present value other than an explicit
3391/// boolean `false` or string `"false"` reads as quarantined, so an unexpected
3392/// encoding fails closed.
3393fn message_is_quarantined(note: &khive_storage::note::Note) -> bool {
3394    let Some(Value::Object(map)) = note.properties.as_ref() else {
3395        return false;
3396    };
3397    match map.get("quarantined") {
3398        None => false,
3399        Some(Value::Bool(value)) => *value,
3400        Some(Value::String(value)) => value != "false",
3401        Some(_) => true,
3402    }
3403}
3404
3405fn message_transport_owned_property_named_in(patch: &Value) -> Option<&'static str> {
3406    let Value::Object(map) = patch else {
3407        return None;
3408    };
3409    MESSAGE_TRANSPORT_OWNED_PROPERTIES
3410        .iter()
3411        .copied()
3412        .find(|key| map.contains_key(*key))
3413}
3414
3415/// The first [`OWNER_ESTABLISHED_PROPERTIES`] key a caller-supplied
3416/// `properties` patch names, if any.
3417///
3418/// Naming a key is the whole test: `update_note` folds the patch with
3419/// `PreferFrom`, so a named key overwrites the stored value and an unnamed one
3420/// leaves it untouched. A non-object patch names nothing.
3421pub(crate) fn owner_established_property_named_in(patch: &Value) -> Option<&'static str> {
3422    let Value::Object(map) = patch else {
3423        return None;
3424    };
3425    OWNER_ESTABLISHED_PROPERTIES
3426        .iter()
3427        .copied()
3428        .find(|key| map.contains_key(*key))
3429}
3430
3431/// Restore the into-note's [`OWNER_ESTABLISHED_PROPERTIES`] into `merged`
3432/// after a property fold.
3433///
3434/// A key absent on the into-note is removed from `merged` rather than left as
3435/// the from-note's value: a record that carried no owner-established value
3436/// must not acquire one by being merged into. That applies to grouping as much
3437/// as to attribution — a note with no `thread_id` must not join a conversation
3438/// because another note was folded into it.
3439///
3440/// A fold can also yield a value that is not an object at all: `merge_json`
3441/// applies a non-object `from` directly under `PreferFrom`, replacing the
3442/// into-note's whole object with a scalar. A scalar cannot carry the
3443/// owner-established keys, so there is nothing to restore them into and they
3444/// would be erased. The into-note's properties are kept instead — the scalar
3445/// contributes no key that could coexist with them, so nothing the fold
3446/// intended is lost.
3447///
3448/// This function only restores values; callers that need to report how many
3449/// properties genuinely survived a merge should diff the final result
3450/// against the into-note's pre-merge properties (see
3451/// [`count_new_property_keys`]) rather than try to track the restoration as
3452/// a correction to the fold's own count — a nested owner-established value
3453/// (an object) makes that correction ill-defined, since the fold's flat
3454/// "keys contributed" number cannot express a partial reversal of a nested
3455/// contribution.
3456pub(crate) fn preserve_owner_established_properties(
3457    into: &Option<Value>,
3458    merged: &mut Option<Value>,
3459) {
3460    preserve_property_keys(OWNER_ESTABLISHED_PROPERTIES, into, merged);
3461}
3462
3463fn preserve_message_transport_properties(into: &Option<Value>, merged: &mut Option<Value>) {
3464    preserve_property_keys(MESSAGE_TRANSPORT_OWNED_PROPERTIES, into, merged);
3465}
3466
3467fn preserve_property_keys(keys: &[&str], into: &Option<Value>, merged: &mut Option<Value>) {
3468    if !matches!(merged, Some(Value::Object(_))) {
3469        let Some(Value::Object(into_map)) = into else {
3470            return;
3471        };
3472        let owned_on_into = keys.iter().any(|key| into_map.contains_key(*key));
3473        if owned_on_into {
3474            *merged = into.clone();
3475        }
3476        return;
3477    }
3478    let Some(Value::Object(merged_map)) = merged.as_mut() else {
3479        return;
3480    };
3481    let into_map = match into {
3482        Some(Value::Object(m)) => Some(m),
3483        _ => None,
3484    };
3485    for key in keys {
3486        match into_map.and_then(|m| m.get(*key)) {
3487            Some(value) => {
3488                // Already present on `into` — restore it verbatim.
3489                merged_map.insert((*key).to_string(), value.clone());
3490            }
3491            None => {
3492                // Absent from `into` — a value here came from `from` and
3493                // must not survive the merge.
3494                merged_map.remove(*key);
3495            }
3496        }
3497    }
3498}
3499
3500/// Count properties present in `final_value` that are new relative to
3501/// `original` — the same "did this key actually get added" question
3502/// [`merge_json`]'s fold answers, but computed from what the record finally
3503/// holds rather than carried forward through the fold-then-restore pipeline.
3504///
3505/// A key present in both `original` and `final_value` is never counted, even
3506/// when its value changed — this matches `merge_json`'s own rule that an
3507/// overwrite of a key already present on `into` is not a merged addition.
3508/// Nested objects recurse only when the key exists on both sides (mirroring
3509/// `merge_json`'s `Union` recursion); a key that is wholly new at some level
3510/// counts once for that level, not once per leaf beneath it.
3511pub(crate) fn count_new_property_keys(
3512    original: Option<&Value>,
3513    final_value: Option<&Value>,
3514    strategy: EntityDedupMergePolicy,
3515) -> usize {
3516    match (original, final_value) {
3517        (_, None) => 0,
3518        (None, Some(Value::Object(map))) => map.len(),
3519        (None, Some(_)) => 1,
3520        (Some(Value::Object(orig_map)), Some(Value::Object(final_map))) => {
3521            count_new_keys_within_object(orig_map, final_map, strategy)
3522        }
3523        // The record ended up holding an object where it previously held
3524        // something else. `merge_json` scores that replacement as ONE
3525        // contribution however many keys the new object carries, and this arm
3526        // keeps that rule rather than counting the keys — the alternative
3527        // silently changes `properties_merged` for ordinary notes, which never
3528        // enter the restoration path and were being reported correctly by the
3529        // fold. The rule here is: an empty final object has no contribution
3530        // left to report, whatever emptied it — restoration removing every
3531        // owner-established key is one way that happens, but an ordinary
3532        // `PreferFrom` replacement with an empty object reaches this same arm.
3533        (Some(_), Some(Value::Object(final_map))) => usize::from(!final_map.is_empty()),
3534        // Whole-value replacement by a non-object. `merge_json` scores a
3535        // `PreferFrom` fold that replaces one properties value with a
3536        // differently-shaped one as a single contribution, and that is the right
3537        // answer: what the record now holds came from the from-note. A bare 0
3538        // here would under-report every such replacement, including on note
3539        // kinds that have no owner-established properties and never enter the
3540        // restoration path at all. Equal values mean nothing was contributed,
3541        // which is the `properties: Some(a)` merged with `properties: None`
3542        // case.
3543        (Some(orig), Some(final_val)) => usize::from(orig != final_val),
3544    }
3545}
3546
3547/// Per-key counting inside a properties object.
3548///
3549/// Deliberately NOT the same rule as the top level: within an object, a key that
3550/// already exists and is merely overwritten counts 0, matching `merge_json`'s
3551/// rule that only keys absent from the into-note are counted as added.
3552///
3553/// Recursion is STRATEGY-AWARE, and it has to be, because `merge_json` only
3554/// descends into a same-named nested object under [`Union`]. Under `PreferFrom`
3555/// an existing top-level key is replaced wholesale, and under `PreferInto` it is
3556/// kept wholesale; in neither case is anything merged *beneath* that key, so
3557/// descending here would count a nested value that the fold never treated as a
3558/// separate contribution. Counting `{"meta":{"old":1}}` merged with
3559/// `{"meta":{"new":2}}` under `PreferFrom` as 1 is exactly that mistake — one
3560/// existing property was replaced, none was added.
3561///
3562/// [`Union`]: EntityDedupMergePolicy::Union
3563fn count_new_keys_within_object(
3564    orig_map: &serde_json::Map<String, Value>,
3565    final_map: &serde_json::Map<String, Value>,
3566    strategy: EntityDedupMergePolicy,
3567) -> usize {
3568    final_map
3569        .iter()
3570        .map(|(key, value)| match orig_map.get(key) {
3571            None => 1,
3572            Some(Value::Object(nested_orig))
3573                if matches!(strategy, EntityDedupMergePolicy::Union) =>
3574            {
3575                match value {
3576                    Value::Object(nested_final) => {
3577                        count_new_keys_within_object(nested_orig, nested_final, strategy)
3578                    }
3579                    _ => 0,
3580                }
3581            }
3582            Some(_) => 0,
3583        })
3584        .sum()
3585}
3586
3587/// Merge two property objects. Returns (merged, count_of_fields_from_from_that_were_added).
3588/// `pub(crate)` so `crate::atomic_prepare` can reuse this exact properties-merge
3589/// semantics when building an `update` write plan's row statement, matching
3590/// `update_entity`/`update_note`'s own patch behavior byte-for-byte.
3591pub(crate) fn merge_properties(
3592    into: &Option<Value>,
3593    from: &Option<Value>,
3594    strategy: EntityDedupMergePolicy,
3595) -> (Option<Value>, usize) {
3596    match (into, from) {
3597        (None, None) => (None, 0),
3598        (Some(a), None) => (Some(a.clone()), 0),
3599        (None, Some(b)) => {
3600            let count = if let Value::Object(m) = b { m.len() } else { 1 };
3601            (Some(b.clone()), count)
3602        }
3603        (Some(into_val), Some(from_val)) => {
3604            let (merged, added) = merge_json(into_val, from_val, strategy);
3605            (Some(merged), added)
3606        }
3607    }
3608}
3609
3610/// Deep-merge two JSON values per strategy. Returns (merged, keys_contributed_by_from).
3611fn merge_json(into: &Value, from: &Value, strategy: EntityDedupMergePolicy) -> (Value, usize) {
3612    match (into, from, strategy) {
3613        (Value::Object(a), Value::Object(b), EntityDedupMergePolicy::Union) => {
3614            let mut result = a.clone();
3615            let mut added = 0usize;
3616            for (k, v_from) in b {
3617                if let Some(v_into) = a.get(k) {
3618                    let (merged, sub_added) =
3619                        merge_json(v_into, v_from, EntityDedupMergePolicy::Union);
3620                    result.insert(k.clone(), merged);
3621                    added += sub_added;
3622                } else {
3623                    result.insert(k.clone(), v_from.clone());
3624                    added += 1;
3625                }
3626            }
3627            (Value::Object(result), added)
3628        }
3629        (Value::Object(a), Value::Object(b), EntityDedupMergePolicy::PreferInto) => {
3630            let mut result = a.clone();
3631            let mut added = 0usize;
3632            for (k, v) in b {
3633                if !a.contains_key(k) {
3634                    result.insert(k.clone(), v.clone());
3635                    added += 1;
3636                }
3637            }
3638            (Value::Object(result), added)
3639        }
3640        (Value::Object(a), Value::Object(b), EntityDedupMergePolicy::PreferFrom) => {
3641            let mut result = a.clone();
3642            let mut added = 0usize;
3643            for (k, v) in b {
3644                result.insert(k.clone(), v.clone());
3645                if !a.contains_key(k) {
3646                    added += 1;
3647                }
3648            }
3649            (Value::Object(result), added)
3650        }
3651        // Non-object scalars: apply strategy directly.
3652        (_into_val, from_val, EntityDedupMergePolicy::PreferFrom) => (from_val.clone(), 1),
3653        _ => (into.clone(), 0),
3654    }
3655}
3656
3657/// `pub(crate)` so `crate::atomic_prepare::prepare_merge` can reuse this for
3658/// atomic/non-atomic parity.
3659pub(crate) fn union_tags(into: &[String], from: &[String]) -> (Vec<String>, usize) {
3660    let mut seen: HashSet<&str> = into.iter().map(|s| s.as_str()).collect();
3661    let mut result: Vec<String> = into.to_vec();
3662    let mut added = 0usize;
3663    for tag in from {
3664        if seen.insert(tag.as_str()) {
3665            result.push(tag.clone());
3666            added += 1;
3667        }
3668    }
3669    (result, added)
3670}
3671
3672// ---------------------------------------------------------------------------
3673// INLINE TEST JUSTIFICATION: tests here exercise patch/merge helpers and the
3674// update_note/update_entity paths that share private merge_properties logic.
3675// Moving them to tests/ would require pub-exporting merge_properties, which is
3676// an internal invariant not suitable for the public API surface. Broad
3677// behavioral curation tests live in tests/integration.rs.
3678// ---------------------------------------------------------------------------
3679
3680#[cfg(test)]
3681mod tests {
3682    use std::sync::Arc;
3683
3684    use super::*;
3685    use crate::runtime::{KhiveRuntime, NamespaceToken};
3686    use khive_storage::types::{Direction, TextFilter, TextQueryMode, TextSearchRequest};
3687    use khive_types::EndpointKind;
3688
3689    fn rt() -> KhiveRuntime {
3690        KhiveRuntime::memory().unwrap()
3691    }
3692
3693    fn outbound_message_note() -> Note {
3694        let mut note = Note::new("local", "message", "hello");
3695        note.properties = Some(serde_json::json!({"direction": "outbound"}));
3696        note
3697    }
3698
3699    #[tokio::test]
3700    async fn claim_outbound_message_external_id_sets_value_and_survives_readback() {
3701        let rt = rt();
3702        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3703        let tok = NamespaceToken::local();
3704        let note = outbound_message_note();
3705        let note_id = note.id;
3706        rt.notes(&tok)
3707            .expect("note store")
3708            .upsert_note(note)
3709            .await
3710            .expect("seed note");
3711
3712        let claimed = rt
3713            .claim_outbound_message_external_id(&tok, note_id, "<abc@example.com>".to_string())
3714            .await
3715            .expect("claim succeeds on a fresh outbound message note");
3716        assert_eq!(
3717            claimed
3718                .properties
3719                .as_ref()
3720                .and_then(|p| p.get("external_id"))
3721                .and_then(|v| v.as_str()),
3722            Some("<abc@example.com>")
3723        );
3724
3725        // Reads the persisted row back independently of the claim call's own
3726        // return value. This is the check that fails if the fix is reverted
3727        // to routing the claim through `dispatch("update", ...)`: that path is
3728        // refused by the owner-established-property gate exercised in
3729        // `generic_update_still_refuses_external_id_on_message_note` below, so
3730        // external_id would never actually persist and this read would come
3731        // back `None`.
3732        let reread = rt
3733            .notes(&tok)
3734            .expect("note store")
3735            .get_note(note_id)
3736            .await
3737            .expect("read note")
3738            .expect("note still exists");
3739        assert_eq!(
3740            reread
3741                .properties
3742                .as_ref()
3743                .and_then(|p| p.get("external_id"))
3744                .and_then(|v| v.as_str()),
3745            Some("<abc@example.com>")
3746        );
3747    }
3748
3749    #[tokio::test]
3750    async fn generic_update_still_refuses_external_id_on_message_note() {
3751        let rt = rt();
3752        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3753        let tok = NamespaceToken::local();
3754        let note = outbound_message_note();
3755        let note_id = note.id;
3756        rt.notes(&tok)
3757            .expect("note store")
3758            .upsert_note(note)
3759            .await
3760            .expect("seed note");
3761
3762        let err = rt
3763            .update_note(
3764                &tok,
3765                note_id,
3766                NotePatch {
3767                    properties: Some(serde_json::json!({"external_id": "<forged@example.com>"})),
3768                    ..Default::default()
3769                },
3770            )
3771            .await
3772            .expect_err("caller-facing update must keep refusing external_id on a message note");
3773        assert!(matches!(err, RuntimeError::InvalidInput(_)), "error: {err}");
3774        assert!(err.to_string().contains("is not patchable"), "error: {err}");
3775
3776        // The owner path is unaffected by the caller-side refusal above.
3777        let claimed = rt
3778            .claim_outbound_message_external_id(&tok, note_id, "<claimed@example.com>".to_string())
3779            .await
3780            .expect("owner-bookkeeping path still claims after a refused caller patch");
3781        assert_eq!(
3782            claimed
3783                .properties
3784                .as_ref()
3785                .and_then(|p| p.get("external_id"))
3786                .and_then(|v| v.as_str()),
3787            Some("<claimed@example.com>")
3788        );
3789    }
3790
3791    #[tokio::test]
3792    async fn claim_refuses_non_message_note() {
3793        let rt = rt();
3794        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3795        let tok = NamespaceToken::local();
3796        let mut note = Note::new("local", "observation", "not a message");
3797        note.properties = Some(serde_json::json!({"direction": "outbound"}));
3798        let note_id = note.id;
3799        rt.notes(&tok)
3800            .expect("note store")
3801            .upsert_note(note)
3802            .await
3803            .expect("seed note");
3804
3805        let err = rt
3806            .claim_outbound_message_external_id(&tok, note_id, "<x@example.com>".to_string())
3807            .await
3808            .expect_err("a non-message note must never accept the claim");
3809        assert!(matches!(err, RuntimeError::InvalidInput(_)), "error: {err}");
3810    }
3811
3812    #[tokio::test]
3813    async fn claim_refuses_inbound_message() {
3814        let rt = rt();
3815        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3816        let tok = NamespaceToken::local();
3817        let mut note = Note::new("local", "message", "inbound content");
3818        note.properties = Some(serde_json::json!({"direction": "inbound"}));
3819        let note_id = note.id;
3820        rt.notes(&tok)
3821            .expect("note store")
3822            .upsert_note(note)
3823            .await
3824            .expect("seed note");
3825
3826        let err = rt
3827            .claim_outbound_message_external_id(&tok, note_id, "<x@example.com>".to_string())
3828            .await
3829            .expect_err("an inbound message note must never accept the claim");
3830        assert!(matches!(err, RuntimeError::InvalidInput(_)), "error: {err}");
3831    }
3832
3833    #[tokio::test]
3834    async fn claim_refuses_when_external_id_already_set() {
3835        let rt = rt();
3836        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3837        let tok = NamespaceToken::local();
3838        let mut note = outbound_message_note();
3839        note.properties = Some(
3840            serde_json::json!({"direction": "outbound", "external_id": "<already@example.com>"}),
3841        );
3842        let note_id = note.id;
3843        rt.notes(&tok)
3844            .expect("note store")
3845            .upsert_note(note)
3846            .await
3847            .expect("seed note");
3848
3849        let err = rt
3850            .claim_outbound_message_external_id(&tok, note_id, "<new@example.com>".to_string())
3851            .await
3852            .expect_err("a note that already carries external_id must refuse re-claim");
3853        assert!(matches!(err, RuntimeError::InvalidInput(_)), "error: {err}");
3854    }
3855
3856    #[tokio::test]
3857    async fn generic_update_can_still_patch_delivered_at_on_message_note() {
3858        let rt = rt();
3859        rt.install_pack_owned_note_kinds(vec!["message".to_string()]);
3860        let tok = NamespaceToken::local();
3861        let note = outbound_message_note();
3862        let note_id = note.id;
3863        rt.notes(&tok)
3864            .expect("note store")
3865            .upsert_note(note)
3866            .await
3867            .expect("seed note");
3868
3869        let updated = rt
3870            .update_note(
3871                &tok,
3872                note_id,
3873                NotePatch {
3874                    properties: Some(serde_json::json!({"delivered_at": "2026-08-09T00:00:00Z"})),
3875                    ..Default::default()
3876                },
3877            )
3878            .await
3879            .expect("delivered_at is not owner-established and must remain patchable");
3880        assert_eq!(
3881            updated
3882                .properties
3883                .as_ref()
3884                .and_then(|p| p.get("delivered_at"))
3885                .and_then(|v| v.as_str()),
3886            Some("2026-08-09T00:00:00Z")
3887        );
3888    }
3889
3890    fn secret_shaped_reason() -> String {
3891        const ALPHANUMERIC: &[u8] =
3892            b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
3893        let candidate: String = (0..48)
3894            .map(|index| char::from(ALPHANUMERIC[(index * 17 + 11) % ALPHANUMERIC.len()]))
3895            .collect();
3896        format!("secret value: {candidate}")
3897    }
3898
3899    #[test]
3900    fn note_embedding_text_ref_borrows_stored_content() {
3901        let note = Note::new("embedding-borrow", "observation", "borrow this content");
3902        let text = note_embedding_text_ref(&note);
3903
3904        assert_eq!(text, note.content.as_str());
3905        assert!(
3906            std::ptr::eq(text, note.content.as_str()),
3907            "internal canonical note text must borrow instead of cloning"
3908        );
3909        let owned: String = note_embedding_text(&note);
3910        assert_eq!(owned.as_str(), note.content.as_str());
3911    }
3912
3913    #[tokio::test]
3914    async fn generic_note_update_errors_when_revision_is_already_i64_max() {
3915        let rt = rt();
3916        let tok = NamespaceToken::local();
3917        let mut note = Note::new("local", "observation", "saturated revision");
3918        note.updated_at = i64::MAX;
3919        let note_id = note.id;
3920        rt.notes(&tok)
3921            .expect("note store")
3922            .upsert_note(note.clone())
3923            .await
3924            .expect("seed saturated note");
3925
3926        let error = rt
3927            .update_note(
3928                &tok,
3929                note_id,
3930                NotePatch::new(None, Some("must not land".to_string()), None, None, None),
3931            )
3932            .await
3933            .expect_err("i64::MAX cannot yield a strictly newer CAS revision");
3934        assert!(
3935            matches!(&error, RuntimeError::Internal(_)),
3936            "revision exhaustion is an internal persisted-state error: {error}"
3937        );
3938        assert!(error.to_string().contains("i64::MAX"), "error: {error}");
3939
3940        let persisted = rt
3941            .notes(&tok)
3942            .expect("note store")
3943            .get_note(note_id)
3944            .await
3945            .expect("read note")
3946            .expect("note remains live");
3947        assert_eq!(persisted, note, "failed revision advance must not mutate");
3948    }
3949
3950    async fn restore_edge_preimage(
3951        rt: &KhiveRuntime,
3952        token: &NamespaceToken,
3953        preimage: &MergeEdgePreimage,
3954    ) {
3955        let edge = khive_storage::types::Edge {
3956            id: preimage.id.into(),
3957            namespace: preimage.namespace.clone(),
3958            source_id: preimage.source_id,
3959            target_id: preimage.target_id,
3960            relation: preimage.relation.parse().expect("stored relation"),
3961            weight: preimage.weight,
3962            created_at: chrono::DateTime::from_timestamp_micros(preimage.created_at)
3963                .expect("stored created_at"),
3964            updated_at: chrono::DateTime::from_timestamp_micros(preimage.updated_at)
3965                .expect("stored updated_at"),
3966            deleted_at: preimage.deleted_at.map(|value| {
3967                chrono::DateTime::from_timestamp_micros(value).expect("stored deleted_at")
3968            }),
3969            metadata: preimage.metadata.clone(),
3970            target_backend: preimage.target_backend.clone(),
3971        };
3972        rt.graph(token)
3973            .expect("graph store")
3974            .upsert_edge(edge)
3975            .await
3976            .expect("restore edge preimage");
3977    }
3978
3979    fn assert_edge_matches_preimage(
3980        edge: &khive_storage::types::Edge,
3981        preimage: &MergeEdgePreimage,
3982    ) {
3983        assert_eq!(Uuid::from(edge.id), preimage.id);
3984        assert_eq!(edge.namespace, preimage.namespace);
3985        assert_eq!(edge.source_id, preimage.source_id);
3986        assert_eq!(edge.target_id, preimage.target_id);
3987        assert_eq!(edge.relation.to_string(), preimage.relation);
3988        assert_eq!(edge.weight, preimage.weight);
3989        assert_eq!(edge.created_at.timestamp_micros(), preimage.created_at);
3990        assert_eq!(edge.updated_at.timestamp_micros(), preimage.updated_at);
3991        assert_eq!(
3992            edge.deleted_at.map(|value| value.timestamp_micros()),
3993            preimage.deleted_at
3994        );
3995        assert_eq!(edge.metadata, preimage.metadata);
3996        assert_eq!(edge.target_backend, preimage.target_backend);
3997    }
3998
3999    // Helper: search FTS5 for `query` in a runtime namespace.
4000    async fn fts_hit(rt: &KhiveRuntime, token: &NamespaceToken, query: &str) -> Vec<Uuid> {
4001        let ns = token.namespace().as_str().to_string();
4002        rt.text(token)
4003            .unwrap()
4004            .search(TextSearchRequest {
4005                query: query.to_string(),
4006                mode: TextQueryMode::Plain,
4007                filter: Some(TextFilter {
4008                    namespaces: vec![ns],
4009                    ..Default::default()
4010                }),
4011                top_k: 50,
4012                snippet_chars: 100,
4013            })
4014            .await
4015            .unwrap()
4016            .into_iter()
4017            .map(|h| h.subject_id)
4018            .collect()
4019    }
4020
4021    #[tokio::test]
4022    async fn update_entity_patch_changes_only_specified_fields() {
4023        let rt = rt();
4024        let tok = NamespaceToken::local();
4025        let entity = rt
4026            .create_entity(
4027                &tok,
4028                "concept",
4029                None,
4030                "OriginalName",
4031                Some("orig desc"),
4032                Some(serde_json::json!({"k":"v"})),
4033                vec![],
4034            )
4035            .await
4036            .unwrap();
4037
4038        let updated = rt
4039            .update_entity(
4040                &tok,
4041                entity.id,
4042                EntityPatch {
4043                    description: Some(Some("new desc".to_string())),
4044                    ..Default::default()
4045                },
4046            )
4047            .await
4048            .unwrap();
4049
4050        assert_eq!(updated.name, "OriginalName");
4051        assert_eq!(updated.description.as_deref(), Some("new desc"));
4052        assert_eq!(updated.properties, Some(serde_json::json!({"k":"v"})));
4053    }
4054
4055    #[tokio::test]
4056    async fn update_entity_type_patch_validates_preserves_fields_and_requires_reindex() {
4057        let rt = rt();
4058        rt.install_entity_type_validator(std::sync::Arc::new(|kind, entity_type| {
4059            let Some(raw) = entity_type else {
4060                return Ok(None);
4061            };
4062            let normalized = raw.trim().to_ascii_lowercase();
4063            if kind == "concept" && normalized == "algorithm" {
4064                Ok(Some(normalized))
4065            } else {
4066                Err(RuntimeError::InvalidInput(format!(
4067                    "unknown entity_type {raw:?} for {kind:?}; valid: algorithm"
4068                )))
4069            }
4070        }));
4071        let tok = NamespaceToken::local();
4072        let entity = rt
4073            .create_entity(
4074                &tok,
4075                "concept",
4076                None,
4077                "HistoricalAlgorithm",
4078                Some("keep description"),
4079                Some(serde_json::json!({"type": "algorithm", "keep": true})),
4080                vec!["keep-tag".to_string()],
4081            )
4082            .await
4083            .unwrap();
4084
4085        let (
4086            prepared,
4087            reindex_required,
4088            changed_fields,
4089            _expected_updated_at,
4090            _expected_deleted_at,
4091        ) = rt
4092            .prepare_update_entity(
4093                &tok,
4094                entity.id,
4095                EntityPatch {
4096                    entity_type: Some(Some(" Algorithm ".to_string())),
4097                    ..Default::default()
4098                },
4099            )
4100            .await
4101            .expect("registered entity_type must validate");
4102
4103        assert_eq!(prepared.entity_type.as_deref(), Some("algorithm"));
4104        assert_eq!(prepared.name, "HistoricalAlgorithm");
4105        assert_eq!(prepared.description.as_deref(), Some("keep description"));
4106        assert_eq!(
4107            prepared.properties,
4108            Some(serde_json::json!({"type": "algorithm", "keep": true}))
4109        );
4110        assert_eq!(prepared.tags, vec!["keep-tag"]);
4111        assert!(
4112            reindex_required,
4113            "changing entity_type must request the normal entity reindex path"
4114        );
4115        assert_eq!(changed_fields, vec!["entity_type"]);
4116
4117        let err = rt
4118            .prepare_update_entity(
4119                &tok,
4120                entity.id,
4121                EntityPatch {
4122                    entity_type: Some(Some("not_registered".to_string())),
4123                    ..Default::default()
4124                },
4125            )
4126            .await
4127            .expect_err("unregistered entity_type must be rejected");
4128        assert!(matches!(err, RuntimeError::InvalidInput(_)), "error: {err}");
4129    }
4130
4131    /// Regression for the entity lost-update race (khive #1753): two writers
4132    /// read the same entity revision, then commit successive patches to
4133    /// independent properties fields. Before the guarded
4134    /// `replace_entity_if_unchanged` primitive, `update_entity_with_embedding_report`
4135    /// wrote an unconditional `entity_upsert_statement`, so both patches
4136    /// "succeeded" and the second silently discarded the first's field
4137    /// (`a=1` was overwritten back to `a=0` when B's stale full-row replace
4138    /// landed). This test forces the interleaving with a `Barrier` — both
4139    /// readers are released together, so both `prepare_update_entity` calls
4140    /// observe the SAME pre-write revision (asserted below) — then commits
4141    /// deterministically in a fixed A-then-B order. It reddens if the guard
4142    /// is dropped from `entity_replace_if_unchanged_statement` ENTIRELY: with
4143    /// an unconditional UPDATE (or `entity_upsert_statement`), B's write would
4144    /// also return `true` and `b` would be lost from the final properties.
4145    ///
4146    /// It does NOT redden when only `?8 > updated_at` is removed: with
4147    /// `updated_at = ?13` intact, B is refused by the revision guard whatever
4148    /// the clock did, so this fixture cannot see that conjunct disappear.
4149    ///
4150    /// It cannot ATTRIBUTE a failure to `updated_at = ?13` either, but for a
4151    /// different reason, and the difference matters. Both racers take their
4152    /// replacement revision from `prepare_update_entity`'s
4153    /// `max(now_micros, expected + 1)` above; this test pins the two EXPECTED
4154    /// revisions equal, never the two REPLACEMENT revisions. So with
4155    /// `updated_at = ?13` removed, whether B is still refused depends on
4156    /// whether B's wall-clock read happened to exceed A's committed revision.
4157    /// That is a race, not a property of the fixture, and no single run of it
4158    /// establishes either answer.
4159    ///
4160    /// Attribution therefore comes from fixtures that force the question:
4161    /// `entity_cas_refuses_a_replacement_revision_that_does_not_advance` for
4162    /// the strict-advance conjunct, and
4163    /// `production_update_entity_refuses_concurrent_stale_writer` for the
4164    /// production wiring. Making this fixture attribute as well would mean
4165    /// pinning both replacement revisions to a common `expected + 1`; it is
4166    /// deliberately left as a whole-guard test instead.
4167    ///
4168    /// SCOPE: this exercises the STORE PRIMITIVE directly and never invokes
4169    /// `update_entity`, so it stays green if the production caller is reverted
4170    /// to an unconditional write. The wiring is covered separately by
4171    /// `production_update_entity_refuses_concurrent_stale_writer`; both are
4172    /// required, neither substitutes for the other.
4173    #[tokio::test]
4174    async fn concurrent_entity_property_patches_from_one_revision_only_one_survives() {
4175        let rt = Arc::new(rt());
4176        let tok = NamespaceToken::local();
4177        let entity = rt
4178            .create_entity(
4179                &tok,
4180                "concept",
4181                None,
4182                "RaceTarget",
4183                None,
4184                Some(serde_json::json!({"a": 0, "b": 0})),
4185                vec![],
4186            )
4187            .await
4188            .expect("seed entity");
4189        let id = entity.id;
4190
4191        let barrier = Arc::new(tokio::sync::Barrier::new(2));
4192
4193        let reader_a = {
4194            let rt = Arc::clone(&rt);
4195            let tok = tok.clone();
4196            let barrier = Arc::clone(&barrier);
4197            tokio::spawn(async move {
4198                barrier.wait().await;
4199                rt.prepare_update_entity(
4200                    &tok,
4201                    id,
4202                    EntityPatch {
4203                        properties: Some(serde_json::json!({"a": 1})),
4204                        ..Default::default()
4205                    },
4206                )
4207                .await
4208            })
4209        };
4210        let reader_b = {
4211            let rt = Arc::clone(&rt);
4212            let tok = tok.clone();
4213            let barrier = Arc::clone(&barrier);
4214            tokio::spawn(async move {
4215                barrier.wait().await;
4216                rt.prepare_update_entity(
4217                    &tok,
4218                    id,
4219                    EntityPatch {
4220                        properties: Some(serde_json::json!({"b": 1})),
4221                        ..Default::default()
4222                    },
4223                )
4224                .await
4225            })
4226        };
4227
4228        let (entity_a, _, _, expected_updated_at_a, expected_deleted_at_a) =
4229            reader_a.await.unwrap().expect("reader A prepares");
4230        let (entity_b, _, _, expected_updated_at_b, expected_deleted_at_b) =
4231            reader_b.await.unwrap().expect("reader B prepares");
4232        assert_eq!(
4233            expected_updated_at_a, expected_updated_at_b,
4234            "both readers must observe the same pre-write revision for this to be a real race"
4235        );
4236
4237        let store = rt.entities(&tok).expect("entity store");
4238        assert!(
4239            store
4240                .replace_entity_if_unchanged(entity_a, expected_updated_at_a, expected_deleted_at_a)
4241                .await
4242                .expect("writer A CAS query"),
4243            "the first committer from a shared revision must win"
4244        );
4245        assert!(
4246            !store
4247                .replace_entity_if_unchanged(entity_b, expected_updated_at_b, expected_deleted_at_b)
4248                .await
4249                .expect("writer B CAS query"),
4250            "the second committer from the SAME stale revision must be refused, not merged"
4251        );
4252
4253        let final_entity = rt.get_entity(&tok, id).await.expect("read final entity");
4254        assert_eq!(
4255            final_entity.properties,
4256            Some(serde_json::json!({"a": 1, "b": 0})),
4257            "writer B's field must not be silently merged into the persisted row: {:?}",
4258            final_entity.properties
4259        );
4260    }
4261
4262    /// Same race as `concurrent_entity_property_patches_from_one_revision_only_one_survives`,
4263    /// but driven entirely through the PRODUCTION entry point
4264    /// (`update_entity_with_embedding_report`) rather than the store's
4265    /// `replace_entity_if_unchanged` primitive directly. This closes a gap
4266    /// the primitive-level test cannot: it would still pass unchanged if the
4267    /// production caller were reverted to an unconditional write, since it
4268    /// never invokes that caller at all. Uses `race_seam::pause_after_read`
4269    /// (test-only, compiled out of non-test builds) to force both concurrent
4270    /// callers to observe the identical pre-write revision deterministically —
4271    /// no sleeps, no reliance on scheduler ordering.
4272    #[tokio::test]
4273    async fn production_update_entity_refuses_concurrent_stale_writer() {
4274        let rt = Arc::new(rt());
4275        let tok = NamespaceToken::local();
4276        let entity = rt
4277            .create_entity(
4278                &tok,
4279                "concept",
4280                None,
4281                "ProductionRaceTarget",
4282                None,
4283                Some(serde_json::json!({"a": 0, "b": 0})),
4284                vec![],
4285            )
4286            .await
4287            .expect("seed entity");
4288        let id = entity.id;
4289
4290        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
4291
4292        let writer_a = {
4293            let rt = Arc::clone(&rt);
4294            let tok = tok.clone();
4295            let barrier = std::sync::Arc::clone(&barrier);
4296            tokio::spawn(race_seam::AFTER_READ_BARRIER.scope(barrier, async move {
4297                rt.update_entity_with_embedding_report(
4298                    &tok,
4299                    id,
4300                    EntityPatch {
4301                        properties: Some(serde_json::json!({"a": 1})),
4302                        ..Default::default()
4303                    },
4304                )
4305                .await
4306            }))
4307        };
4308        let writer_b = {
4309            let rt = Arc::clone(&rt);
4310            let tok = tok.clone();
4311            let barrier = std::sync::Arc::clone(&barrier);
4312            tokio::spawn(race_seam::AFTER_READ_BARRIER.scope(barrier, async move {
4313                rt.update_entity_with_embedding_report(
4314                    &tok,
4315                    id,
4316                    EntityPatch {
4317                        properties: Some(serde_json::json!({"b": 1})),
4318                        ..Default::default()
4319                    },
4320                )
4321                .await
4322            }))
4323        };
4324
4325        let result_a = writer_a.await.expect("writer A task");
4326        let result_b = writer_b.await.expect("writer B task");
4327        let successes = [result_a.is_ok(), result_b.is_ok()]
4328            .into_iter()
4329            .filter(|ok| *ok)
4330            .count();
4331        assert_eq!(
4332            successes, 1,
4333            "exactly one production caller must win the race; the other must be refused: \
4334             a={result_a:?} b={result_b:?}"
4335        );
4336        let refused = if result_a.is_err() {
4337            result_a
4338        } else {
4339            result_b
4340        };
4341        match &refused {
4342            Err(RuntimeError::Khive(khive_error)) => {
4343                assert_eq!(
4344                    khive_error.kind(),
4345                    khive_types::ErrorKind::Conflict,
4346                    "the losing production caller must surface a typed conflict, not \
4347                     silently overwrite: {refused:?}"
4348                );
4349            }
4350            other => panic!("expected a typed conflict error, got {other:?}"),
4351        }
4352
4353        let final_entity = rt.get_entity(&tok, id).await.expect("read final entity");
4354        assert_ne!(
4355            final_entity.properties,
4356            Some(serde_json::json!({"a": 1, "b": 1})),
4357            "both racers' fields must never both land: that would mean the loser's stale \
4358             write silently succeeded"
4359        );
4360    }
4361
4362    /// Isolating fixture for the `AND ?8 > updated_at` conjunct of
4363    /// `entity_replace_if_unchanged_statement`.
4364    ///
4365    /// The concurrent-race tests above cannot cover it. What is measured, and
4366    /// deterministic: tautologizing `?8 > updated_at` alone reddened NOTHING in
4367    /// `khive-runtime` before this test existed, because the revision guard
4368    /// (`updated_at = ?13`) refuses the losing writer on its own whatever the
4369    /// clock did. Tautologizing `updated_at = ?13` + `deleted_at IS ?14`
4370    /// reddens only `production_update_entity_refuses_concurrent_stale_writer`,
4371    /// and defeating all three at once reddens the race tests.
4372    ///
4373    /// What is NOT claimed, because the fixture cannot support it: that the two
4374    /// guards are each independently sufficient. The race fixture pins the two
4375    /// racers' EXPECTED revisions equal but never their REPLACEMENT revisions,
4376    /// which both come from `max(now, expected + 1)`. So with `updated_at = ?13`
4377    /// removed, whether strict advance still refuses depends on which clock read
4378    /// won — a race, not a property of the fixture. This test strips the second
4379    /// mechanism by construction instead:
4380    /// it supplies the CORRECT expected revision and deletion marker, so
4381    /// `?13`/`?14` are satisfied by construction, and the ONLY thing that can
4382    /// refuse the write is the strict-advance conjunct.
4383    #[tokio::test]
4384    async fn entity_cas_refuses_a_replacement_revision_that_does_not_advance() {
4385        let rt = rt();
4386        let tok = NamespaceToken::local();
4387        let entity = rt
4388            .create_entity(
4389                &tok,
4390                "concept",
4391                None,
4392                "NonAdvancing",
4393                None,
4394                Some(serde_json::json!({"a": 0})),
4395                vec![],
4396            )
4397            .await
4398            .expect("seed entity");
4399        let id = entity.id;
4400
4401        let (mut replacement, _, _, expected_updated_at, expected_deleted_at) = rt
4402            .prepare_update_entity(
4403                &tok,
4404                id,
4405                EntityPatch {
4406                    properties: Some(serde_json::json!({"a": 1})),
4407                    ..Default::default()
4408                },
4409            )
4410            .await
4411            .expect("prepare update");
4412
4413        // Force the replacement revision to EQUAL the stored one, then PROVE the
4414        // isolation rather than asserting it in prose. Reading the row back is
4415        // what makes `?13` and `?14` observed facts here instead of values
4416        // carried out of `prepare_update_entity`'s setup read.
4417        replacement.updated_at = expected_updated_at;
4418
4419        let store = rt.entities(&tok).expect("entity store");
4420        let stored = store
4421            .get_entity_including_deleted(id)
4422            .await
4423            .expect("read stored row")
4424            .expect("row present before CAS");
4425        assert_eq!(
4426            stored.updated_at, expected_updated_at,
4427            "fixture premise: nothing moved the stored revision between prepare and CAS, \
4428             otherwise `?13` would refuse and this stops being an isolating fixture"
4429        );
4430        assert_eq!(
4431            stored.deleted_at, expected_deleted_at,
4432            "fixture premise: the stored deletion marker must still equal the snapshot's, \
4433             otherwise `deleted_at IS ?14` would refuse and this stops being an isolating \
4434             fixture"
4435        );
4436        assert_eq!(
4437            replacement.updated_at, stored.updated_at,
4438            "fixture premise: the replacement revision must NOT advance past the stored one, \
4439             which is the single condition under test"
4440        );
4441
4442        let committed = store
4443            .replace_entity_if_unchanged(replacement, expected_updated_at, expected_deleted_at)
4444            .await
4445            .expect("CAS query");
4446        assert!(
4447            !committed,
4448            "a replacement whose revision does not strictly advance past the stored one must \
4449             be refused: without `?8 > updated_at` the CAS would accept a write that leaves \
4450             `updated_at` unmoved, so a later writer holding the same snapshot would still \
4451             see its expected revision match and overwrite this one"
4452        );
4453
4454        let stored = rt.get_entity(&tok, id).await.expect("read back");
4455        assert_eq!(
4456            stored.properties,
4457            Some(serde_json::json!({"a": 0})),
4458            "the refused write must not have landed"
4459        );
4460    }
4461
4462    /// Isolating fixture for the `AND deleted_at IS ?14` conjunct of
4463    /// `entity_replace_if_unchanged_statement`.
4464    ///
4465    /// The revision-based race fixtures cannot reach it, because a soft delete
4466    /// does not move the revision: `entity_soft_delete_statement` is
4467    /// `SET deleted_at = ?1 WHERE id = ?2 AND deleted_at IS NULL` and never
4468    /// touches `updated_at`. So a writer holding a pre-delete snapshot still has
4469    /// the CORRECT expected revision after the row is tombstoned, and its
4470    /// replacement revision still advances. Every conjunct except `?14` is
4471    /// satisfied, and dropping `?14` would let that writer's `deleted_at = NULL`
4472    /// land — resurrecting a tombstone, with no revision conflict anywhere to
4473    /// signal it.
4474    ///
4475    /// This fixture does not merely claim that isolation, it asserts it: both
4476    /// other conjuncts are checked against the post-delete row before the CAS
4477    /// runs, so a future change that makes one of them refuse instead turns this
4478    /// test red rather than silently converting it into a whole-guard test.
4479    #[tokio::test]
4480    async fn entity_cas_refuses_a_stale_replacement_that_would_resurrect_a_tombstone() {
4481        let rt = rt();
4482        let tok = NamespaceToken::local();
4483        let entity = rt
4484            .create_entity(
4485                &tok,
4486                "concept",
4487                None,
4488                "Tombstoned",
4489                None,
4490                Some(serde_json::json!({"a": 0})),
4491                vec![],
4492            )
4493            .await
4494            .expect("seed entity");
4495        let id = entity.id;
4496
4497        // Snapshot BEFORE the delete: this is the stale writer's view.
4498        let (replacement, _, _, expected_updated_at, expected_deleted_at) = rt
4499            .prepare_update_entity(
4500                &tok,
4501                id,
4502                EntityPatch {
4503                    properties: Some(serde_json::json!({"a": 1})),
4504                    ..Default::default()
4505                },
4506            )
4507            .await
4508            .expect("prepare update");
4509        assert_eq!(
4510            expected_deleted_at, None,
4511            "fixture premise: the snapshot must be of a LIVE row"
4512        );
4513
4514        rt.delete_entity(&tok, id, false)
4515            .await
4516            .expect("soft delete");
4517
4518        let store = rt.entities(&tok).expect("entity store");
4519        let tombstoned = store
4520            .get_entity_including_deleted(id)
4521            .await
4522            .expect("read tombstone")
4523            .expect("row still present after soft delete");
4524
4525        // Prove the isolation rather than asserting it in prose. `?13` matches
4526        // because the soft delete left the revision alone, and `?8 > updated_at`
4527        // holds because the prepared replacement advanced past it. That leaves
4528        // `deleted_at IS ?14` as the only conjunct able to refuse the write.
4529        assert_eq!(
4530            tombstoned.updated_at, expected_updated_at,
4531            "fixture premise: soft delete must NOT move `updated_at`, otherwise \
4532             `?13` would refuse and this stops being an isolating fixture"
4533        );
4534        assert!(
4535            replacement.updated_at > tombstoned.updated_at,
4536            "fixture premise: the replacement revision must still advance, \
4537             otherwise `?8 > updated_at` would refuse and this stops being an \
4538             isolating fixture"
4539        );
4540        assert!(
4541            tombstoned.deleted_at.is_some(),
4542            "fixture premise: the row must actually be tombstoned"
4543        );
4544
4545        let committed = store
4546            .replace_entity_if_unchanged(replacement, expected_updated_at, expected_deleted_at)
4547            .await
4548            .expect("CAS query");
4549        assert!(
4550            !committed,
4551            "a replacement carrying a pre-delete snapshot must be refused after the row is \
4552             soft-deleted: without `deleted_at IS ?14` it would write `deleted_at = NULL` over \
4553             the tombstone and silently resurrect a deleted entity"
4554        );
4555
4556        let after = store
4557            .get_entity_including_deleted(id)
4558            .await
4559            .expect("read back")
4560            .expect("row present");
4561        assert!(
4562            after.deleted_at.is_some(),
4563            "the tombstone must survive the refused write"
4564        );
4565        assert_eq!(
4566            after.properties,
4567            Some(serde_json::json!({"a": 0})),
4568            "the refused write must not have landed"
4569        );
4570    }
4571
4572    /// Regression: the entity CAS requires the replacement revision to be
4573    /// STRICTLY greater than the stored one. If the replacement is computed
4574    /// as a raw `Utc::now()` read, a stored revision that is at or ahead of
4575    /// wall-clock time (a clock step backward, or — deterministically,
4576    /// reproduced here — a stored revision manufactured slightly ahead of
4577    /// "now") makes the new value fail to advance, and the CAS refuses a
4578    /// write with NO concurrent writer involved at all. The fix must clamp
4579    /// the replacement to `max(now, stored + 1)`; this test sets the stored
4580    /// revision one full second into the future (far outside normal clock
4581    /// skew) and asserts the update still succeeds instead of surfacing a
4582    /// spurious conflict.
4583    ///
4584    /// SCOPE: this is a revision-clamp test, NOT CAS regression coverage. Its
4585    /// assertion is that the write SUCCEEDS, which an unconditional UPDATE
4586    /// also satisfies, so it stays green if the `updated_at = ?13` /
4587    /// `?8 > updated_at` guard is dropped entirely. The guard's regression
4588    /// coverage is
4589    /// `concurrent_entity_property_patches_from_one_revision_only_one_survives`
4590    /// (primitive) and `production_update_entity_refuses_concurrent_stale_writer`
4591    /// (production wiring); do not count this test toward it.
4592    #[tokio::test]
4593    async fn update_entity_succeeds_when_stored_revision_is_ahead_of_wall_clock() {
4594        let rt = rt();
4595        let tok = NamespaceToken::local();
4596        let entity = rt
4597            .create_entity(
4598                &tok,
4599                "concept",
4600                None,
4601                "FutureRevisionTarget",
4602                None,
4603                None,
4604                vec![],
4605            )
4606            .await
4607            .expect("seed entity");
4608        let id = entity.id;
4609
4610        let future_micros = chrono::Utc::now().timestamp_micros() + 1_000_000;
4611        let pool = rt.backend().pool_arc();
4612        let id_str = id.to_string();
4613        tokio::task::spawn_blocking(move || {
4614            let guard = pool.writer().expect("writer connection");
4615            guard
4616                .execute(
4617                    "UPDATE entities SET updated_at = ?1 WHERE id = ?2",
4618                    rusqlite::params![future_micros, id_str],
4619                )
4620                .expect("force future revision")
4621        })
4622        .await
4623        .expect("join");
4624
4625        let updated = rt
4626            .update_entity(
4627                &tok,
4628                id,
4629                EntityPatch {
4630                    description: Some(Some("patched after a forced future revision".to_string())),
4631                    ..Default::default()
4632                },
4633            )
4634            .await
4635            .expect(
4636                "update must succeed and advance past the stored revision, not report a \
4637                 spurious conflict when nothing else wrote to this row",
4638            );
4639        assert!(updated.updated_at > future_micros);
4640    }
4641
4642    #[tokio::test]
4643    async fn update_entity_clear_description_with_some_none() {
4644        let rt = rt();
4645        let tok = NamespaceToken::local();
4646        let entity = rt
4647            .create_entity(
4648                &tok,
4649                "concept",
4650                None,
4651                "ClearDesc",
4652                Some("has description"),
4653                None,
4654                vec![],
4655            )
4656            .await
4657            .unwrap();
4658
4659        let updated = rt
4660            .update_entity(
4661                &tok,
4662                entity.id,
4663                EntityPatch {
4664                    description: Some(None),
4665                    ..Default::default()
4666                },
4667            )
4668            .await
4669            .unwrap();
4670
4671        assert!(
4672            updated.description.is_none(),
4673            "description should be cleared"
4674        );
4675    }
4676
4677    #[tokio::test]
4678    async fn update_entity_reindexes_when_name_changes() {
4679        let rt = rt();
4680        let tok = NamespaceToken::local();
4681        let entity = rt
4682            .create_entity(&tok, "concept", None, "OldName", None, None, vec![])
4683            .await
4684            .unwrap();
4685
4686        let hits_before = fts_hit(&rt, &tok, "OldName").await;
4687        assert!(
4688            hits_before.contains(&entity.id),
4689            "entity should be findable by old name"
4690        );
4691
4692        rt.update_entity(
4693            &tok,
4694            entity.id,
4695            EntityPatch {
4696                name: Some("NewName".to_string()),
4697                ..Default::default()
4698            },
4699        )
4700        .await
4701        .unwrap();
4702
4703        let hits_old = fts_hit(&rt, &tok, "OldName").await;
4704        let hits_new = fts_hit(&rt, &tok, "NewName").await;
4705
4706        assert!(
4707            !hits_old.contains(&entity.id),
4708            "old name should no longer match after rename"
4709        );
4710        assert!(
4711            hits_new.contains(&entity.id),
4712            "new name should be findable after rename"
4713        );
4714    }
4715
4716    #[tokio::test]
4717    async fn update_entity_properties_merges_preserving_existing_keys() {
4718        let rt = rt();
4719        let tok = NamespaceToken::local();
4720        let entity = rt
4721            .create_entity(
4722                &tok,
4723                "concept",
4724                None,
4725                "MergeProps",
4726                None,
4727                Some(serde_json::json!({
4728                    "domain": "inference",
4729                    "repo": "lattice",
4730                    "status": "researched",
4731                })),
4732                vec![],
4733            )
4734            .await
4735            .unwrap();
4736
4737        let updated = rt
4738            .update_entity(
4739                &tok,
4740                entity.id,
4741                EntityPatch {
4742                    properties: Some(serde_json::json!({"status": "implemented"})),
4743                    ..Default::default()
4744                },
4745            )
4746            .await
4747            .unwrap();
4748
4749        let props = updated.properties.expect("properties should remain set");
4750        assert_eq!(props["domain"], "inference", "domain key must be preserved");
4751        assert_eq!(props["repo"], "lattice", "repo key must be preserved");
4752        assert_eq!(
4753            props["status"], "implemented",
4754            "status key must be updated by patch"
4755        );
4756    }
4757
4758    #[tokio::test]
4759    async fn update_entity_skips_reindex_when_only_properties_change() {
4760        let rt = rt();
4761        let tok = NamespaceToken::local();
4762        let entity = rt
4763            .create_entity(&tok, "concept", None, "StableIndexed", None, None, vec![])
4764            .await
4765            .unwrap();
4766
4767        let hits_before = fts_hit(&rt, &tok, "StableIndexed").await;
4768        assert!(hits_before.contains(&entity.id));
4769
4770        rt.update_entity(
4771            &tok,
4772            entity.id,
4773            EntityPatch {
4774                properties: Some(serde_json::json!({"new": "prop"})),
4775                ..Default::default()
4776            },
4777        )
4778        .await
4779        .unwrap();
4780
4781        let hits_after = fts_hit(&rt, &tok, "StableIndexed").await;
4782        assert!(
4783            hits_after.contains(&entity.id),
4784            "still findable after props-only patch"
4785        );
4786    }
4787
4788    #[tokio::test]
4789    async fn merge_entity_rewires_edges() {
4790        let rt = rt();
4791        let tok = NamespaceToken::local();
4792        let a = rt
4793            .create_entity(&tok, "concept", None, "A", None, None, vec![])
4794            .await
4795            .unwrap();
4796        let b = rt
4797            .create_entity(&tok, "concept", None, "B", None, None, vec![])
4798            .await
4799            .unwrap();
4800        let c = rt
4801            .create_entity(&tok, "concept", None, "C", None, None, vec![])
4802            .await
4803            .unwrap();
4804        let d = rt
4805            .create_entity(&tok, "concept", None, "D", None, None, vec![])
4806            .await
4807            .unwrap();
4808
4809        // A→B and C→B; merge B into D → should become A→D and C→D.
4810        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
4811            .await
4812            .unwrap();
4813        rt.link(&tok, c.id, b.id, EdgeRelation::Extends, 1.0, None)
4814            .await
4815            .unwrap();
4816
4817        let summary = rt
4818            .merge_entity_with_reason(
4819                &tok,
4820                d.id,
4821                b.id,
4822                EntityDedupMergePolicy::PreferInto,
4823                ContentMergeStrategy::Append,
4824                false,
4825                None,
4826            )
4827            .await
4828            .unwrap();
4829
4830        assert_eq!(summary.kept_id, d.id);
4831        assert_eq!(summary.removed_id, b.id);
4832        assert_eq!(summary.edges_rewired, 2);
4833
4834        let a_neighbors = rt
4835            .neighbors(&tok, a.id, Direction::Out, None, None)
4836            .await
4837            .unwrap();
4838        assert_eq!(a_neighbors.len(), 1);
4839        assert_eq!(a_neighbors[0].node_id, d.id);
4840
4841        let c_neighbors = rt
4842            .neighbors(&tok, c.id, Direction::Out, None, None)
4843            .await
4844            .unwrap();
4845        assert_eq!(c_neighbors.len(), 1);
4846        assert_eq!(c_neighbors[0].node_id, d.id);
4847    }
4848
4849    // khive#1236: edges incident to `from_id` but stamped with a namespace other
4850    // than the merge caller's must still be discovered and rewired — by-ID edge
4851    // endpoints are namespace-agnostic (ADR-007 Rev 6), and `link` stamps an edge
4852    // with its *creator's* namespace, not either endpoint's.
4853    #[tokio::test]
4854    async fn merge_entity_rewires_edges_from_other_namespaces() {
4855        use crate::Namespace;
4856
4857        let rt = rt();
4858        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
4859        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
4860
4861        let into_a = rt
4862            .create_entity(&ns_a, "concept", None, "Into A", None, None, vec![])
4863            .await
4864            .unwrap();
4865        let from_a = rt
4866            .create_entity(&ns_a, "concept", None, "From A", None, None, vec![])
4867            .await
4868            .unwrap();
4869        let foreign_b = rt
4870            .create_entity(&ns_b, "concept", None, "Foreign B", None, None, vec![])
4871            .await
4872            .unwrap();
4873
4874        // Edge created by an ns_b caller, stamped with ns_b, whose target lives in
4875        // ns_a — legal because by-ID link endpoints are namespace-agnostic.
4876        rt.link(
4877            &ns_b,
4878            foreign_b.id,
4879            from_a.id,
4880            EdgeRelation::Extends,
4881            1.0,
4882            None,
4883        )
4884        .await
4885        .unwrap();
4886
4887        let summary = rt
4888            .merge_entity_with_reason(
4889                &ns_a,
4890                into_a.id,
4891                from_a.id,
4892                EntityDedupMergePolicy::PreferInto,
4893                ContentMergeStrategy::Append,
4894                false,
4895                None,
4896            )
4897            .await
4898            .unwrap();
4899
4900        assert_eq!(
4901            summary.edges_rewired, 1,
4902            "the ns_b-stamped edge incident to from_id must be discovered and rewired, not missed"
4903        );
4904
4905        let foreign_neighbors = rt
4906            .neighbors(&ns_b, foreign_b.id, Direction::Out, None, None)
4907            .await
4908            .unwrap();
4909        assert_eq!(
4910            foreign_neighbors.len(),
4911            1,
4912            "cross-namespace edge must survive the merge, rewired to point at into_id"
4913        );
4914        assert_eq!(foreign_neighbors[0].node_id, into_a.id);
4915    }
4916
4917    // khive#1216: a merge rewire must re-check the pack endpoint contract for the
4918    // POST-rewrite pair, not just carry the pre-merge edge over. into_id and
4919    // from_id share `kind` (enforced by the caller) but may differ in
4920    // `entity_type`, so a pack rule scoped via `EntityOfType` can accept
4921    // `from_id`'s edge yet reject the identical relation once rewritten onto
4922    // `into_id`.
4923    #[tokio::test]
4924    async fn merge_entity_drops_edge_violating_endpoint_contract_after_rewire() {
4925        let rt = rt();
4926        let tok = NamespaceToken::local();
4927
4928        // depends_on is NOT in the base concept->concept allowlist; only this
4929        // pack rule (theorem -> definition) accepts it.
4930        rt.install_edge_rules(vec![EdgeEndpointRule {
4931            relation: EdgeRelation::DependsOn,
4932            source: EndpointKind::EntityOfType {
4933                kind: "concept",
4934                entity_type: "theorem",
4935            },
4936            target: EndpointKind::EntityOfType {
4937                kind: "concept",
4938                entity_type: "definition",
4939            },
4940        }]);
4941
4942        let def_entity = rt
4943            .create_entity(
4944                &tok,
4945                "concept",
4946                Some("definition"),
4947                "Def",
4948                None,
4949                None,
4950                vec![],
4951            )
4952            .await
4953            .unwrap();
4954        let from_theorem = rt
4955            .create_entity(
4956                &tok,
4957                "concept",
4958                Some("theorem"),
4959                "FromTheorem",
4960                None,
4961                None,
4962                vec![],
4963            )
4964            .await
4965            .unwrap();
4966        // Same base kind ("concept") as from_theorem, but a different entity_type
4967        // — the merge's same-kind constraint allows this, the endpoint contract
4968        // (entity_type-scoped) does not.
4969        let into_lemma = rt
4970            .create_entity(
4971                &tok,
4972                "concept",
4973                Some("lemma"),
4974                "IntoLemma",
4975                None,
4976                None,
4977                vec![],
4978            )
4979            .await
4980            .unwrap();
4981
4982        rt.link(
4983            &tok,
4984            from_theorem.id,
4985            def_entity.id,
4986            EdgeRelation::DependsOn,
4987            1.0,
4988            None,
4989        )
4990        .await
4991        .unwrap();
4992
4993        let summary = rt
4994            .merge_entity_with_reason(
4995                &tok,
4996                into_lemma.id,
4997                from_theorem.id,
4998                EntityDedupMergePolicy::PreferInto,
4999                ContentMergeStrategy::Append,
5000                false,
5001                None,
5002            )
5003            .await
5004            .unwrap();
5005
5006        assert_eq!(
5007            summary.edges_rewired, 0,
5008            "the contract-violating rewire must not be counted as rewired"
5009        );
5010        assert_eq!(
5011            summary.edges_contract_skipped, 1,
5012            "the depends_on edge must be dropped, not silently rewritten past the endpoint contract"
5013        );
5014
5015        let def_neighbors = rt
5016            .neighbors(&tok, def_entity.id, Direction::In, None, None)
5017            .await
5018            .unwrap();
5019        assert!(
5020            def_neighbors.is_empty(),
5021            "no contract-violating depends_on edge should survive onto into_lemma; got {def_neighbors:?}"
5022        );
5023    }
5024
5025    // Dry-run counterpart: a contract-violating rewire must be predicted as
5026    // skipped (not rewired), and no write occurs.
5027    #[tokio::test]
5028    async fn merge_entity_dry_run_predicts_contract_skip_without_writing() {
5029        let rt = rt();
5030        let tok = NamespaceToken::local();
5031
5032        rt.install_edge_rules(vec![EdgeEndpointRule {
5033            relation: EdgeRelation::DependsOn,
5034            source: EndpointKind::EntityOfType {
5035                kind: "concept",
5036                entity_type: "theorem",
5037            },
5038            target: EndpointKind::EntityOfType {
5039                kind: "concept",
5040                entity_type: "definition",
5041            },
5042        }]);
5043
5044        let def_entity = rt
5045            .create_entity(
5046                &tok,
5047                "concept",
5048                Some("definition"),
5049                "Def",
5050                None,
5051                None,
5052                vec![],
5053            )
5054            .await
5055            .unwrap();
5056        let from_theorem = rt
5057            .create_entity(
5058                &tok,
5059                "concept",
5060                Some("theorem"),
5061                "FromTheorem",
5062                None,
5063                None,
5064                vec![],
5065            )
5066            .await
5067            .unwrap();
5068        let into_lemma = rt
5069            .create_entity(
5070                &tok,
5071                "concept",
5072                Some("lemma"),
5073                "IntoLemma",
5074                None,
5075                None,
5076                vec![],
5077            )
5078            .await
5079            .unwrap();
5080
5081        rt.link(
5082            &tok,
5083            from_theorem.id,
5084            def_entity.id,
5085            EdgeRelation::DependsOn,
5086            1.0,
5087            None,
5088        )
5089        .await
5090        .unwrap();
5091
5092        let summary = rt
5093            .merge_entity_with_reason(
5094                &tok,
5095                into_lemma.id,
5096                from_theorem.id,
5097                EntityDedupMergePolicy::PreferInto,
5098                ContentMergeStrategy::Append,
5099                true, // dry_run
5100                None,
5101            )
5102            .await
5103            .unwrap();
5104
5105        assert_eq!(summary.edges_rewired, 0);
5106        assert_eq!(summary.edges_contract_skipped, 1);
5107
5108        // Nothing written: the original edge is untouched.
5109        let def_neighbors = rt
5110            .neighbors(&tok, def_entity.id, Direction::In, None, None)
5111            .await
5112            .unwrap();
5113        assert_eq!(def_neighbors.len(), 1);
5114        assert_eq!(def_neighbors[0].node_id, from_theorem.id);
5115    }
5116
5117    // A conflicting rewire must leave the surviving edge untouched (ADR-039
5118    // DO NOTHING) — the merged-from edge's attributes never overwrite it.
5119    #[tokio::test]
5120    async fn merge_entity_conflict_keeps_survivor_edge_attributes() {
5121        let rt = rt();
5122        let tok = NamespaceToken::local();
5123        let into = rt
5124            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
5125            .await
5126            .unwrap();
5127        let from = rt
5128            .create_entity(&tok, "concept", None, "From", None, None, vec![])
5129            .await
5130            .unwrap();
5131        let shared = rt
5132            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
5133            .await
5134            .unwrap();
5135
5136        let survivor = rt
5137            .link(&tok, into.id, shared.id, EdgeRelation::Extends, 0.9, None)
5138            .await
5139            .unwrap();
5140        rt.link(&tok, from.id, shared.id, EdgeRelation::Extends, 0.2, None)
5141            .await
5142            .unwrap();
5143
5144        rt.merge_entity(
5145            &tok,
5146            into.id,
5147            from.id,
5148            EntityDedupMergePolicy::PreferInto,
5149            ContentMergeStrategy::Append,
5150            false,
5151        )
5152        .await
5153        .unwrap();
5154
5155        let edges = rt
5156            .list_edges(
5157                &tok,
5158                crate::EdgeListFilter {
5159                    source_id: Some(into.id),
5160                    target_id: Some(shared.id),
5161                    relations: vec![EdgeRelation::Extends],
5162                    ..Default::default()
5163                },
5164                10,
5165                0,
5166            )
5167            .await
5168            .unwrap();
5169        assert_eq!(edges.len(), 1);
5170        assert_eq!(edges[0].id, survivor.id);
5171        assert!(
5172            (edges[0].weight - 0.9).abs() < f64::EPSILON,
5173            "survivor weight must not be overwritten by the merged-from edge; got {}",
5174            edges[0].weight
5175        );
5176    }
5177
5178    #[tokio::test]
5179    async fn merge_entity_conflict_records_restorable_edge_and_annotation_preimages() {
5180        let rt = rt();
5181        let tok = NamespaceToken::local();
5182        let into = rt
5183            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
5184            .await
5185            .unwrap();
5186        let from = rt
5187            .create_entity(&tok, "concept", None, "From", None, None, vec![])
5188            .await
5189            .unwrap();
5190        let shared = rt
5191            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
5192            .await
5193            .unwrap();
5194        let annotator = rt
5195            .create_note(
5196                &tok,
5197                "observation",
5198                None,
5199                "edge judgment",
5200                None,
5201                None,
5202                vec![],
5203            )
5204            .await
5205            .unwrap();
5206        let nested_annotator = rt
5207            .create_note(
5208                &tok,
5209                "observation",
5210                None,
5211                "judgment review",
5212                None,
5213                None,
5214                vec![],
5215            )
5216            .await
5217            .unwrap();
5218
5219        let survivor = rt
5220            .link(
5221                &tok,
5222                into.id,
5223                shared.id,
5224                EdgeRelation::Extends,
5225                0.9,
5226                Some(serde_json::json!({"source": "survivor"})),
5227            )
5228            .await
5229            .unwrap();
5230        let dropped = rt
5231            .link(
5232                &tok,
5233                from.id,
5234                shared.id,
5235                EdgeRelation::Extends,
5236                0.2,
5237                Some(serde_json::json!({"source": "dropped"})),
5238            )
5239            .await
5240            .unwrap();
5241        let annotation = rt
5242            .link(
5243                &tok,
5244                annotator.id,
5245                dropped.id.into(),
5246                EdgeRelation::Annotates,
5247                0.7,
5248                Some(serde_json::json!({"basis": "manual"})),
5249            )
5250            .await
5251            .unwrap();
5252        let nested_annotation = rt
5253            .link(
5254                &tok,
5255                nested_annotator.id,
5256                annotation.id.into(),
5257                EdgeRelation::Annotates,
5258                0.6,
5259                Some(serde_json::json!({"review": "confirmed"})),
5260            )
5261            .await
5262            .unwrap();
5263        rt.delete_edge(&tok, annotation.id.into(), false)
5264            .await
5265            .unwrap();
5266
5267        let summary = rt
5268            .merge_entity(
5269                &tok,
5270                into.id,
5271                from.id,
5272                EntityDedupMergePolicy::PreferInto,
5273                ContentMergeStrategy::Append,
5274                false,
5275            )
5276            .await
5277            .unwrap();
5278
5279        let [conflict] = summary.edge_conflict_preimages.as_slice() else {
5280            panic!(
5281                "expected one edge-conflict preimage, got {:?}",
5282                summary.edge_conflict_preimages
5283            );
5284        };
5285        assert_eq!(conflict.surviving_edge_id, Uuid::from(survivor.id));
5286        assert_eq!(conflict.dropped_edge.id, Uuid::from(dropped.id));
5287        assert_eq!(conflict.dropped_edge.source_id, from.id);
5288        assert_eq!(conflict.dropped_edge.target_id, shared.id);
5289        assert_eq!(conflict.dropped_edge.relation, "extends");
5290        assert_eq!(conflict.dropped_edge.weight, 0.2);
5291        assert_eq!(
5292            conflict.dropped_edge.metadata,
5293            Some(serde_json::json!({"source": "dropped"}))
5294        );
5295        assert_eq!(conflict.incident_edge_preimages.len(), 2);
5296        assert_eq!(
5297            conflict.incident_edge_preimages[0].id,
5298            Uuid::from(annotation.id)
5299        );
5300        assert_eq!(
5301            conflict.incident_edge_preimages[1].id,
5302            Uuid::from(nested_annotation.id)
5303        );
5304
5305        for id in [dropped.id, annotation.id, nested_annotation.id] {
5306            assert!(
5307                rt.get_edge_including_deleted(&tok, id.into())
5308                    .await
5309                    .unwrap()
5310                    .is_none(),
5311                "merge conflict cascade must leave no dangling edge row for {id}"
5312            );
5313        }
5314
5315        let events = rt
5316            .events(&tok)
5317            .unwrap()
5318            .query_events(
5319                khive_storage::EventFilter {
5320                    kinds: vec![EventKind::EntityMerged],
5321                    ..Default::default()
5322                },
5323                khive_storage::types::PageRequest {
5324                    offset: 0,
5325                    limit: 10,
5326                },
5327            )
5328            .await
5329            .unwrap();
5330        assert_eq!(events.items.len(), 1);
5331        assert_eq!(
5332            events.items[0].payload["edge_conflict_preimages"],
5333            serde_json::to_value(&summary.edge_conflict_preimages).unwrap()
5334        );
5335
5336        restore_edge_preimage(&rt, &tok, &conflict.dropped_edge).await;
5337        for preimage in &conflict.incident_edge_preimages {
5338            restore_edge_preimage(&rt, &tok, preimage).await;
5339        }
5340        for preimage in
5341            std::iter::once(&conflict.dropped_edge).chain(conflict.incident_edge_preimages.iter())
5342        {
5343            let restored = rt
5344                .get_edge_including_deleted(&tok, preimage.id)
5345                .await
5346                .unwrap()
5347                .expect("restored edge");
5348            assert_edge_matches_preimage(&restored, preimage);
5349        }
5350    }
5351
5352    // A dry run must predict the same conflict preimages a committing merge
5353    // would produce, without deleting or mutating a single row. The incident
5354    // cascade is two levels deep (an annotation on the dropped edge, and a
5355    // nested annotation on that annotation) so the root-to-leaf ordering
5356    // ADR-014 promises is actually exercised, not just a one-element vec that
5357    // trivially satisfies any order. Every row touched by the merge — both
5358    // entities and every edge — is snapshotted before the dry run and
5359    // compared field-for-field against its post-run state.
5360    #[tokio::test]
5361    async fn merge_entity_dry_run_conflict_returns_preimages_without_mutating() {
5362        let rt = rt();
5363        let tok = NamespaceToken::local();
5364        let into = rt
5365            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
5366            .await
5367            .unwrap();
5368        let from = rt
5369            .create_entity(&tok, "concept", None, "From", None, None, vec![])
5370            .await
5371            .unwrap();
5372        let shared = rt
5373            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
5374            .await
5375            .unwrap();
5376        let annotator = rt
5377            .create_note(
5378                &tok,
5379                "observation",
5380                None,
5381                "edge judgment",
5382                None,
5383                None,
5384                vec![],
5385            )
5386            .await
5387            .unwrap();
5388        let nested_annotator = rt
5389            .create_note(
5390                &tok,
5391                "observation",
5392                None,
5393                "judgment review",
5394                None,
5395                None,
5396                vec![],
5397            )
5398            .await
5399            .unwrap();
5400
5401        let survivor = rt
5402            .link(
5403                &tok,
5404                into.id,
5405                shared.id,
5406                EdgeRelation::Extends,
5407                0.9,
5408                Some(serde_json::json!({"source": "survivor"})),
5409            )
5410            .await
5411            .unwrap();
5412        let dropped = rt
5413            .link(
5414                &tok,
5415                from.id,
5416                shared.id,
5417                EdgeRelation::Extends,
5418                0.2,
5419                Some(serde_json::json!({"source": "dropped"})),
5420            )
5421            .await
5422            .unwrap();
5423        let annotation = rt
5424            .link(
5425                &tok,
5426                annotator.id,
5427                dropped.id.into(),
5428                EdgeRelation::Annotates,
5429                0.7,
5430                Some(serde_json::json!({"basis": "manual"})),
5431            )
5432            .await
5433            .unwrap();
5434        let nested_annotation = rt
5435            .link(
5436                &tok,
5437                nested_annotator.id,
5438                annotation.id.into(),
5439                EdgeRelation::Annotates,
5440                0.6,
5441                Some(serde_json::json!({"basis": "nested"})),
5442            )
5443            .await
5444            .unwrap();
5445        rt.delete_edge(&tok, nested_annotation.id.into(), false)
5446            .await
5447            .unwrap();
5448
5449        let survivor_before = rt
5450            .get_edge_including_deleted(&tok, survivor.id.into())
5451            .await
5452            .unwrap()
5453            .expect("survivor edge exists");
5454        let dropped_before = rt
5455            .get_edge_including_deleted(&tok, dropped.id.into())
5456            .await
5457            .unwrap()
5458            .expect("dropped edge exists");
5459        let annotation_before = rt
5460            .get_edge_including_deleted(&tok, annotation.id.into())
5461            .await
5462            .unwrap()
5463            .expect("annotation edge exists");
5464        let nested_annotation_before = rt
5465            .get_edge_including_deleted(&tok, nested_annotation.id.into())
5466            .await
5467            .unwrap()
5468            .expect("nested annotation edge exists");
5469        let into_before = rt
5470            .get_entity(&tok, into.id)
5471            .await
5472            .expect("into entity exists");
5473        let from_before = rt
5474            .get_entity(&tok, from.id)
5475            .await
5476            .expect("from entity exists");
5477
5478        let summary = rt
5479            .merge_entity(
5480                &tok,
5481                into.id,
5482                from.id,
5483                EntityDedupMergePolicy::PreferInto,
5484                ContentMergeStrategy::Append,
5485                true,
5486            )
5487            .await
5488            .unwrap();
5489
5490        let [conflict] = summary.edge_conflict_preimages.as_slice() else {
5491            panic!(
5492                "expected one edge-conflict preimage from the dry run, got {:?}",
5493                summary.edge_conflict_preimages
5494            );
5495        };
5496        assert_eq!(conflict.surviving_edge_id, Uuid::from(survivor.id));
5497        assert_eq!(conflict.dropped_edge.id, Uuid::from(dropped.id));
5498        assert_eq!(conflict.dropped_edge.source_id, from.id);
5499        assert_eq!(conflict.dropped_edge.target_id, shared.id);
5500        assert_eq!(conflict.dropped_edge.weight, 0.2);
5501        // Root-to-leaf order (ADR-014): the direct annotation on the dropped
5502        // edge must precede the annotation nested on top of it.
5503        assert_eq!(conflict.incident_edge_preimages.len(), 2);
5504        assert_eq!(
5505            conflict.incident_edge_preimages[0].id,
5506            Uuid::from(annotation.id)
5507        );
5508        assert!(
5509            conflict.incident_edge_preimages[0].deleted_at.is_none(),
5510            "the direct annotation was never soft-deleted"
5511        );
5512        assert_eq!(
5513            conflict.incident_edge_preimages[1].id,
5514            Uuid::from(nested_annotation.id)
5515        );
5516        assert!(
5517            conflict.incident_edge_preimages[1].deleted_at.is_some(),
5518            "dry-run preimage must retain the nested annotation's tombstone state"
5519        );
5520
5521        let survivor_after = rt
5522            .get_edge_including_deleted(&tok, survivor.id.into())
5523            .await
5524            .unwrap()
5525            .expect("dry run must not delete the survivor edge");
5526        let dropped_after = rt
5527            .get_edge_including_deleted(&tok, dropped.id.into())
5528            .await
5529            .unwrap()
5530            .expect("dry run must not delete the dropped edge");
5531        let annotation_after = rt
5532            .get_edge_including_deleted(&tok, annotation.id.into())
5533            .await
5534            .unwrap()
5535            .expect("dry run must not delete the cascaded annotation");
5536        let nested_annotation_after = rt
5537            .get_edge_including_deleted(&tok, nested_annotation.id.into())
5538            .await
5539            .unwrap()
5540            .expect("dry run must not delete the nested cascaded annotation");
5541        assert_eq!(
5542            serde_json::to_value(&survivor_before).unwrap(),
5543            serde_json::to_value(&survivor_after).unwrap(),
5544            "dry run must not mutate the surviving edge's row at all"
5545        );
5546        assert_eq!(
5547            serde_json::to_value(&dropped_before).unwrap(),
5548            serde_json::to_value(&dropped_after).unwrap(),
5549            "dry run must not mutate the would-be-dropped edge's row at all"
5550        );
5551        assert_eq!(
5552            serde_json::to_value(&annotation_before).unwrap(),
5553            serde_json::to_value(&annotation_after).unwrap(),
5554            "dry run must not mutate the incident annotation's row at all"
5555        );
5556        assert_eq!(
5557            serde_json::to_value(&nested_annotation_before).unwrap(),
5558            serde_json::to_value(&nested_annotation_after).unwrap(),
5559            "dry run must not mutate the nested incident annotation's row at all"
5560        );
5561
5562        let into_after = rt
5563            .get_entity(&tok, into.id)
5564            .await
5565            .expect("into entity must remain unmerged after a dry run");
5566        let from_after = rt
5567            .get_entity(&tok, from.id)
5568            .await
5569            .expect("from entity must not be merged away by a dry run");
5570        assert_eq!(
5571            serde_json::to_value(&into_before).unwrap(),
5572            serde_json::to_value(&into_after).unwrap(),
5573            "dry run must not mutate the into entity's row at all"
5574        );
5575        assert_eq!(
5576            serde_json::to_value(&from_before).unwrap(),
5577            serde_json::to_value(&from_after).unwrap(),
5578            "dry run must not mutate the from entity's row at all"
5579        );
5580        assert_eq!(from_after.deleted_at, None);
5581        assert_eq!(from_after.merged_into, None);
5582        assert_eq!(from_after.merge_event_id, None);
5583
5584        let events = rt
5585            .events(&tok)
5586            .unwrap()
5587            .query_events(
5588                khive_storage::EventFilter {
5589                    kinds: vec![EventKind::EntityMerged],
5590                    ..Default::default()
5591                },
5592                khive_storage::types::PageRequest {
5593                    offset: 0,
5594                    limit: 10,
5595                },
5596            )
5597            .await
5598            .unwrap();
5599        assert!(
5600            events.items.is_empty(),
5601            "a dry run must not record a merge audit event"
5602        );
5603    }
5604
5605    // A soft-deleted surviving edge must not be resurrected by a conflicting
5606    // rewire — the from-edge is dropped and the tombstone stays.
5607    #[tokio::test]
5608    async fn merge_entity_conflict_does_not_resurrect_tombstoned_edge() {
5609        let rt = rt();
5610        let tok = NamespaceToken::local();
5611        let into = rt
5612            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
5613            .await
5614            .unwrap();
5615        let from = rt
5616            .create_entity(&tok, "concept", None, "From", None, None, vec![])
5617            .await
5618            .unwrap();
5619        let shared = rt
5620            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
5621            .await
5622            .unwrap();
5623
5624        let survivor = rt
5625            .link(&tok, into.id, shared.id, EdgeRelation::Extends, 0.9, None)
5626            .await
5627            .unwrap();
5628        rt.delete_edge(&tok, survivor.id.into(), false)
5629            .await
5630            .unwrap();
5631        rt.link(&tok, from.id, shared.id, EdgeRelation::Extends, 0.2, None)
5632            .await
5633            .unwrap();
5634
5635        rt.merge_entity(
5636            &tok,
5637            into.id,
5638            from.id,
5639            EntityDedupMergePolicy::PreferInto,
5640            ContentMergeStrategy::Append,
5641            false,
5642        )
5643        .await
5644        .unwrap();
5645
5646        for (src, label) in [(into.id, "into"), (from.id, "from")] {
5647            let edges = rt
5648                .list_edges(
5649                    &tok,
5650                    crate::EdgeListFilter {
5651                        source_id: Some(src),
5652                        target_id: Some(shared.id),
5653                        relations: vec![EdgeRelation::Extends],
5654                        ..Default::default()
5655                    },
5656                    10,
5657                    0,
5658                )
5659                .await
5660                .unwrap();
5661            assert!(
5662                edges.is_empty(),
5663                "no live {label}→shared edge may exist after merging over a tombstone; got: {edges:?}"
5664            );
5665        }
5666    }
5667
5668    // The survivor row write must not null columns it doesn't merge —
5669    // entity_type (and the old entity-owned content_ref) were lost by the old full-row
5670    // INSERT OR REPLACE.
5671    #[tokio::test]
5672    async fn merge_entity_preserves_survivor_entity_type() {
5673        let rt = rt();
5674        let tok = NamespaceToken::local();
5675        let into = rt
5676            .create_entity(&tok, "resource", Some("skill"), "Into", None, None, vec![])
5677            .await
5678            .unwrap();
5679        assert_eq!(into.entity_type.as_deref(), Some("skill"));
5680        let from = rt
5681            .create_entity(&tok, "resource", None, "From", None, None, vec![])
5682            .await
5683            .unwrap();
5684
5685        rt.merge_entity(
5686            &tok,
5687            into.id,
5688            from.id,
5689            EntityDedupMergePolicy::PreferInto,
5690            ContentMergeStrategy::Append,
5691            false,
5692        )
5693        .await
5694        .unwrap();
5695
5696        let got = rt.get_entity(&tok, into.id).await.unwrap();
5697        assert_eq!(
5698            got.entity_type.as_deref(),
5699            Some("skill"),
5700            "merge must not null the survivor's entity_type"
5701        );
5702    }
5703
5704    #[tokio::test]
5705    async fn merge_entity_preserves_survivor_content_ref() {
5706        let rt = rt();
5707        let tok = NamespaceToken::local();
5708        let into = rt
5709            .create_entity(&tok, "document", None, "Into", None, None, vec![])
5710            .await
5711            .unwrap();
5712        let from = rt
5713            .create_entity(&tok, "document", None, "From", None, None, vec![])
5714            .await
5715            .unwrap();
5716
5717        let content_ref = khive_storage::ContentRef::from_hex("0".repeat(64)).unwrap();
5718        let store = rt.entities(&tok).unwrap();
5719        rt.attachments()
5720            .unwrap()
5721            .upsert_attachment(khive_storage::Attachment::from_new(
5722                into.id,
5723                khive_storage::AttachmentSubstrate::Entity,
5724                khive_storage::NewAttachment {
5725                    role: "content".to_string(),
5726                    content_ref: content_ref.clone(),
5727                    media_type: None,
5728                    size_bytes: None,
5729                },
5730                into.created_at,
5731            ))
5732            .await
5733            .unwrap();
5734
5735        rt.merge_entity(
5736            &tok,
5737            into.id,
5738            from.id,
5739            EntityDedupMergePolicy::PreferInto,
5740            ContentMergeStrategy::Append,
5741            false,
5742        )
5743        .await
5744        .unwrap();
5745
5746        let got = store.get_entity(into.id).await.unwrap().unwrap();
5747        assert_eq!(
5748            got.content_ref.as_deref(),
5749            Some(content_ref.as_str()),
5750            "merge must not null the survivor's content_ref"
5751        );
5752    }
5753
5754    #[tokio::test]
5755    async fn merge_entity_self_merge_rejected() {
5756        let rt = rt();
5757        let tok = NamespaceToken::local();
5758        let a = rt
5759            .create_entity(&tok, "concept", None, "A", None, None, vec![])
5760            .await
5761            .unwrap();
5762        let err = rt
5763            .merge_entity_with_reason(
5764                &tok,
5765                a.id,
5766                a.id,
5767                EntityDedupMergePolicy::PreferInto,
5768                ContentMergeStrategy::Append,
5769                false,
5770                None,
5771            )
5772            .await
5773            .unwrap_err();
5774        assert!(
5775            format!("{err:?}").contains("cannot merge an entity into itself"),
5776            "expected self-merge rejection, got: {err:?}"
5777        );
5778    }
5779
5780    #[tokio::test]
5781    async fn merge_entity_prefer_into_strategy() {
5782        let rt = rt();
5783        let tok = NamespaceToken::local();
5784        let into = rt
5785            .create_entity(
5786                &tok,
5787                "concept",
5788                None,
5789                "Into",
5790                None,
5791                Some(serde_json::json!({"a": 1})),
5792                vec![],
5793            )
5794            .await
5795            .unwrap();
5796        let from = rt
5797            .create_entity(
5798                &tok,
5799                "concept",
5800                None,
5801                "From",
5802                None,
5803                Some(serde_json::json!({"a": 2, "b": 3})),
5804                vec![],
5805            )
5806            .await
5807            .unwrap();
5808
5809        rt.merge_entity_with_reason(
5810            &tok,
5811            into.id,
5812            from.id,
5813            EntityDedupMergePolicy::PreferInto,
5814            ContentMergeStrategy::Append,
5815            false,
5816            None,
5817        )
5818        .await
5819        .unwrap();
5820
5821        let kept = rt.get_entity(&tok, into.id).await.unwrap();
5822        let props = kept.properties.unwrap();
5823        // a stays as 1 (into wins), b is added from from.
5824        assert_eq!(props["a"], 1);
5825        assert_eq!(props["b"], 3);
5826    }
5827
5828    #[tokio::test]
5829    async fn merge_entity_prefer_from_strategy() {
5830        let rt = rt();
5831        let tok = NamespaceToken::local();
5832        let into = rt
5833            .create_entity(
5834                &tok,
5835                "concept",
5836                None,
5837                "Into",
5838                None,
5839                Some(serde_json::json!({"a": 1})),
5840                vec![],
5841            )
5842            .await
5843            .unwrap();
5844        let from = rt
5845            .create_entity(
5846                &tok,
5847                "concept",
5848                None,
5849                "From",
5850                None,
5851                Some(serde_json::json!({"a": 2, "b": 3})),
5852                vec![],
5853            )
5854            .await
5855            .unwrap();
5856
5857        rt.merge_entity_with_reason(
5858            &tok,
5859            into.id,
5860            from.id,
5861            EntityDedupMergePolicy::PreferFrom,
5862            ContentMergeStrategy::Append,
5863            false,
5864            None,
5865        )
5866        .await
5867        .unwrap();
5868
5869        let kept = rt.get_entity(&tok, into.id).await.unwrap();
5870        let props = kept.properties.unwrap();
5871        // from wins on a, b also from from.
5872        assert_eq!(props["a"], 2);
5873        assert_eq!(props["b"], 3);
5874    }
5875
5876    #[tokio::test]
5877    async fn merge_entity_union_strategy() {
5878        let rt = rt();
5879        let tok = NamespaceToken::local();
5880        let into = rt
5881            .create_entity(
5882                &tok,
5883                "concept",
5884                None,
5885                "Into",
5886                None,
5887                Some(serde_json::json!({"a": 1})),
5888                vec![],
5889            )
5890            .await
5891            .unwrap();
5892        let from = rt
5893            .create_entity(
5894                &tok,
5895                "concept",
5896                None,
5897                "From",
5898                None,
5899                Some(serde_json::json!({"a": 2, "b": 3})),
5900                vec![],
5901            )
5902            .await
5903            .unwrap();
5904
5905        rt.merge_entity_with_reason(
5906            &tok,
5907            into.id,
5908            from.id,
5909            EntityDedupMergePolicy::Union,
5910            ContentMergeStrategy::Append,
5911            false,
5912            None,
5913        )
5914        .await
5915        .unwrap();
5916
5917        let kept = rt.get_entity(&tok, into.id).await.unwrap();
5918        let props = kept.properties.unwrap();
5919        // Scalar conflict: into wins → a=1. b added from from.
5920        assert_eq!(props["a"], 1);
5921        assert_eq!(props["b"], 3);
5922    }
5923
5924    #[tokio::test]
5925    async fn merge_entity_unions_tags() {
5926        let rt = rt();
5927        let tok = NamespaceToken::local();
5928        let into = rt
5929            .create_entity(
5930                &tok,
5931                "concept",
5932                None,
5933                "Into",
5934                None,
5935                None,
5936                vec!["x".to_string(), "y".to_string()],
5937            )
5938            .await
5939            .unwrap();
5940        let from = rt
5941            .create_entity(
5942                &tok,
5943                "concept",
5944                None,
5945                "From",
5946                None,
5947                None,
5948                vec!["y".to_string(), "z".to_string()],
5949            )
5950            .await
5951            .unwrap();
5952
5953        rt.merge_entity_with_reason(
5954            &tok,
5955            into.id,
5956            from.id,
5957            EntityDedupMergePolicy::PreferInto,
5958            ContentMergeStrategy::Append,
5959            false,
5960            None,
5961        )
5962        .await
5963        .unwrap();
5964
5965        let kept = rt.get_entity(&tok, into.id).await.unwrap();
5966        let mut tags = kept.tags.clone();
5967        tags.sort();
5968        assert_eq!(tags, vec!["x", "y", "z"]);
5969    }
5970
5971    #[tokio::test]
5972    async fn merge_entity_drops_self_loops() {
5973        let rt = rt();
5974        let tok = NamespaceToken::local();
5975        let a = rt
5976            .create_entity(&tok, "concept", None, "A", None, None, vec![])
5977            .await
5978            .unwrap();
5979        let b = rt
5980            .create_entity(&tok, "concept", None, "B", None, None, vec![])
5981            .await
5982            .unwrap();
5983
5984        // A `extends` B — merging B into A would produce A `extends` A → drop it.
5985        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
5986            .await
5987            .unwrap();
5988
5989        let summary = rt
5990            .merge_entity_with_reason(
5991                &tok,
5992                a.id,
5993                b.id,
5994                EntityDedupMergePolicy::PreferInto,
5995                ContentMergeStrategy::Append,
5996                false,
5997                None,
5998            )
5999            .await
6000            .unwrap();
6001
6002        assert_eq!(
6003            summary.edges_rewired, 0,
6004            "self-loop should be dropped, not rewired"
6005        );
6006
6007        let a_out = rt
6008            .neighbors(&tok, a.id, Direction::Out, None, None)
6009            .await
6010            .unwrap();
6011        assert!(a_out.is_empty(), "no self-loop should remain");
6012    }
6013
6014    // ---- content_strategy for entity merge ----
6015
6016    #[tokio::test]
6017    async fn merge_entity_append_strategy_concatenates_descriptions() {
6018        let rt = rt();
6019        let tok = NamespaceToken::local();
6020        let into = rt
6021            .create_entity(&tok, "concept", None, "Into", Some("desc A"), None, vec![])
6022            .await
6023            .unwrap();
6024        let from = rt
6025            .create_entity(&tok, "concept", None, "From", Some("desc B"), None, vec![])
6026            .await
6027            .unwrap();
6028
6029        let summary = rt
6030            .merge_entity_with_reason(
6031                &tok,
6032                into.id,
6033                from.id,
6034                EntityDedupMergePolicy::PreferInto,
6035                ContentMergeStrategy::Append,
6036                false,
6037                None,
6038            )
6039            .await
6040            .unwrap();
6041
6042        assert!(
6043            summary.content_appended,
6044            "append strategy with two non-empty descriptions must report content_appended=true"
6045        );
6046        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6047        assert_eq!(kept.description.as_deref(), Some("desc A\n\n---\n\ndesc B"));
6048    }
6049
6050    #[tokio::test]
6051    async fn merge_entity_append_strategy_from_empty_is_noop() {
6052        let rt = rt();
6053        let tok = NamespaceToken::local();
6054        let into = rt
6055            .create_entity(&tok, "concept", None, "Into", Some("desc A"), None, vec![])
6056            .await
6057            .unwrap();
6058        let from = rt
6059            .create_entity(&tok, "concept", None, "From", None, None, vec![])
6060            .await
6061            .unwrap();
6062
6063        let summary = rt
6064            .merge_entity_with_reason(
6065                &tok,
6066                into.id,
6067                from.id,
6068                EntityDedupMergePolicy::PreferInto,
6069                ContentMergeStrategy::Append,
6070                false,
6071                None,
6072            )
6073            .await
6074            .unwrap();
6075
6076        assert!(
6077            !summary.content_appended,
6078            "from's empty description means nothing was appended"
6079        );
6080        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6081        assert_eq!(kept.description.as_deref(), Some("desc A"));
6082    }
6083
6084    #[tokio::test]
6085    async fn merge_entity_append_strategy_into_empty_takes_from() {
6086        let rt = rt();
6087        let tok = NamespaceToken::local();
6088        let into = rt
6089            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
6090            .await
6091            .unwrap();
6092        let from = rt
6093            .create_entity(&tok, "concept", None, "From", Some("desc B"), None, vec![])
6094            .await
6095            .unwrap();
6096
6097        let summary = rt
6098            .merge_entity_with_reason(
6099                &tok,
6100                into.id,
6101                from.id,
6102                EntityDedupMergePolicy::PreferInto,
6103                ContentMergeStrategy::Append,
6104                false,
6105                None,
6106            )
6107            .await
6108            .unwrap();
6109
6110        assert!(
6111            summary.content_appended,
6112            "taking from's description into an empty into is real content preservation"
6113        );
6114        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6115        assert_eq!(kept.description.as_deref(), Some("desc B"));
6116    }
6117
6118    #[tokio::test]
6119    async fn merge_entity_prefer_into_strategy_still_discards_explicitly() {
6120        let rt = rt();
6121        let tok = NamespaceToken::local();
6122        let into = rt
6123            .create_entity(&tok, "concept", None, "Into", Some("desc A"), None, vec![])
6124            .await
6125            .unwrap();
6126        let from = rt
6127            .create_entity(&tok, "concept", None, "From", Some("desc B"), None, vec![])
6128            .await
6129            .unwrap();
6130
6131        let summary = rt
6132            .merge_entity_with_reason(
6133                &tok,
6134                into.id,
6135                from.id,
6136                EntityDedupMergePolicy::PreferInto,
6137                ContentMergeStrategy::PreferInto,
6138                false,
6139                None,
6140            )
6141            .await
6142            .unwrap();
6143
6144        assert!(
6145            !summary.content_appended,
6146            "explicit PreferInto opt-out must not report an append"
6147        );
6148        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6149        assert_eq!(
6150            kept.description.as_deref(),
6151            Some("desc A"),
6152            "explicit PreferInto opt-out keeps the old discard behavior"
6153        );
6154    }
6155
6156    /// `content_strategy` must be followed directly, independent of the
6157    /// entity-field `strategy`: with the default entity policy `prefer_into`,
6158    /// an explicit `content_strategy=prefer_from` must still keep the
6159    /// from-description.
6160    #[tokio::test]
6161    async fn merge_entity_prefer_from_content_strategy_wins_over_default_entity_policy() {
6162        let rt = rt();
6163        let tok = NamespaceToken::local();
6164        let into = rt
6165            .create_entity(&tok, "concept", None, "Into", Some("desc A"), None, vec![])
6166            .await
6167            .unwrap();
6168        let from = rt
6169            .create_entity(&tok, "concept", None, "From", Some("desc B"), None, vec![])
6170            .await
6171            .unwrap();
6172
6173        let summary = rt
6174            .merge_entity_with_reason(
6175                &tok,
6176                into.id,
6177                from.id,
6178                EntityDedupMergePolicy::PreferInto,
6179                ContentMergeStrategy::PreferFrom,
6180                false,
6181                None,
6182            )
6183            .await
6184            .unwrap();
6185
6186        assert!(
6187            !summary.content_appended,
6188            "explicit PreferFrom is not an append"
6189        );
6190        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6191        assert_eq!(
6192            kept.description.as_deref(),
6193            Some("desc B"),
6194            "content_strategy=prefer_from must win over the default prefer_into entity policy"
6195        );
6196    }
6197
6198    #[tokio::test]
6199    async fn merge_entity_dry_run_previews_append() {
6200        let rt = rt();
6201        let tok = NamespaceToken::local();
6202        let into = rt
6203            .create_entity(&tok, "concept", None, "Into", Some("desc A"), None, vec![])
6204            .await
6205            .unwrap();
6206        let from = rt
6207            .create_entity(&tok, "concept", None, "From", Some("desc B"), None, vec![])
6208            .await
6209            .unwrap();
6210
6211        let summary = rt
6212            .merge_entity_with_reason(
6213                &tok,
6214                into.id,
6215                from.id,
6216                EntityDedupMergePolicy::PreferInto,
6217                ContentMergeStrategy::Append,
6218                true,
6219                None,
6220            )
6221            .await
6222            .unwrap();
6223
6224        assert!(summary.dry_run);
6225        assert!(
6226            summary.content_appended,
6227            "dry-run must preview the append outcome without writing"
6228        );
6229        let kept = rt.get_entity(&tok, into.id).await.unwrap();
6230        assert_eq!(
6231            kept.description.as_deref(),
6232            Some("desc A"),
6233            "dry_run=true must not mutate the into entity's description"
6234        );
6235    }
6236
6237    /// Dry-run must be a read-only, accurate preview: it must predict
6238    /// `edges_rewired` without writing, and must not append an `EntityMerged` event.
6239    #[tokio::test]
6240    async fn merge_entity_dry_run_predicts_edges_rewired_without_writing() {
6241        use khive_storage::EdgeRelation;
6242
6243        let rt = rt();
6244        let tok = NamespaceToken::local();
6245        let a = rt
6246            .create_entity(&tok, "concept", None, "A", None, None, vec![])
6247            .await
6248            .unwrap();
6249        let into = rt
6250            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
6251            .await
6252            .unwrap();
6253        let from = rt
6254            .create_entity(&tok, "concept", None, "From", None, None, vec![])
6255            .await
6256            .unwrap();
6257
6258        rt.link(&tok, a.id, from.id, EdgeRelation::Extends, 1.0, None)
6259            .await
6260            .unwrap();
6261
6262        let summary = rt
6263            .merge_entity_with_reason(
6264                &tok,
6265                into.id,
6266                from.id,
6267                EntityDedupMergePolicy::PreferInto,
6268                ContentMergeStrategy::Append,
6269                true,
6270                None,
6271            )
6272            .await
6273            .unwrap();
6274
6275        assert!(summary.dry_run);
6276        assert_eq!(
6277            summary.edges_rewired, 1,
6278            "dry-run must predict the edge that would be rewired, not report zero"
6279        );
6280
6281        let a_neighbors = rt
6282            .neighbors(&tok, a.id, Direction::Out, None, None)
6283            .await
6284            .unwrap();
6285        assert_eq!(a_neighbors.len(), 1);
6286        assert_eq!(
6287            a_neighbors[0].node_id, from.id,
6288            "dry_run=true must not rewire any edges"
6289        );
6290
6291        let events = rt
6292            .events(&tok)
6293            .unwrap()
6294            .query_events(
6295                khive_storage::EventFilter {
6296                    kinds: vec![EventKind::EntityMerged],
6297                    ..Default::default()
6298                },
6299                khive_storage::types::PageRequest {
6300                    offset: 0,
6301                    limit: 10,
6302                },
6303            )
6304            .await
6305            .unwrap();
6306        assert!(
6307            events.items.is_empty(),
6308            "dry_run=true must not append an EntityMerged event"
6309        );
6310    }
6311
6312    /// ADR-014: `reason` is additive — when supplied it must land in the
6313    /// `EntityMerged` payload verbatim; the key must be entirely absent (not
6314    /// `null`) when the caller omits it.
6315    #[tokio::test]
6316    async fn merge_entity_event_reason_present_when_supplied_absent_when_not() {
6317        let rt = rt();
6318        let tok = NamespaceToken::local();
6319
6320        let into_a = rt
6321            .create_entity(&tok, "concept", None, "IntoA", None, None, vec![])
6322            .await
6323            .unwrap();
6324        let from_a = rt
6325            .create_entity(&tok, "concept", None, "FromA", None, None, vec![])
6326            .await
6327            .unwrap();
6328        rt.merge_entity_with_reason(
6329            &tok,
6330            into_a.id,
6331            from_a.id,
6332            EntityDedupMergePolicy::PreferInto,
6333            ContentMergeStrategy::Append,
6334            false,
6335            Some("duplicate".to_string()),
6336        )
6337        .await
6338        .unwrap();
6339
6340        let into_b = rt
6341            .create_entity(&tok, "concept", None, "IntoB", None, None, vec![])
6342            .await
6343            .unwrap();
6344        let from_b = rt
6345            .create_entity(&tok, "concept", None, "FromB", None, None, vec![])
6346            .await
6347            .unwrap();
6348        rt.merge_entity_with_reason(
6349            &tok,
6350            into_b.id,
6351            from_b.id,
6352            EntityDedupMergePolicy::PreferInto,
6353            ContentMergeStrategy::Append,
6354            false,
6355            None,
6356        )
6357        .await
6358        .unwrap();
6359
6360        let events = rt
6361            .events(&tok)
6362            .unwrap()
6363            .query_events(
6364                khive_storage::EventFilter {
6365                    kinds: vec![EventKind::EntityMerged],
6366                    ..Default::default()
6367                },
6368                khive_storage::types::PageRequest {
6369                    offset: 0,
6370                    limit: 10,
6371                },
6372            )
6373            .await
6374            .unwrap();
6375        assert_eq!(events.items.len(), 2);
6376
6377        let with_reason = events
6378            .items
6379            .iter()
6380            .find(|e| {
6381                e.payload.get("from_id").and_then(|v| v.as_str())
6382                    == Some(from_a.id.to_string()).as_deref()
6383            })
6384            .expect("event for the reasoned merge must exist");
6385        assert_eq!(
6386            with_reason.payload.get("reason").and_then(|v| v.as_str()),
6387            Some("duplicate"),
6388            "reason must be threaded verbatim into the payload when supplied"
6389        );
6390
6391        let without_reason = events
6392            .items
6393            .iter()
6394            .find(|e| {
6395                e.payload.get("from_id").and_then(|v| v.as_str())
6396                    == Some(from_b.id.to_string()).as_deref()
6397            })
6398            .expect("event for the reasonless merge must exist");
6399        assert!(
6400            without_reason.payload.get("reason").is_none(),
6401            "reason key must be absent (never null) when the caller omits it, got: {:?}",
6402            without_reason.payload
6403        );
6404    }
6405
6406    #[tokio::test]
6407    async fn merge_entity_with_reason_preserves_an_explicit_empty_reason() {
6408        let rt = rt();
6409        let tok = NamespaceToken::local();
6410        let into = rt
6411            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
6412            .await
6413            .unwrap();
6414        let from = rt
6415            .create_entity(&tok, "concept", None, "From", None, None, vec![])
6416            .await
6417            .unwrap();
6418
6419        rt.merge_entity_with_reason(
6420            &tok,
6421            into.id,
6422            from.id,
6423            EntityDedupMergePolicy::PreferInto,
6424            ContentMergeStrategy::Append,
6425            false,
6426            Some(String::new()),
6427        )
6428        .await
6429        .unwrap();
6430
6431        let events = rt
6432            .events(&tok)
6433            .unwrap()
6434            .query_events(
6435                khive_storage::EventFilter {
6436                    kinds: vec![EventKind::EntityMerged],
6437                    ..Default::default()
6438                },
6439                khive_storage::types::PageRequest {
6440                    offset: 0,
6441                    limit: 10,
6442                },
6443            )
6444            .await
6445            .unwrap();
6446        assert_eq!(events.items.len(), 1);
6447        assert_eq!(
6448            events.items[0].payload.get("reason"),
6449            Some(&Value::String(String::new()))
6450        );
6451    }
6452
6453    #[tokio::test]
6454    async fn merge_entity_with_reason_rejects_secrets_before_reads_or_writes() {
6455        let rt = rt();
6456        let tok = NamespaceToken::local();
6457        let into = rt
6458            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
6459            .await
6460            .unwrap();
6461        let from = rt
6462            .create_entity(&tok, "concept", None, "From", None, None, vec![])
6463            .await
6464            .unwrap();
6465        let secret = secret_shaped_reason();
6466
6467        let error = rt
6468            .merge_entity_with_reason(
6469                &tok,
6470                into.id,
6471                from.id,
6472                EntityDedupMergePolicy::PreferInto,
6473                ContentMergeStrategy::Append,
6474                false,
6475                Some(secret),
6476            )
6477            .await
6478            .unwrap_err();
6479
6480        assert!(matches!(error, RuntimeError::SecretDetected(_)));
6481        assert_eq!(rt.get_entity(&tok, into.id).await.unwrap().id, into.id);
6482        assert_eq!(rt.get_entity(&tok, from.id).await.unwrap().id, from.id);
6483        let event_count = rt
6484            .events(&tok)
6485            .unwrap()
6486            .count_events(khive_storage::EventFilter {
6487                kinds: vec![EventKind::EntityMerged],
6488                ..Default::default()
6489            })
6490            .await
6491            .unwrap();
6492        assert_eq!(event_count, 0);
6493    }
6494
6495    /// ADR-014: `merge_note` must be as auditable as `merge_entity` — exactly one
6496    /// `NoteMerged` event, carrying kept/absorbed ids, per note merge.
6497    #[tokio::test]
6498    async fn merge_note_emits_exactly_one_note_merged_event_with_kept_and_absorbed_ids() {
6499        let rt = rt();
6500        let tok = NamespaceToken::local();
6501        let into = rt
6502            .create_note(&tok, "observation", None, "into note", None, None, vec![])
6503            .await
6504            .unwrap();
6505        let from = rt
6506            .create_note(&tok, "observation", None, "from note", None, None, vec![])
6507            .await
6508            .unwrap();
6509
6510        let summary = rt
6511            .merge_note_with_reason(
6512                &tok,
6513                into.id,
6514                from.id,
6515                EntityDedupMergePolicy::PreferInto,
6516                ContentMergeStrategy::Append,
6517                false,
6518                Some("duplicate".to_string()),
6519            )
6520            .await
6521            .unwrap();
6522
6523        let events = rt
6524            .events(&tok)
6525            .unwrap()
6526            .query_events(
6527                khive_storage::EventFilter {
6528                    kinds: vec![EventKind::NoteMerged],
6529                    ..Default::default()
6530                },
6531                khive_storage::types::PageRequest {
6532                    offset: 0,
6533                    limit: 10,
6534                },
6535            )
6536            .await
6537            .unwrap();
6538        assert_eq!(
6539            events.items.len(),
6540            1,
6541            "merge_note must emit exactly one NoteMerged event"
6542        );
6543
6544        let payload = &events.items[0].payload;
6545        assert_eq!(
6546            payload.get("into_id").and_then(|v| v.as_str()),
6547            Some(summary.kept_id.to_string()).as_deref()
6548        );
6549        assert_eq!(
6550            payload.get("from_id").and_then(|v| v.as_str()),
6551            Some(summary.removed_id.to_string()).as_deref()
6552        );
6553        assert_eq!(
6554            payload.get("reason").and_then(|v| v.as_str()),
6555            Some("duplicate")
6556        );
6557    }
6558
6559    #[tokio::test]
6560    async fn merge_note_with_reason_preserves_an_explicit_empty_reason() {
6561        let rt = rt();
6562        let tok = NamespaceToken::local();
6563        let into = rt
6564            .create_note(&tok, "observation", None, "into note", None, None, vec![])
6565            .await
6566            .unwrap();
6567        let from = rt
6568            .create_note(&tok, "observation", None, "from note", None, None, vec![])
6569            .await
6570            .unwrap();
6571
6572        rt.merge_note_with_reason(
6573            &tok,
6574            into.id,
6575            from.id,
6576            EntityDedupMergePolicy::PreferInto,
6577            ContentMergeStrategy::Append,
6578            false,
6579            Some(String::new()),
6580        )
6581        .await
6582        .unwrap();
6583
6584        let events = rt
6585            .events(&tok)
6586            .unwrap()
6587            .query_events(
6588                khive_storage::EventFilter {
6589                    kinds: vec![EventKind::NoteMerged],
6590                    ..Default::default()
6591                },
6592                khive_storage::types::PageRequest {
6593                    offset: 0,
6594                    limit: 10,
6595                },
6596            )
6597            .await
6598            .unwrap();
6599        assert_eq!(events.items.len(), 1);
6600        assert_eq!(
6601            events.items[0].payload.get("reason"),
6602            Some(&Value::String(String::new()))
6603        );
6604    }
6605
6606    #[tokio::test]
6607    async fn merge_note_with_reason_rejects_secrets_before_reads_or_writes() {
6608        let rt = rt();
6609        let tok = NamespaceToken::local();
6610        let into = rt
6611            .create_note(&tok, "observation", None, "into note", None, None, vec![])
6612            .await
6613            .unwrap();
6614        let from = rt
6615            .create_note(&tok, "observation", None, "from note", None, None, vec![])
6616            .await
6617            .unwrap();
6618        let secret = secret_shaped_reason();
6619
6620        let error = rt
6621            .merge_note_with_reason(
6622                &tok,
6623                into.id,
6624                from.id,
6625                EntityDedupMergePolicy::PreferInto,
6626                ContentMergeStrategy::Append,
6627                false,
6628                Some(secret),
6629            )
6630            .await
6631            .unwrap_err();
6632
6633        assert!(matches!(error, RuntimeError::SecretDetected(_)));
6634        let note_store = rt.notes(&tok).unwrap();
6635        assert_eq!(
6636            note_store.get_note(into.id).await.unwrap().unwrap().id,
6637            into.id
6638        );
6639        assert_eq!(
6640            note_store.get_note(from.id).await.unwrap().unwrap().id,
6641            from.id
6642        );
6643        let event_count = rt
6644            .events(&tok)
6645            .unwrap()
6646            .count_events(khive_storage::EventFilter {
6647                kinds: vec![EventKind::NoteMerged],
6648                ..Default::default()
6649            })
6650            .await
6651            .unwrap();
6652        assert_eq!(event_count, 0);
6653    }
6654
6655    #[tokio::test]
6656    async fn legacy_merge_methods_remain_source_compatible() {
6657        let rt = rt();
6658        let tok = NamespaceToken::local();
6659        let into_entity = rt
6660            .create_entity(&tok, "concept", None, "Entity A", None, None, vec![])
6661            .await
6662            .unwrap();
6663        let from_entity = rt
6664            .create_entity(&tok, "concept", None, "Entity B", None, None, vec![])
6665            .await
6666            .unwrap();
6667        let into_note = rt
6668            .create_note(&tok, "observation", None, "note A", None, None, vec![])
6669            .await
6670            .unwrap();
6671        let from_note = rt
6672            .create_note(&tok, "observation", None, "note B", None, None, vec![])
6673            .await
6674            .unwrap();
6675
6676        rt.merge_entity(
6677            &tok,
6678            into_entity.id,
6679            from_entity.id,
6680            EntityDedupMergePolicy::PreferInto,
6681            ContentMergeStrategy::Append,
6682            false,
6683        )
6684        .await
6685        .unwrap();
6686        rt.merge_note(
6687            &tok,
6688            into_note.id,
6689            from_note.id,
6690            EntityDedupMergePolicy::PreferInto,
6691            ContentMergeStrategy::Append,
6692            false,
6693        )
6694        .await
6695        .unwrap();
6696    }
6697
6698    // ---- interim merged_into miss-hint (data-integrity, precedes ADR-113 chase) ----
6699
6700    #[tokio::test]
6701    async fn get_entity_after_merge_discloses_kept_id() {
6702        let rt = rt();
6703        let tok = NamespaceToken::local();
6704        let into = rt
6705            .create_entity(&tok, "concept", None, "Kept", None, None, vec![])
6706            .await
6707            .unwrap();
6708        let from = rt
6709            .create_entity(&tok, "concept", None, "Absorbed", None, None, vec![])
6710            .await
6711            .unwrap();
6712
6713        rt.merge_entity(
6714            &tok,
6715            into.id,
6716            from.id,
6717            EntityDedupMergePolicy::PreferInto,
6718            ContentMergeStrategy::Append,
6719            false,
6720        )
6721        .await
6722        .unwrap();
6723
6724        let err = rt.get_entity(&tok, from.id).await.unwrap_err();
6725        let msg = err.to_string();
6726        assert!(
6727            msg.contains("was merged into") && msg.contains(&into.id.to_string()),
6728            "expected a merged_into disclosure naming {}, got {msg:?}",
6729            into.id
6730        );
6731    }
6732
6733    #[tokio::test]
6734    async fn get_entity_on_plain_soft_delete_stays_bare_not_found() {
6735        let rt = rt();
6736        let tok = NamespaceToken::local();
6737        let entity = rt
6738            .create_entity(&tok, "concept", None, "Deleted", None, None, vec![])
6739            .await
6740            .unwrap();
6741        assert!(rt.delete_entity(&tok, entity.id, false).await.unwrap());
6742
6743        let err = rt.get_entity(&tok, entity.id).await.unwrap_err();
6744        let msg = err.to_string();
6745        assert!(
6746            !msg.contains("merged into"),
6747            "plain soft-delete must not gain a merge hint, got {msg:?}"
6748        );
6749        assert_eq!(msg, format!("not found: entity {}", entity.id));
6750    }
6751
6752    #[tokio::test]
6753    async fn get_entity_on_absent_id_stays_bare_not_found() {
6754        let rt = rt();
6755        let tok = NamespaceToken::local();
6756        let absent = Uuid::new_v4();
6757
6758        let err = rt.get_entity(&tok, absent).await.unwrap_err();
6759        let msg = err.to_string();
6760        assert!(
6761            !msg.contains("merged into"),
6762            "a never-existed id must not gain a merge hint, got {msg:?}"
6763        );
6764        assert_eq!(msg, format!("not found: entity {absent}"));
6765    }
6766
6767    // ---- merge helper unit tests ----
6768
6769    #[test]
6770    fn union_tags_deduplicates() {
6771        let (tags, added) = union_tags(
6772            &["x".to_string(), "y".to_string()],
6773            &["y".to_string(), "z".to_string()],
6774        );
6775        let mut sorted = tags.clone();
6776        sorted.sort();
6777        assert_eq!(sorted, vec!["x", "y", "z"]);
6778        assert_eq!(added, 1);
6779    }
6780
6781    #[test]
6782    fn merge_properties_prefer_into_fills_missing_keys() {
6783        let a = serde_json::json!({"a": 1});
6784        let b = serde_json::json!({"a": 99, "b": 2});
6785        let (merged, added) =
6786            merge_properties(&Some(a), &Some(b), EntityDedupMergePolicy::PreferInto);
6787        let m = merged.unwrap();
6788        assert_eq!(m["a"], 1);
6789        assert_eq!(m["b"], 2);
6790        assert_eq!(added, 1);
6791    }
6792
6793    // ---- tombstone and note merge tests ----
6794
6795    #[tokio::test]
6796    async fn merge_entity_tombstones_source_with_provenance() {
6797        let rt = rt();
6798        let tok = NamespaceToken::local();
6799        let into = rt
6800            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
6801            .await
6802            .unwrap();
6803        let from = rt
6804            .create_entity(&tok, "concept", None, "From", None, None, vec![])
6805            .await
6806            .unwrap();
6807        let from_id = from.id;
6808
6809        rt.merge_entity_with_reason(
6810            &tok,
6811            into.id,
6812            from_id,
6813            EntityDedupMergePolicy::PreferInto,
6814            ContentMergeStrategy::Append,
6815            false,
6816            None,
6817        )
6818        .await
6819        .unwrap();
6820
6821        assert!(
6822            rt.get_entity(&tok, from_id).await.is_err(),
6823            "tombstoned source should not be returned by get_entity"
6824        );
6825
6826        let pool = rt.backend().pool_arc();
6827        let (deleted_at, merged_into): (Option<i64>, Option<String>) =
6828            tokio::task::spawn_blocking(move || {
6829                let guard = pool.writer().unwrap();
6830                guard
6831                    .conn()
6832                    .query_row(
6833                        "SELECT deleted_at, merged_into FROM entities WHERE id = ?1",
6834                        [from_id.to_string()],
6835                        |row| Ok((row.get(0)?, row.get(1)?)),
6836                    )
6837                    .unwrap()
6838            })
6839            .await
6840            .unwrap();
6841        assert!(
6842            deleted_at.is_some(),
6843            "tombstoned entity must have deleted_at set"
6844        );
6845        assert_eq!(
6846            merged_into.as_deref(),
6847            Some(into.id.to_string().as_str()),
6848            "merged_into must point to into_id"
6849        );
6850    }
6851
6852    #[tokio::test]
6853    async fn generic_update_and_merge_reject_schedule_managed_notes() {
6854        let rt = rt();
6855        let tok = NamespaceToken::local();
6856        let schedule_a = rt
6857            .create_note(
6858                &tok,
6859                "scheduled_event",
6860                None,
6861                "stats()",
6862                None,
6863                Some(serde_json::json!({
6864                    "event_type": "schedule",
6865                    "payload": "stats()",
6866                    "status": "pending",
6867                    "trigger_at": "2099-01-01T00:00:00Z"
6868                })),
6869                vec![],
6870            )
6871            .await
6872            .unwrap();
6873        let schedule_b = rt
6874            .create_note(
6875                &tok,
6876                "scheduled_event",
6877                None,
6878                "stats()",
6879                None,
6880                Some(serde_json::json!({
6881                    "event_type": "schedule",
6882                    "payload": "stats()",
6883                    "status": "pending",
6884                    "trigger_at": "2099-01-02T00:00:00Z"
6885                })),
6886                vec![],
6887            )
6888            .await
6889            .unwrap();
6890
6891        let update_error = rt
6892            .update_note(
6893                &tok,
6894                schedule_a.id,
6895                NotePatch::new(
6896                    None,
6897                    None,
6898                    None,
6899                    None,
6900                    Some(serde_json::json!({ "payload": "delete(id=\"victim\")" })),
6901                ),
6902            )
6903            .await
6904            .expect_err("schedule-managed note update must fail");
6905        assert!(
6906            update_error.to_string().contains("schedule-managed"),
6907            "{update_error}"
6908        );
6909
6910        for (into_id, from_id) in [
6911            (schedule_a.id, schedule_b.id),
6912            (schedule_b.id, schedule_a.id),
6913        ] {
6914            let merge_error = rt
6915                .merge_note(
6916                    &tok,
6917                    into_id,
6918                    from_id,
6919                    EntityDedupMergePolicy::PreferFrom,
6920                    ContentMergeStrategy::PreferFrom,
6921                    false,
6922                )
6923                .await
6924                .expect_err("either schedule-managed merge operand must fail");
6925            assert!(
6926                merge_error.to_string().contains("schedule-managed"),
6927                "{merge_error}"
6928            );
6929        }
6930
6931        let store = rt.notes(&tok).unwrap();
6932        for (id, trigger_at) in [
6933            (schedule_a.id, "2099-01-01T00:00:00Z"),
6934            (schedule_b.id, "2099-01-02T00:00:00Z"),
6935        ] {
6936            let note = store
6937                .get_note(id)
6938                .await
6939                .unwrap()
6940                .expect("rejected generic mutation leaves the schedule intact");
6941            assert_eq!(note.properties.as_ref().unwrap()["trigger_at"], trigger_at);
6942        }
6943    }
6944
6945    #[tokio::test]
6946    async fn merge_note_refuses_quarantined_message_in_either_role() {
6947        let rt = rt();
6948        let tok = NamespaceToken::local();
6949        let capability = crate::pack::ChannelIngestCapability { _sealed: () };
6950        let ordinary = rt
6951            .create_note(
6952                &tok,
6953                "message",
6954                None,
6955                "ordinary message",
6956                None,
6957                None,
6958                vec![],
6959            )
6960            .await
6961            .unwrap();
6962        let quarantined = rt
6963            .try_create_note_as_trusted_ingest(
6964                &capability,
6965                &tok,
6966                "message",
6967                None,
6968                "quarantined transport content",
6969                Some(serde_json::json!({"quarantined": true})),
6970            )
6971            .await
6972            .unwrap()
6973            .expect("quarantined insert");
6974
6975        for (into_id, from_id) in [(ordinary.id, quarantined.id), (quarantined.id, ordinary.id)] {
6976            let error = rt
6977                .merge_note(
6978                    &tok,
6979                    into_id,
6980                    from_id,
6981                    EntityDedupMergePolicy::PreferFrom,
6982                    ContentMergeStrategy::Append,
6983                    false,
6984                )
6985                .await
6986                .expect_err("a quarantined message must not merge in either role");
6987            assert!(error.to_string().contains("quarantined"), "{error}");
6988        }
6989
6990        // Neither operand was mutated by the refused merges.
6991        let store = rt.notes(&tok).unwrap();
6992        let kept = store
6993            .get_note(quarantined.id)
6994            .await
6995            .unwrap()
6996            .expect("quarantined note intact");
6997        assert_eq!(
6998            kept.properties.as_ref().unwrap()["quarantined"],
6999            serde_json::json!(true)
7000        );
7001        assert_eq!(kept.content, "quarantined transport content");
7002    }
7003
7004    #[tokio::test]
7005    async fn merge_note_refuses_string_encoded_quarantine_marker() {
7006        let rt = rt();
7007        let tok = NamespaceToken::local();
7008        let capability = crate::pack::ChannelIngestCapability { _sealed: () };
7009        let ordinary = rt
7010            .create_note(
7011                &tok,
7012                "message",
7013                None,
7014                "ordinary message",
7015                None,
7016                None,
7017                vec![],
7018            )
7019            .await
7020            .unwrap();
7021        // Some channel adapters record the marker as the string "true".
7022        let quarantined = rt
7023            .try_create_note_as_trusted_ingest(
7024                &capability,
7025                &tok,
7026                "message",
7027                None,
7028                "string-marked quarantined content",
7029                Some(serde_json::json!({"quarantined": "true"})),
7030            )
7031            .await
7032            .unwrap()
7033            .expect("quarantined insert");
7034
7035        let error = rt
7036            .merge_note(
7037                &tok,
7038                ordinary.id,
7039                quarantined.id,
7040                EntityDedupMergePolicy::PreferFrom,
7041                ContentMergeStrategy::Append,
7042                false,
7043            )
7044            .await
7045            .expect_err("string-encoded quarantine marker must also refuse the merge");
7046        assert!(error.to_string().contains("quarantined"), "{error}");
7047    }
7048
7049    #[tokio::test]
7050    async fn merge_note_still_merges_unquarantined_messages() {
7051        let rt = rt();
7052        let tok = NamespaceToken::local();
7053        let into = rt
7054            .create_note(&tok, "message", None, "into message", None, None, vec![])
7055            .await
7056            .unwrap();
7057        let from = rt
7058            .create_note(&tok, "message", None, "from message", None, None, vec![])
7059            .await
7060            .unwrap();
7061        rt.merge_note(
7062            &tok,
7063            into.id,
7064            from.id,
7065            EntityDedupMergePolicy::PreferInto,
7066            ContentMergeStrategy::Append,
7067            false,
7068        )
7069        .await
7070        .expect("ordinary message merge must still work");
7071    }
7072
7073    #[tokio::test]
7074    async fn merge_note_same_kind_appends_content() {
7075        let rt = rt();
7076        let tok = NamespaceToken::local();
7077        let into = rt
7078            .create_note(
7079                &tok,
7080                "observation",
7081                None,
7082                "Into content",
7083                None,
7084                None,
7085                vec![],
7086            )
7087            .await
7088            .unwrap();
7089        let from = rt
7090            .create_note(
7091                &tok,
7092                "observation",
7093                None,
7094                "From content",
7095                None,
7096                None,
7097                vec![],
7098            )
7099            .await
7100            .unwrap();
7101        let from_id = from.id;
7102
7103        let summary = rt
7104            .merge_note_with_reason(
7105                &tok,
7106                into.id,
7107                from_id,
7108                EntityDedupMergePolicy::PreferInto,
7109                ContentMergeStrategy::Append,
7110                false,
7111                None,
7112            )
7113            .await
7114            .unwrap();
7115
7116        assert_eq!(summary.kept_id, into.id);
7117        assert_eq!(summary.removed_id, from_id);
7118        assert!(summary.content_appended);
7119        assert!(!summary.dry_run);
7120
7121        let from_store = rt.notes(&tok).unwrap();
7122        assert!(
7123            from_store.get_note(from_id).await.unwrap().is_none(),
7124            "merged-from note should be soft-deleted"
7125        );
7126    }
7127
7128    // Note merge must absorb a conflicting edge natural key exactly like entity
7129    // merge does, since both route through the shared EDGE_SYMMETRIC_*_SQL arms.
7130    #[tokio::test]
7131    async fn merge_note_survives_shared_edge_to_third_party() {
7132        use khive_storage::EdgeRelation;
7133        let rt = rt();
7134        let tok = NamespaceToken::local();
7135
7136        let into = rt
7137            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7138            .await
7139            .unwrap();
7140        let from = rt
7141            .create_note(&tok, "observation", None, "From", None, None, vec![])
7142            .await
7143            .unwrap();
7144        let shared = rt
7145            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
7146            .await
7147            .unwrap();
7148
7149        // Both into and from annotate the same shared entity — rewiring from's
7150        // edge onto into during merge produces a duplicate (into, shared,
7151        // annotates) triple, exercising the conflict-probe/delete arms.
7152        rt.link(&tok, into.id, shared.id, EdgeRelation::Annotates, 1.0, None)
7153            .await
7154            .unwrap();
7155        rt.link(&tok, from.id, shared.id, EdgeRelation::Annotates, 1.0, None)
7156            .await
7157            .unwrap();
7158
7159        let summary = rt
7160            .merge_note_with_reason(
7161                &tok,
7162                into.id,
7163                from.id,
7164                EntityDedupMergePolicy::PreferInto,
7165                ContentMergeStrategy::Append,
7166                false,
7167                None,
7168            )
7169            .await
7170            .expect("merge must succeed even when both notes annotate the same entity");
7171
7172        assert_eq!(summary.kept_id, into.id);
7173        assert_eq!(summary.removed_id, from.id);
7174
7175        let into_edges = rt
7176            .list_edges(
7177                &tok,
7178                crate::EdgeListFilter {
7179                    source_id: Some(into.id),
7180                    target_id: Some(shared.id),
7181                    relations: vec![EdgeRelation::Annotates],
7182                    ..Default::default()
7183                },
7184                10,
7185                0,
7186            )
7187            .await
7188            .unwrap();
7189        assert_eq!(
7190            into_edges.len(),
7191            1,
7192            "exactly one live into→shared annotates edge must exist after merge; got: {into_edges:?}"
7193        );
7194    }
7195
7196    #[tokio::test]
7197    async fn merge_note_conflict_records_dropped_edge_and_cascades_annotation() {
7198        let rt = rt();
7199        let tok = NamespaceToken::local();
7200        let into = rt
7201            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7202            .await
7203            .unwrap();
7204        let from = rt
7205            .create_note(&tok, "observation", None, "From", None, None, vec![])
7206            .await
7207            .unwrap();
7208        let annotator = rt
7209            .create_note(
7210                &tok,
7211                "observation",
7212                None,
7213                "edge annotation",
7214                None,
7215                None,
7216                vec![],
7217            )
7218            .await
7219            .unwrap();
7220        let shared = rt
7221            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
7222            .await
7223            .unwrap();
7224
7225        let survivor = rt
7226            .link(
7227                &tok,
7228                into.id,
7229                shared.id,
7230                EdgeRelation::Annotates,
7231                1.0,
7232                Some(serde_json::json!({"source": "survivor"})),
7233            )
7234            .await
7235            .unwrap();
7236        let dropped = rt
7237            .link(
7238                &tok,
7239                from.id,
7240                shared.id,
7241                EdgeRelation::Annotates,
7242                0.4,
7243                Some(serde_json::json!({"source": "dropped"})),
7244            )
7245            .await
7246            .unwrap();
7247        let annotation = rt
7248            .link(
7249                &tok,
7250                annotator.id,
7251                dropped.id.into(),
7252                EdgeRelation::Annotates,
7253                0.8,
7254                Some(serde_json::json!({"why": "duplicate claim"})),
7255            )
7256            .await
7257            .unwrap();
7258        rt.delete_edge(&tok, annotation.id.into(), false)
7259            .await
7260            .unwrap();
7261
7262        let summary = rt
7263            .merge_note(
7264                &tok,
7265                into.id,
7266                from.id,
7267                EntityDedupMergePolicy::PreferInto,
7268                ContentMergeStrategy::Append,
7269                false,
7270            )
7271            .await
7272            .unwrap();
7273
7274        let [conflict] = summary.edge_conflict_preimages.as_slice() else {
7275            panic!(
7276                "expected one note-merge edge conflict, got {:?}",
7277                summary.edge_conflict_preimages
7278            );
7279        };
7280        assert_eq!(conflict.surviving_edge_id, Uuid::from(survivor.id));
7281        assert_eq!(conflict.dropped_edge.id, Uuid::from(dropped.id));
7282        assert_eq!(conflict.dropped_edge.source_id, from.id);
7283        assert_eq!(conflict.dropped_edge.weight, 0.4);
7284        assert_eq!(
7285            conflict.dropped_edge.metadata,
7286            Some(serde_json::json!({"source": "dropped"}))
7287        );
7288        assert_eq!(conflict.incident_edge_preimages.len(), 1);
7289        assert_eq!(
7290            conflict.incident_edge_preimages[0].id,
7291            Uuid::from(annotation.id)
7292        );
7293        assert_eq!(
7294            conflict.incident_edge_preimages[0].metadata,
7295            Some(serde_json::json!({"why": "duplicate claim"}))
7296        );
7297        assert!(
7298            conflict.incident_edge_preimages[0].deleted_at.is_some(),
7299            "the cascade preimage must retain an annotation's tombstone state"
7300        );
7301        assert!(rt
7302            .get_edge_including_deleted(&tok, dropped.id.into())
7303            .await
7304            .unwrap()
7305            .is_none());
7306        assert!(
7307            rt.get_edge_including_deleted(&tok, annotation.id.into())
7308                .await
7309                .unwrap()
7310                .is_none(),
7311            "annotation targeting the dropped edge must be cascaded, not left dangling"
7312        );
7313
7314        let events = rt
7315            .events(&tok)
7316            .unwrap()
7317            .query_events(
7318                khive_storage::EventFilter {
7319                    kinds: vec![EventKind::NoteMerged],
7320                    ..Default::default()
7321                },
7322                khive_storage::types::PageRequest {
7323                    offset: 0,
7324                    limit: 10,
7325                },
7326            )
7327            .await
7328            .unwrap();
7329        assert_eq!(events.items.len(), 1);
7330        assert_eq!(
7331            events.items[0].payload["edge_conflict_preimages"],
7332            serde_json::to_value(&summary.edge_conflict_preimages).unwrap()
7333        );
7334    }
7335
7336    // A dry run must predict the same conflict preimages a committing note
7337    // merge would produce, without deleting or mutating a single row. The
7338    // incident cascade is two levels deep (an annotation on the dropped
7339    // edge, and a nested annotation on that annotation) so the root-to-leaf
7340    // ordering ADR-014 promises is actually exercised, not just a
7341    // one-element vec that trivially satisfies any order. Every row touched
7342    // by the merge — both notes and every edge — is snapshotted before the
7343    // dry run and compared field-for-field against its post-run state.
7344    #[tokio::test]
7345    async fn merge_note_dry_run_conflict_returns_preimages_without_mutating() {
7346        let rt = rt();
7347        let tok = NamespaceToken::local();
7348        let into = rt
7349            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7350            .await
7351            .unwrap();
7352        let from = rt
7353            .create_note(&tok, "observation", None, "From", None, None, vec![])
7354            .await
7355            .unwrap();
7356        let annotator = rt
7357            .create_note(
7358                &tok,
7359                "observation",
7360                None,
7361                "edge annotation",
7362                None,
7363                None,
7364                vec![],
7365            )
7366            .await
7367            .unwrap();
7368        let nested_annotator = rt
7369            .create_note(
7370                &tok,
7371                "observation",
7372                None,
7373                "nested edge annotation",
7374                None,
7375                None,
7376                vec![],
7377            )
7378            .await
7379            .unwrap();
7380        let shared = rt
7381            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
7382            .await
7383            .unwrap();
7384
7385        let survivor = rt
7386            .link(
7387                &tok,
7388                into.id,
7389                shared.id,
7390                EdgeRelation::Annotates,
7391                1.0,
7392                Some(serde_json::json!({"source": "survivor"})),
7393            )
7394            .await
7395            .unwrap();
7396        let dropped = rt
7397            .link(
7398                &tok,
7399                from.id,
7400                shared.id,
7401                EdgeRelation::Annotates,
7402                0.4,
7403                Some(serde_json::json!({"source": "dropped"})),
7404            )
7405            .await
7406            .unwrap();
7407        let annotation = rt
7408            .link(
7409                &tok,
7410                annotator.id,
7411                dropped.id.into(),
7412                EdgeRelation::Annotates,
7413                0.8,
7414                Some(serde_json::json!({"why": "duplicate claim"})),
7415            )
7416            .await
7417            .unwrap();
7418        let nested_annotation = rt
7419            .link(
7420                &tok,
7421                nested_annotator.id,
7422                annotation.id.into(),
7423                EdgeRelation::Annotates,
7424                0.6,
7425                Some(serde_json::json!({"why": "nested duplicate claim"})),
7426            )
7427            .await
7428            .unwrap();
7429        rt.delete_edge(&tok, nested_annotation.id.into(), false)
7430            .await
7431            .unwrap();
7432
7433        let survivor_before = rt
7434            .get_edge_including_deleted(&tok, survivor.id.into())
7435            .await
7436            .unwrap()
7437            .expect("survivor edge exists");
7438        let dropped_before = rt
7439            .get_edge_including_deleted(&tok, dropped.id.into())
7440            .await
7441            .unwrap()
7442            .expect("dropped edge exists");
7443        let annotation_before = rt
7444            .get_edge_including_deleted(&tok, annotation.id.into())
7445            .await
7446            .unwrap()
7447            .expect("annotation edge exists");
7448        let nested_annotation_before = rt
7449            .get_edge_including_deleted(&tok, nested_annotation.id.into())
7450            .await
7451            .unwrap()
7452            .expect("nested annotation edge exists");
7453        let into_before = rt
7454            .get_note_including_deleted(&tok, into.id)
7455            .await
7456            .unwrap()
7457            .expect("into note exists");
7458        let from_before = rt
7459            .get_note_including_deleted(&tok, from.id)
7460            .await
7461            .unwrap()
7462            .expect("from note exists");
7463
7464        let summary = rt
7465            .merge_note(
7466                &tok,
7467                into.id,
7468                from.id,
7469                EntityDedupMergePolicy::PreferInto,
7470                ContentMergeStrategy::Append,
7471                true,
7472            )
7473            .await
7474            .unwrap();
7475
7476        let [conflict] = summary.edge_conflict_preimages.as_slice() else {
7477            panic!(
7478                "expected one note-merge edge conflict from the dry run, got {:?}",
7479                summary.edge_conflict_preimages
7480            );
7481        };
7482        assert_eq!(conflict.surviving_edge_id, Uuid::from(survivor.id));
7483        assert_eq!(conflict.dropped_edge.id, Uuid::from(dropped.id));
7484        assert_eq!(conflict.dropped_edge.source_id, from.id);
7485        assert_eq!(conflict.dropped_edge.weight, 0.4);
7486        // Root-to-leaf order (ADR-014): the direct annotation on the dropped
7487        // edge must precede the annotation nested on top of it.
7488        assert_eq!(conflict.incident_edge_preimages.len(), 2);
7489        assert_eq!(
7490            conflict.incident_edge_preimages[0].id,
7491            Uuid::from(annotation.id)
7492        );
7493        assert!(
7494            conflict.incident_edge_preimages[0].deleted_at.is_none(),
7495            "the direct annotation was never soft-deleted"
7496        );
7497        assert_eq!(
7498            conflict.incident_edge_preimages[1].id,
7499            Uuid::from(nested_annotation.id)
7500        );
7501        assert!(
7502            conflict.incident_edge_preimages[1].deleted_at.is_some(),
7503            "dry-run preimage must retain the nested annotation's tombstone state"
7504        );
7505
7506        let survivor_after = rt
7507            .get_edge_including_deleted(&tok, survivor.id.into())
7508            .await
7509            .unwrap()
7510            .expect("dry run must not delete the survivor edge");
7511        let dropped_after = rt
7512            .get_edge_including_deleted(&tok, dropped.id.into())
7513            .await
7514            .unwrap()
7515            .expect("dry run must not delete the dropped edge");
7516        let annotation_after = rt
7517            .get_edge_including_deleted(&tok, annotation.id.into())
7518            .await
7519            .unwrap()
7520            .expect("dry run must not delete the cascaded annotation");
7521        let nested_annotation_after = rt
7522            .get_edge_including_deleted(&tok, nested_annotation.id.into())
7523            .await
7524            .unwrap()
7525            .expect("dry run must not delete the nested cascaded annotation");
7526        assert_eq!(
7527            serde_json::to_value(&survivor_before).unwrap(),
7528            serde_json::to_value(&survivor_after).unwrap(),
7529            "dry run must not mutate the surviving edge's row at all"
7530        );
7531        assert_eq!(
7532            serde_json::to_value(&dropped_before).unwrap(),
7533            serde_json::to_value(&dropped_after).unwrap(),
7534            "dry run must not mutate the would-be-dropped edge's row at all"
7535        );
7536        assert_eq!(
7537            serde_json::to_value(&annotation_before).unwrap(),
7538            serde_json::to_value(&annotation_after).unwrap(),
7539            "dry run must not mutate the incident annotation's row at all"
7540        );
7541        assert_eq!(
7542            serde_json::to_value(&nested_annotation_before).unwrap(),
7543            serde_json::to_value(&nested_annotation_after).unwrap(),
7544            "dry run must not mutate the nested incident annotation's row at all"
7545        );
7546
7547        let into_after = rt
7548            .get_note_including_deleted(&tok, into.id)
7549            .await
7550            .unwrap()
7551            .expect("into note must remain unmerged after a dry run");
7552        let from_after = rt
7553            .get_note_including_deleted(&tok, from.id)
7554            .await
7555            .unwrap()
7556            .expect("from note must not be deleted by a dry run");
7557        assert_eq!(
7558            serde_json::to_value(&into_before).unwrap(),
7559            serde_json::to_value(&into_after).unwrap(),
7560            "dry run must not mutate the into note's row at all"
7561        );
7562        assert_eq!(
7563            serde_json::to_value(&from_before).unwrap(),
7564            serde_json::to_value(&from_after).unwrap(),
7565            "dry run must not mutate the from note's row at all"
7566        );
7567        assert_eq!(from_after.status, from_before.status);
7568        assert_eq!(from_after.deleted_at, None);
7569
7570        let events = rt
7571            .events(&tok)
7572            .unwrap()
7573            .query_events(
7574                khive_storage::EventFilter {
7575                    kinds: vec![EventKind::NoteMerged],
7576                    ..Default::default()
7577                },
7578                khive_storage::types::PageRequest {
7579                    offset: 0,
7580                    limit: 10,
7581                },
7582            )
7583            .await
7584            .unwrap();
7585        assert!(
7586            events.items.is_empty(),
7587            "a dry run must not record a merge audit event"
7588        );
7589    }
7590
7591    // The rewire contract check must preserve note→note supersedes, supports,
7592    // and refutes — `validate_edge_relation_endpoints` permits any note→note
7593    // pair for these relations, so the merge matcher must too, or a note merge
7594    // deletes valid epistemic/supersession edges.
7595    #[tokio::test]
7596    async fn merge_note_preserves_note_to_note_epistemic_and_supersession_edges() {
7597        use khive_storage::EdgeRelation;
7598        let rt = rt();
7599        let tok = NamespaceToken::local();
7600
7601        let into = rt
7602            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7603            .await
7604            .unwrap();
7605        let from = rt
7606            .create_note(&tok, "observation", None, "From", None, None, vec![])
7607            .await
7608            .unwrap();
7609        let superseded = rt
7610            .create_note(&tok, "observation", None, "Old", None, None, vec![])
7611            .await
7612            .unwrap();
7613        let claim = rt
7614            .create_note(&tok, "insight", None, "Claim", None, None, vec![])
7615            .await
7616            .unwrap();
7617        let counter = rt
7618            .create_note(&tok, "observation", None, "Counter", None, None, vec![])
7619            .await
7620            .unwrap();
7621
7622        // Outgoing from `from` (source rewires) and incoming onto `from`
7623        // (target rewires) — both directions must survive.
7624        rt.link(
7625            &tok,
7626            from.id,
7627            superseded.id,
7628            EdgeRelation::Supersedes,
7629            1.0,
7630            None,
7631        )
7632        .await
7633        .unwrap();
7634        rt.link(&tok, from.id, claim.id, EdgeRelation::Supports, 1.0, None)
7635            .await
7636            .unwrap();
7637        rt.link(&tok, counter.id, from.id, EdgeRelation::Refutes, 1.0, None)
7638            .await
7639            .unwrap();
7640
7641        let summary = rt
7642            .merge_note_with_reason(
7643                &tok,
7644                into.id,
7645                from.id,
7646                EntityDedupMergePolicy::PreferInto,
7647                ContentMergeStrategy::Append,
7648                false,
7649                None,
7650            )
7651            .await
7652            .unwrap();
7653
7654        assert_eq!(
7655            summary.edges_rewired, 3,
7656            "all three note→note edges must be rewired, not contract-dropped"
7657        );
7658        assert_eq!(
7659            summary.edges_contract_skipped, 0,
7660            "no valid note→note supersedes/supports/refutes edge may be dropped"
7661        );
7662
7663        for (src, tgt, rel) in [
7664            (into.id, superseded.id, EdgeRelation::Supersedes),
7665            (into.id, claim.id, EdgeRelation::Supports),
7666            (counter.id, into.id, EdgeRelation::Refutes),
7667        ] {
7668            let edges = rt
7669                .list_edges(
7670                    &tok,
7671                    crate::EdgeListFilter {
7672                        source_id: Some(src),
7673                        target_id: Some(tgt),
7674                        relations: vec![rel],
7675                        ..Default::default()
7676                    },
7677                    10,
7678                    0,
7679                )
7680                .await
7681                .unwrap();
7682            assert_eq!(
7683                edges.len(),
7684                1,
7685                "rewired {rel:?} edge {src}→{tgt} must survive the merge; got {edges:?}"
7686            );
7687        }
7688    }
7689
7690    // Annotates targets may be edges or events — substrates
7691    // `resolve_merge_edge_endpoint` cannot resolve. The contract check must
7692    // exempt annotates BEFORE endpoint resolution, or a note merge deletes
7693    // valid annotates edges pointing at them.
7694    #[tokio::test]
7695    async fn merge_note_preserves_annotates_edges_targeting_edges_and_events() {
7696        use khive_storage::EdgeRelation;
7697        let rt = rt();
7698        let tok = NamespaceToken::local();
7699
7700        // An edge to annotate.
7701        let a = rt
7702            .create_entity(&tok, "concept", None, "A", None, None, vec![])
7703            .await
7704            .unwrap();
7705        let b = rt
7706            .create_entity(&tok, "concept", None, "B", None, None, vec![])
7707            .await
7708            .unwrap();
7709        let annotated_edge = rt
7710            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
7711            .await
7712            .unwrap();
7713
7714        // An event to annotate: a throwaway note merge emits a NoteMerged
7715        // event (creation ops don't emit in this harness).
7716        let scrap_into = rt
7717            .create_note(&tok, "observation", None, "ScrapInto", None, None, vec![])
7718            .await
7719            .unwrap();
7720        let scrap_from = rt
7721            .create_note(&tok, "observation", None, "ScrapFrom", None, None, vec![])
7722            .await
7723            .unwrap();
7724        rt.merge_note_with_reason(
7725            &tok,
7726            scrap_into.id,
7727            scrap_from.id,
7728            EntityDedupMergePolicy::PreferInto,
7729            ContentMergeStrategy::Append,
7730            false,
7731            None,
7732        )
7733        .await
7734        .unwrap();
7735        let events = rt
7736            .events(&tok)
7737            .unwrap()
7738            .query_events(
7739                khive_storage::EventFilter {
7740                    kinds: vec![EventKind::NoteMerged],
7741                    ..Default::default()
7742                },
7743                khive_storage::types::PageRequest {
7744                    offset: 0,
7745                    limit: 1,
7746                },
7747            )
7748            .await
7749            .unwrap();
7750        let annotated_event_id = events.items[0].id;
7751
7752        let into = rt
7753            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7754            .await
7755            .unwrap();
7756        let from = rt
7757            .create_note(&tok, "observation", None, "From", None, None, vec![])
7758            .await
7759            .unwrap();
7760
7761        rt.link(
7762            &tok,
7763            from.id,
7764            annotated_edge.id.0,
7765            EdgeRelation::Annotates,
7766            1.0,
7767            None,
7768        )
7769        .await
7770        .unwrap();
7771        rt.link(
7772            &tok,
7773            from.id,
7774            annotated_event_id,
7775            EdgeRelation::Annotates,
7776            1.0,
7777            None,
7778        )
7779        .await
7780        .unwrap();
7781
7782        let summary = rt
7783            .merge_note_with_reason(
7784                &tok,
7785                into.id,
7786                from.id,
7787                EntityDedupMergePolicy::PreferInto,
7788                ContentMergeStrategy::Append,
7789                false,
7790                None,
7791            )
7792            .await
7793            .unwrap();
7794
7795        assert_eq!(
7796            summary.edges_rewired, 2,
7797            "annotates edges targeting an edge and an event must be rewired"
7798        );
7799        assert_eq!(
7800            summary.edges_contract_skipped, 0,
7801            "no valid annotates edge may be dropped as contract-violating"
7802        );
7803
7804        for tgt in [annotated_edge.id.0, annotated_event_id] {
7805            let edges = rt
7806                .list_edges(
7807                    &tok,
7808                    crate::EdgeListFilter {
7809                        source_id: Some(into.id),
7810                        target_id: Some(tgt),
7811                        relations: vec![EdgeRelation::Annotates],
7812                        ..Default::default()
7813                    },
7814                    10,
7815                    0,
7816                )
7817                .await
7818                .unwrap();
7819            assert_eq!(
7820                edges.len(),
7821                1,
7822                "rewired annotates edge onto target {tgt} must survive the merge; got {edges:?}"
7823            );
7824        }
7825    }
7826
7827    // A note dry-run must predict edges_rewired like the entity path does,
7828    // and must not touch topology.
7829    #[tokio::test]
7830    async fn merge_note_dry_run_predicts_edges_rewired() {
7831        use khive_storage::EdgeRelation;
7832        let rt = rt();
7833        let tok = NamespaceToken::local();
7834        let into = rt
7835            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7836            .await
7837            .unwrap();
7838        let from = rt
7839            .create_note(&tok, "observation", None, "From", None, None, vec![])
7840            .await
7841            .unwrap();
7842        let shared = rt
7843            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
7844            .await
7845            .unwrap();
7846        rt.link(&tok, from.id, shared.id, EdgeRelation::Annotates, 1.0, None)
7847            .await
7848            .unwrap();
7849
7850        let summary = rt
7851            .merge_note_with_reason(
7852                &tok,
7853                into.id,
7854                from.id,
7855                EntityDedupMergePolicy::PreferInto,
7856                ContentMergeStrategy::Append,
7857                true,
7858                None,
7859            )
7860            .await
7861            .unwrap();
7862        assert!(summary.dry_run);
7863        assert_eq!(
7864            summary.edges_rewired, 1,
7865            "note dry-run must predict the rewire count"
7866        );
7867
7868        let from_edges = rt
7869            .list_edges(
7870                &tok,
7871                crate::EdgeListFilter {
7872                    source_id: Some(from.id),
7873                    target_id: Some(shared.id),
7874                    relations: vec![EdgeRelation::Annotates],
7875                    ..Default::default()
7876                },
7877                10,
7878                0,
7879            )
7880            .await
7881            .unwrap();
7882        assert_eq!(from_edges.len(), 1, "dry-run must leave topology untouched");
7883    }
7884
7885    #[tokio::test]
7886    async fn merge_note_different_kinds_rejected() {
7887        let rt = rt();
7888        let tok = NamespaceToken::local();
7889        let into = rt
7890            .create_note(&tok, "observation", None, "Into", None, None, vec![])
7891            .await
7892            .unwrap();
7893        let from = rt
7894            .create_note(&tok, "decision", None, "From", None, None, vec![])
7895            .await
7896            .unwrap();
7897
7898        let result = rt
7899            .merge_note_with_reason(
7900                &tok,
7901                into.id,
7902                from.id,
7903                EntityDedupMergePolicy::PreferInto,
7904                ContentMergeStrategy::Append,
7905                false,
7906                None,
7907            )
7908            .await;
7909        assert!(result.is_err(), "merging different note kinds must fail");
7910    }
7911
7912    #[tokio::test]
7913    async fn merge_note_dry_run_leaves_notes_unchanged() {
7914        let rt = rt();
7915        let tok = NamespaceToken::local();
7916        let into = rt
7917            .create_note(
7918                &tok,
7919                "observation",
7920                None,
7921                "Into content",
7922                None,
7923                None,
7924                vec![],
7925            )
7926            .await
7927            .unwrap();
7928        let from = rt
7929            .create_note(
7930                &tok,
7931                "observation",
7932                None,
7933                "From content",
7934                None,
7935                None,
7936                vec![],
7937            )
7938            .await
7939            .unwrap();
7940        let into_id = into.id;
7941        let from_id = from.id;
7942
7943        let summary = rt
7944            .merge_note_with_reason(
7945                &tok,
7946                into_id,
7947                from_id,
7948                EntityDedupMergePolicy::PreferInto,
7949                ContentMergeStrategy::Append,
7950                true,
7951                None,
7952            )
7953            .await
7954            .unwrap();
7955
7956        assert!(summary.dry_run);
7957
7958        let store = rt.notes(&tok).unwrap();
7959        let into_after = store.get_note(into_id).await.unwrap().unwrap();
7960        let from_after = store.get_note(from_id).await.unwrap().unwrap();
7961        assert_eq!(
7962            into_after.content, "Into content",
7963            "dry_run must not mutate into-note"
7964        );
7965        assert_eq!(
7966            from_after.content, "From content",
7967            "dry_run must not mutate from-note"
7968        );
7969
7970        let events = rt
7971            .events(&tok)
7972            .unwrap()
7973            .query_events(
7974                khive_storage::EventFilter {
7975                    kinds: vec![EventKind::NoteMerged],
7976                    ..Default::default()
7977                },
7978                khive_storage::types::PageRequest {
7979                    offset: 0,
7980                    limit: 10,
7981                },
7982            )
7983            .await
7984            .unwrap();
7985        assert!(
7986            events.items.is_empty(),
7987            "dry_run=true must not append a NoteMerged event"
7988        );
7989    }
7990
7991    // Merging two nameless notes with no embedding model configured: a raw SQL FTS
7992    // INSERT binding &merged_name directly would store SQL NULL for a nameless
7993    // note, while Fts5TextSearch::upsert_document stores an empty string:
7994    // note_fts_scalars must keep the round-trip field-identical.
7995    #[tokio::test]
7996    async fn merge_nameless_notes_fts_document_is_parity_correct() {
7997        use khive_storage::types::TextSearchRequest;
7998
7999        let rt = rt(); // in-memory runtime — no embedding model configured
8000        let tok = NamespaceToken::local();
8001
8002        let into = rt
8003            .create_note(
8004                &tok,
8005                "observation",
8006                None,
8007                "intosentinelzxq body",
8008                None,
8009                Some(serde_json::json!({"src": "into"})),
8010                vec![],
8011            )
8012            .await
8013            .expect("create into-note");
8014        let from = rt
8015            .create_note(
8016                &tok,
8017                "observation",
8018                None,
8019                "fromsentinelzxq body",
8020                None,
8021                None,
8022                vec![],
8023            )
8024            .await
8025            .expect("create from-note");
8026
8027        let into_id = into.id;
8028        let from_id = from.id;
8029
8030        rt.merge_note_with_reason(
8031            &tok,
8032            into_id,
8033            from_id,
8034            EntityDedupMergePolicy::PreferInto,
8035            ContentMergeStrategy::Append,
8036            false,
8037            None,
8038        )
8039        .await
8040        .expect("merge_note must succeed");
8041
8042        let note_store = rt.notes(&tok).expect("note store");
8043        let merged_note = note_store
8044            .get_note(into_id)
8045            .await
8046            .expect("get_note")
8047            .expect("merged note must exist");
8048
8049        let expected = note_fts_document(&merged_note);
8050
8051        let fts = rt.text_for_notes(&tok).expect("FTS store");
8052        let stored = fts
8053            .get_document("local", into_id)
8054            .await
8055            .expect("get_document must not error")
8056            .expect("FTS document must exist after merge");
8057
8058        assert_eq!(stored.subject_id, expected.subject_id, "subject_id");
8059        assert_eq!(
8060            stored.title, expected.title,
8061            "title (None for nameless note)"
8062        );
8063        assert_eq!(stored.body, expected.body, "body");
8064        assert_eq!(stored.namespace, expected.namespace, "namespace");
8065        assert_eq!(stored.kind, expected.kind, "kind");
8066
8067        assert!(
8068            stored.title.is_none(),
8069            "nameless merged note must have title=None in FTS (was NULL before fix)"
8070        );
8071
8072        // The merged note must be searchable by a unique token from the into-note body.
8073        let hits = fts
8074            .search(TextSearchRequest {
8075                query: "intosentinelzxq".to_string(),
8076                mode: khive_storage::types::TextQueryMode::Plain,
8077                filter: None,
8078                top_k: 10,
8079                snippet_chars: 0,
8080            })
8081            .await
8082            .expect("search");
8083        assert!(
8084            hits.iter().any(|h| h.subject_id == into_id),
8085            "merged note must be searchable by into-note content"
8086        );
8087    }
8088
8089    #[tokio::test]
8090    async fn update_edge_updates_properties() {
8091        use khive_storage::EdgeRelation;
8092        let rt = rt();
8093        let tok = NamespaceToken::local();
8094        let a = rt
8095            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8096            .await
8097            .unwrap();
8098        let b = rt
8099            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8100            .await
8101            .unwrap();
8102        let edge = rt
8103            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.5, None)
8104            .await
8105            .unwrap();
8106        let edge_id: Uuid = edge.id.into();
8107
8108        let updated = rt
8109            .update_edge(
8110                &tok,
8111                edge_id,
8112                EdgePatch {
8113                    properties: Some(serde_json::json!({"source": "manual"})),
8114                    ..Default::default()
8115                },
8116            )
8117            .await
8118            .unwrap();
8119
8120        assert_eq!(updated.metadata.as_ref().unwrap()["source"], "manual");
8121        assert!((updated.weight - 0.5).abs() < 0.001, "weight unchanged");
8122    }
8123
8124    // Merge must not crash when both entities share a common third-party edge
8125    // (duplicate triple after rewire): a double-ON-CONFLICT INSERT would
8126    // otherwise raise a UNIQUE constraint error and abort mid-transaction.
8127    #[tokio::test]
8128    async fn merge_entity_survives_shared_edge_to_third_party() {
8129        use khive_storage::EdgeRelation;
8130        let rt = rt();
8131        let tok = NamespaceToken::local();
8132
8133        // A and B will be merged; shared is the common target. `extends` is used
8134        // since concept→concept is a valid endpoint combination.
8135        let a = rt
8136            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8137            .await
8138            .unwrap();
8139        let b = rt
8140            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8141            .await
8142            .unwrap();
8143        let shared = rt
8144            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
8145            .await
8146            .unwrap();
8147
8148        // Both A and B extend the same shared concept — this creates a duplicate
8149        // triple (A/B → shared, extends) that triggers the crash on rewire.
8150        rt.link(&tok, a.id, shared.id, EdgeRelation::Extends, 1.0, None)
8151            .await
8152            .unwrap();
8153        rt.link(&tok, b.id, shared.id, EdgeRelation::Extends, 1.0, None)
8154            .await
8155            .unwrap();
8156
8157        let summary = rt
8158            .merge_entity_with_reason(
8159                &tok,
8160                a.id,
8161                b.id,
8162                crate::EntityDedupMergePolicy::PreferInto,
8163                ContentMergeStrategy::Append,
8164                false,
8165                None,
8166            )
8167            .await
8168            .expect(
8169                "C1: merge must succeed even when both entities share an edge to a third party",
8170            );
8171
8172        assert_eq!(summary.kept_id, a.id);
8173        assert_eq!(summary.removed_id, b.id);
8174        // A already had the Extends edge to shared; rewiring B->shared onto it
8175        // hits the natural-key conflict arm, which drops the incoming (B-side)
8176        // duplicate rather than erroring or touching A's surviving row (ADR-039
8177        // `ON CONFLICT ... DO NOTHING`). The invariant checked below is that
8178        // exactly one live edge A->shared remains.
8179        let a_edges = rt
8180            .list_edges(
8181                &tok,
8182                crate::EdgeListFilter {
8183                    source_id: Some(a.id),
8184                    target_id: Some(shared.id),
8185                    relations: vec![EdgeRelation::Extends],
8186                    ..Default::default()
8187                },
8188                10,
8189                0,
8190            )
8191            .await
8192            .unwrap();
8193        assert_eq!(
8194            a_edges.len(),
8195            1,
8196            "C1: exactly one live A→shared Extends edge must exist after merge; got: {a_edges:?}"
8197        );
8198
8199        // get_entity filters deleted_at IS NULL, so a tombstoned entity returns None.
8200        let b_after = rt.entities(&tok).unwrap().get_entity(b.id).await.unwrap();
8201        assert!(
8202            b_after.is_none(),
8203            "C3: from_entity must be tombstoned (get_entity returns None for deleted) after merge; got: {b_after:?}"
8204        );
8205    }
8206
8207    // ADR-039 conflict-arm regression (#1191): on a symmetric-edge merge collision,
8208    // the surviving row's own weight/metadata must never be overwritten with the
8209    // incoming (dropped) duplicate's values.
8210    #[tokio::test]
8211    async fn merge_entity_symmetric_conflict_preserves_survivor_fields() {
8212        use khive_storage::EdgeRelation;
8213        let rt = rt();
8214        let tok = NamespaceToken::local();
8215
8216        let a = rt
8217            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8218            .await
8219            .unwrap();
8220        let b = rt
8221            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8222            .await
8223            .unwrap();
8224        let shared = rt
8225            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
8226            .await
8227            .unwrap();
8228
8229        let survivor_edge = rt
8230            .link(
8231                &tok,
8232                a.id,
8233                shared.id,
8234                EdgeRelation::Extends,
8235                1.0,
8236                Some(serde_json::json!({"source": "survivor"})),
8237            )
8238            .await
8239            .unwrap();
8240        rt.link(
8241            &tok,
8242            b.id,
8243            shared.id,
8244            EdgeRelation::Extends,
8245            0.3,
8246            Some(serde_json::json!({"source": "loser"})),
8247        )
8248        .await
8249        .unwrap();
8250
8251        rt.merge_entity_with_reason(
8252            &tok,
8253            a.id,
8254            b.id,
8255            crate::EntityDedupMergePolicy::PreferInto,
8256            ContentMergeStrategy::Append,
8257            false,
8258            None,
8259        )
8260        .await
8261        .expect("merge must succeed across the symmetric-edge collision");
8262
8263        let after = rt
8264            .get_edge(&tok, survivor_edge.id.into())
8265            .await
8266            .unwrap()
8267            .expect("survivor edge must still exist after merge");
8268        assert!(
8269            (after.weight - 1.0).abs() < 0.001,
8270            "survivor weight must be untouched by the dropped duplicate; got {}",
8271            after.weight
8272        );
8273        assert_eq!(
8274            after.metadata.as_ref().unwrap()["source"],
8275            "survivor",
8276            "survivor metadata must be untouched by the dropped duplicate; got {:?}",
8277            after.metadata
8278        );
8279    }
8280
8281    // ADR-039 conflict-arm regression (#1191): a soft-deleted survivor row must
8282    // stay soft-deleted after a merge collision, never resurrected.
8283    #[tokio::test]
8284    async fn merge_entity_symmetric_conflict_does_not_resurrect_soft_deleted_survivor() {
8285        use khive_storage::EdgeRelation;
8286        let rt = rt();
8287        let tok = NamespaceToken::local();
8288
8289        let a = rt
8290            .create_entity(&tok, "concept", None, "A", None, None, vec![])
8291            .await
8292            .unwrap();
8293        let b = rt
8294            .create_entity(&tok, "concept", None, "B", None, None, vec![])
8295            .await
8296            .unwrap();
8297        let shared = rt
8298            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
8299            .await
8300            .unwrap();
8301
8302        let survivor_edge = rt
8303            .link(&tok, a.id, shared.id, EdgeRelation::Extends, 1.0, None)
8304            .await
8305            .unwrap();
8306        rt.delete_edge(&tok, survivor_edge.id.into(), false)
8307            .await
8308            .unwrap();
8309        rt.link(&tok, b.id, shared.id, EdgeRelation::Extends, 0.5, None)
8310            .await
8311            .unwrap();
8312
8313        rt.merge_entity_with_reason(
8314            &tok,
8315            a.id,
8316            b.id,
8317            crate::EntityDedupMergePolicy::PreferInto,
8318            ContentMergeStrategy::Append,
8319            false,
8320            None,
8321        )
8322        .await
8323        .expect("merge must succeed even when the surviving edge is soft-deleted");
8324
8325        let after = rt
8326            .get_edge_including_deleted(&tok, survivor_edge.id.into())
8327            .await
8328            .unwrap()
8329            .expect("survivor edge row must still exist after merge");
8330        assert!(
8331            after.deleted_at.is_some(),
8332            "soft-deleted survivor must stay soft-deleted after merge collision; got: {after:?}"
8333        );
8334    }
8335
8336    // merge_entity at the runtime level must reject cross-kind merges: without this
8337    // guard, a direct runtime caller could merge concept+project, silently
8338    // tombstoning the source entity, even though the pack handler also checks it.
8339    #[tokio::test]
8340    async fn merge_entity_cross_kind_rejected_at_runtime() {
8341        let rt = rt();
8342        let tok = NamespaceToken::local();
8343
8344        let concept = rt
8345            .create_entity(&tok, "concept", None, "H2Concept", None, None, vec![])
8346            .await
8347            .unwrap();
8348        let project = rt
8349            .create_entity(&tok, "project", None, "H2Project", None, None, vec![])
8350            .await
8351            .unwrap();
8352
8353        let err = rt
8354            .merge_entity_with_reason(
8355                &tok,
8356                concept.id,
8357                project.id,
8358                crate::EntityDedupMergePolicy::PreferInto,
8359                ContentMergeStrategy::Append,
8360                false,
8361                None,
8362            )
8363            .await
8364            .expect_err("H2: cross-kind merge must be rejected by runtime");
8365        assert!(
8366            matches!(err, crate::RuntimeError::InvalidInput(_)),
8367            "H2: expected InvalidInput, got: {err:?}"
8368        );
8369
8370        let concept_after = rt.get_entity(&tok, concept.id).await;
8371        let project_after = rt.get_entity(&tok, project.id).await;
8372        assert!(
8373            concept_after.is_ok(),
8374            "H2: concept must remain live after rejected merge; got: {concept_after:?}"
8375        );
8376        assert!(
8377            project_after.is_ok(),
8378            "H2: project must remain live after rejected merge; got: {project_after:?}"
8379        );
8380    }
8381
8382    // Same-kind merge must succeed.
8383    #[tokio::test]
8384    async fn merge_entity_same_kind_succeeds() {
8385        let rt = rt();
8386        let tok = NamespaceToken::local();
8387
8388        let c1 = rt
8389            .create_entity(&tok, "concept", None, "Concept1", None, None, vec![])
8390            .await
8391            .unwrap();
8392        let c2 = rt
8393            .create_entity(&tok, "concept", None, "Concept2", None, None, vec![])
8394            .await
8395            .unwrap();
8396
8397        let summary = rt
8398            .merge_entity_with_reason(
8399                &tok,
8400                c1.id,
8401                c2.id,
8402                crate::EntityDedupMergePolicy::PreferInto,
8403                ContentMergeStrategy::Append,
8404                false,
8405                None,
8406            )
8407            .await
8408            .expect("same-kind merge must succeed");
8409        assert_eq!(summary.kept_id, c1.id);
8410        assert_eq!(summary.removed_id, c2.id);
8411
8412        let c2_after = rt.entities(&tok).unwrap().get_entity(c2.id).await.unwrap();
8413        assert!(c2_after.is_none(), "from_entity must be tombstoned");
8414    }
8415
8416    #[tokio::test]
8417    async fn merge_entity_explicit_policy_rereads_names_before_commit() {
8418        let rt = rt();
8419        let tok = NamespaceToken::local();
8420
8421        let into = rt
8422            .create_entity(
8423                &tok,
8424                "concept",
8425                None,
8426                "Transactional Guard",
8427                None,
8428                None,
8429                vec![],
8430            )
8431            .await
8432            .unwrap();
8433        let from = rt
8434            .create_entity(
8435                &tok,
8436                "concept",
8437                None,
8438                "Transactional Guard",
8439                None,
8440                None,
8441                vec![],
8442            )
8443            .await
8444            .unwrap();
8445
8446        validate_entity_merge_floor(&into, &from)
8447            .expect("the handler's fast-path validation would initially pass");
8448        let renamed_into = rt
8449            .update_entity(
8450                &tok,
8451                into.id,
8452                EntityPatch {
8453                    name: Some("Unrelated Renamed Target".to_string()),
8454                    ..Default::default()
8455                },
8456            )
8457            .await
8458            .unwrap();
8459        let expected = validate_entity_merge_floor(&renamed_into, &from)
8460            .expect_err("the renamed transactional state must violate the name guard");
8461        let RuntimeError::Khive(expected) = entity_merge_guard_error(expected) else {
8462            unreachable!("merge guard errors are structured Khive errors")
8463        };
8464
8465        let err = rt
8466            .merge_entity_with_reason_and_force(
8467                &tok,
8468                into.id,
8469                from.id,
8470                EntityDedupMergePolicy::PreferInto,
8471                ContentMergeStrategy::Append,
8472                false,
8473                None,
8474                false,
8475            )
8476            .await
8477            .expect_err("the explicit non-forced path must validate its transactional reread");
8478        let RuntimeError::Khive(err) = err else {
8479            panic!("expected a structured merge-guard conflict, got {err:?}");
8480        };
8481        assert_eq!(err.kind(), expected.kind());
8482        assert_eq!(err.message(), expected.message());
8483        assert_eq!(err.code(), expected.code());
8484        assert_eq!(err.details(), expected.details());
8485        assert!(
8486            rt.get_entity(&tok, from.id).await.is_ok(),
8487            "a refused merge must leave the source entity live"
8488        );
8489    }
8490
8491    // Cross-namespace merge_note must be denied on either ID.
8492
8493    #[tokio::test]
8494    async fn merge_note_cross_namespace_either_id_returns_not_found() {
8495        use crate::error::RuntimeError;
8496        use crate::Namespace;
8497
8498        let rt = rt();
8499        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8500        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8501
8502        let into_a = rt
8503            .create_note(&ns_a, "observation", None, "Into A", None, None, vec![])
8504            .await
8505            .unwrap();
8506        let from_a = rt
8507            .create_note(&ns_a, "observation", None, "From A", None, None, vec![])
8508            .await
8509            .unwrap();
8510        let note_b = rt
8511            .create_note(&ns_b, "observation", None, "Note B", None, None, vec![])
8512            .await
8513            .unwrap();
8514
8515        // foreign into_id: note_b belongs to ns_b, caller token is ns_a
8516        let foreign_into = rt
8517            .merge_note_with_reason(
8518                &ns_a,
8519                note_b.id,
8520                from_a.id,
8521                EntityDedupMergePolicy::PreferInto,
8522                ContentMergeStrategy::Append,
8523                false,
8524                None,
8525            )
8526            .await;
8527        assert!(
8528            matches!(foreign_into, Err(RuntimeError::NotFound(_))),
8529            "foreign into_id must be denied before merge, got {foreign_into:?}"
8530        );
8531
8532        // foreign from_id: note_b belongs to ns_b, caller token is ns_a
8533        let foreign_from = rt
8534            .merge_note_with_reason(
8535                &ns_a,
8536                into_a.id,
8537                note_b.id,
8538                EntityDedupMergePolicy::PreferInto,
8539                ContentMergeStrategy::Append,
8540                false,
8541                None,
8542            )
8543            .await;
8544        assert!(
8545            matches!(foreign_from, Err(RuntimeError::NotFound(_))),
8546            "foreign from_id must be denied before merge, got {foreign_from:?}"
8547        );
8548    }
8549
8550    // Cross-namespace update now succeeds (shared-brain model).
8551
8552    #[tokio::test]
8553    async fn update_entity_cross_namespace_succeeds() {
8554        use crate::Namespace;
8555
8556        let rt = rt();
8557        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8558        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8559
8560        let entity = rt
8561            .create_entity(
8562                &ns_a,
8563                "concept",
8564                None,
8565                "Alpha",
8566                Some("original"),
8567                None,
8568                vec![],
8569            )
8570            .await
8571            .unwrap();
8572
8573        let result = rt
8574            .update_entity(
8575                &ns_b,
8576                entity.id,
8577                EntityPatch {
8578                    name: Some("Updated".into()),
8579                    ..Default::default()
8580                },
8581            )
8582            .await;
8583
8584        assert!(
8585            result.is_ok(),
8586            "cross-namespace update must succeed in shared-brain OSS; got {result:?}"
8587        );
8588        assert_eq!(result.unwrap().name, "Updated");
8589    }
8590
8591    // merge_entity still requires both entities to be in the same namespace as
8592    // the token's write namespace (enforced at the SQL transaction layer, not the
8593    // runtime layer).  This is a merge-semantic constraint, not tenant isolation.
8594    #[tokio::test]
8595    async fn merge_entity_cross_namespace_ids_fail_at_sql_layer() {
8596        use crate::Namespace;
8597
8598        let rt = rt();
8599        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
8600        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
8601
8602        let into_a = rt
8603            .create_entity(&ns_a, "concept", None, "Into A", None, None, vec![])
8604            .await
8605            .unwrap();
8606        let from_a = rt
8607            .create_entity(&ns_a, "concept", None, "From A", None, None, vec![])
8608            .await
8609            .unwrap();
8610        let foreign_b = rt
8611            .create_entity(&ns_b, "concept", None, "Foreign B", None, None, vec![])
8612            .await
8613            .unwrap();
8614
8615        // foreign into_id: SQL read_merge_entity checks ns matches token namespace.
8616        let foreign_into = rt
8617            .merge_entity_with_reason(
8618                &ns_a,
8619                foreign_b.id,
8620                from_a.id,
8621                EntityDedupMergePolicy::PreferInto,
8622                ContentMergeStrategy::Append,
8623                false,
8624                None,
8625            )
8626            .await;
8627        assert!(
8628            foreign_into.is_err(),
8629            "cross-namespace into_id must still fail at SQL layer; got {foreign_into:?}"
8630        );
8631
8632        // foreign from_id: same SQL constraint.
8633        let foreign_from = rt
8634            .merge_entity_with_reason(
8635                &ns_a,
8636                into_a.id,
8637                foreign_b.id,
8638                EntityDedupMergePolicy::PreferInto,
8639                ContentMergeStrategy::Append,
8640                false,
8641                None,
8642            )
8643            .await;
8644        assert!(
8645            foreign_from.is_err(),
8646            "cross-namespace from_id must still fail at SQL layer; got {foreign_from:?}"
8647        );
8648
8649        // All three entities survive the failed merges.
8650        assert!(rt.get_entity(&ns_a, into_a.id).await.is_ok());
8651        assert!(rt.get_entity(&ns_a, from_a.id).await.is_ok());
8652        assert!(rt.get_entity(&ns_b, foreign_b.id).await.is_ok());
8653    }
8654
8655    // Parity: entity_fts_document must produce the same body/title as the
8656    // create_entity and update_entity FTS write paths.
8657    #[test]
8658    fn entity_fts_document_with_description() {
8659        let mut entity = Entity::new("local", "concept", "MyEntity");
8660        entity = entity.with_description("some description text");
8661        let doc = entity_fts_document(&entity);
8662        assert_eq!(doc.subject_id, entity.id);
8663        assert_eq!(doc.namespace, "local");
8664        assert_eq!(doc.title.as_deref(), Some("MyEntity"));
8665        assert_eq!(doc.body, "MyEntity some description text");
8666        assert_eq!(doc.kind, khive_types::SubstrateKind::Entity);
8667    }
8668
8669    #[test]
8670    fn entity_fts_document_without_description() {
8671        let entity = Entity::new("local", "concept", "NameOnly");
8672        let doc = entity_fts_document(&entity);
8673        assert_eq!(doc.title.as_deref(), Some("NameOnly"));
8674        assert_eq!(doc.body, "NameOnly");
8675    }
8676
8677    #[test]
8678    fn entity_fts_document_empty_description_uses_name_only() {
8679        let mut entity = Entity::new("local", "concept", "TitleOnly");
8680        entity = entity.with_description("");
8681        let doc = entity_fts_document(&entity);
8682        assert_eq!(
8683            doc.body, "TitleOnly",
8684            "empty description must not be appended"
8685        );
8686    }
8687
8688    // Cross-path equality: an entity created through the runtime (operations.rs
8689    // create_entity path) must produce a stored FTS document field-identical to
8690    // entity_fts_document() called on the same Entity.
8691    #[tokio::test]
8692    async fn entity_fts_document_matches_runtime_create_path() {
8693        let rt = rt();
8694        let tok = NamespaceToken::local();
8695
8696        let entity = rt
8697            .create_entity(
8698                &tok,
8699                "concept",
8700                None,
8701                "CrossPathTitle",
8702                Some("cross path description body"),
8703                Some(serde_json::json!({"key": "val"})),
8704                vec!["tag1".to_string()],
8705            )
8706            .await
8707            .expect("create_entity");
8708
8709        let fts = rt.text(&tok).expect("FTS store");
8710        let stored = fts
8711            .get_document("local", entity.id)
8712            .await
8713            .expect("get_document")
8714            .expect("document must exist after create_entity");
8715
8716        let expected = entity_fts_document(&entity);
8717
8718        assert_eq!(stored.subject_id, expected.subject_id, "subject_id");
8719        assert_eq!(stored.kind, expected.kind, "kind");
8720        assert_eq!(stored.title, expected.title, "title");
8721        assert_eq!(stored.body, expected.body, "body");
8722        assert_eq!(stored.namespace, expected.namespace, "namespace");
8723    }
8724
8725    // Cross-path equality: update_entity must produce a stored FTS document
8726    // field-identical to entity_fts_document() on the updated Entity.
8727    #[tokio::test]
8728    async fn entity_fts_document_matches_runtime_update_path() {
8729        let rt = rt();
8730        let tok = NamespaceToken::local();
8731
8732        let entity = rt
8733            .create_entity(
8734                &tok,
8735                "concept",
8736                None,
8737                "OldName",
8738                Some("old desc"),
8739                None,
8740                vec![],
8741            )
8742            .await
8743            .expect("create_entity");
8744
8745        let updated = rt
8746            .update_entity(
8747                &tok,
8748                entity.id,
8749                EntityPatch {
8750                    name: Some("NewName".to_string()),
8751                    description: Some(Some("new desc".to_string())),
8752                    ..Default::default()
8753                },
8754            )
8755            .await
8756            .expect("update_entity");
8757
8758        let fts = rt.text(&tok).expect("FTS store");
8759        let stored = fts
8760            .get_document("local", updated.id)
8761            .await
8762            .expect("get_document")
8763            .expect("document must exist after update_entity");
8764
8765        let expected = entity_fts_document(&updated);
8766
8767        assert_eq!(stored.title, expected.title, "title after update");
8768        assert_eq!(stored.body, expected.body, "body after update");
8769    }
8770
8771    // Verify that merge_entity / merge_note delete from_id vectors from ALL
8772    // registered model vec tables, not just the default-model table. Uses the
8773    // same ConstVecProvider/ConstVecService pattern as operations.rs so no
8774    // real model files are required.
8775
8776    struct MergeTestVecService {
8777        dims: usize,
8778    }
8779
8780    #[async_trait::async_trait]
8781    impl lattice_embed::EmbeddingService for MergeTestVecService {
8782        async fn embed(
8783            &self,
8784            texts: &[String],
8785            _model: lattice_embed::EmbeddingModel,
8786        ) -> std::result::Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
8787            Ok(texts.iter().map(|_| vec![1.0_f32; self.dims]).collect())
8788        }
8789
8790        fn supports_model(&self, _model: lattice_embed::EmbeddingModel) -> bool {
8791            true
8792        }
8793
8794        fn name(&self) -> &'static str {
8795            "merge-test-const-vec"
8796        }
8797    }
8798
8799    struct MergeTestVecProvider {
8800        provider_name: String,
8801        dims: usize,
8802    }
8803
8804    impl MergeTestVecProvider {
8805        fn new(name: &str, dims: usize) -> Self {
8806            Self {
8807                provider_name: name.to_owned(),
8808                dims,
8809            }
8810        }
8811    }
8812
8813    #[async_trait::async_trait]
8814    impl crate::embedder_registry::EmbedderProvider for MergeTestVecProvider {
8815        fn name(&self) -> &str {
8816            &self.provider_name
8817        }
8818
8819        fn dimensions(&self) -> usize {
8820            self.dims
8821        }
8822
8823        async fn build(
8824            &self,
8825        ) -> crate::error::RuntimeResult<std::sync::Arc<dyn lattice_embed::EmbeddingService>>
8826        {
8827            Ok(std::sync::Arc::new(MergeTestVecService { dims: self.dims }))
8828        }
8829    }
8830
8831    #[tokio::test]
8832    async fn entity_reindex_with_captured_merge_plan_excludes_late_model() {
8833        const DIMS: usize = 4;
8834        const PLANNED: &str = "merge-entity-plan-existing";
8835        const LATE: &str = "merge-entity-plan-late";
8836        let rt = KhiveRuntime::memory().unwrap();
8837        let ns = crate::Namespace::parse("merge-entity-plan-snapshot").unwrap();
8838        let tok = NamespaceToken::for_namespace(ns);
8839        let entity = rt
8840            .create_entity(
8841                &tok,
8842                "concept",
8843                None,
8844                "CapturedEntityPlan",
8845                Some("full source remains indexed"),
8846                None,
8847                vec![],
8848            )
8849            .await
8850            .expect("create entity before registering embedders");
8851
8852        rt.register_embedder(MergeTestVecProvider::new(PLANNED, DIMS));
8853        let embedding_plan = EmbeddingModelPlan::capture(&rt);
8854        rt.register_embedder(MergeTestVecProvider::new(LATE, DIMS));
8855
8856        rt.reindex_entity_with_plan(&tok, &entity, &embedding_plan)
8857            .await
8858            .expect("reindex entity with captured merge plan");
8859
8860        assert_eq!(embedding_plan.model_names().len(), 1);
8861        assert_eq!(embedding_plan.model_names()[0].as_str(), PLANNED);
8862        assert_eq!(
8863            rt.vectors_for_model(&tok, PLANNED)
8864                .unwrap()
8865                .count()
8866                .await
8867                .unwrap(),
8868            1
8869        );
8870        assert_eq!(
8871            rt.vectors_for_model(&tok, LATE)
8872                .unwrap()
8873                .count()
8874                .await
8875                .unwrap(),
8876            0,
8877            "a provider registered after plan capture must not join survivor reindex"
8878        );
8879    }
8880
8881    #[tokio::test]
8882    async fn note_reindex_with_captured_merge_plan_excludes_late_model() {
8883        const DIMS: usize = 4;
8884        const PLANNED: &str = "merge-note-plan-existing";
8885        const LATE: &str = "merge-note-plan-late";
8886        let rt = KhiveRuntime::memory().unwrap();
8887        let ns = crate::Namespace::parse("merge-note-plan-snapshot").unwrap();
8888        let tok = NamespaceToken::for_namespace(ns);
8889        let note = rt
8890            .create_note(
8891                &tok,
8892                "observation",
8893                None,
8894                "full note source remains indexed",
8895                None,
8896                None,
8897                vec![],
8898            )
8899            .await
8900            .expect("create note before registering embedders");
8901
8902        rt.register_embedder(MergeTestVecProvider::new(PLANNED, DIMS));
8903        let embedding_plan = EmbeddingModelPlan::capture(&rt);
8904        rt.register_embedder(MergeTestVecProvider::new(LATE, DIMS));
8905
8906        rt.reindex_note_with_plan(&tok, &note, &embedding_plan)
8907            .await
8908            .expect("reindex note with captured merge plan");
8909
8910        assert_eq!(embedding_plan.model_names().len(), 1);
8911        assert_eq!(embedding_plan.model_names()[0].as_str(), PLANNED);
8912        assert_eq!(
8913            rt.vectors_for_model(&tok, PLANNED)
8914                .unwrap()
8915                .count()
8916                .await
8917                .unwrap(),
8918            1
8919        );
8920        assert_eq!(
8921            rt.vectors_for_model(&tok, LATE)
8922                .unwrap()
8923                .count()
8924                .await
8925                .unwrap(),
8926            0,
8927            "a provider registered after plan capture must not join survivor reindex"
8928        );
8929    }
8930
8931    /// merge_entity must delete from_id vectors from ALL registered model tables.
8932    ///
8933    /// Two custom embedders ("merge-vec-a", "merge-vec-b") are registered.  Both
8934    /// entities are embedded so each has a row in both model tables.  After merge,
8935    /// from_id must have zero surviving rows in either table.
8936    #[tokio::test]
8937    async fn merge_entity_clears_vectors_from_all_registered_models() {
8938        const DIMS: usize = 4;
8939        let rt = KhiveRuntime::memory().unwrap();
8940        rt.register_embedder(MergeTestVecProvider::new("merge-vec-a", DIMS));
8941        rt.register_embedder(MergeTestVecProvider::new("merge-vec-b", DIMS));
8942
8943        let ns_str = "merge-entity-vec-cleanup";
8944        let ns = crate::Namespace::parse(ns_str).unwrap();
8945        let tok = NamespaceToken::for_namespace(ns);
8946
8947        let into_e = rt
8948            .create_entity(
8949                &tok,
8950                "concept",
8951                None,
8952                "IntoVecEntity",
8953                Some("desc a"),
8954                None,
8955                vec![],
8956            )
8957            .await
8958            .expect("create into");
8959        let from_e = rt
8960            .create_entity(
8961                &tok,
8962                "concept",
8963                None,
8964                "FromVecEntity",
8965                Some("desc b"),
8966                None,
8967                vec![],
8968            )
8969            .await
8970            .expect("create from");
8971
8972        // Confirm both entities have vectors in both model tables before merge.
8973        let vs_a = rt.vectors_for_model(&tok, "merge-vec-a").unwrap();
8974        let vs_b = rt.vectors_for_model(&tok, "merge-vec-b").unwrap();
8975        use khive_storage::types::VectorSearchRequest;
8976        let query = vec![1.0_f32; DIMS];
8977        let pre_a = vs_a
8978            .search(VectorSearchRequest {
8979                query_vectors: vec![query.clone()],
8980                top_k: 100,
8981                namespace: Some(ns_str.to_string()),
8982                kind: Some(khive_types::SubstrateKind::Entity),
8983                embedding_model: Some("merge-vec-a".to_string()),
8984                filter: None,
8985                backend_hints: None,
8986            })
8987            .await
8988            .unwrap();
8989        assert!(
8990            pre_a.iter().any(|h| h.subject_id == into_e.id)
8991                && pre_a.iter().any(|h| h.subject_id == from_e.id),
8992            "both entities must be in model-a before merge; got {pre_a:?}"
8993        );
8994
8995        // model-b must ALSO hold both entities pre-merge, else the post-merge
8996        // model-b emptiness check below is vacuous (nothing to delete).
8997        let pre_b = vs_b
8998            .search(VectorSearchRequest {
8999                query_vectors: vec![query.clone()],
9000                top_k: 100,
9001                namespace: Some(ns_str.to_string()),
9002                kind: Some(khive_types::SubstrateKind::Entity),
9003                embedding_model: Some("merge-vec-b".to_string()),
9004                filter: None,
9005                backend_hints: None,
9006            })
9007            .await
9008            .unwrap();
9009        assert!(
9010            pre_b.iter().any(|h| h.subject_id == into_e.id)
9011                && pre_b.iter().any(|h| h.subject_id == from_e.id),
9012            "both entities must be in model-b before merge; got {pre_b:?}"
9013        );
9014
9015        rt.merge_entity_with_reason(
9016            &tok,
9017            into_e.id,
9018            from_e.id,
9019            EntityDedupMergePolicy::PreferInto,
9020            ContentMergeStrategy::Append,
9021            false,
9022            None,
9023        )
9024        .await
9025        .expect("merge_entity");
9026
9027        let post_a = vs_a
9028            .search(VectorSearchRequest {
9029                query_vectors: vec![query.clone()],
9030                top_k: 100,
9031                namespace: Some(ns_str.to_string()),
9032                kind: Some(khive_types::SubstrateKind::Entity),
9033                embedding_model: Some("merge-vec-a".to_string()),
9034                filter: None,
9035                backend_hints: None,
9036            })
9037            .await
9038            .unwrap();
9039        let from_ids_a: Vec<_> = post_a
9040            .iter()
9041            .filter(|h| h.subject_id == from_e.id)
9042            .collect();
9043        assert!(
9044            from_ids_a.is_empty(),
9045            "from_id must have no vectors in model-a after merge; got {from_ids_a:?}"
9046        );
9047
9048        let post_b = vs_b
9049            .search(VectorSearchRequest {
9050                query_vectors: vec![query],
9051                top_k: 100,
9052                namespace: Some(ns_str.to_string()),
9053                kind: Some(khive_types::SubstrateKind::Entity),
9054                embedding_model: Some("merge-vec-b".to_string()),
9055                filter: None,
9056                backend_hints: None,
9057            })
9058            .await
9059            .unwrap();
9060        let from_ids_b: Vec<_> = post_b
9061            .iter()
9062            .filter(|h| h.subject_id == from_e.id)
9063            .collect();
9064        assert!(
9065            from_ids_b.is_empty(),
9066            "from_id must have no vectors in model-b after merge; got {from_ids_b:?}"
9067        );
9068    }
9069
9070    /// merge_note must delete from_id vectors from ALL registered model tables.
9071    ///
9072    /// Two custom embedders ("merge-note-vec-a", "merge-note-vec-b") are registered.
9073    /// Both notes are embedded so each has a row in both model tables.  After merge,
9074    /// from_id must have zero surviving rows in either table.
9075    #[tokio::test]
9076    async fn merge_note_clears_vectors_from_all_registered_models() {
9077        const DIMS: usize = 4;
9078        let rt = KhiveRuntime::memory().unwrap();
9079        rt.register_embedder(MergeTestVecProvider::new("merge-note-vec-a", DIMS));
9080        rt.register_embedder(MergeTestVecProvider::new("merge-note-vec-b", DIMS));
9081
9082        let ns_str = "merge-note-vec-cleanup";
9083        let ns = crate::Namespace::parse(ns_str).unwrap();
9084        let tok = NamespaceToken::for_namespace(ns);
9085
9086        let into_n = rt
9087            .create_note(
9088                &tok,
9089                "observation",
9090                None,
9091                "IntoVecNote content",
9092                None,
9093                None,
9094                vec![],
9095            )
9096            .await
9097            .expect("create into note");
9098        let from_n = rt
9099            .create_note(
9100                &tok,
9101                "observation",
9102                None,
9103                "FromVecNote content",
9104                None,
9105                None,
9106                vec![],
9107            )
9108            .await
9109            .expect("create from note");
9110
9111        let vs_a = rt.vectors_for_model(&tok, "merge-note-vec-a").unwrap();
9112        let vs_b = rt.vectors_for_model(&tok, "merge-note-vec-b").unwrap();
9113        use khive_storage::types::VectorSearchRequest;
9114        let query = vec![1.0_f32; DIMS];
9115
9116        let pre_a = vs_a
9117            .search(VectorSearchRequest {
9118                query_vectors: vec![query.clone()],
9119                top_k: 100,
9120                namespace: Some(ns_str.to_string()),
9121                kind: Some(khive_types::SubstrateKind::Note),
9122                embedding_model: Some("merge-note-vec-a".to_string()),
9123                filter: None,
9124                backend_hints: None,
9125            })
9126            .await
9127            .unwrap();
9128        assert!(
9129            pre_a.iter().any(|h| h.subject_id == into_n.id)
9130                && pre_a.iter().any(|h| h.subject_id == from_n.id),
9131            "both notes must be in model-a before merge; got {pre_a:?}"
9132        );
9133
9134        // model-b must ALSO hold both notes pre-merge, else the post-merge
9135        // model-b emptiness check below is vacuous (nothing to delete).
9136        let pre_b = vs_b
9137            .search(VectorSearchRequest {
9138                query_vectors: vec![query.clone()],
9139                top_k: 100,
9140                namespace: Some(ns_str.to_string()),
9141                kind: Some(khive_types::SubstrateKind::Note),
9142                embedding_model: Some("merge-note-vec-b".to_string()),
9143                filter: None,
9144                backend_hints: None,
9145            })
9146            .await
9147            .unwrap();
9148        assert!(
9149            pre_b.iter().any(|h| h.subject_id == into_n.id)
9150                && pre_b.iter().any(|h| h.subject_id == from_n.id),
9151            "both notes must be in model-b before merge; got {pre_b:?}"
9152        );
9153
9154        rt.merge_note_with_reason(
9155            &tok,
9156            into_n.id,
9157            from_n.id,
9158            EntityDedupMergePolicy::PreferInto,
9159            ContentMergeStrategy::PreferInto,
9160            false,
9161            None,
9162        )
9163        .await
9164        .expect("merge_note");
9165
9166        let post_a = vs_a
9167            .search(VectorSearchRequest {
9168                query_vectors: vec![query.clone()],
9169                top_k: 100,
9170                namespace: Some(ns_str.to_string()),
9171                kind: Some(khive_types::SubstrateKind::Note),
9172                embedding_model: Some("merge-note-vec-a".to_string()),
9173                filter: None,
9174                backend_hints: None,
9175            })
9176            .await
9177            .unwrap();
9178        let from_ids_a: Vec<_> = post_a
9179            .iter()
9180            .filter(|h| h.subject_id == from_n.id)
9181            .collect();
9182        assert!(
9183            from_ids_a.is_empty(),
9184            "from_id must have no vectors in model-a after merge; got {from_ids_a:?}"
9185        );
9186
9187        let post_b = vs_b
9188            .search(VectorSearchRequest {
9189                query_vectors: vec![query],
9190                top_k: 100,
9191                namespace: Some(ns_str.to_string()),
9192                kind: Some(khive_types::SubstrateKind::Note),
9193                embedding_model: Some("merge-note-vec-b".to_string()),
9194                filter: None,
9195                backend_hints: None,
9196            })
9197            .await
9198            .unwrap();
9199        let from_ids_b: Vec<_> = post_b
9200            .iter()
9201            .filter(|h| h.subject_id == from_n.id)
9202            .collect();
9203        assert!(
9204            from_ids_b.is_empty(),
9205            "from_id must have no vectors in model-b after merge; got {from_ids_b:?}"
9206        );
9207    }
9208
9209    // Cross-path equality: merge_entity must produce a stored FTS document for
9210    // the kept entity that is field-identical to entity_fts_document().
9211    #[tokio::test]
9212    async fn entity_fts_document_matches_runtime_merge_path() {
9213        let rt = rt();
9214        let tok = NamespaceToken::local();
9215
9216        let into_e = rt
9217            .create_entity(
9218                &tok,
9219                "concept",
9220                None,
9221                "IntoEntity",
9222                Some("into desc"),
9223                None,
9224                vec![],
9225            )
9226            .await
9227            .expect("create into");
9228        let from_e = rt
9229            .create_entity(
9230                &tok,
9231                "concept",
9232                None,
9233                "FromEntity",
9234                Some("from desc"),
9235                None,
9236                vec![],
9237            )
9238            .await
9239            .expect("create from");
9240
9241        let summary = rt
9242            .merge_entity_with_reason(
9243                &tok,
9244                into_e.id,
9245                from_e.id,
9246                EntityDedupMergePolicy::PreferInto,
9247                ContentMergeStrategy::Append,
9248                false,
9249                None,
9250            )
9251            .await
9252            .expect("merge_entity");
9253
9254        let kept = rt
9255            .get_entity(&tok, summary.kept_id)
9256            .await
9257            .expect("get kept");
9258
9259        let fts = rt.text(&tok).expect("FTS store");
9260        let stored = fts
9261            .get_document("local", kept.id)
9262            .await
9263            .expect("get_document")
9264            .expect("FTS document must exist for kept entity after merge");
9265
9266        let expected = entity_fts_document(&kept);
9267
9268        assert_eq!(stored.title, expected.title, "title after merge");
9269        assert_eq!(stored.body, expected.body, "body after merge");
9270    }
9271
9272    /// The recomputed `properties_merged` count must agree with the fold on
9273    /// whole-value replacement.
9274    ///
9275    /// `merge_json` scores a `PreferFrom` replace of one properties value by a
9276    /// differently-shaped one as a single contribution. An earlier version of
9277    /// `count_new_property_keys` returned 0 for that shape, which under-reported
9278    /// every such merge — including on note kinds with no owner-established
9279    /// properties, which never enter the restoration path and were being counted
9280    /// correctly before the recompute was introduced. Measured at the time:
9281    /// fold=1, recompute=0, on both orderings.
9282    ///
9283    /// The flat-overwrite control is load-bearing: it is what distinguishes this
9284    /// test from one that a function returning 1 unconditionally would also pass.
9285    #[test]
9286    fn recomputed_count_agrees_with_fold_on_whole_value_replacement() {
9287        use serde_json::json;
9288
9289        for (into, from, label) in [
9290            (json!({"a": 1}), json!(5), "object replaced by scalar"),
9291            (
9292                json!(7),
9293                json!({"b": 2}),
9294                "scalar replaced by single-key object",
9295            ),
9296            // A whole-value replacement is ONE contribution however many keys
9297            // the replacing object carries. The single-key vector above cannot
9298            // see the difference between that rule and counting the object's
9299            // keys, so it stayed green while the count was wrong for ordinary
9300            // notes. This vector is the one that distinguishes them.
9301            (
9302                json!(7),
9303                json!({"b": 2, "c": 3}),
9304                "scalar replaced by multi-key object",
9305            ),
9306        ] {
9307            let (merged, fold_count) = merge_json(&into, &from, EntityDedupMergePolicy::PreferFrom);
9308            let recomputed = count_new_property_keys(
9309                Some(&into),
9310                Some(&merged),
9311                EntityDedupMergePolicy::PreferFrom,
9312            );
9313            assert_eq!(
9314                recomputed, fold_count,
9315                "{label}: recomputed count must match the fold's own count",
9316            );
9317            assert_eq!(recomputed, 1, "{label}: one value was contributed");
9318        }
9319
9320        // Control: an ordinary overwrite of an existing key contributes nothing
9321        // under BOTH rules. Without this arm, a function returning 1 for every
9322        // differing pair would pass the loop above.
9323        let (merged, fold_count) = merge_json(
9324            &json!({"a": 1}),
9325            &json!({"a": 2}),
9326            EntityDedupMergePolicy::PreferFrom,
9327        );
9328        let recomputed = count_new_property_keys(
9329            Some(&json!({"a": 1})),
9330            Some(&merged),
9331            EntityDedupMergePolicy::PreferFrom,
9332        );
9333        assert_eq!(fold_count, 0, "control: overwrite is never a fold addition");
9334        assert_eq!(recomputed, 0, "control: overwrite is never a new key");
9335
9336        // Control: equal values mean nothing was contributed (the `from` note
9337        // carrying no properties at all).
9338        assert_eq!(
9339            count_new_property_keys(
9340                Some(&json!({"a": 1})),
9341                Some(&json!({"a": 1})),
9342                EntityDedupMergePolicy::PreferFrom,
9343            ),
9344            0,
9345            "control: an unchanged properties object contributes nothing",
9346        );
9347    }
9348
9349    /// Recursion into a same-named nested object is only correct under `Union`.
9350    ///
9351    /// `merge_json` descends into a nested object ONLY for `Union`. Under
9352    /// `PreferFrom` an existing top-level key is replaced wholesale and under
9353    /// `PreferInto` it is kept wholesale, so nothing is merged beneath that key
9354    /// and nothing beneath it may be counted. An earlier version of the
9355    /// recomputation recursed unconditionally and reported 1 for the
9356    /// `PreferFrom` case below, where one existing property was replaced and
9357    /// none was added. This affects ordinary notes with no owner-established
9358    /// properties, which never reach the restoration path at all.
9359    #[test]
9360    fn recomputed_count_recurses_into_nested_objects_only_under_union() {
9361        use serde_json::json;
9362
9363        let into = json!({"meta": {"old": 1}});
9364        let from = json!({"meta": {"new": 2}});
9365
9366        for (strategy, expected, label) in [
9367            (
9368                EntityDedupMergePolicy::PreferFrom,
9369                0,
9370                "prefer_from replaces the whole key",
9371            ),
9372            (
9373                EntityDedupMergePolicy::PreferInto,
9374                0,
9375                "prefer_into keeps the whole key",
9376            ),
9377            (
9378                EntityDedupMergePolicy::Union,
9379                1,
9380                "union merges beneath the key",
9381            ),
9382        ] {
9383            let (merged, fold_count) = merge_json(&into, &from, strategy);
9384            let recomputed = count_new_property_keys(Some(&into), Some(&merged), strategy);
9385            assert_eq!(
9386                recomputed, fold_count,
9387                "{label}: recomputed count must match the fold's own count",
9388            );
9389            assert_eq!(recomputed, expected, "{label}");
9390        }
9391    }
9392
9393    /// An object emptied by restoration contributed nothing, and the count must
9394    /// say so.
9395    ///
9396    /// When the surviving record's properties were not an object and the fold
9397    /// installed the from-note's object, restoration removes the owner keys the
9398    /// survivor never had — which can leave `{}`. Scoring that as a whole-value
9399    /// replacement would report 1 for a record holding no properties at all.
9400    #[test]
9401    fn recomputed_count_is_zero_when_restoration_empties_the_object() {
9402        use serde_json::json;
9403
9404        assert_eq!(
9405            count_new_property_keys(
9406                Some(&json!("scalar-properties")),
9407                Some(&json!({})),
9408                EntityDedupMergePolicy::PreferFrom,
9409            ),
9410            0,
9411            "an emptied object retains nothing from the absorbed record",
9412        );
9413
9414        // Control: the same shape with a surviving key counts that key, so the
9415        // arm above is not simply returning 0 for every non-object original.
9416        assert_eq!(
9417            count_new_property_keys(
9418                Some(&json!("scalar-properties")),
9419                Some(&json!({"kept": 1})),
9420                EntityDedupMergePolicy::PreferFrom,
9421            ),
9422            1,
9423            "a surviving key is still counted",
9424        );
9425    }
9426
9427    // ---- merge transaction budget tests ----
9428
9429    /// Run `merge_entity_sql` directly on the writer connection with explicit
9430    /// limits, mapping the two-variant error the way the production fallback
9431    /// path does. The budget refusal must surface as the SQLite-side error
9432    /// whose message carries the observed counts.
9433    async fn run_entity_merge_with_limits(
9434        rt: &KhiveRuntime,
9435        into_id: Uuid,
9436        from_id: Uuid,
9437        limits: MergeTxLimits,
9438    ) -> Result<(MergeSummary, Entity), SqliteError> {
9439        let pack_rules = rt.pack_edge_rules();
9440        let pool = rt.backend().pool_arc();
9441        tokio::task::spawn_blocking(move || {
9442            let guard = pool.writer().unwrap();
9443            guard.transaction(|conn| {
9444                merge_entity_sql(
9445                    conn,
9446                    "local".to_string(),
9447                    "fts_entities".to_string(),
9448                    Vec::new(),
9449                    into_id,
9450                    from_id,
9451                    EntityDedupMergePolicy::PreferInto,
9452                    ContentMergeStrategy::Append,
9453                    false,
9454                    pack_rules,
9455                    EntityMergeValidation::LegacyKind,
9456                    limits,
9457                )
9458                .map_err(|error| match error {
9459                    MergeEntitySqlError::Sqlite(error) => error,
9460                    MergeEntitySqlError::Refusal(_) => SqliteError::InvalidData(
9461                        "unexpected transactional policy refusal".to_string(),
9462                    ),
9463                })
9464            })
9465        })
9466        .await
9467        .unwrap()
9468    }
9469
9470    /// Preview-only variant of [`run_entity_merge_with_limits`]: runs
9471    /// `merge_entity_sql` with `dry_run = true` and an unlimited budget, and
9472    /// returns the observed byte charge without committing any write. Lets a
9473    /// test read back the probe's true cost for a record and then reuse that
9474    /// exact number to place a tight `MergeTxLimits` threshold, instead of
9475    /// guessing at fanout/overhead constants.
9476    async fn preview_entity_merge_bytes(rt: &KhiveRuntime, into_id: Uuid, from_id: Uuid) -> usize {
9477        let pack_rules = rt.pack_edge_rules();
9478        let pool = rt.backend().pool_arc();
9479        let (summary, _) = tokio::task::spawn_blocking(move || {
9480            let guard = pool.writer().unwrap();
9481            guard.transaction(|conn| {
9482                merge_entity_sql(
9483                    conn,
9484                    "local".to_string(),
9485                    "fts_entities".to_string(),
9486                    Vec::new(),
9487                    into_id,
9488                    from_id,
9489                    EntityDedupMergePolicy::PreferInto,
9490                    ContentMergeStrategy::Append,
9491                    true,
9492                    pack_rules,
9493                    EntityMergeValidation::LegacyKind,
9494                    MergeTxLimits {
9495                        max_rows: usize::MAX,
9496                        max_bytes: usize::MAX,
9497                    },
9498                )
9499                .map_err(|error| match error {
9500                    MergeEntitySqlError::Sqlite(error) => error,
9501                    MergeEntitySqlError::Refusal(_) => SqliteError::InvalidData(
9502                        "unexpected transactional policy refusal".to_string(),
9503                    ),
9504                })
9505            })
9506        })
9507        .await
9508        .unwrap()
9509        .unwrap();
9510        summary.tx_budget.bytes_charged
9511    }
9512
9513    /// The byte-budget probe must count actual UTF-8 bytes, not SQLite's
9514    /// `LENGTH(text)` character count. Two records with an identical
9515    /// character count but different UTF-8 byte sizes (an ASCII control vs.
9516    /// a CJK payload, each 200 characters) must charge the budget
9517    /// differently — proving the probe casts to BLOB before measuring —
9518    /// and a budget threshold placed strictly between the two true costs
9519    /// must accept the ASCII control and reject the multibyte payload.
9520    #[tokio::test]
9521    async fn merge_entity_byte_budget_rejects_multibyte_properties_char_count_would_pass() {
9522        let rt = rt();
9523        let tok = NamespaceToken::local();
9524
9525        let ascii_payload = "x".repeat(200);
9526        let multibyte_payload = "\u{4e2d}".repeat(200);
9527        assert_eq!(
9528            ascii_payload.chars().count(),
9529            multibyte_payload.chars().count(),
9530            "control and payload must share one character count"
9531        );
9532        assert!(
9533            multibyte_payload.len() > ascii_payload.len(),
9534            "multibyte payload must have more UTF-8 bytes than the ASCII control"
9535        );
9536
9537        let into_ascii = rt
9538            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
9539            .await
9540            .unwrap();
9541        let from_ascii = rt
9542            .create_entity(
9543                &tok,
9544                "concept",
9545                None,
9546                "From",
9547                None,
9548                Some(serde_json::json!({ "note": ascii_payload })),
9549                vec![],
9550            )
9551            .await
9552            .unwrap();
9553        let into_multi = rt
9554            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
9555            .await
9556            .unwrap();
9557        let from_multi = rt
9558            .create_entity(
9559                &tok,
9560                "concept",
9561                None,
9562                "From",
9563                None,
9564                Some(serde_json::json!({ "note": multibyte_payload })),
9565                vec![],
9566            )
9567            .await
9568            .unwrap();
9569
9570        let ascii_total_bytes = preview_entity_merge_bytes(&rt, into_ascii.id, from_ascii.id).await;
9571        let multi_total_bytes = preview_entity_merge_bytes(&rt, into_multi.id, from_multi.id).await;
9572        assert!(
9573            multi_total_bytes > ascii_total_bytes,
9574            "byte-accurate probe must charge more for the multibyte record: \
9575             ascii={ascii_total_bytes} multi={multi_total_bytes}"
9576        );
9577
9578        // A threshold pinned exactly at the ASCII control's true cost must
9579        // accept it and reject the multibyte record, which a character-
9580        // counting probe would have under-charged into passing too.
9581        let limits = MergeTxLimits {
9582            max_rows: usize::MAX,
9583            max_bytes: ascii_total_bytes,
9584        };
9585
9586        run_entity_merge_with_limits(&rt, into_ascii.id, from_ascii.id, limits)
9587            .await
9588            .expect("ASCII control's true byte cost must fit its own threshold");
9589
9590        let error = run_entity_merge_with_limits(&rt, into_multi.id, from_multi.id, limits)
9591            .await
9592            .unwrap_err();
9593        let msg = error.to_string();
9594        assert!(
9595            msg.contains("merge transaction budget exceeded"),
9596            "multibyte properties must be rejected by the byte-accurate probe; got: {msg}"
9597        );
9598        assert!(msg.contains("reading merge records"), "got: {msg}");
9599        assert!(
9600            rt.get_entity(&tok, from_multi.id).await.is_ok(),
9601            "from-entity must survive a budget-rejected merge"
9602        );
9603    }
9604
9605    async fn run_note_merge_with_limits(
9606        rt: &KhiveRuntime,
9607        into_id: Uuid,
9608        from_id: Uuid,
9609        pack_rules: Vec<khive_types::EdgeEndpointRule>,
9610        limits: MergeTxLimits,
9611    ) -> Result<(MergeSummary, Note), SqliteError> {
9612        let pool = rt.backend().pool_arc();
9613        tokio::task::spawn_blocking(move || {
9614            let guard = pool.writer().unwrap();
9615            guard.transaction(|conn| {
9616                merge_note_sql(
9617                    conn,
9618                    "local".to_string(),
9619                    "fts_notes".to_string(),
9620                    Vec::new(),
9621                    into_id,
9622                    from_id,
9623                    EntityDedupMergePolicy::PreferInto,
9624                    ContentMergeStrategy::Append,
9625                    false,
9626                    pack_rules,
9627                    false,
9628                    limits,
9629                )
9630            })
9631        })
9632        .await
9633        .unwrap()
9634    }
9635
9636    #[tokio::test]
9637    async fn merge_entity_rejects_row_budget_while_collecting_incident_edges() {
9638        use khive_storage::EdgeRelation;
9639        let rt = rt();
9640        let tok = NamespaceToken::local();
9641        let into = rt
9642            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
9643            .await
9644            .unwrap();
9645        let from = rt
9646            .create_entity(&tok, "concept", None, "From", None, None, vec![])
9647            .await
9648            .unwrap();
9649        for name in ["T1", "T2", "T3"] {
9650            let target = rt
9651                .create_entity(&tok, "concept", None, name, None, None, vec![])
9652                .await
9653                .unwrap();
9654            rt.link(&tok, from.id, target.id, EdgeRelation::Extends, 1.0, None)
9655                .await
9656                .unwrap();
9657        }
9658
9659        // Two merge records charge first; the cap of 4 admits the first two
9660        // incident edges and trips on the third, before it is retained.
9661        let error = run_entity_merge_with_limits(
9662            &rt,
9663            into.id,
9664            from.id,
9665            MergeTxLimits {
9666                max_rows: 4,
9667                max_bytes: usize::MAX,
9668            },
9669        )
9670        .await
9671        .unwrap_err();
9672        let msg = error.to_string();
9673        assert!(
9674            msg.contains("merge transaction budget exceeded"),
9675            "got: {msg}"
9676        );
9677        assert!(msg.contains("collecting incident edges"), "got: {msg}");
9678
9679        // The rejected transaction must roll back completely.
9680        assert!(
9681            rt.get_entity(&tok, from.id).await.is_ok(),
9682            "from-entity must survive a budget-rejected merge"
9683        );
9684        let edges = rt
9685            .list_edges(
9686                &tok,
9687                EdgeListFilter {
9688                    source_id: Some(from.id),
9689                    ..Default::default()
9690                },
9691                10,
9692                0,
9693            )
9694            .await
9695            .unwrap();
9696        assert_eq!(
9697            edges.len(),
9698            3,
9699            "every incident edge must survive a budget-rejected merge"
9700        );
9701    }
9702
9703    #[tokio::test]
9704    async fn merge_entity_rejects_row_budget_while_collecting_conflict_cascade_rows() {
9705        use khive_storage::EdgeRelation;
9706        let rt = rt();
9707        let tok = NamespaceToken::local();
9708        let into = rt
9709            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
9710            .await
9711            .unwrap();
9712        let from = rt
9713            .create_entity(&tok, "concept", None, "From", None, None, vec![])
9714            .await
9715            .unwrap();
9716        let shared = rt
9717            .create_entity(&tok, "concept", None, "Shared", None, None, vec![])
9718            .await
9719            .unwrap();
9720        let annotator = rt
9721            .create_note(
9722                &tok,
9723                "observation",
9724                None,
9725                "annotator note",
9726                None,
9727                None,
9728                vec![],
9729            )
9730            .await
9731            .unwrap();
9732        let nested_annotator = rt
9733            .create_note(&tok, "observation", None, "nested note", None, None, vec![])
9734            .await
9735            .unwrap();
9736        rt.link(&tok, into.id, shared.id, EdgeRelation::Extends, 0.9, None)
9737            .await
9738            .unwrap();
9739        let dropped = rt
9740            .link(&tok, from.id, shared.id, EdgeRelation::Extends, 0.2, None)
9741            .await
9742            .unwrap();
9743        let annotation = rt
9744            .link(
9745                &tok,
9746                annotator.id,
9747                dropped.id.into(),
9748                EdgeRelation::Annotates,
9749                0.7,
9750                None,
9751            )
9752            .await
9753            .unwrap();
9754        let nested_annotation = rt
9755            .link(
9756                &tok,
9757                nested_annotator.id,
9758                annotation.id.into(),
9759                EdgeRelation::Annotates,
9760                0.6,
9761                None,
9762            )
9763            .await
9764            .unwrap();
9765
9766        // Row walk under a cap of 5: two merge records, one incident edge,
9767        // one endpoint-contract resolution, then the natural-key conflict's
9768        // recursive cascade collection charges the annotation chain and trips
9769        // on its second (nested) row.
9770        let error = run_entity_merge_with_limits(
9771            &rt,
9772            into.id,
9773            from.id,
9774            MergeTxLimits {
9775                max_rows: 5,
9776                max_bytes: usize::MAX,
9777            },
9778        )
9779        .await
9780        .unwrap_err();
9781        let msg = error.to_string();
9782        assert!(
9783            msg.contains("merge transaction budget exceeded"),
9784            "got: {msg}"
9785        );
9786        assert!(
9787            msg.contains("collecting conflict cascade rows"),
9788            "got: {msg}"
9789        );
9790
9791        // Roll back means the whole annotation chain is still present.
9792        for id in [dropped.id, annotation.id, nested_annotation.id] {
9793            assert!(
9794                rt.get_edge_including_deleted(&tok, id.into())
9795                    .await
9796                    .unwrap()
9797                    .is_some(),
9798                "edge {id} must survive a budget-rejected merge"
9799            );
9800        }
9801        assert!(
9802            rt.get_entity(&tok, from.id).await.is_ok(),
9803            "from-entity must survive a budget-rejected merge"
9804        );
9805    }
9806
9807    #[tokio::test]
9808    async fn merge_note_rejects_byte_budget_while_reading_merge_records() {
9809        let rt = rt();
9810        let tok = NamespaceToken::local();
9811        let into = rt
9812            .create_note(
9813                &tok,
9814                "observation",
9815                None,
9816                "into content",
9817                None,
9818                None,
9819                vec![],
9820            )
9821            .await
9822            .unwrap();
9823        let fat = "x".repeat(8192);
9824        let from = rt
9825            .create_note(&tok, "observation", None, &fat, None, None, vec![])
9826            .await
9827            .unwrap();
9828
9829        let error = run_note_merge_with_limits(
9830            &rt,
9831            into.id,
9832            from.id,
9833            Vec::new(),
9834            MergeTxLimits {
9835                max_rows: usize::MAX,
9836                max_bytes: 4096,
9837            },
9838        )
9839        .await
9840        .unwrap_err();
9841        let msg = error.to_string();
9842        assert!(
9843            msg.contains("merge transaction budget exceeded"),
9844            "got: {msg}"
9845        );
9846        assert!(msg.contains("reading merge records"), "got: {msg}");
9847
9848        assert!(
9849            rt.notes(&tok)
9850                .unwrap()
9851                .get_note(from.id)
9852                .await
9853                .unwrap()
9854                .is_some(),
9855            "from-note must survive a budget-rejected merge"
9856        );
9857    }
9858
9859    /// The byte budget must be charged from a cheap SQL-side length probe
9860    /// BEFORE the merge fully loads and JSON-parses a record's `properties`
9861    /// column — never after. Prove it adversarially: store an oversized
9862    /// `properties` value that is also invalid JSON directly on `from`,
9863    /// bypassing the create path's own validation. If the budget were still
9864    /// charged only after `read_merge_entity`'s full load-and-parse (the
9865    /// pre-fix ordering), this merge would fail with a JSON parse error
9866    /// instead of a budget error, because the parse would run before the
9867    /// stale post-read charge was ever reached. Charging from the pre-parse
9868    /// length probe must reject on budget first, so `serde_json::from_str`
9869    /// never runs on this column at all.
9870    #[tokio::test]
9871    async fn merge_entity_rejects_byte_budget_before_parsing_oversized_malformed_properties() {
9872        let rt = rt();
9873        let tok = NamespaceToken::local();
9874        let into = rt
9875            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
9876            .await
9877            .unwrap();
9878        let from = rt
9879            .create_entity(&tok, "concept", None, "From", None, None, vec![])
9880            .await
9881            .unwrap();
9882
9883        let huge_malformed_properties = format!("{{not valid json: {}", "x".repeat(8192));
9884        let pool = rt.backend().pool_arc();
9885        let from_id = from.id;
9886        tokio::task::spawn_blocking(move || {
9887            let guard = pool.writer().unwrap();
9888            guard.transaction(|conn| {
9889                conn.execute(
9890                    "UPDATE entities SET properties = ?1 WHERE id = ?2",
9891                    rusqlite::params![huge_malformed_properties, from_id.to_string()],
9892                )?;
9893                Ok(())
9894            })
9895        })
9896        .await
9897        .unwrap()
9898        .unwrap();
9899
9900        let error = run_entity_merge_with_limits(
9901            &rt,
9902            into.id,
9903            from.id,
9904            MergeTxLimits {
9905                max_rows: usize::MAX,
9906                max_bytes: 4096,
9907            },
9908        )
9909        .await
9910        .unwrap_err();
9911        let msg = error.to_string();
9912        assert!(
9913            msg.contains("merge transaction budget exceeded"),
9914            "expected an early budget rejection, not a JSON parse failure; got: {msg}"
9915        );
9916        assert!(msg.contains("reading merge records"), "got: {msg}");
9917
9918        // `get_entity` would itself fail to parse the malformed properties this
9919        // test deliberately stored, so check survival via a raw row count
9920        // instead of the parsing read path.
9921        let pool = rt.backend().pool_arc();
9922        let still_present: i64 = tokio::task::spawn_blocking(move || {
9923            let guard = pool.writer().unwrap();
9924            guard.transaction(|conn| {
9925                conn.query_row(
9926                    "SELECT COUNT(*) FROM entities WHERE id = ?1 AND deleted_at IS NULL",
9927                    rusqlite::params![from_id.to_string()],
9928                    |row| row.get(0),
9929                )
9930                .map_err(SqliteError::Rusqlite)
9931            })
9932        })
9933        .await
9934        .unwrap()
9935        .unwrap();
9936        assert_eq!(
9937            still_present, 1,
9938            "from-entity must survive a budget-rejected merge"
9939        );
9940    }
9941
9942    #[tokio::test]
9943    async fn merge_note_rejects_row_budget_while_collecting_incident_edges() {
9944        use khive_storage::EdgeRelation;
9945        let rt = rt();
9946        let tok = NamespaceToken::local();
9947        let into = rt
9948            .create_note(&tok, "observation", None, "Into", None, None, vec![])
9949            .await
9950            .unwrap();
9951        let from = rt
9952            .create_note(&tok, "observation", None, "From", None, None, vec![])
9953            .await
9954            .unwrap();
9955        for name in ["T1", "T2", "T3"] {
9956            let target = rt
9957                .create_entity(&tok, "concept", None, name, None, None, vec![])
9958                .await
9959                .unwrap();
9960            rt.link(&tok, from.id, target.id, EdgeRelation::Annotates, 1.0, None)
9961                .await
9962                .unwrap();
9963        }
9964
9965        let error = run_note_merge_with_limits(
9966            &rt,
9967            into.id,
9968            from.id,
9969            rt.pack_edge_rules(),
9970            MergeTxLimits {
9971                max_rows: 4,
9972                max_bytes: usize::MAX,
9973            },
9974        )
9975        .await
9976        .unwrap_err();
9977        let msg = error.to_string();
9978        assert!(
9979            msg.contains("merge transaction budget exceeded"),
9980            "got: {msg}"
9981        );
9982        assert!(msg.contains("collecting incident edges"), "got: {msg}");
9983
9984        let edges = rt
9985            .list_edges(
9986                &tok,
9987                EdgeListFilter {
9988                    source_id: Some(from.id),
9989                    ..Default::default()
9990                },
9991                10,
9992                0,
9993            )
9994            .await
9995            .unwrap();
9996        assert_eq!(
9997            edges.len(),
9998            3,
9999            "every incident edge must survive a budget-rejected merge"
10000        );
10001    }
10002
10003    // The post-commit budget logs are captured by the process-global tracing
10004    // subscriber owned by `crate::pack::tests` — one test binary supports at
10005    // most one `set_global_default`, and a thread-local `set_default` guard
10006    // here proved lossy under parallel tests (the same event-loss class the
10007    // pack tests' subscriber documents). Each test selects its own rows from
10008    // the append-only sink by the merge's `into_id`.
10009    use crate::pack::tests::budget_log_events;
10010
10011    #[tokio::test]
10012    async fn merge_entity_reports_and_logs_tx_budget_after_commit() {
10013        use khive_storage::EdgeRelation;
10014        let events = budget_log_events();
10015
10016        let rt = rt();
10017        let tok = NamespaceToken::local();
10018        let into = rt
10019            .create_entity(&tok, "concept", None, "Into", None, None, vec![])
10020            .await
10021            .unwrap();
10022        let from = rt
10023            .create_entity(&tok, "concept", None, "From", None, None, vec![])
10024            .await
10025            .unwrap();
10026        let target = rt
10027            .create_entity(&tok, "concept", None, "Target", None, None, vec![])
10028            .await
10029            .unwrap();
10030        rt.link(&tok, from.id, target.id, EdgeRelation::Extends, 1.0, None)
10031            .await
10032            .unwrap();
10033
10034        // A dry run reports the same predictive budget usage but must not
10035        // emit the post-commit log: nothing committed.
10036        let preview = rt
10037            .merge_entity(
10038                &tok,
10039                into.id,
10040                from.id,
10041                EntityDedupMergePolicy::PreferInto,
10042                ContentMergeStrategy::Append,
10043                true,
10044            )
10045            .await
10046            .unwrap();
10047        assert!(preview.tx_budget.rows_charged >= 2);
10048        assert_eq!(preview.tx_budget.max_rows, MERGE_TX_MAX_ROWS);
10049        assert_eq!(preview.tx_budget.max_bytes, MERGE_TX_MAX_BYTES);
10050        assert!(
10051            events
10052                .lock()
10053                .unwrap()
10054                .iter()
10055                .all(|e| e.into_id != into.id.to_string()),
10056            "a dry-run preview must not emit the post-commit budget log"
10057        );
10058
10059        let summary = rt
10060            .merge_entity(
10061                &tok,
10062                into.id,
10063                from.id,
10064                EntityDedupMergePolicy::PreferInto,
10065                ContentMergeStrategy::Append,
10066                false,
10067            )
10068            .await
10069            .unwrap();
10070        assert!(summary.tx_budget.rows_charged >= 2);
10071        assert!(summary.tx_budget.bytes_charged > 0);
10072
10073        let captured = events.lock().unwrap();
10074        let row = captured
10075            .iter()
10076            .find(|e| {
10077                e.into_id == summary.kept_id.to_string()
10078                    && e.message == "merge_entity: transaction materialization budget"
10079            })
10080            .expect("committing entity merge must emit the post-commit budget log");
10081        assert_eq!(
10082            row.budget_rows as usize, summary.tx_budget.rows_charged,
10083            "the log must carry the same observed row count the summary reports"
10084        );
10085    }
10086
10087    #[tokio::test]
10088    async fn merge_note_reports_and_logs_tx_budget_after_commit() {
10089        let events = budget_log_events();
10090
10091        let rt = rt();
10092        let tok = NamespaceToken::local();
10093        let into = rt
10094            .create_note(&tok, "observation", None, "Into", None, None, vec![])
10095            .await
10096            .unwrap();
10097        let from = rt
10098            .create_note(&tok, "observation", None, "From", None, None, vec![])
10099            .await
10100            .unwrap();
10101
10102        let summary = rt
10103            .merge_note(
10104                &tok,
10105                into.id,
10106                from.id,
10107                EntityDedupMergePolicy::PreferInto,
10108                ContentMergeStrategy::Append,
10109                false,
10110            )
10111            .await
10112            .unwrap();
10113        assert!(summary.tx_budget.rows_charged >= 2);
10114        assert!(summary.tx_budget.bytes_charged > 0);
10115
10116        let captured = events.lock().unwrap();
10117        let row = captured
10118            .iter()
10119            .find(|e| {
10120                e.into_id == summary.kept_id.to_string()
10121                    && e.message == "merge_note: transaction materialization budget"
10122            })
10123            .expect("committing note merge must emit the post-commit budget log");
10124        assert_eq!(
10125            row.budget_rows as usize, summary.tx_budget.rows_charged,
10126            "the log must carry the same observed row count the summary reports"
10127        );
10128    }
10129
10130    // ── Universal reserved-key reservation (ADR-115 Amendment 1, first rung) ──
10131
10132    fn reserved_key_props() -> serde_json::Value {
10133        serde_json::json!({"khive:secret_gate": "exempted:content-sha256-manifest-v1"})
10134    }
10135
10136    #[tokio::test]
10137    async fn update_entity_rejects_reserved_secret_gate_key() {
10138        let rt = rt();
10139        let tok = NamespaceToken::local();
10140        let entity = rt
10141            .create_entity(
10142                &tok,
10143                "concept",
10144                None,
10145                "reservation-target-entity",
10146                None,
10147                Some(serde_json::json!({"k": "v"})),
10148                vec![],
10149            )
10150            .await
10151            .unwrap();
10152
10153        let err = rt
10154            .update_entity(
10155                &tok,
10156                entity.id,
10157                EntityPatch {
10158                    properties: Some(reserved_key_props()),
10159                    ..Default::default()
10160                },
10161            )
10162            .await
10163            .expect_err("caller-supplied reserved key must be rejected on patch update");
10164        assert!(
10165            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
10166            "unexpected error: {err:?}"
10167        );
10168
10169        // No partial mutation: the original properties must be unchanged.
10170        let unchanged = rt
10171            .entities(&tok)
10172            .unwrap()
10173            .get_entity(entity.id)
10174            .await
10175            .unwrap()
10176            .unwrap();
10177        assert_eq!(unchanged.properties, Some(serde_json::json!({"k": "v"})));
10178    }
10179
10180    #[tokio::test]
10181    async fn update_note_rejects_reserved_secret_gate_key() {
10182        let rt = rt();
10183        let tok = NamespaceToken::local();
10184        let note = rt
10185            .create_note(
10186                &tok,
10187                "observation",
10188                None,
10189                "reservation target note",
10190                None,
10191                Some(serde_json::json!({"k": "v"})),
10192                vec![],
10193            )
10194            .await
10195            .unwrap();
10196
10197        let err = rt
10198            .update_note(
10199                &tok,
10200                note.id,
10201                NotePatch::new(None, None, None, None, Some(reserved_key_props())),
10202            )
10203            .await
10204            .expect_err("caller-supplied reserved key must be rejected on patch update");
10205        assert!(
10206            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("khive:secret_gate")),
10207            "unexpected error: {err:?}"
10208        );
10209
10210        let unchanged = rt
10211            .notes(&tok)
10212            .unwrap()
10213            .get_note(note.id)
10214            .await
10215            .unwrap()
10216            .unwrap();
10217        assert_eq!(unchanged.properties, Some(serde_json::json!({"k": "v"})));
10218    }
10219}