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` or an alias the entity holds (ADR-221) 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` or a held alias — 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. No other stage reports this value, so a caller can tell a
75/// stage-3 hit by it; the kg `resolve` verb reads it to set `matched_alias`.
76pub const EXACT_NAME_CONFIDENCE: f64 = 0.98;
77/// Hybrid-search fallback: the top hit auto-resolves over a runner-up only
78/// when it leads by at least this ratio — RRF scores are not on a fixed
79/// 0..1 confidence scale, so a fixed absolute bar can't express "decisively
80/// best" the way it can for the ring. Below the margin, every hit above the
81/// score floor is surfaced as a candidate instead.
82const SEARCH_MARGIN_RATIO: f64 = 2.0;
83/// Vector hits below this raw cosine-similarity score are removed before RRF
84/// fusion. Lexical hits remain admissible because RRF magnitude encodes rank,
85/// not textual relevance, and genuine partial-name matches score below this floor.
86///
87/// This is a raw cosine value in `[-1.0, 1.0]`, matching the canonical
88/// vector-store score produced by `khive-db` (`1 - cosine_distance`).
89const SEARCH_VECTOR_SIMILARITY_FLOOR: f64 = 0.3;
90/// Confidence reported on a search-stage `Resolved` outcome: not the raw
91/// RRF score, which lives on a much smaller scale (`sum 1/(k + rank)`, e.g.
92/// ~0.016-0.033) and would never clear a 0..1 confidence bar. Fixed below
93/// both ring bands so callers can tell "the ring recognized this" from
94/// "search picked this out" by confidence alone; the raw RRF value is still
95/// preserved in `ReferenceCandidate.score` for `Ambiguous` listings.
96const SEARCH_RESOLVED_CONFIDENCE: f64 = 0.6;
97/// Floor on the retrieval depth stage 4 asks `hybrid_search` for, independent
98/// of the caller's requested `limit`.
99///
100/// `KhiveRuntime::hybrid_search` truncates its returned hit list to exactly
101/// the `limit` it is called with (its final step is `fused.truncate(limit as
102/// usize)`), so that `limit` doubles as both "how deep to search" and "how
103/// many hits to hand back" — for `resolve`, whose caller-facing default
104/// `limit` is 5 (`khive_pack_kg::handlers::resolve::DEFAULT_LIMIT`), a
105/// caller asking for a short candidate list was silently also asking for a
106/// shallow search. A genuine canonical-name match ranked, say, 6th-to-10th —
107/// exactly where a qualified natural-language ref (a project prefix ahead of
108/// a short canonical name) lands when it beats the exact-name stage above
109/// but only partially matches the text leg and is corroborated by the vector
110/// leg — was truncated out of the stage-4 candidate set entirely even though
111/// the same query against a wider `limit` (e.g. the `search` verb's own
112/// default of 10) surfaces it as the top hit (#908). Retrieving at this
113/// floor decouples "how deep to search" from "how many candidates the caller
114/// asked for". The full pool is retained for the decisiveness check, while an
115/// `Ambiguous` payload is truncated back to the caller's `limit` before it is
116/// returned.
117const STAGE4_MIN_SEARCH_LIMIT: u32 = 20;
118
119/// Resolve one natural-language reference for `token`'s actor.
120///
121/// `limit` bounds the hybrid-search fallback candidate count (Layer-0 stage
122/// 4); it has no effect on the id-string or ring stages, which are always
123/// exact-or-nothing / small in-memory scans. `entity_kind`, if set, restricts
124/// stage 3 to that entity kind (e.g. `"concept"`); the id-string and ring
125/// stages are kind-agnostic by construction (a ring entry or an explicit id
126/// is not filtered by kind).
127pub async fn resolve_reference(
128    runtime: &KhiveRuntime,
129    ring: &ReferenceRing,
130    token: &NamespaceToken,
131    nl_ref: &str,
132    limit: u32,
133    entity_kind: Option<&str>,
134) -> RuntimeResult<ReferenceResolution> {
135    resolve_reference_with_entity_type(runtime, ring, token, nl_ref, limit, entity_kind, None).await
136}
137
138/// Resolve with an optional canonical entity subtype in the exact-name and
139/// search stages. ID and ring matches retain their existing kind-agnostic
140/// behavior, so a subtype filter cannot turn an explicit ID into a fuzzy hit.
141#[allow(clippy::too_many_arguments)]
142pub async fn resolve_reference_with_entity_type(
143    runtime: &KhiveRuntime,
144    ring: &ReferenceRing,
145    token: &NamespaceToken,
146    nl_ref: &str,
147    limit: u32,
148    entity_kind: Option<&str>,
149    entity_type: Option<&str>,
150) -> RuntimeResult<ReferenceResolution> {
151    let trimmed = nl_ref.trim();
152    if trimmed.is_empty() {
153        return Ok(ReferenceResolution::NotFound);
154    }
155
156    // Stage 1: id-string passthrough (UUID / 8+ hex prefix) via the existing
157    // by-ID path. A ref shaped like an id but absent from storage is
158    // NotFound, not a fallthrough to ring/search: the caller named a
159    // specific id, so a miss there is the true answer. Scoped to entity ids
160    // only (both full-UUID and prefix forms) to match the ring's entity-only
161    // contract (`reference_ring::substrate_admits_as_entity`); a non-entity
162    // id-string is `NotFound` here: callers needing those already have `get`.
163    if let Ok(uuid) = Uuid::from_str(trimmed) {
164        return match runtime.resolve_by_id(token, uuid).await? {
165            Some(Resolved::Entity(_)) => Ok(ReferenceResolution::Resolved {
166                id: uuid,
167                confidence: 1.0,
168            }),
169            Some(_) | None => Ok(ReferenceResolution::NotFound),
170        };
171    }
172    if is_hex_prefix(trimmed) {
173        return match runtime.resolve_prefix_unfiltered(trimmed).await {
174            Ok(Some(uuid)) => match runtime.resolve_by_id(token, uuid).await? {
175                Some(Resolved::Entity(_)) => Ok(ReferenceResolution::Resolved {
176                    id: uuid,
177                    confidence: 1.0,
178                }),
179                Some(_) | None => Ok(ReferenceResolution::NotFound),
180            },
181            Ok(None) => Ok(ReferenceResolution::NotFound),
182            Err(RuntimeError::AmbiguousPrefix { matches, .. }) => {
183                let mut entity_matches = Vec::with_capacity(matches.len());
184                for id in matches {
185                    if matches!(
186                        runtime.resolve_by_id(token, id).await?,
187                        Some(Resolved::Entity(_))
188                    ) {
189                        entity_matches.push(id);
190                    }
191                }
192                match entity_matches.len() {
193                    0 => Ok(ReferenceResolution::NotFound),
194                    1 => Ok(ReferenceResolution::Resolved {
195                        id: entity_matches[0],
196                        confidence: 1.0,
197                    }),
198                    _ => Ok(ReferenceResolution::Ambiguous {
199                        candidates: entity_matches
200                            .into_iter()
201                            .map(|id| ReferenceCandidate {
202                                id,
203                                name: None,
204                                score: 1.0,
205                            })
206                            .collect(),
207                    }),
208                }
209            }
210            Err(e) => Err(e),
211        };
212    }
213
214    // Stage 2: recently-referenced ring.
215    let actor = token.actor();
216    let actor_key = format!("{}:{}", actor.kind, actor.id);
217    let ring_entries = ring.snapshot(token.namespace().as_str(), &actor_key);
218    let needle = trimmed.to_ascii_lowercase();
219
220    let exact: Vec<ReferenceCandidate> = ring_entries
221        .iter()
222        .filter(|e| {
223            e.name
224                .as_deref()
225                .is_some_and(|n| n.to_ascii_lowercase() == needle)
226        })
227        .map(|e| ReferenceCandidate {
228            id: e.id,
229            name: e.name.clone(),
230            score: RING_EXACT_CONFIDENCE,
231        })
232        .collect();
233    let exact = collapse_merged_candidates(runtime, token, exact).await?;
234    if let Some(resolution) = resolve_from_candidates(exact) {
235        return Ok(resolution);
236    }
237
238    let substring: Vec<ReferenceCandidate> = ring_entries
239        .iter()
240        .filter(|e| {
241            e.name.as_deref().is_some_and(|n| {
242                let n_lower = n.to_ascii_lowercase();
243                n_lower.contains(&needle) || needle.contains(&n_lower)
244            })
245        })
246        .map(|e| ReferenceCandidate {
247            id: e.id,
248            name: e.name.clone(),
249            score: RING_SUBSTRING_CONFIDENCE,
250        })
251        .collect();
252    let substring = collapse_merged_candidates(runtime, token, substring).await?;
253    if let Some(resolution) = resolve_from_candidates(substring) {
254        return Ok(resolution);
255    }
256
257    // Stage 3: exact-name storage lookup (#849) — a deterministic,
258    // case-sensitive match against `entities.name` or a held alias in the caller's
259    // namespace, run before the hybrid-search fallback so an existing exact
260    // name always resolves regardless of FTS ranking, RRF score, or whether
261    // this actor's session ever referenced the entity (the ring's blind
262    // spot). Single match resolves; multiple exact matches are `Ambiguous`;
263    // none falls through to hybrid search unchanged.
264    if let Some(resolution) =
265        exact_name_match(runtime, token, trimmed, entity_kind, entity_type).await?
266    {
267        return Ok(resolution);
268    }
269
270    // Stage 4: hybrid-search fallback over the namespace. Search deeper than
271    // the caller's requested `limit` (see `STAGE4_MIN_SEARCH_LIMIT`) so a
272    // genuine match ranked just outside a small `limit` isn't truncated out
273    // of the pool before it's even ranked against the alternatives; the
274    // caller's `limit` still bounds how many candidates get rendered below.
275    let candidate_limit = limit.max(1);
276    let search_limit = candidate_limit.max(STAGE4_MIN_SEARCH_LIMIT);
277    let hits = runtime
278        .hybrid_search_with_vector_similarity_floor(
279            token,
280            trimmed,
281            None,
282            search_limit,
283            entity_kind,
284            entity_type,
285            &[],
286            None,
287            SEARCH_VECTOR_SIMILARITY_FLOOR,
288        )
289        .await?;
290    let candidates: Vec<ReferenceCandidate> = hits
291        .into_iter()
292        .map(|h| ReferenceCandidate {
293            id: h.entity_id,
294            name: h.title,
295            score: h.score.to_f64(),
296        })
297        .collect();
298
299    match candidates.len() {
300        0 => Ok(ReferenceResolution::NotFound),
301        // A lone hit is presence-decisive: there is no competing candidate to
302        // be ambiguous against, regardless of its raw RRF magnitude (see
303        // `SEARCH_RESOLVED_CONFIDENCE`).
304        1 => Ok(ReferenceResolution::Resolved {
305            id: candidates[0].id,
306            confidence: SEARCH_RESOLVED_CONFIDENCE,
307        }),
308        _ => {
309            let top_score = candidates[0].score;
310            let second_score = candidates[1].score;
311            let decisive =
312                second_score <= f64::EPSILON || top_score / second_score >= SEARCH_MARGIN_RATIO;
313            if decisive {
314                Ok(ReferenceResolution::Resolved {
315                    id: candidates[0].id,
316                    confidence: SEARCH_RESOLVED_CONFIDENCE,
317                })
318            } else {
319                // Non-exact ambiguity: bound the payload to the caller's
320                // `limit`. Any deterministic identity (an exact canonical
321                // name) was already resolved by stage 3 above, so nothing
322                // withheld here is "the" answer — outside exact matches there
323                // is no oracle for a single canonical candidate. Raising
324                // `limit` surfaces deeper ranks (#970; resolve() contract).
325                let mut candidates = candidates;
326                candidates.truncate(candidate_limit as usize);
327                Ok(ReferenceResolution::Ambiguous { candidates })
328            }
329        }
330    }
331}
332
333/// Merge hops a ring candidate is followed through before it is left as is.
334const MAX_MERGE_HOPS: usize = 32;
335
336/// Count ring candidates by the entity they name now (ADR-221 section 3): a
337/// merged-away entity the ring still holds by its old name and the live entity
338/// it was merged into are one entity, so they collapse onto the live id. A
339/// candidate whose chain ends at a deleted entity or runs past
340/// [`MAX_MERGE_HOPS`] stays as it is. One candidate or none is returned
341/// unread.
342async fn collapse_merged_candidates(
343    runtime: &KhiveRuntime,
344    token: &NamespaceToken,
345    candidates: Vec<ReferenceCandidate>,
346) -> RuntimeResult<Vec<ReferenceCandidate>> {
347    if candidates.len() < 2 {
348        return Ok(candidates);
349    }
350    let store = runtime.entities(token)?;
351    let mut collapsed: Vec<ReferenceCandidate> = Vec::with_capacity(candidates.len());
352    for mut candidate in candidates {
353        let mut current = candidate.id;
354        for _ in 0..MAX_MERGE_HOPS {
355            let Some(entity) = store.get_entity_including_deleted(current).await? else {
356                break;
357            };
358            match (entity.deleted_at, entity.merged_into) {
359                (Some(_), Some(next)) => current = next,
360                (None, _) => {
361                    candidate.id = current;
362                    break;
363                }
364                (Some(_), None) => break,
365            }
366        }
367        if !collapsed.iter().any(|held| held.id == candidate.id) {
368            collapsed.push(candidate);
369        }
370    }
371    Ok(collapsed)
372}
373
374/// Apply the shared "single-above-bar resolves, multiple is ambiguous"
375/// contract to a candidate set already known to be an exact or substring
376/// ring match. Returns `None` when `candidates` is empty — the caller falls
377/// through to the next resolution stage instead of reporting `NotFound`
378/// prematurely.
379fn resolve_from_candidates(candidates: Vec<ReferenceCandidate>) -> Option<ReferenceResolution> {
380    match candidates.len() {
381        0 => None,
382        1 => {
383            let top = &candidates[0];
384            Some(if top.score >= RING_AUTO_RESOLVE_CONFIDENCE {
385                ReferenceResolution::Resolved {
386                    id: top.id,
387                    confidence: top.score,
388                }
389            } else {
390                ReferenceResolution::Ambiguous { candidates }
391            })
392        }
393        _ => Some(ReferenceResolution::Ambiguous { candidates }),
394    }
395}
396
397/// Stage 3 of `resolve_reference` (#849): a deterministic, case-sensitive
398/// exact match against `entities.name` or an alias the entity holds
399/// (ADR-221 section 2; an entity matching by both counts once), scoped to `token.namespace()` (the
400/// same single-namespace default the rest of this pipeline and the sibling
401/// by-name lookup in `khive-pack-kg`'s `resolve_name_async` use) and to
402/// `entity_kind` when the caller filtered by one. `query_entities` already
403/// excludes soft-deleted rows (`deleted_at IS NULL` is baked into every
404/// query — see `khive-db::stores::entity::build_entity_where`), so no
405/// separate filter is needed here. Returns `None` (fall through to the next
406/// stage) when nothing matches; `Some(Resolved)` on a single hit; and
407/// `Some(Ambiguous)` when the name is not unique.
408async fn exact_name_match(
409    runtime: &KhiveRuntime,
410    token: &NamespaceToken,
411    name: &str,
412    entity_kind: Option<&str>,
413    entity_type: Option<&str>,
414) -> RuntimeResult<Option<ReferenceResolution>> {
415    let mut filter = EntityFilter {
416        name_or_alias_exact: Some(name.to_string()),
417        kinds: entity_kind.map(|k| vec![k.to_string()]).unwrap_or_default(),
418        ..EntityFilter::default()
419    };
420    if let (Some(kind), Some(entity_type)) = (entity_kind, entity_type) {
421        filter
422            .entity_types_by_kind
423            .insert(kind.to_string(), vec![entity_type.to_string()]);
424    }
425    // A storage-level `name = ?` predicate (not `name_prefix` + in-memory
426    // filter) so a namespace with many newer case variants of `name` can
427    // never page the exact target out from under a `created_at DESC` sort
428    // (#849, #852) — every row this query returns already carries `name` as its name or an alias.
429    // The page is small (10, not 1), but the zero/one/many decision is made
430    // from `page.total` (the storage-computed COUNT(*) under the same
431    // predicate), never from `page.items.len()` — with 11+ byte-identical
432    // exact names the fetched page is still only 10 rows, and deciding from
433    // its length alone would under-report cardinality. `Ambiguous.candidates`
434    // is a bounded sample of up to 10 of the `page.total` matches, not the
435    // complete set — the variant carries no total field, so callers must not
436    // assume `candidates.len() == page.total` (#852).
437    let page = runtime
438        .entities(token)?
439        .query_entities(
440            token.namespace().as_str(),
441            filter,
442            PageRequest {
443                offset: 0,
444                limit: 10,
445            },
446        )
447        .await
448        .map_err(RuntimeError::Storage)?;
449
450    let total = page.total.unwrap_or(page.items.len() as u64);
451
452    let exact: Vec<ReferenceCandidate> = page
453        .items
454        .into_iter()
455        .map(|e| ReferenceCandidate {
456            id: e.id,
457            name: Some(e.name),
458            score: EXACT_NAME_CONFIDENCE,
459        })
460        .collect();
461
462    Ok(match total {
463        0 => None,
464        1 => exact
465            .into_iter()
466            .next()
467            .map(|top| ReferenceResolution::Resolved {
468                id: top.id,
469                confidence: EXACT_NAME_CONFIDENCE,
470            }),
471        _ => Some(ReferenceResolution::Ambiguous { candidates: exact }),
472    })
473}
474
475fn is_hex_prefix(s: &str) -> bool {
476    s.len() >= 8 && s.chars().all(|c| c.is_ascii_hexdigit())
477}
478
479#[cfg(test)]
480#[path = "reference_resolution_tests.rs"]
481mod tests;