Skip to main content

khive_runtime/
reference_resolution.rs

1//! `resolve_reference`: the Layer-0 deterministic reference resolver from the
2//! "unified-verb" draft ADR (Slice 1 — resolver + ring).
3//!
4//! Turns a natural-language reference into an id through four ordered
5//! stages, never guessing among close candidates:
6//!
7//! 1. **Id-string passthrough.** A ref that already looks like a UUID or an
8//!    8+ hex-char prefix resolves through the existing by-ID path
9//!    (`KhiveRuntime::resolve_by_id` / `resolve_prefix_unfiltered`) instead of
10//!    being treated as free text — it must not error just because it arrived
11//!    through `resolve_reference` rather than `get`. Scoped to entity ids
12//!    only, identically for the full-UUID and prefix forms (matching the
13//!    ring's entity-only contract); a note/edge/event id-string is
14//!    `NotFound` here, not an error — a caller resolving those uses `get`.
15//! 2. **Recently-referenced ring.** An exact (case-insensitive) or substring
16//!    match against this actor's ring (`reference_ring::ReferenceRing`).
17//! 3. **Exact-name storage lookup.** A deterministic, case-sensitive match
18//!    against `entities.name` in the caller's namespace (`deleted_at IS
19//!    NULL`) — covers any entity that already exists but was never
20//!    created/get/updated/deleted/merged/linked by this actor in this
21//!    session, so stage 2's ring never saw it (#849).
22//! 4. **Hybrid-search fallback.** `KhiveRuntime::hybrid_search` over the
23//!    caller's namespace, ranked by RRF score.
24//!
25//! A single candidate clearing the stage's confidence bar resolves; multiple
26//! viable candidates or none never silently pick — they return `Ambiguous`
27//! or `NotFound` for the caller to disambiguate.
28
29use std::str::FromStr;
30
31use uuid::Uuid;
32
33use khive_storage::types::PageRequest;
34use khive_storage::EntityFilter;
35
36use crate::error::{RuntimeError, RuntimeResult};
37use crate::operations::Resolved;
38use crate::reference_ring::ReferenceRing;
39use crate::runtime::{KhiveRuntime, NamespaceToken};
40
41/// A candidate id surfaced when a reference did not resolve outright.
42#[derive(Clone, Debug, PartialEq)]
43pub struct ReferenceCandidate {
44    pub id: Uuid,
45    pub name: Option<String>,
46    pub score: f64,
47}
48
49/// Outcome of `resolve_reference`. Never a silent pick among close
50/// candidates: `Ambiguous` always lists what it found instead of guessing.
51#[derive(Clone, Debug, PartialEq)]
52pub enum ReferenceResolution {
53    Resolved { id: Uuid, confidence: f64 },
54    Ambiguous { candidates: Vec<ReferenceCandidate> },
55    NotFound,
56}
57
58/// Ring-match confidence for an exact (case-insensitive) name match.
59const RING_EXACT_CONFIDENCE: f64 = 0.95;
60/// Ring-match confidence for a substring match (either direction).
61const RING_SUBSTRING_CONFIDENCE: f64 = 0.7;
62/// A single ring candidate auto-resolves only at or above this bar; below
63/// it the candidate is still surfaced as `Ambiguous` rather than silently
64/// accepted or dropped. Ring scores are fixed constants on a 0..1 scale, so
65/// a fixed bar is meaningful here: the search stage below needs a
66/// different rule (`SEARCH_RESOLVED_CONFIDENCE`) because RRF scores aren't
67/// on that scale.
68const RING_AUTO_RESOLVE_CONFIDENCE: f64 = 0.7;
69/// Confidence for a stage-3 exact-name storage match: a deterministic,
70/// case-sensitive equality on `entities.name` — stronger evidence than the
71/// ring's case-insensitive session cache (`RING_EXACT_CONFIDENCE`), so it
72/// sits above both ring bands, but still below the absolute certainty of an
73/// id-string passthrough (1.0), which the caller supplied directly rather
74/// than by name.
75const EXACT_NAME_CONFIDENCE: f64 = 0.98;
76/// Hybrid-search fallback: the top hit auto-resolves over a runner-up only
77/// when it leads by at least this ratio — RRF scores are not on a fixed
78/// 0..1 confidence scale, so a fixed absolute bar can't express "decisively
79/// best" the way it can for the ring. Below the margin, every hit above the
80/// score floor is surfaced as a candidate instead.
81const SEARCH_MARGIN_RATIO: f64 = 2.0;
82/// Vector hits below this raw cosine-similarity score are removed before RRF
83/// fusion. Lexical hits remain admissible because RRF magnitude encodes rank,
84/// not textual relevance, and genuine partial-name matches score below this floor.
85///
86/// This is a raw cosine value in `[-1.0, 1.0]`, matching the canonical
87/// vector-store score produced by `khive-db` (`1 - cosine_distance`).
88const SEARCH_VECTOR_SIMILARITY_FLOOR: f64 = 0.3;
89/// Confidence reported on a search-stage `Resolved` outcome: not the raw
90/// RRF score, which lives on a much smaller scale (`sum 1/(k + rank)`, e.g.
91/// ~0.016-0.033) and would never clear a 0..1 confidence bar. Fixed below
92/// both ring bands so callers can tell "the ring recognized this" from
93/// "search picked this out" by confidence alone; the raw RRF value is still
94/// preserved in `ReferenceCandidate.score` for `Ambiguous` listings.
95const SEARCH_RESOLVED_CONFIDENCE: f64 = 0.6;
96/// Floor on the retrieval depth stage 4 asks `hybrid_search` for, independent
97/// of the caller's requested `limit`.
98///
99/// `KhiveRuntime::hybrid_search` truncates its returned hit list to exactly
100/// the `limit` it is called with (its final step is `fused.truncate(limit as
101/// usize)`), so that `limit` doubles as both "how deep to search" and "how
102/// many hits to hand back" — for `resolve`, whose caller-facing default
103/// `limit` is 5 (`khive_pack_kg::handlers::resolve::DEFAULT_LIMIT`), a
104/// caller asking for a short candidate list was silently also asking for a
105/// shallow search. A genuine canonical-name match ranked, say, 6th-to-10th —
106/// exactly where a qualified natural-language ref (a project prefix ahead of
107/// a short canonical name) lands when it beats the exact-name stage above
108/// but only partially matches the text leg and is corroborated by the vector
109/// leg — was truncated out of the stage-4 candidate set entirely even though
110/// the same query against a wider `limit` (e.g. the `search` verb's own
111/// default of 10) surfaces it as the top hit (#908). Retrieving at this
112/// floor decouples "how deep to search" from "how many candidates the caller
113/// asked for". The full pool is retained for the decisiveness check, while an
114/// `Ambiguous` payload is truncated back to the caller's `limit` before it is
115/// returned.
116const STAGE4_MIN_SEARCH_LIMIT: u32 = 20;
117
118/// Resolve one natural-language reference for `token`'s actor.
119///
120/// `limit` bounds the hybrid-search fallback candidate count (Layer-0 stage
121/// 4); it has no effect on the id-string or ring stages, which are always
122/// exact-or-nothing / small in-memory scans. `entity_kind`, if set, restricts
123/// stage 3 to that entity kind (e.g. `"concept"`); the id-string and ring
124/// stages are kind-agnostic by construction (a ring entry or an explicit id
125/// is not filtered by kind).
126pub async fn resolve_reference(
127    runtime: &KhiveRuntime,
128    ring: &ReferenceRing,
129    token: &NamespaceToken,
130    nl_ref: &str,
131    limit: u32,
132    entity_kind: Option<&str>,
133) -> RuntimeResult<ReferenceResolution> {
134    let trimmed = nl_ref.trim();
135    if trimmed.is_empty() {
136        return Ok(ReferenceResolution::NotFound);
137    }
138
139    // Stage 1: id-string passthrough (UUID / 8+ hex prefix) via the existing
140    // by-ID path. A ref shaped like an id but absent from storage is
141    // NotFound, not a fallthrough to ring/search: the caller named a
142    // specific id, so a miss there is the true answer. Scoped to entity ids
143    // only (both full-UUID and prefix forms) to match the ring's entity-only
144    // contract (`reference_ring::substrate_admits_as_entity`); a non-entity
145    // id-string is `NotFound` here: callers needing those already have `get`.
146    if let Ok(uuid) = Uuid::from_str(trimmed) {
147        return match runtime.resolve_by_id(token, uuid).await? {
148            Some(Resolved::Entity(_)) => Ok(ReferenceResolution::Resolved {
149                id: uuid,
150                confidence: 1.0,
151            }),
152            Some(_) | None => Ok(ReferenceResolution::NotFound),
153        };
154    }
155    if is_hex_prefix(trimmed) {
156        return match runtime.resolve_prefix_unfiltered(trimmed).await {
157            Ok(Some(uuid)) => match runtime.resolve_by_id(token, uuid).await? {
158                Some(Resolved::Entity(_)) => Ok(ReferenceResolution::Resolved {
159                    id: uuid,
160                    confidence: 1.0,
161                }),
162                Some(_) | None => Ok(ReferenceResolution::NotFound),
163            },
164            Ok(None) => Ok(ReferenceResolution::NotFound),
165            Err(RuntimeError::AmbiguousPrefix { matches, .. }) => {
166                let mut entity_matches = Vec::with_capacity(matches.len());
167                for id in matches {
168                    if matches!(
169                        runtime.resolve_by_id(token, id).await?,
170                        Some(Resolved::Entity(_))
171                    ) {
172                        entity_matches.push(id);
173                    }
174                }
175                match entity_matches.len() {
176                    0 => Ok(ReferenceResolution::NotFound),
177                    1 => Ok(ReferenceResolution::Resolved {
178                        id: entity_matches[0],
179                        confidence: 1.0,
180                    }),
181                    _ => Ok(ReferenceResolution::Ambiguous {
182                        candidates: entity_matches
183                            .into_iter()
184                            .map(|id| ReferenceCandidate {
185                                id,
186                                name: None,
187                                score: 1.0,
188                            })
189                            .collect(),
190                    }),
191                }
192            }
193            Err(e) => Err(e),
194        };
195    }
196
197    // Stage 2: recently-referenced ring.
198    let actor = token.actor();
199    let actor_key = format!("{}:{}", actor.kind, actor.id);
200    let ring_entries = ring.snapshot(token.namespace().as_str(), &actor_key);
201    let needle = trimmed.to_ascii_lowercase();
202
203    let exact: Vec<ReferenceCandidate> = ring_entries
204        .iter()
205        .filter(|e| {
206            e.name
207                .as_deref()
208                .is_some_and(|n| n.to_ascii_lowercase() == needle)
209        })
210        .map(|e| ReferenceCandidate {
211            id: e.id,
212            name: e.name.clone(),
213            score: RING_EXACT_CONFIDENCE,
214        })
215        .collect();
216    if let Some(resolution) = resolve_from_candidates(exact) {
217        return Ok(resolution);
218    }
219
220    let substring: Vec<ReferenceCandidate> = ring_entries
221        .iter()
222        .filter(|e| {
223            e.name.as_deref().is_some_and(|n| {
224                let n_lower = n.to_ascii_lowercase();
225                n_lower.contains(&needle) || needle.contains(&n_lower)
226            })
227        })
228        .map(|e| ReferenceCandidate {
229            id: e.id,
230            name: e.name.clone(),
231            score: RING_SUBSTRING_CONFIDENCE,
232        })
233        .collect();
234    if let Some(resolution) = resolve_from_candidates(substring) {
235        return Ok(resolution);
236    }
237
238    // Stage 3: exact-name storage lookup (#849) — a deterministic,
239    // case-sensitive match against `entities.name` in the caller's
240    // namespace, run before the hybrid-search fallback so an existing exact
241    // name always resolves regardless of FTS ranking, RRF score, or whether
242    // this actor's session ever referenced the entity (the ring's blind
243    // spot). Single match resolves; multiple exact matches are `Ambiguous`;
244    // none falls through to hybrid search unchanged.
245    if let Some(resolution) = exact_name_match(runtime, token, trimmed, entity_kind).await? {
246        return Ok(resolution);
247    }
248
249    // Stage 4: hybrid-search fallback over the namespace. Search deeper than
250    // the caller's requested `limit` (see `STAGE4_MIN_SEARCH_LIMIT`) so a
251    // genuine match ranked just outside a small `limit` isn't truncated out
252    // of the pool before it's even ranked against the alternatives; the
253    // caller's `limit` still bounds how many candidates get rendered below.
254    let candidate_limit = limit.max(1);
255    let search_limit = candidate_limit.max(STAGE4_MIN_SEARCH_LIMIT);
256    let hits = runtime
257        .hybrid_search_with_vector_similarity_floor(
258            token,
259            trimmed,
260            None,
261            search_limit,
262            entity_kind,
263            None,
264            &[],
265            None,
266            SEARCH_VECTOR_SIMILARITY_FLOOR,
267        )
268        .await?;
269    let candidates: Vec<ReferenceCandidate> = hits
270        .into_iter()
271        .map(|h| ReferenceCandidate {
272            id: h.entity_id,
273            name: h.title,
274            score: h.score.to_f64(),
275        })
276        .collect();
277
278    match candidates.len() {
279        0 => Ok(ReferenceResolution::NotFound),
280        // A lone hit is presence-decisive: there is no competing candidate to
281        // be ambiguous against, regardless of its raw RRF magnitude (see
282        // `SEARCH_RESOLVED_CONFIDENCE`).
283        1 => Ok(ReferenceResolution::Resolved {
284            id: candidates[0].id,
285            confidence: SEARCH_RESOLVED_CONFIDENCE,
286        }),
287        _ => {
288            let top_score = candidates[0].score;
289            let second_score = candidates[1].score;
290            let decisive =
291                second_score <= f64::EPSILON || top_score / second_score >= SEARCH_MARGIN_RATIO;
292            if decisive {
293                Ok(ReferenceResolution::Resolved {
294                    id: candidates[0].id,
295                    confidence: SEARCH_RESOLVED_CONFIDENCE,
296                })
297            } else {
298                // Non-exact ambiguity: bound the payload to the caller's
299                // `limit`. Any deterministic identity (an exact canonical
300                // name) was already resolved by stage 3 above, so nothing
301                // withheld here is "the" answer — outside exact matches there
302                // is no oracle for a single canonical candidate. Raising
303                // `limit` surfaces deeper ranks (#970; resolve() contract).
304                let mut candidates = candidates;
305                candidates.truncate(candidate_limit as usize);
306                Ok(ReferenceResolution::Ambiguous { candidates })
307            }
308        }
309    }
310}
311
312/// Apply the shared "single-above-bar resolves, multiple is ambiguous"
313/// contract to a candidate set already known to be an exact or substring
314/// ring match. Returns `None` when `candidates` is empty — the caller falls
315/// through to the next resolution stage instead of reporting `NotFound`
316/// prematurely.
317fn resolve_from_candidates(candidates: Vec<ReferenceCandidate>) -> Option<ReferenceResolution> {
318    match candidates.len() {
319        0 => None,
320        1 => {
321            let top = &candidates[0];
322            Some(if top.score >= RING_AUTO_RESOLVE_CONFIDENCE {
323                ReferenceResolution::Resolved {
324                    id: top.id,
325                    confidence: top.score,
326                }
327            } else {
328                ReferenceResolution::Ambiguous { candidates }
329            })
330        }
331        _ => Some(ReferenceResolution::Ambiguous { candidates }),
332    }
333}
334
335/// Stage 3 of `resolve_reference` (#849): a deterministic, case-sensitive
336/// exact match against `entities.name`, scoped to `token.namespace()` (the
337/// same single-namespace default the rest of this pipeline and the sibling
338/// by-name lookup in `khive-pack-kg`'s `resolve_name_async` use) and to
339/// `entity_kind` when the caller filtered by one. `query_entities` already
340/// excludes soft-deleted rows (`deleted_at IS NULL` is baked into every
341/// query — see `khive-db::stores::entity::build_entity_where`), so no
342/// separate filter is needed here. Returns `None` (fall through to the next
343/// stage) when nothing matches; `Some(Resolved)` on a single hit; and
344/// `Some(Ambiguous)` when the name is not unique.
345async fn exact_name_match(
346    runtime: &KhiveRuntime,
347    token: &NamespaceToken,
348    name: &str,
349    entity_kind: Option<&str>,
350) -> RuntimeResult<Option<ReferenceResolution>> {
351    let filter = EntityFilter {
352        name_exact: Some(name.to_string()),
353        kinds: entity_kind.map(|k| vec![k.to_string()]).unwrap_or_default(),
354        ..EntityFilter::default()
355    };
356    // A storage-level `name = ?` predicate (not `name_prefix` + in-memory
357    // filter) so a namespace with many newer case variants of `name` can
358    // never page the exact target out from under a `created_at DESC` sort
359    // (#849, #852) — every row this query returns already equals `name`.
360    // The page is small (10, not 1), but the zero/one/many decision is made
361    // from `page.total` (the storage-computed COUNT(*) under the same
362    // predicate), never from `page.items.len()` — with 11+ byte-identical
363    // exact names the fetched page is still only 10 rows, and deciding from
364    // its length alone would under-report cardinality. `Ambiguous.candidates`
365    // is a bounded sample of up to 10 of the `page.total` matches, not the
366    // complete set — the variant carries no total field, so callers must not
367    // assume `candidates.len() == page.total` (#852).
368    let page = runtime
369        .entities(token)?
370        .query_entities(
371            token.namespace().as_str(),
372            filter,
373            PageRequest {
374                offset: 0,
375                limit: 10,
376            },
377        )
378        .await
379        .map_err(RuntimeError::Storage)?;
380
381    let total = page.total.unwrap_or(page.items.len() as u64);
382
383    let exact: Vec<ReferenceCandidate> = page
384        .items
385        .into_iter()
386        .map(|e| ReferenceCandidate {
387            id: e.id,
388            name: Some(e.name),
389            score: EXACT_NAME_CONFIDENCE,
390        })
391        .collect();
392
393    Ok(match total {
394        0 => None,
395        1 => exact
396            .into_iter()
397            .next()
398            .map(|top| ReferenceResolution::Resolved {
399                id: top.id,
400                confidence: EXACT_NAME_CONFIDENCE,
401            }),
402        _ => Some(ReferenceResolution::Ambiguous { candidates: exact }),
403    })
404}
405
406fn is_hex_prefix(s: &str) -> bool {
407    s.len() >= 8 && s.chars().all(|c| c.is_ascii_hexdigit())
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use crate::config::{NamespaceToken as TokenCtor, RuntimeConfig};
414    use crate::embedder_registry::EmbedderProvider;
415    use crate::retrieval::SearchSource;
416    use khive_gate::ActorRef;
417    use khive_types::{namespace::Namespace, SubstrateKind};
418    use lattice_embed::{EmbeddingModel, EmbeddingService};
419    use std::sync::Arc;
420
421    struct ConstantEmbeddingService {
422        dimensions: usize,
423    }
424
425    #[async_trait::async_trait]
426    impl EmbeddingService for ConstantEmbeddingService {
427        async fn embed(
428            &self,
429            texts: &[String],
430            _model: EmbeddingModel,
431        ) -> Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
432            Ok(texts.iter().map(|_| vec![1.0; self.dimensions]).collect())
433        }
434
435        fn supports_model(&self, _model: EmbeddingModel) -> bool {
436            true
437        }
438
439        fn name(&self) -> &'static str {
440            "resolve-test-constant-embedding"
441        }
442    }
443
444    struct ConstantEmbedderProvider {
445        name: String,
446        dimensions: usize,
447    }
448
449    #[async_trait::async_trait]
450    impl EmbedderProvider for ConstantEmbedderProvider {
451        fn name(&self) -> &str {
452            &self.name
453        }
454
455        fn dimensions(&self) -> usize {
456            self.dimensions
457        }
458
459        async fn build(&self) -> RuntimeResult<Arc<dyn EmbeddingService>> {
460            Ok(Arc::new(ConstantEmbeddingService {
461                dimensions: self.dimensions,
462            }))
463        }
464    }
465
466    fn runtime_with_constant_embeddings() -> KhiveRuntime {
467        let model = EmbeddingModel::AllMiniLmL6V2;
468        let runtime = KhiveRuntime::new(RuntimeConfig {
469            db_path: None,
470            embedding_model: Some(model),
471            packs: vec!["kg".to_string()],
472            ..RuntimeConfig::no_embeddings()
473        })
474        .expect("in-memory runtime");
475        runtime.register_embedder(ConstantEmbedderProvider {
476            name: model.to_string(),
477            dimensions: model.dimensions(),
478        });
479        runtime
480    }
481
482    fn actor_token(actor_id: &str) -> NamespaceToken {
483        TokenCtor::mint_authorized(Namespace::local(), ActorRef::new("agent", actor_id))
484    }
485
486    #[tokio::test]
487    async fn id_string_passthrough_resolves_full_uuid() {
488        let rt = KhiveRuntime::memory().expect("in-memory runtime");
489        let token = actor_token("resolver-test");
490        let ring = ReferenceRing::new();
491
492        let entity = rt
493            .create_entity(
494                &token,
495                "concept",
496                None,
497                "PassthroughTarget",
498                None,
499                None,
500                vec![],
501            )
502            .await
503            .expect("create entity");
504
505        let resolution = resolve_reference(&rt, &ring, &token, &entity.id.to_string(), 5, None)
506            .await
507            .expect("resolve_reference");
508        assert_eq!(
509            resolution,
510            ReferenceResolution::Resolved {
511                id: entity.id,
512                confidence: 1.0
513            }
514        );
515    }
516
517    #[tokio::test]
518    async fn id_string_passthrough_never_errors_on_a_miss() {
519        let rt = KhiveRuntime::memory().expect("in-memory runtime");
520        let token = actor_token("resolver-test");
521        let ring = ReferenceRing::new();
522
523        let missing = Uuid::new_v4();
524        let resolution = resolve_reference(&rt, &ring, &token, &missing.to_string(), 5, None)
525            .await
526            .expect("must not error, only report NotFound");
527        assert_eq!(resolution, ReferenceResolution::NotFound);
528    }
529
530    #[tokio::test]
531    async fn ring_exact_match_resolves_without_search() {
532        let rt = KhiveRuntime::memory().expect("in-memory runtime");
533        let token = actor_token("resolver-test");
534        let ring = ReferenceRing::new();
535        let actor = token.actor();
536        let actor_key = format!("{}:{}", actor.kind, actor.id);
537
538        let id = Uuid::new_v4();
539        ring.admit(
540            token.namespace().as_str(),
541            &actor_key,
542            id,
543            Some("the old record".to_string()),
544        );
545
546        let resolution = resolve_reference(&rt, &ring, &token, "the old record", 5, None)
547            .await
548            .expect("resolve_reference");
549        assert_eq!(
550            resolution,
551            ReferenceResolution::Resolved {
552                id,
553                confidence: RING_EXACT_CONFIDENCE
554            }
555        );
556    }
557
558    #[tokio::test]
559    async fn ring_ambiguous_on_multiple_exact_matches() {
560        let rt = KhiveRuntime::memory().expect("in-memory runtime");
561        let token = actor_token("resolver-test");
562        let ring = ReferenceRing::new();
563        let actor = token.actor();
564        let actor_key = format!("{}:{}", actor.kind, actor.id);
565
566        let id_a = Uuid::new_v4();
567        let id_b = Uuid::new_v4();
568        ring.admit(
569            token.namespace().as_str(),
570            &actor_key,
571            id_a,
572            Some("duplicate name".to_string()),
573        );
574        ring.admit(
575            token.namespace().as_str(),
576            &actor_key,
577            id_b,
578            Some("duplicate name".to_string()),
579        );
580
581        let resolution = resolve_reference(&rt, &ring, &token, "duplicate name", 5, None)
582            .await
583            .expect("resolve_reference");
584        match resolution {
585            ReferenceResolution::Ambiguous { candidates } => {
586                assert_eq!(candidates.len(), 2);
587            }
588            other => panic!("expected Ambiguous, got {other:?}"),
589        }
590    }
591
592    #[tokio::test]
593    async fn no_ring_entry_and_no_search_hit_is_not_found() {
594        let rt = KhiveRuntime::memory().expect("in-memory runtime");
595        let token = actor_token("resolver-test");
596        let ring = ReferenceRing::new();
597
598        let resolution =
599            resolve_reference(&rt, &ring, &token, "nothing matches this at all", 5, None)
600                .await
601                .expect("resolve_reference");
602        assert_eq!(resolution, ReferenceResolution::NotFound);
603    }
604
605    #[tokio::test]
606    async fn actor_isolation_blocks_cross_actor_ring_reads() {
607        let rt = KhiveRuntime::memory().expect("in-memory runtime");
608        let token_a = actor_token("actor-a");
609        let token_b = actor_token("actor-b");
610        let ring = ReferenceRing::new();
611        let actor_a = token_a.actor();
612        let actor_key_a = format!("{}:{}", actor_a.kind, actor_a.id);
613
614        let id = Uuid::new_v4();
615        ring.admit(
616            token_a.namespace().as_str(),
617            &actor_key_a,
618            id,
619            Some("shared-namespace-name".to_string()),
620        );
621
622        // actor-b, same namespace, must NOT resolve via actor-a's ring entry.
623        let resolution = resolve_reference(&rt, &ring, &token_b, "shared-namespace-name", 5, None)
624            .await
625            .expect("resolve_reference");
626        assert_eq!(resolution, ReferenceResolution::NotFound);
627    }
628
629    // Regression for #849/#852: the stage-3 exact-name lookup used to filter
630    // `name_prefix` (`LIKE 'RoLoRA%'`) in memory, and `query_entities` ranks
631    // a `name_prefix` page by `CASE WHEN LOWER(name) = prefix THEN 0 ELSE 1
632    // END, created_at DESC`. Case-insensitive variants of the target name
633    // tie for priority 0 with the true exact match, so 100+ *newer*
634    // lowercase variants can fill the `LIMIT 100` page and page the older,
635    // case-exact target out entirely — the stage then falls through to
636    // hybrid search instead of resolving deterministically. The fix issues a
637    // storage-level `name = ?` (binary) predicate instead, so decoys that
638    // merely match case-insensitively never enter the result set at all.
639    #[tokio::test]
640    async fn exact_name_stage_survives_many_newer_case_variant_decoys() {
641        let rt = KhiveRuntime::memory().expect("in-memory runtime");
642        let token = actor_token("resolver-test");
643        let ring = ReferenceRing::new();
644
645        let target = rt
646            .create_entity(&token, "concept", None, "RoLoRA", None, None, vec![])
647            .await
648            .expect("create target entity");
649
650        // Case variants of the same name, not suffixed variants: SQLite's
651        // `LIKE` is case-insensitive for ASCII, so a `rolora`-named decoy
652        // still matches the `LIKE 'RoLoRA%'` pattern the buggy `name_prefix`
653        // stage used, and the exact-match-ranking `CASE WHEN LOWER(name) =
654        // ...` ties every one of these decoys with the true target at
655        // priority 0 — leaving `created_at DESC` as the only tiebreak.
656        let decoy_cases = ["rolora", "ROLORA", "RoLoRa", "roLORA"];
657        for i in 0..120 {
658            rt.create_entity(
659                &token,
660                "concept",
661                None,
662                decoy_cases[i % decoy_cases.len()],
663                None,
664                None,
665                vec![],
666            )
667            .await
668            .expect("create decoy entity");
669        }
670
671        let resolution = resolve_reference(&rt, &ring, &token, "RoLoRA", 5, None)
672            .await
673            .expect("resolve_reference");
674        assert_eq!(
675            resolution,
676            ReferenceResolution::Resolved {
677                id: target.id,
678                confidence: EXACT_NAME_CONFIDENCE,
679            }
680        );
681    }
682
683    /// Issue #852: the zero/one/many decision must come from the
684    /// storage-computed `page.total` (a full `COUNT(*)` under the exact-name
685    /// predicate), not from `page.items.len()`, which the stage's own
686    /// `LIMIT 10` caps regardless of true cardinality. 11 byte-identical
687    /// exact names exceed that page limit, so the fetched page can only ever
688    /// carry 10 rows — `Ambiguous` must still fire (storage says 11 total,
689    /// not the truncated 10), and the returned `candidates` are a bounded
690    /// sample of the match set, not its entirety. That truncation is an
691    /// intentional, documented contract of this stage, not a bug: this test
692    /// pins both halves so a future change can't silently drop one.
693    #[tokio::test]
694    async fn exact_name_ambiguous_decision_uses_storage_total_not_page_len() {
695        let rt = KhiveRuntime::memory().expect("in-memory runtime");
696        let token = actor_token("resolver-test");
697        let ring = ReferenceRing::new();
698
699        for _ in 0..11 {
700            rt.create_entity(&token, "concept", None, "DupeExactName", None, None, vec![])
701                .await
702                .expect("create duplicate-named entity");
703        }
704
705        let resolution = resolve_reference(&rt, &ring, &token, "DupeExactName", 5, None)
706            .await
707            .expect("resolve_reference");
708
709        match resolution {
710            ReferenceResolution::Ambiguous { candidates } => {
711                assert_eq!(
712                    candidates.len(),
713                    10,
714                    "candidate set is a bounded 10-row sample of the 11 storage matches, \
715                     not the complete set"
716                );
717            }
718            other => panic!("expected Ambiguous driven by storage total (11), got {other:?}"),
719        }
720    }
721
722    // Regression for #908 / #970: an exact canonical-name ref resolves to a
723    // single id through the stage-3 exact-name lookup, which short-circuits
724    // BEFORE the stage-4 hybrid fallback and its `limit` bound. Many other
725    // entities are strong hybrid matches for the same term — enough that
726    // hybrid alone would rank them close together and return `Ambiguous` — yet
727    // the exact name resolves deterministically to its owner. The returned
728    // `EXACT_NAME_CONFIDENCE` (not the stage-4 `SEARCH_RESOLVED_CONFIDENCE`)
729    // proves the result came from stage 3, regardless of the target's hybrid
730    // rank. An exact name is an identity, not a ranked candidate.
731    #[tokio::test]
732    async fn exact_name_resolves_ahead_of_competing_hybrid_matches() {
733        let rt = KhiveRuntime::memory().expect("in-memory runtime");
734        let token = actor_token("resolver-test");
735        let ring = ReferenceRing::new();
736
737        let target = rt
738            .create_entity(
739                &token,
740                "concept",
741                None,
742                "ADR-040",
743                Some("khive ADR-040"),
744                None,
745                vec![],
746            )
747            .await
748            .expect("create target entity");
749
750        // Competitors that also match "ADR-040" strongly in hybrid search but
751        // do NOT carry it as an exact name; only the target owns the exact
752        // name, so only the target satisfies the stage-3 lookup.
753        for i in 0..12 {
754            rt.create_entity(
755                &token,
756                "concept",
757                None,
758                &format!("ADR-040 companion {i}"),
759                Some("ADR-040 ADR-040 ADR-040 ADR-040 ADR-040"),
760                None,
761                vec![],
762            )
763            .await
764            .expect("create competing entity");
765        }
766
767        // Even at limit = 1 — the tightest bound — the exact name resolves to
768        // the target, at the stage-3 confidence, never a ranked hybrid pick.
769        let resolution = resolve_reference(&rt, &ring, &token, "ADR-040", 1, None)
770            .await
771            .expect("resolve_reference");
772        assert_eq!(
773            resolution,
774            ReferenceResolution::Resolved {
775                id: target.id,
776                confidence: EXACT_NAME_CONFIDENCE,
777            }
778        );
779    }
780
781    // The complement of the exact-name contract: a NON-exact ref (no entity
782    // carries it as an exact name) that stays ambiguous returns a bounded
783    // sample capped at the caller's `limit`. Outside exact matches there is no
784    // oracle for a single "canonical" candidate, so the bound is the
785    // intentional, documented resolve() contract (raise `limit` to surface
786    // deeper ranks) — not a withheld identity. Any deterministic identity
787    // would have resolved upstream in stage 3.
788    #[tokio::test]
789    async fn fallback_stage_bounds_non_exact_payload_to_limit() {
790        let rt = KhiveRuntime::memory().expect("in-memory runtime");
791        let token = actor_token("resolver-test");
792        let ring = ReferenceRing::new();
793
794        // Twelve near-equal matches, each with a distinct name and the same
795        // descriptive text — none is the "right" answer, so the result is a
796        // genuinely bounded ambiguous sample, not a suppressed target.
797        for i in 0..12 {
798            rt.create_entity(
799                &token,
800                "concept",
801                None,
802                &format!("Retrieval Fusion Note {i}"),
803                Some("khive retrieval fusion ranking note"),
804                None,
805                vec![],
806            )
807            .await
808            .expect("create entity");
809        }
810
811        let resolution = resolve_reference(
812            &rt,
813            &ring,
814            &token,
815            "khive retrieval fusion ranking",
816            5,
817            None,
818        )
819        .await
820        .expect("resolve_reference");
821
822        match resolution {
823            ReferenceResolution::Ambiguous { candidates } => {
824                assert_eq!(
825                    candidates.len(),
826                    5,
827                    "a non-exact ref's ambiguity payload is bounded to the caller's limit"
828                );
829            }
830            other => panic!("expected a bounded Ambiguous sample, got {other:?}"),
831        }
832    }
833
834    // Regression for #908: genuine ambiguity — two entities with the exact
835    // same canonical name — must still return `Ambiguous`, never a silent
836    // pick, after widening stage 4's retrieval floor.
837    #[tokio::test]
838    async fn fallback_stage_still_reports_ambiguous_on_genuine_tie() {
839        let rt = KhiveRuntime::memory().expect("in-memory runtime");
840        let token = actor_token("resolver-test");
841        let ring = ReferenceRing::new();
842
843        let a = rt
844            .create_entity(
845                &token,
846                "concept",
847                None,
848                "Twin Record",
849                Some("khive Twin Record document"),
850                None,
851                vec![],
852            )
853            .await
854            .expect("create entity a");
855        let b = rt
856            .create_entity(
857                &token,
858                "concept",
859                None,
860                "Twin Record",
861                Some("khive Twin Record document"),
862                None,
863                vec![],
864            )
865            .await
866            .expect("create entity b");
867
868        // Exact byte-identical names hit stage 3 (exact-name storage
869        // lookup), not stage 4 — but the same "must not silently pick"
870        // contract applies at both stages, and stage 3 is a cheaper,
871        // deterministic way to pin it.
872        let resolution = resolve_reference(&rt, &ring, &token, "Twin Record", 5, None)
873            .await
874            .expect("resolve_reference");
875
876        match resolution {
877            ReferenceResolution::Ambiguous { candidates } => {
878                let ids: std::collections::HashSet<Uuid> =
879                    candidates.iter().map(|c| c.id).collect();
880                assert!(ids.contains(&a.id) && ids.contains(&b.id));
881            }
882            other => panic!("expected Ambiguous on a genuine name tie, got {other:?}"),
883        }
884    }
885
886    #[tokio::test]
887    async fn fallback_stage_resolves_high_similarity_semantic_only_candidate() {
888        let rt = runtime_with_constant_embeddings();
889        let token = actor_token("resolver-test");
890        let ring = ReferenceRing::new();
891
892        let entity = rt
893            .create_entity(&token, "concept", None, "Canine", None, None, vec![])
894            .await
895            .expect("create semantic match");
896
897        let raw_hits = rt
898            .vector_search(
899                &token,
900                None,
901                Some("domestic dog"),
902                5,
903                Some(SubstrateKind::Entity),
904            )
905            .await
906            .expect("vector search");
907        assert_eq!(raw_hits.len(), 1);
908        assert_eq!(raw_hits[0].subject_id, entity.id);
909        // Identical constant embeddings have canonical cosine score 1.0,
910        // well above the raw-cosine floor of 0.3.
911        assert!((raw_hits[0].score.to_f64() - 1.0).abs() < 1e-6);
912
913        let hits = rt
914            .hybrid_search(&token, "domestic dog", None, 5, None, None, &[], None)
915            .await
916            .expect("hybrid search");
917        assert_eq!(hits.len(), 1);
918        assert_eq!(hits[0].source, SearchSource::Vector);
919
920        let resolution = resolve_reference(&rt, &ring, &token, "domestic dog", 5, None)
921            .await
922            .expect("resolve_reference");
923
924        assert_eq!(
925            resolution,
926            ReferenceResolution::Resolved {
927                id: entity.id,
928                confidence: SEARCH_RESOLVED_CONFIDENCE,
929            }
930        );
931    }
932
933    #[tokio::test]
934    async fn fallback_stage_resolves_moderate_similarity_semantic_only_candidate() {
935        // A canonical cosine score of 0.5 clears the raw-cosine floor of 0.3.
936        // This guards against reintroducing the legacy `(1 + cos) / 2` floor
937        // conversion, which would incorrectly raise the comparison floor to
938        // 0.65 after vector-store scores moved to the canonical cosine scale.
939        let rt = runtime_with_constant_embeddings();
940        let token = actor_token("resolver-test");
941        let ring = ReferenceRing::new();
942        let dimensions = EmbeddingModel::AllMiniLmL6V2.dimensions();
943
944        let entity = rt
945            .create_entity(
946                &token,
947                "concept",
948                None,
949                "Moderately Similar Candidate",
950                None,
951                None,
952                vec![],
953            )
954            .await
955            .expect("create moderate-similarity entity");
956        let vectors = rt.vectors(&token).expect("vector store");
957        vectors
958            .delete(entity.id)
959            .await
960            .expect("delete generated vector");
961        let aligned = dimensions * 3 / 4;
962        let mut moderate_vector = vec![1.0f32; aligned];
963        moderate_vector.extend(vec![-1.0f32; dimensions - aligned]);
964        vectors
965            .insert(
966                entity.id,
967                SubstrateKind::Entity,
968                token.namespace().as_str(),
969                "entity.body",
970                vec![moderate_vector],
971            )
972            .await
973            .expect("insert moderate-similarity vector");
974
975        let query = "totally-nonexistent-moderate-zzz";
976        let raw_hits = rt
977            .vector_search(&token, None, Some(query), 5, Some(SubstrateKind::Entity))
978            .await
979            .expect("vector search");
980        assert_eq!(raw_hits.len(), 1);
981        assert_eq!(raw_hits[0].subject_id, entity.id);
982        assert!((raw_hits[0].score.to_f64() - 0.5).abs() < 1e-6);
983
984        let resolution = resolve_reference(&rt, &ring, &token, query, 5, None)
985            .await
986            .expect("resolve_reference");
987
988        assert_eq!(
989            resolution,
990            ReferenceResolution::Resolved {
991                id: entity.id,
992                confidence: SEARCH_RESOLVED_CONFIDENCE,
993            }
994        );
995    }
996
997    #[tokio::test]
998    async fn fallback_stage_drops_orthogonal_semantic_only_candidate() {
999        // An orthogonal vector has canonical cosine score 0.0, below the
1000        // raw-cosine floor of 0.3. A sole semantic candidate at this
1001        // similarity must be dropped, not resolved.
1002        let rt = runtime_with_constant_embeddings();
1003        let token = actor_token("resolver-test");
1004        let ring = ReferenceRing::new();
1005        let dimensions = EmbeddingModel::AllMiniLmL6V2.dimensions();
1006
1007        let entity = rt
1008            .create_entity(
1009                &token,
1010                "concept",
1011                None,
1012                "Unrelated Orthogonal",
1013                None,
1014                None,
1015                vec![],
1016            )
1017            .await
1018            .expect("create unrelated entity");
1019        let vectors = rt.vectors(&token).expect("vector store");
1020        vectors
1021            .delete(entity.id)
1022            .await
1023            .expect("delete generated vector");
1024        let mut orthogonal_vector = vec![1.0f32; dimensions / 2];
1025        orthogonal_vector.extend(vec![-1.0f32; dimensions - dimensions / 2]);
1026        vectors
1027            .insert(
1028                entity.id,
1029                SubstrateKind::Entity,
1030                token.namespace().as_str(),
1031                "entity.body",
1032                vec![orthogonal_vector],
1033            )
1034            .await
1035            .expect("insert orthogonal vector");
1036
1037        let raw_hits = rt
1038            .vector_search(
1039                &token,
1040                None,
1041                Some("totally-nonexistent-orthogonal-zzz"),
1042                5,
1043                Some(SubstrateKind::Entity),
1044            )
1045            .await
1046            .expect("vector search");
1047        assert_eq!(raw_hits.len(), 1);
1048        assert!((raw_hits[0].score.to_f64() - 0.0).abs() < 1e-6);
1049
1050        let resolution = resolve_reference(
1051            &rt,
1052            &ring,
1053            &token,
1054            "totally-nonexistent-orthogonal-zzz",
1055            5,
1056            None,
1057        )
1058        .await
1059        .expect("resolve_reference");
1060
1061        assert_eq!(resolution, ReferenceResolution::NotFound);
1062    }
1063
1064    #[tokio::test]
1065    async fn fallback_stage_drops_low_similarity_semantic_only_candidates() {
1066        let rt = runtime_with_constant_embeddings();
1067        let token = actor_token("resolver-test");
1068        let ring = ReferenceRing::new();
1069        let dimensions = EmbeddingModel::AllMiniLmL6V2.dimensions();
1070
1071        let entity = rt
1072            .create_entity(
1073                &token,
1074                "concept",
1075                None,
1076                "Unrelated Alpha",
1077                None,
1078                None,
1079                vec![],
1080            )
1081            .await
1082            .expect("create unrelated entity");
1083        let vectors = rt.vectors(&token).expect("vector store");
1084        vectors
1085            .delete(entity.id)
1086            .await
1087            .expect("delete generated vector");
1088        // A quarter of dimensions aligned, three-quarters opposed against the
1089        // constant all-ones query embedding: canonical cosine score
1090        // 2*0.25 - 1 == -0.5. This is below the floor without being the
1091        // maximally-opposite case, so it exercises a genuine below-floor
1092        // mismatch rather than the degenerate cosine -1 extreme.
1093        let quarter = dimensions / 4;
1094        let mut mismatched_vector = vec![1.0f32; quarter];
1095        mismatched_vector.extend(vec![-1.0f32; dimensions - quarter]);
1096        vectors
1097            .insert(
1098                entity.id,
1099                SubstrateKind::Entity,
1100                token.namespace().as_str(),
1101                "entity.body",
1102                vec![mismatched_vector],
1103            )
1104            .await
1105            .expect("insert mismatched vector");
1106
1107        let raw_hits = rt
1108            .vector_search(
1109                &token,
1110                None,
1111                Some("totally-nonexistent-zzz"),
1112                5,
1113                Some(SubstrateKind::Entity),
1114            )
1115            .await
1116            .expect("vector search");
1117        assert_eq!(raw_hits.len(), 1);
1118        assert!((raw_hits[0].score.to_f64() + 0.5).abs() < 1e-6);
1119
1120        let resolution = resolve_reference(&rt, &ring, &token, "totally-nonexistent-zzz", 5, None)
1121            .await
1122            .expect("resolve_reference");
1123
1124        assert_eq!(resolution, ReferenceResolution::NotFound);
1125    }
1126
1127    // Regression for #908: garbage input that matches nothing must still be
1128    // `NotFound` after widening stage 4's retrieval floor — the widened pool
1129    // must not turn "nothing relevant exists" into a spurious pick.
1130    #[tokio::test]
1131    async fn fallback_stage_still_not_found_on_garbage() {
1132        let rt = KhiveRuntime::memory().expect("in-memory runtime");
1133        let token = actor_token("resolver-test");
1134        let ring = ReferenceRing::new();
1135
1136        rt.create_entity(
1137            &token,
1138            "concept",
1139            None,
1140            "ADR-040",
1141            Some("khive ADR-040"),
1142            None,
1143            vec![],
1144        )
1145        .await
1146        .expect("create unrelated entity");
1147
1148        let resolution = resolve_reference(
1149            &rt,
1150            &ring,
1151            &token,
1152            "zzqxw completely unrelated garbage nonsense",
1153            5,
1154            None,
1155        )
1156        .await
1157        .expect("resolve_reference");
1158        assert_eq!(resolution, ReferenceResolution::NotFound);
1159    }
1160}