Skip to main content

innate_core/kb/
mod.rs

1//! KnowledgeBase — all 8 Public APIs.
2
3/// Return type for pack(): (selected_chunks, skipped_groups, skip_reasons)
4type PackResult = (
5    Vec<Value>,
6    Vec<(Vec<Value>, f64, usize)>,
7    std::collections::HashMap<String, String>,
8);
9
10use std::collections::{HashMap, HashSet};
11use std::path::Path;
12use std::sync::Arc;
13
14use serde_json::{json, Value};
15
16use crate::embedding::{DummyEmbeddingProvider, EmbeddingProvider};
17use crate::errors::{InnateError, Result};
18use crate::refine::{
19    DefaultSanitizer, DistilledChunk, Distiller, HeuristicDistiller, NoopReranker, NullRefiner,
20    Refiner, Reranker, Sanitizer,
21};
22use crate::storage::{ChunkRow, EpisodicLogRow, Storage};
23use crate::utils::{
24    agent_source, content_hash, estimate_tokens, gen_uuid, pack_embedding, utc_now_iso,
25    SanitizeAction,
26};
27
28mod appraise;
29mod curate;
30mod evolve;
31mod inspection;
32mod lifecycle;
33mod recall;
34mod record;
35mod repair;
36mod situation;
37
38pub use appraise::{
39    AbstainReason, AppraiseParams, Contributor, FlaggedPoint, Tier, Valence, Verdict,
40    APPRAISE_ADVISORY,
41};
42pub use recall::RecallParams;
43pub use record::RecordParams;
44pub use repair::TraceRepairReport;
45pub use situation::Situation;
46
47// ---------------------------------------------------------------------------
48// Tuning defaults
49// ---------------------------------------------------------------------------
50
51// Fused recall score weights. These intentionally sum to 1.05 (not 1.0): the
52// score is a relative ranking signal, not a calibrated probability, so the extra
53// 0.05 of headroom on content similarity is deliberate and the result is never
54// re-normalised. Keep this in mind before "fixing" the sum.
55const W_CONTENT: f64 = 0.55;
56const W_TRIGGER: f64 = 0.25;
57const W_CONFIDENCE: f64 = 0.10;
58const W_CONTEXT: f64 = 0.15;
59const W_ACTIVATION: f64 = 0.08;
60// Hybrid 检索:lexical/BM25 channel weight. Modest by default so exact-term
61// matches lift the right chunk without overpowering semantic similarity.
62const W_LEXICAL: f64 = 0.25;
63// ACT-R spreading-activation channel (SAG-inspired associative recall). Weight of
64// the spread score in the fused sum. Defaults to 0.0 — OFF — so the no-LLM hot
65// path is byte-for-byte unchanged until a multi-hop eval set justifies turning it
66// on. When 0, recall skips the entity-expansion work entirely (zero added cost).
67const W_SPREAD: f64 = 0.0;
68// Entities linking more chunks than this are treated as non-discriminative and
69// dropped from the spread (ACT-R fan effect taken to its limit). Keeps promiscuous
70// tokens (`--release`, `rust`) from flooding the candidate set.
71const SPREAD_FAN_CAP: i64 = 50;
72// Number of top base-relevance candidates whose entities seed the 2-hop spread.
73const SPREAD_SEED_N: usize = 5;
74const TOP_K_CANDIDATES: usize = 20;
75const ANTI_TRIGGER_PENALTY: f64 = 0.6;
76const DENSITY_REFILL: bool = true;
77
78const LOW_CONF_THRESHOLD: f64 = 0.25;
79const LOW_CONF_IDLE_DAYS: i64 = 60;
80const REPEAT_SELECT_MIN: i64 = 10;
81const REPEAT_SELECT_CONF_MAX: f64 = 0.5;
82const NEVER_USED_AGE_DAYS: i64 = 30;
83const OPEN_TTL_DAYS: i64 = 14;
84const SCREENING_TIMEOUT_MINUTES: i64 = 30;
85const METRICS_RETAIN_DAYS: i64 = 30;
86const PROMOTE_USED_SUCCESS_MIN: i64 = 3;
87const PROMOTE_CONFIDENCE_MIN: f64 = 0.60;
88const DECAY_FLOOR: f64 = 0.20;
89const EVOLVE_THRESHOLD: i64 = 5;
90const DISTILL_BATCH_SIZE: usize = 20;
91const PENDING_RECALL_PENALTY: f64 = 0.60;
92
93// Intuition / appraise critic defaults (Spec §8). The appraise path reuses the
94// same fused score as recall; these only govern how that score is tiered/flagged.
95const APPRAISE_TIER_WEAK: f64 = 0.30;
96const APPRAISE_TIER_STRONG: f64 = 0.65;
97const APPRAISE_MIN_STRENGTH: f64 = 0.40;
98const APPRAISE_TOP: usize = 8;
99const APPRAISE_TRIGGER_HIT_MIN: f64 = 0.50;
100const APPRAISE_CANDIDATE_IN_EMBED: bool = true;
101// 弃权门(方案 A/F/G)。默认值保持现行行为(门2/门3/门4 关闭),由 meta 调参激活。
102//   门2 signature_floor=0.0   → 关闭(任何一致度都放行)
103//   门3 min_evidence=0        → 关闭(不要求观测历史)
104//   门4 conflict_ceiling=1.0  → 关闭(离散度上界恒不触发)
105// 门1 弱共振无需阈值:prune 后候选为空即弃权(WeakResonance),天然作动。
106const APPRAISE_SIGNATURE_FLOOR: f64 = 0.0;
107const APPRAISE_MIN_EVIDENCE: i64 = 0;
108const APPRAISE_CONFLICT_CEILING: f64 = 1.0;
109// 方案 D 基率锚定先验:prior = Beta(m·g0, m·(1-g0))。默认 m=2, g0=0.5 与旧 Laplace
110// (wins+1)/(evidence+2) 完全等价 → 零行为变化,调大 m / 设真实基率即激活。
111// **仅作用于 appraise(直觉/校准)路径**:实施文档明确范围不含 recall。
112const INTUITION_PRIOR_M: f64 = 2.0;
113const INTUITION_BASE_RATE: f64 = 0.5;
114// recall(图书管理员)路径恒用中性 Laplace 先验(m=2, g0=0.5),与历史
115// (wins+1)/(evidence+2) 逐位等价,绝不受 intuition.* 校准旋钮影响。方案 D 与 recall 解耦。
116const RECALL_PRIOR_M: f64 = 2.0;
117const RECALL_BASE_RATE: f64 = 0.5;
118// 方案 E 校准映射桶数。
119const CALIBRATION_BINS: i64 = 10;
120const SITUATION_COARSE_KEYS: &str = "stage,error_class,file_type";
121// Part (c) — query-embedding granularity. When true, recall folds the normalized
122// situation signature (stage/error_class/file_type) into the embedded query text so
123// the embedding anchors on the situation, not just raw words. Default OFF: opt-in
124// and reversible (chunks are embedded from content/trigger, so enabling it shifts
125// only the query side — measure with `innate recall-eval` before turning on).
126const EMBED_SITUATION_SIGNATURE: bool = false;
127const GOVERNANCE_ARCHIVE_THRESHOLD: i64 = 3;
128const NEGATIVE_FEEDBACK_ARCHIVE_THRESHOLD: i64 = 5;
129const GOVERNANCE_EVOLVE_THRESHOLD: i64 = 3;
130const FAILURE_MIN_USES: i64 = 5;
131const FAILURE_MAX_SUCCESS_RATE: f64 = 0.20;
132const FAILURE_CONFIDENCE_MAX: f64 = 0.35;
133const LOG_COMPACT_DAYS: i64 = 30;
134
135// ---------------------------------------------------------------------------
136// Public result types
137// ---------------------------------------------------------------------------
138
139#[derive(Debug, Default, Clone)]
140pub struct RecallResult {
141    pub knowledge: Vec<Value>,
142    pub sparks: Vec<Value>,
143    pub trace_id: String,
144    pub empty: bool,
145    pub depth_skipped: Vec<String>,
146    pub skipped_reasons: HashMap<String, String>,
147}
148
149#[derive(Debug, Default)]
150pub struct CurateReport {
151    pub archived: Vec<String>,
152    pub deduped: Vec<String>,
153    pub decayed: Vec<String>,
154    pub cycles: Vec<Vec<String>>,
155    pub orphans: Vec<String>,
156    pub recovered: Vec<String>,
157    pub warnings: Vec<String>,
158    pub stats: HashMap<String, Value>,
159}
160
161#[derive(Debug, Default)]
162struct DistillBatchReport {
163    distilled: usize,
164    failed: usize,
165}
166
167/// Scope for a single Curate run — allows limiting governance to a subset of chunks.
168#[derive(Debug, Default, Clone)]
169pub struct CurateScope {
170    /// If set, only process chunks with this origin (e.g. "distilled").
171    pub origin: Option<String>,
172    /// If set, only process chunks belonging to this skill.
173    pub skill_name: Option<String>,
174    /// When true, compute the report but do not write any changes.
175    pub dry_run: bool,
176}
177
178/// Replaceable governance interface (§二·六). Inject via `KnowledgeBase::open_with`.
179/// Default implementation: `BuiltinCurator`.
180pub trait Curator: Send + Sync {
181    fn run(&self, kb: &KnowledgeBase, scope: &CurateScope) -> Result<CurateReport>;
182}
183
184/// Built-in curator — implements the full §四 governance pipeline.
185pub struct BuiltinCurator;
186
187impl Curator for BuiltinCurator {
188    fn run(&self, kb: &KnowledgeBase, scope: &CurateScope) -> Result<CurateReport> {
189        kb.builtin_curate_impl(scope)
190    }
191}
192
193// ---------------------------------------------------------------------------
194// KnowledgeBase
195// ---------------------------------------------------------------------------
196
197pub struct KnowledgeBase {
198    pub storage: Storage,
199    embedding: Arc<dyn EmbeddingProvider>,
200    refiner: Arc<dyn Refiner>,
201    distiller: Arc<dyn Distiller>,
202    curator: Arc<dyn Curator>,
203    sanitizer: Arc<dyn Sanitizer>,
204    /// Opt-in offline reranker (part d). Defaults to `NoopReranker` (fused order
205    /// preserved); set via `with_reranker` when an LLM is configured.
206    reranker: Arc<dyn Reranker>,
207
208    // Tuning params (loaded from meta at init)
209    w_content: f64,
210    w_trigger: f64,
211    w_confidence: f64,
212    w_context: f64,
213    w_activation: f64,
214    w_lexical: f64,
215    w_spread: f64,
216    spread_fan_cap: i64,
217    spread_seed_n: usize,
218    top_k_candidates: usize,
219    anti_trigger_penalty: f64,
220    density_refill: bool,
221
222    low_conf_threshold: f64,
223    low_conf_idle_days: i64,
224    repeat_select_min: i64,
225    repeat_select_conf_max: f64,
226    never_used_age_days: i64,
227    open_ttl_days: i64,
228    screening_timeout_minutes: i64,
229    metrics_retain_days: i64,
230    promote_used_success_min: i64,
231    promote_confidence_min: f64,
232    decay_floor: f64,
233    evolve_threshold: i64,
234    distill_batch_size: usize,
235    evolve_schedule_interval_hours: i64,
236    governance_archive_threshold: i64,
237    negative_feedback_archive_threshold: i64,
238    governance_evolve_threshold: i64,
239    governance_proposal_max_age_days: i64,
240    failure_min_uses: i64,
241    failure_max_success_rate: f64,
242    failure_confidence_max: f64,
243    log_compact_days: i64,
244
245    // Intuition / appraise critic params
246    appraise_tier_weak: f64,
247    appraise_tier_strong: f64,
248    appraise_min_strength: f64,
249    appraise_top: usize,
250    appraise_trigger_hit_min: f64,
251    appraise_candidate_in_embed: bool,
252    appraise_signature_floor: f64,
253    appraise_min_evidence: i64,
254    appraise_conflict_ceiling: f64,
255    intuition_prior_m: f64,
256    intuition_base_rate: f64,
257    calibration_bins: i64,
258    situation_coarse_keys: String,
259    embed_situation_signature: bool,
260}
261
262impl KnowledgeBase {
263    pub fn open(db_path: impl AsRef<Path>) -> Result<Self> {
264        Self::open_with(db_path, None, None, None, None, None)
265    }
266
267    /// Persist a content embedding, rejecting any vector whose dimension differs
268    /// from the configured provider. A mismatched vector is silently skipped at
269    /// search time (cosine search only scores equal-dimension vectors), so an
270    /// unchecked write becomes invisible recall loss with no error. Fail closed
271    /// at the write boundary instead. All vector writers route through here.
272    pub(crate) fn store_vec_content(&self, chunk_id: &str, cvec: &[f32]) -> Result<()> {
273        let want = self.embedding.content_dim();
274        if cvec.len() != want {
275            return Err(InnateError::InvalidState(format!(
276                "content embedding dim {} != configured {want} (chunk {chunk_id})",
277                cvec.len()
278            )));
279        }
280        self.storage
281            .insert_vec_content(chunk_id, &pack_embedding(cvec))
282    }
283
284    /// Trigger-vector counterpart of [`store_vec_content`]; same fail-closed
285    /// dimension guard against `trigger_dim()`.
286    pub(crate) fn store_vec_trigger(&self, chunk_id: &str, tvec: &[f32]) -> Result<()> {
287        let want = self.embedding.trigger_dim();
288        if tvec.len() != want {
289            return Err(InnateError::InvalidState(format!(
290                "trigger embedding dim {} != configured {want} (chunk {chunk_id})",
291                tvec.len()
292            )));
293        }
294        self.storage
295            .insert_vec_trigger(chunk_id, &pack_embedding(tvec))
296    }
297
298    pub fn open_with(
299        db_path: impl AsRef<Path>,
300        embedding: Option<Arc<dyn EmbeddingProvider>>,
301        refiner: Option<Arc<dyn Refiner>>,
302        distiller: Option<Arc<dyn Distiller>>,
303        curator: Option<Arc<dyn Curator>>,
304        sanitizer: Option<Arc<dyn Sanitizer>>,
305    ) -> Result<Self> {
306        let embedding = embedding.unwrap_or_else(|| Arc::new(DummyEmbeddingProvider::default()));
307        let refiner = refiner.unwrap_or_else(|| Arc::new(NullRefiner));
308        let distiller = distiller.unwrap_or_else(|| Arc::new(HeuristicDistiller));
309        let curator = curator.unwrap_or_else(|| Arc::new(BuiltinCurator));
310        let sanitizer = sanitizer.unwrap_or_else(|| Arc::new(DefaultSanitizer));
311        let reranker: Arc<dyn Reranker> = Arc::new(NoopReranker);
312
313        let storage = Storage::open(db_path, embedding.content_dim(), embedding.trigger_dim())?;
314
315        let mut kb = Self {
316            storage,
317            embedding,
318            refiner,
319            distiller,
320            curator,
321            sanitizer,
322            reranker,
323            w_lexical: W_LEXICAL,
324            w_spread: W_SPREAD,
325            spread_fan_cap: SPREAD_FAN_CAP,
326            spread_seed_n: SPREAD_SEED_N,
327            embed_situation_signature: EMBED_SITUATION_SIGNATURE,
328            w_content: W_CONTENT,
329            w_trigger: W_TRIGGER,
330            w_confidence: W_CONFIDENCE,
331            w_context: W_CONTEXT,
332            w_activation: W_ACTIVATION,
333            top_k_candidates: TOP_K_CANDIDATES,
334            anti_trigger_penalty: ANTI_TRIGGER_PENALTY,
335            density_refill: DENSITY_REFILL,
336            low_conf_threshold: LOW_CONF_THRESHOLD,
337            low_conf_idle_days: LOW_CONF_IDLE_DAYS,
338            repeat_select_min: REPEAT_SELECT_MIN,
339            repeat_select_conf_max: REPEAT_SELECT_CONF_MAX,
340            never_used_age_days: NEVER_USED_AGE_DAYS,
341            open_ttl_days: OPEN_TTL_DAYS,
342            metrics_retain_days: METRICS_RETAIN_DAYS,
343            screening_timeout_minutes: SCREENING_TIMEOUT_MINUTES,
344            promote_used_success_min: PROMOTE_USED_SUCCESS_MIN,
345            promote_confidence_min: PROMOTE_CONFIDENCE_MIN,
346            decay_floor: DECAY_FLOOR,
347            evolve_threshold: EVOLVE_THRESHOLD,
348            distill_batch_size: DISTILL_BATCH_SIZE,
349            evolve_schedule_interval_hours: 6,
350            governance_archive_threshold: GOVERNANCE_ARCHIVE_THRESHOLD,
351            negative_feedback_archive_threshold: NEGATIVE_FEEDBACK_ARCHIVE_THRESHOLD,
352            governance_evolve_threshold: GOVERNANCE_EVOLVE_THRESHOLD,
353            governance_proposal_max_age_days: 30,
354            failure_min_uses: FAILURE_MIN_USES,
355            failure_max_success_rate: FAILURE_MAX_SUCCESS_RATE,
356            failure_confidence_max: FAILURE_CONFIDENCE_MAX,
357            log_compact_days: LOG_COMPACT_DAYS,
358            appraise_tier_weak: APPRAISE_TIER_WEAK,
359            appraise_tier_strong: APPRAISE_TIER_STRONG,
360            appraise_min_strength: APPRAISE_MIN_STRENGTH,
361            appraise_top: APPRAISE_TOP,
362            appraise_trigger_hit_min: APPRAISE_TRIGGER_HIT_MIN,
363            appraise_candidate_in_embed: APPRAISE_CANDIDATE_IN_EMBED,
364            appraise_signature_floor: APPRAISE_SIGNATURE_FLOOR,
365            appraise_min_evidence: APPRAISE_MIN_EVIDENCE,
366            appraise_conflict_ceiling: APPRAISE_CONFLICT_CEILING,
367            intuition_prior_m: INTUITION_PRIOR_M,
368            intuition_base_rate: INTUITION_BASE_RATE,
369            calibration_bins: CALIBRATION_BINS,
370            situation_coarse_keys: SITUATION_COARSE_KEYS.to_string(),
371        };
372        kb.init_meta()?;
373        kb.load_params()?;
374        Ok(kb)
375    }
376
377    /// Install an opt-in offline reranker (part d). Used by `open_kb` when an LLM is
378    /// configured; recall only invokes it when a caller passes `rerank=true`, so the
379    /// default hook path stays no-LLM regardless.
380    pub fn with_reranker(mut self, reranker: Arc<dyn Reranker>) -> Self {
381        self.reranker = reranker;
382        self
383    }
384
385    fn init_meta(&self) -> Result<()> {
386        let lib_id = gen_uuid();
387        let content_dim = self.embedding.content_dim().to_string();
388        let trigger_dim = self.embedding.trigger_dim().to_string();
389        let embed_model = self.embedding.model_name();
390
391        for (key, expected) in [
392            ("content_dim", self.embedding.content_dim()),
393            ("trigger_dim", self.embedding.trigger_dim()),
394        ] {
395            if let Some(stored) = self.storage.get_meta(key)? {
396                let actual = stored.parse::<usize>().map_err(|_| {
397                    InnateError::Other(format!("invalid {key} metadata value: {stored}"))
398                })?;
399                if actual != expected {
400                    return Err(InnateError::Other(format!(
401                        "{key} mismatch: database uses {actual}, embedding provider uses {expected}"
402                    )));
403                }
404            }
405        }
406
407        let defaults: &[(&str, &str)] = &[
408            ("lib_id", &lib_id),
409            ("lib_role", "personal"),
410            ("schema_version", "4.14"),
411            ("content_dim", &content_dim),
412            ("trigger_dim", &trigger_dim),
413            ("embed_model", embed_model),
414            ("embed_version", "1"),
415            ("vector_revision", "0"),
416            ("last_agg_ts", "1970-01-01T00:00:00.000Z"),
417            ("recall.w_content", "0.55"),
418            ("recall.w_trigger", "0.25"),
419            ("recall.w_confidence", "0.10"),
420            ("recall.w_context", "0.15"),
421            ("recall.w_activation", "0.08"),
422            ("recall.w_lexical", "0.25"),
423            ("recall.w_spread", "0.0"),
424            ("recall.spread_fan_cap", "50"),
425            ("recall.spread_seed_n", "5"),
426            ("recall.embed_situation_signature", "false"),
427            ("recall.top_k_candidates", "20"),
428            ("recall.anti_trigger_penalty", "0.6"),
429            ("recall.density_refill", "true"),
430            ("curate.low_conf_threshold", "0.25"),
431            ("curate.low_conf_idle_days", "60"),
432            ("curate.repeat_select_min", "10"),
433            ("curate.repeat_select_conf_max", "0.5"),
434            ("curate.never_used_age_days", "30"),
435            ("metrics.retain_days", "30"),
436            ("curate.open_ttl_days", "14"),
437            ("curate.screening_timeout_minutes", "30"),
438            ("curate.promote_used_success_min", "3"),
439            ("curate.promote_confidence_min", "0.60"),
440            ("curate.decay_floor", "0.20"),
441            ("evolve.threshold_new_count", "5"),
442            ("evolve.distill_batch_size", "20"),
443            ("evolve.schedule_interval_hours", "6"),
444            ("curate.soft_mature_threshold", "5"),
445            ("evolve.distill_token_window_hours", "24"),
446            ("curate.governance_archive_threshold", "3"),
447            ("curate.negative_feedback_archive_threshold", "5"),
448            ("evolve.governance_pending_threshold", "3"),
449            ("curate.governance_proposal_max_age_days", "30"),
450            ("curate.failure_min_uses", "5"),
451            ("curate.failure_max_success_rate", "0.20"),
452            ("curate.failure_confidence_max", "0.35"),
453            ("curate.log_compact_days", "30"),
454            ("appraise.tier_weak", "0.30"),
455            ("appraise.tier_strong", "0.65"),
456            ("appraise.min_strength", "0.40"),
457            ("appraise.top", "8"),
458            ("appraise.trigger_hit_min", "0.50"),
459            ("appraise.candidate_in_embed", "true"),
460            ("appraise.signature_floor", "0.0"),
461            ("appraise.min_evidence", "0"),
462            ("appraise.conflict_ceiling", "1.0"),
463            ("intuition.prior_m", "2.0"),
464            ("intuition.base_rate", "0.5"),
465            ("intuition.calibration_bins", "10"),
466            ("situation.coarse_keys", "stage,error_class,file_type"),
467        ];
468        self.storage.begin_immediate()?;
469        let result = (|| -> Result<()> {
470            for (k, v) in defaults {
471                if self.storage.get_meta(k)?.is_none() {
472                    self.storage.set_meta(k, v)?;
473                }
474            }
475            self.storage.commit()
476        })();
477        if result.is_err() {
478            let _ = self.storage.rollback();
479        }
480        result
481    }
482
483    fn load_params(&mut self) -> Result<()> {
484        let f = |k: &str, d: f64| -> f64 {
485            self.storage
486                .get_meta(k)
487                .ok()
488                .flatten()
489                .and_then(|v| v.parse().ok())
490                .unwrap_or(d)
491        };
492        let i = |k: &str, d: i64| -> i64 {
493            self.storage
494                .get_meta(k)
495                .ok()
496                .flatten()
497                .and_then(|v| v.parse().ok())
498                .unwrap_or(d)
499        };
500        let b = |k: &str, d: bool| -> bool {
501            self.storage
502                .get_meta(k)
503                .ok()
504                .flatten()
505                .map(|v| v.to_lowercase() == "true")
506                .unwrap_or(d)
507        };
508        self.w_content = f("recall.w_content", W_CONTENT);
509        self.w_trigger = f("recall.w_trigger", W_TRIGGER);
510        self.w_confidence = f("recall.w_confidence", W_CONFIDENCE);
511        self.w_context = f("recall.w_context", W_CONTEXT);
512        self.w_lexical = f("recall.w_lexical", W_LEXICAL);
513        self.w_spread = f("recall.w_spread", W_SPREAD);
514        self.spread_fan_cap = i("recall.spread_fan_cap", SPREAD_FAN_CAP).max(1);
515        self.spread_seed_n = i("recall.spread_seed_n", SPREAD_SEED_N as i64).max(0) as usize;
516        self.embed_situation_signature =
517            b("recall.embed_situation_signature", EMBED_SITUATION_SIGNATURE);
518        self.w_activation = f("recall.w_activation", W_ACTIVATION);
519        self.top_k_candidates =
520            i("recall.top_k_candidates", TOP_K_CANDIDATES as i64).max(1) as usize;
521        self.anti_trigger_penalty = f("recall.anti_trigger_penalty", ANTI_TRIGGER_PENALTY);
522        self.density_refill = b("recall.density_refill", DENSITY_REFILL);
523        self.low_conf_threshold = f("curate.low_conf_threshold", LOW_CONF_THRESHOLD);
524        self.low_conf_idle_days = i("curate.low_conf_idle_days", LOW_CONF_IDLE_DAYS);
525        self.repeat_select_min = i("curate.repeat_select_min", REPEAT_SELECT_MIN);
526        self.metrics_retain_days = i("metrics.retain_days", METRICS_RETAIN_DAYS);
527        self.repeat_select_conf_max = f("curate.repeat_select_conf_max", REPEAT_SELECT_CONF_MAX);
528        self.never_used_age_days = i("curate.never_used_age_days", NEVER_USED_AGE_DAYS);
529        self.open_ttl_days = i("curate.open_ttl_days", OPEN_TTL_DAYS);
530        self.screening_timeout_minutes = i(
531            "curate.screening_timeout_minutes",
532            SCREENING_TIMEOUT_MINUTES,
533        );
534        self.promote_used_success_min =
535            i("curate.promote_used_success_min", PROMOTE_USED_SUCCESS_MIN);
536        self.promote_confidence_min = f("curate.promote_confidence_min", PROMOTE_CONFIDENCE_MIN);
537        self.decay_floor = f("curate.decay_floor", DECAY_FLOOR).clamp(0.0, 0.4);
538        self.evolve_threshold = i("evolve.threshold_new_count", EVOLVE_THRESHOLD);
539        self.distill_batch_size =
540            i("evolve.distill_batch_size", DISTILL_BATCH_SIZE as i64) as usize;
541        self.evolve_schedule_interval_hours = i("evolve.schedule_interval_hours", 6).max(1);
542        self.governance_archive_threshold = i(
543            "curate.governance_archive_threshold",
544            GOVERNANCE_ARCHIVE_THRESHOLD,
545        )
546        .max(1);
547        self.negative_feedback_archive_threshold = i(
548            "curate.negative_feedback_archive_threshold",
549            NEGATIVE_FEEDBACK_ARCHIVE_THRESHOLD,
550        )
551        .max(1);
552        self.governance_evolve_threshold = i(
553            "evolve.governance_pending_threshold",
554            GOVERNANCE_EVOLVE_THRESHOLD,
555        )
556        .max(1);
557        self.governance_proposal_max_age_days =
558            i("curate.governance_proposal_max_age_days", 30).max(1);
559        self.failure_min_uses = i("curate.failure_min_uses", FAILURE_MIN_USES).max(1);
560        self.failure_max_success_rate =
561            f("curate.failure_max_success_rate", FAILURE_MAX_SUCCESS_RATE).clamp(0.0, 1.0);
562        self.failure_confidence_max =
563            f("curate.failure_confidence_max", FAILURE_CONFIDENCE_MAX).clamp(0.0, 1.0);
564        self.log_compact_days = i("curate.log_compact_days", LOG_COMPACT_DAYS).max(1);
565        let s = |k: &str, d: &str| -> String {
566            self.storage
567                .get_meta(k)
568                .ok()
569                .flatten()
570                .filter(|v| !v.trim().is_empty())
571                .unwrap_or_else(|| d.to_string())
572        };
573        self.appraise_tier_weak = f("appraise.tier_weak", APPRAISE_TIER_WEAK).clamp(0.0, 1.0);
574        self.appraise_tier_strong = f("appraise.tier_strong", APPRAISE_TIER_STRONG).clamp(0.0, 1.0);
575        self.appraise_min_strength =
576            f("appraise.min_strength", APPRAISE_MIN_STRENGTH).clamp(0.0, 1.0);
577        self.appraise_top = i("appraise.top", APPRAISE_TOP as i64).max(1) as usize;
578        self.appraise_trigger_hit_min =
579            f("appraise.trigger_hit_min", APPRAISE_TRIGGER_HIT_MIN).clamp(0.0, 1.0);
580        self.appraise_candidate_in_embed =
581            b("appraise.candidate_in_embed", APPRAISE_CANDIDATE_IN_EMBED);
582        self.appraise_signature_floor =
583            f("appraise.signature_floor", APPRAISE_SIGNATURE_FLOOR).clamp(0.0, 1.0);
584        self.appraise_min_evidence = i("appraise.min_evidence", APPRAISE_MIN_EVIDENCE).max(0);
585        self.appraise_conflict_ceiling =
586            f("appraise.conflict_ceiling", APPRAISE_CONFLICT_CEILING).clamp(0.0, 1.0);
587        self.intuition_prior_m = f("intuition.prior_m", INTUITION_PRIOR_M).max(0.0);
588        self.intuition_base_rate = f("intuition.base_rate", INTUITION_BASE_RATE).clamp(0.0, 1.0);
589        self.calibration_bins = i("intuition.calibration_bins", CALIBRATION_BINS).clamp(2, 100);
590        self.situation_coarse_keys = s("situation.coarse_keys", SITUATION_COARSE_KEYS);
591        Ok(())
592    }
593}
594
595// ---------------------------------------------------------------------------
596// Helpers
597// ---------------------------------------------------------------------------
598
599struct CandidateInfo {
600    chunk: Value,
601    sim_content: f32,
602    sim_trigger: f32,
603    /// Lexical/BM25 channel score ∈ [0,1] (hybrid 检索). Zero when the chunk was
604    /// found only by vector search; positive when an exact-term match recovered it.
605    sim_lexical: f32,
606    /// ACT-R spreading-activation score ∈ [0,1]. Positive when the chunk was
607    /// reached via a shared entity (with the query or a high-relevance seed),
608    /// even if no similarity/lexical channel surfaced it. Zero on the default
609    /// (w_spread = 0) path.
610    sim_spread: f32,
611}
612
613/// True when a coarse signature carries at least one real value (not empty /
614/// `none` / `unknown`) — used to decide whether folding it into the embed query
615/// adds signal or just noise.
616fn signature_has_signal(sig: &str) -> bool {
617    sig.split('|').any(|p| {
618        p.split_once('=')
619            .map(|(_, v)| !v.is_empty() && v != "none" && v != "unknown")
620            .unwrap_or(false)
621    })
622}
623
624/// Fresh candidate from a chunk with all channel sims zeroed (callers set the
625/// channel(s) that surfaced it). Centralised so adding a channel touches one place.
626fn new_candidate(chunk: &Value) -> CandidateInfo {
627    CandidateInfo {
628        chunk: chunk.clone(),
629        sim_content: 0.0,
630        sim_trigger: 0.0,
631        sim_lexical: 0.0,
632        sim_spread: 0.0,
633    }
634}
635
636fn chunk_is_valid_for_recall(chunk: &Value, embed_version: i64) -> bool {
637    chunk.get("state").and_then(Value::as_str) != Some("archived")
638        && chunk.get("origin").and_then(Value::as_str) != Some("spark")
639        && chunk
640            .get("embed_version")
641            .and_then(Value::as_i64)
642            .unwrap_or(1)
643            >= embed_version
644}
645
646/// Normalize a query string before hashing into a context_key.
647///
648/// Goals: collapse whitespace variations and case differences so that
649/// semantically equivalent queries (same words, different capitalisation or
650/// spacing) accumulate statistics in the same context_stat bucket.
651///
652/// Deliberately conservative: no stemming, no stop-word removal. The canonical
653/// query guidance in SKILL.md handles vocabulary consistency at the agent level.
654fn normalize_query(query: &str) -> String {
655    const STOP_WORDS: &[&str] = &[
656        "a", "an", "and", "for", "in", "of", "on", "the", "to", "with",
657    ];
658    let cleaned: String = query
659        .to_lowercase()
660        .chars()
661        .map(|ch| {
662            if ch.is_alphanumeric() || ch.is_whitespace() {
663                ch
664            } else {
665                ' '
666            }
667        })
668        .collect();
669    let mut tokens: Vec<&str> = cleaned
670        .split_whitespace()
671        .filter(|token| !STOP_WORDS.contains(token))
672        .collect();
673    tokens.sort_unstable();
674    tokens.dedup();
675    tokens.join(" ")
676}
677
678fn estimate_distill_prompt_tokens(log: &Value, related_logs: &[Value]) -> i64 {
679    let primary: i64 = [
680        "query",
681        "recall_snapshot",
682        "output",
683        "output_summary",
684        "nomination",
685    ]
686    .iter()
687    .filter_map(|key| log.get(*key).and_then(Value::as_str))
688    .map(|text| estimate_tokens(text) as i64)
689    .sum();
690    let log_id = log.get("id").and_then(Value::as_str).unwrap_or("");
691    let context_key = log.get("context_key").and_then(Value::as_str);
692    let related: i64 = related_logs
693        .iter()
694        .filter(|other| other.get("id").and_then(Value::as_str).unwrap_or("") != log_id)
695        .filter(|other| {
696            context_key.is_some() && other.get("context_key").and_then(Value::as_str) == context_key
697        })
698        .take(4)
699        .flat_map(|other| {
700            ["query", "output_summary", "outcome"]
701                .into_iter()
702                .filter_map(|key| other.get(key).and_then(Value::as_str))
703        })
704        .map(|text| estimate_tokens(text) as i64)
705        .sum();
706    primary + related
707}
708
709fn estimate_distilled_chunk_tokens(chunk: &DistilledChunk) -> i64 {
710    estimate_tokens(&chunk.content) as i64
711        + chunk
712            .trigger_desc
713            .as_deref()
714            .map(estimate_tokens)
715            .unwrap_or(0) as i64
716        + chunk
717            .anti_trigger_desc
718            .as_deref()
719            .map(estimate_tokens)
720            .unwrap_or(0) as i64
721}
722
723fn anti_trigger_hit(query: &str, anti: &str) -> bool {
724    let q_lower = query.to_lowercase();
725    anti.to_lowercase().split(',').any(|part| {
726        let p = part.trim();
727        !p.is_empty() && q_lower.contains(p)
728    })
729}
730
731fn block_cost(block: &[Value]) -> usize {
732    block
733        .iter()
734        .map(|b| {
735            b.get("token_count")
736                .and_then(Value::as_u64)
737                .map(|t| t as usize)
738                .unwrap_or_else(|| {
739                    estimate_tokens(b.get("content").and_then(Value::as_str).unwrap_or("")).max(100)
740                })
741        })
742        .sum()
743}
744
745fn limit_knowledge(knowledge: Vec<Value>, top: Option<usize>) -> Vec<Value> {
746    match top {
747        None => knowledge,
748        Some(0) => vec![],
749        Some(n) => knowledge.into_iter().take(n).collect(),
750    }
751}
752
753fn usage_state(used: Option<&[String]>) -> &'static str {
754    match used {
755        None => "unknown",
756        Some([]) => "known_none",
757        Some(_) => "known_some",
758    }
759}
760
761fn ratio(numerator: i64, denominator: i64) -> f64 {
762    if denominator <= 0 {
763        0.0
764    } else {
765        ((numerator as f64 / denominator as f64) * 1000.0).round() / 1000.0
766    }
767}
768
769fn validate_source(source: &str) -> Result<()> {
770    if !matches!(
771        source,
772        "mcp" | "sdk" | "cli" | "hook" | "daemon" | "augmented"
773    ) {
774        return Err(InnateError::InvalidState(format!(
775            "invalid event source: {source}"
776        )));
777    }
778    Ok(())
779}
780
781fn count_query(storage: &Storage, sql: &str) -> Result<i64> {
782    Ok(storage
783        .query_chunks(sql)?
784        .first()
785        .and_then(|r| r.as_object())
786        .and_then(|m| m.values().next())
787        .and_then(Value::as_i64)
788        .unwrap_or(0))
789}
790
791fn count_query_params<P: rusqlite::Params>(storage: &Storage, sql: &str, p: P) -> Result<i64> {
792    Ok(storage
793        .query_chunks_params(sql, p)?
794        .first()
795        .and_then(|r| r.as_object())
796        .and_then(|m| m.values().next())
797        .and_then(Value::as_i64)
798        .unwrap_or(0))
799}
800
801fn days_ago(now_iso: &str, days: i64) -> String {
802    use chrono::{DateTime, Duration, Utc};
803    if let Ok(t) = now_iso.parse::<DateTime<Utc>>() {
804        let cutoff = t - Duration::days(days);
805        return cutoff.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
806    }
807    now_iso.to_string()
808}
809
810fn hours_ago(now_iso: &str, hours: i64) -> String {
811    use chrono::{DateTime, Duration, Utc};
812    if let Ok(t) = now_iso.parse::<DateTime<Utc>>() {
813        let cutoff = t - Duration::hours(hours);
814        return cutoff.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
815    }
816    now_iso.to_string()
817}
818
819impl KnowledgeBase {
820    /// Time a fallible operation, persist a one-row `operation_runs` summary (P3a,
821    /// design doc §5.3), and return its result unchanged. Instrumentation is
822    /// **non-fatal**: a failed metrics insert never affects the wrapped operation.
823    /// Raw LLM detail still lives in `llm_trace.log`; this holds only the aggregatable
824    /// summary (status / duration / error_kind). `error_kind` comes from the closed
825    /// vocabulary in `storage::metrics::classify_error` so the top-list groups cleanly.
826    pub(crate) fn measure<T>(
827        &self,
828        op: &str,
829        source: Option<&str>,
830        trace_id: Option<&str>,
831        f: impl FnOnce() -> Result<T>,
832    ) -> Result<T> {
833        let started = std::time::Instant::now();
834        let started_at = utc_now_iso();
835        let result = f();
836        let duration_ms = started.elapsed().as_millis() as i64;
837        let (status, error_kind) = match &result {
838            Ok(_) => ("ok", None),
839            Err(e) => (
840                "error",
841                Some(crate::storage::metrics::classify_error(e).to_string()),
842            ),
843        };
844        let run = crate::storage::metrics::OperationRun {
845            id: gen_uuid(),
846            trace_id: trace_id.map(|s| s.to_string()),
847            op: op.to_string(),
848            source: source.map(|s| s.to_string()),
849            agent: crate::utils::agent_source(),
850            status: status.to_string(),
851            error_kind,
852            started_at,
853            duration_ms,
854            counts_json: None,
855            params_json: None,
856        };
857        let _ = self.storage.insert_operation_run(&run);
858        result
859    }
860
861    /// Embed content+trigger as one timed `embed` operation_run (full-path coverage:
862    /// add / spark / promote / distill / rebuild_embeddings). Returns the two Results
863    /// **unchanged** so each caller keeps its own embedding-failure fallback. The op row
864    /// is best-effort/non-fatal; when called inside an open transaction it simply joins
865    /// it (same connection, no lock conflict). `error_kind` uses the closed vocabulary.
866    pub(crate) fn embed_pair(
867        &self,
868        content: &str,
869        trigger: &str,
870        source: &str,
871    ) -> (Result<Vec<f32>>, Result<Vec<f32>>) {
872        let started = std::time::Instant::now();
873        let started_at = utc_now_iso();
874        let c = self.embedding.embed_content(content);
875        let t = self.embedding.embed_trigger(trigger);
876        let duration_ms = started.elapsed().as_millis() as i64;
877        let (status, error_kind) = match c.as_ref().err().or(t.as_ref().err()) {
878            None => ("ok", None),
879            Some(e) => (
880                "error",
881                Some(crate::storage::metrics::classify_error(e).to_string()),
882            ),
883        };
884        let run = crate::storage::metrics::OperationRun {
885            id: gen_uuid(),
886            trace_id: None,
887            op: "embed".to_string(),
888            source: Some(source.to_string()),
889            agent: crate::utils::agent_source(),
890            status: status.to_string(),
891            error_kind,
892            started_at,
893            duration_ms,
894            counts_json: None,
895            params_json: None,
896        };
897        let _ = self.storage.insert_operation_run(&run);
898        (c, t)
899    }
900}
901
902fn minutes_ago(now_iso: &str, minutes: i64) -> String {
903    use chrono::{DateTime, Duration, Utc};
904    if let Ok(t) = now_iso.parse::<DateTime<Utc>>() {
905        let cutoff = t - Duration::minutes(minutes);
906        return cutoff.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
907    }
908    now_iso.to_string()
909}
910
911fn minutes_after(now_iso: &str, minutes: i64) -> String {
912    use chrono::{DateTime, Duration, Utc};
913    if let Ok(t) = now_iso.parse::<DateTime<Utc>>() {
914        let cutoff = t + Duration::minutes(minutes);
915        return cutoff.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
916    }
917    now_iso.to_string()
918}
919
920fn hours_after(now_iso: &str, hours: i64) -> String {
921    use chrono::{DateTime, Duration, Utc};
922    if let Ok(t) = now_iso.parse::<DateTime<Utc>>() {
923        let cutoff = t + Duration::hours(hours);
924        return cutoff.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
925    }
926    now_iso.to_string()
927}
928
929/// Return the number of whole days between two ISO timestamps (now - past; clamped ≥ 0).
930fn iso_days_diff(now_iso: &str, past_iso: &str) -> i64 {
931    use chrono::{DateTime, Utc};
932    let parse = |s: &str| s.parse::<DateTime<Utc>>().ok();
933    if let (Some(a), Some(b)) = (parse(now_iso), parse(past_iso)) {
934        let diff = a - b;
935        diff.num_days().max(0)
936    } else {
937        0
938    }
939}
940
941/// Fractional days between two ISO timestamps (≥ 0). Finer than `iso_days_diff`
942/// so the activation recency term keeps sub-day resolution.
943fn iso_fractional_days(now_iso: &str, past_iso: &str) -> f64 {
944    use chrono::{DateTime, Utc};
945    let parse = |s: &str| s.parse::<DateTime<Utc>>().ok();
946    if let (Some(a), Some(b)) = (parse(now_iso), parse(past_iso)) {
947        ((a - b).num_seconds().max(0)) as f64 / 86_400.0
948    } else {
949        0.0
950    }
951}
952
953/// ACT-R decay exponent for the base-level activation recency term.
954const ACTR_DECAY: f64 = 0.5;
955
956/// ACT-R-inspired base-level activation, bounded to `(0, 1)`.
957///
958/// Fuses **frequency** (how often a chunk has been used) and **recency** (time
959/// since last use) into one re-ranking signal, following the standard ACT-R
960/// approximation `B = ln(n) − d·ln(t)` (Petrov 2006), here using
961/// `B = ln(1 + used_count) − d·ln(1 + recency_days)` and squashed with a
962/// logistic so it stays on the same `[0, 1]` scale as the other fused-score
963/// terms (content/trigger sim, confidence, context).
964///
965/// Returns `0.0` for never-used chunks (no usage history → no boost), which
966/// keeps recall **zero-regression** for freshly-added knowledge: a chunk with
967/// `used_count == 0` contributes nothing to the fused score.
968pub(super) fn actr_activation(used_count: i64, last_used_at: Option<&str>, now_iso: &str) -> f64 {
969    if used_count <= 0 {
970        return 0.0;
971    }
972    let Some(last) = last_used_at else {
973        return 0.0;
974    };
975    let recency_days = iso_fractional_days(now_iso, last);
976    let b = (1.0 + used_count as f64).ln() - ACTR_DECAY * (1.0 + recency_days).ln();
977    1.0 / (1.0 + (-b).exp())
978}
979
980/// DFS-based cycle detection on the hard-dep graph. Returns list of cycles (each is a Vec of ids).
981fn detect_cycles(deps: &[Value]) -> Vec<Vec<String>> {
982    use std::collections::HashMap;
983    let mut adj: HashMap<String, Vec<String>> = HashMap::new();
984    for d in deps {
985        let src = d
986            .get("src")
987            .and_then(Value::as_str)
988            .unwrap_or("")
989            .to_string();
990        let dst = d
991            .get("dst")
992            .and_then(Value::as_str)
993            .unwrap_or("")
994            .to_string();
995        if !src.is_empty() && !dst.is_empty() {
996            adj.entry(src).or_default().push(dst);
997        }
998    }
999    let nodes: Vec<String> = adj.keys().cloned().collect();
1000    let mut visited: HashSet<String> = HashSet::new();
1001    let mut on_stack: HashSet<String> = HashSet::new();
1002    let mut cycles: Vec<Vec<String>> = vec![];
1003
1004    fn dfs(
1005        node: &str,
1006        adj: &HashMap<String, Vec<String>>,
1007        visited: &mut HashSet<String>,
1008        on_stack: &mut HashSet<String>,
1009        path: &mut Vec<String>,
1010        cycles: &mut Vec<Vec<String>>,
1011    ) {
1012        if on_stack.contains(node) {
1013            // Found cycle — extract loop segment.
1014            let start = path.iter().position(|n| n == node).unwrap_or(0);
1015            cycles.push(path[start..].to_vec());
1016            return;
1017        }
1018        if visited.contains(node) {
1019            return;
1020        }
1021        visited.insert(node.to_string());
1022        on_stack.insert(node.to_string());
1023        path.push(node.to_string());
1024        if let Some(children) = adj.get(node) {
1025            for child in children {
1026                dfs(child, adj, visited, on_stack, path, cycles);
1027            }
1028        }
1029        path.pop();
1030        on_stack.remove(node);
1031    }
1032
1033    for node in nodes {
1034        let mut path = vec![];
1035        dfs(
1036            &node,
1037            &adj,
1038            &mut visited,
1039            &mut on_stack,
1040            &mut path,
1041            &mut cycles,
1042        );
1043    }
1044    cycles
1045}