1type 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
47const 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;
60const W_LEXICAL: f64 = 0.25;
63const W_SPREAD: f64 = 0.0;
68const SPREAD_FAN_CAP: i64 = 50;
72const 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
93const 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;
101const APPRAISE_SIGNATURE_FLOOR: f64 = 0.0;
107const APPRAISE_MIN_EVIDENCE: i64 = 0;
108const APPRAISE_CONFLICT_CEILING: f64 = 1.0;
109const INTUITION_PRIOR_M: f64 = 2.0;
113const INTUITION_BASE_RATE: f64 = 0.5;
114const RECALL_PRIOR_M: f64 = 2.0;
117const RECALL_BASE_RATE: f64 = 0.5;
118const CALIBRATION_BINS: i64 = 10;
120const SITUATION_COARSE_KEYS: &str = "stage,error_class,file_type";
121const 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#[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#[derive(Debug, Default, Clone)]
169pub struct CurateScope {
170 pub origin: Option<String>,
172 pub skill_name: Option<String>,
174 pub dry_run: bool,
176}
177
178pub trait Curator: Send + Sync {
181 fn run(&self, kb: &KnowledgeBase, scope: &CurateScope) -> Result<CurateReport>;
182}
183
184pub 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
193pub 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 reranker: Arc<dyn Reranker>,
207
208 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 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 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 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 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
595struct CandidateInfo {
600 chunk: Value,
601 sim_content: f32,
602 sim_trigger: f32,
603 sim_lexical: f32,
606 sim_spread: f32,
611}
612
613fn 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
624fn 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
646fn 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 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 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
929fn 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
941fn 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
953const ACTR_DECAY: f64 = 0.5;
955
956pub(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
980fn 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 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}