Skip to main content

adk_harness/facts/
consolidate.rs

1//! Fact consolidation: the consolidation tick's two passes over long-term facts, the loss
2//! cap, the tick record and `undo` (spec 3.2 §7.5, §10 HK2, §9.2 K-I12, K-I22, §13 Q12).
3//!
4//! | Step | Model call | Writes |
5//! |---|---|---|
6//! | Distillation of the sessions the per-session distiller never reached ([`Harness::distill_sessions`]) | one per session | `Assumed` facts only: verified-quote promotion is off |
7//! | Pass 1 | none | the older of two `Assumed` facts at cosine ≥ `dedup_score` → `Superseded { by: newer }`; an unused, low-confidence `Assumed` fact older than `assumed_ttl` → `Forgotten` (reason `expired`) |
8//! | Pass 2 | one per cluster, at most `max_clusters_per_tick` | a merged `Assumed` fact, source `AgentInferred`, its provenance listing the sources; the sources it names in `supersedes` → `Superseded { by: merged }` |
9//! | Loss cap | — | nothing from either pass when they would lose more than `max(1, ⌊max_loss_fraction × live⌋)` of a scope's live facts: one per pass-1 change, and per merge the facts it supersedes less the one it writes |
10//!
11//! `Known` facts are never superseded, merged or expired, and an `Assumed` fact never
12//! supersedes a `Known` one: it is stored beside it and listed for a person to confirm
13//! (K-I22). History is kept, so [`undo_consolidation`] is a status flip.
14//!
15//! [`Harness::distill_sessions`]: crate::Harness::distill_sessions
16
17#[cfg(feature = "runner")]
18use std::collections::{HashMap, HashSet};
19use std::time::Duration;
20
21use adk_core::principal::SubjectRef;
22use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, RunBudget};
23use chrono::{DateTime, Utc};
24use serde::{Deserialize, Serialize};
25
26#[cfg(feature = "runner")]
27use super::index::cosine;
28use super::store::FactStore;
29#[cfg(feature = "runner")]
30use super::types::{FactKind, MemoryFact, fact_digest};
31use super::types::{FactScope, FactStatus};
32
33/// Least cosine similarity of two facts in one pass-2 cluster (spec 3.2 §7.5): at or above
34/// it and below `dedup_score`, facts are similar but not equivalent, so a model merges them.
35///
36/// # Example
37///
38/// ```rust
39/// assert_eq!(adk_harness::CONSOLIDATION_CLUSTER_SCORE, 0.80);
40/// ```
41pub const CONSOLIDATION_CLUSTER_SCORE: f32 = 0.80;
42
43/// Most facts in one pass-2 cluster, so a merge prompt stays small.
44#[cfg(feature = "runner")]
45const CLUSTER_MAX_FACTS: usize = 8;
46
47/// The fact-consolidation settings of a consolidation tick (spec 3.2 §7.5, §13 Q12): the
48/// thresholds of the two passes, the loss cap and the tick's token cap, with the defaults
49/// spec 3.2 gives `ConsolidationTick`.
50///
51/// # Example
52///
53/// ```rust
54/// use std::time::Duration;
55/// use adk_harness::ConsolidationConfig;
56///
57/// let config = ConsolidationConfig::default();
58/// assert_eq!((config.dedup_score, config.expire_confidence), (0.92, 0.5));
59/// assert_eq!(config.assumed_ttl, Duration::from_secs(90 * 24 * 60 * 60));
60/// assert_eq!((config.max_clusters_per_tick, config.max_loss_fraction), (20, 0.25));
61/// ```
62#[derive(Clone, Debug, PartialEq)]
63pub struct ConsolidationConfig {
64    /// Pass 1 collapses `Assumed` facts of one scope and kind at or above this cosine
65    /// similarity: the older becomes `Superseded` by the newer.
66    pub dedup_score: f32,
67    /// Pass 1 expires an unused `Assumed` fact whose confidence is under this.
68    pub expire_confidence: f32,
69    /// Pass 1 expires an unused, low-confidence `Assumed` fact older than this.
70    pub assumed_ttl: Duration,
71    /// Most clusters pass 2 sends to the model in one tick.
72    pub max_clusters_per_tick: usize,
73    /// The passes apply nothing when they would lose more than this share of a scope's
74    /// live facts, rounded down, and at least one fact. A pass-1 supersession or expiry
75    /// loses one fact; a pass-2 merge loses the facts it supersedes less the one it writes.
76    pub max_loss_fraction: f32,
77    /// Most tokens the tick's model calls spend: distillation and pass 2 together.
78    pub max_tokens_per_tick: u64,
79}
80
81impl Default for ConsolidationConfig {
82    fn default() -> Self {
83        Self {
84            dedup_score: 0.92,
85            expire_confidence: 0.5,
86            assumed_ttl: Duration::from_secs(90 * 24 * 60 * 60),
87            max_clusters_per_tick: 20,
88            max_loss_fraction: 0.25,
89            max_tokens_per_tick: 50_000,
90        }
91    }
92}
93
94/// One consolidation tick asked of [`Harness::consolidate_memory`] (spec 3.2 §7.5).
95///
96/// [`Harness::consolidate_memory`]: crate::Harness::consolidate_memory
97///
98/// # Example
99///
100/// ```rust
101/// use adk_harness::ConsolidationRequest;
102///
103/// let request = ConsolidationRequest::new()
104///     .with_tick_id("pid-01J")
105///     .with_partition("work")
106///     .with_sessions(["s1", "s2"]);
107/// assert_eq!(request.sessions.len(), 2);
108/// ```
109#[derive(Clone, Debug, Default)]
110pub struct ConsolidationRequest {
111    /// The tick's id, the kernel process's pid under a kernel; a new ULID when `None`.
112    pub tick_id: Option<String>,
113    /// The partition the tick runs for; `default` when `None`.
114    pub partition: Option<String>,
115    /// Sessions to distil when the per-session distiller never reached them.
116    pub sessions: Vec<String>,
117    /// The passes' thresholds and caps.
118    pub config: ConsolidationConfig,
119    /// The tick's share of the partition's proactive budget; `max_tokens_per_tick` caps
120    /// its tokens whatever it says.
121    pub budget: Option<RunBudget>,
122    /// The tick's clock reading; now when `None`.
123    pub at: Option<DateTime<Utc>>,
124}
125
126impl ConsolidationRequest {
127    /// A tick with the default settings and no session to distil.
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    /// This request with tick id `tick_id`.
133    #[must_use]
134    pub fn with_tick_id(mut self, tick_id: impl Into<String>) -> Self {
135        self.tick_id = Some(tick_id.into());
136        self
137    }
138
139    /// This request for partition `partition`.
140    #[must_use]
141    pub fn with_partition(mut self, partition: impl Into<String>) -> Self {
142        self.partition = Some(partition.into());
143        self
144    }
145
146    /// This request distilling `sessions` the per-session distiller never reached.
147    #[must_use]
148    pub fn with_sessions(mut self, sessions: impl IntoIterator<Item = impl Into<String>>) -> Self {
149        self.sessions = sessions.into_iter().map(Into::into).collect();
150        self
151    }
152
153    /// This request with `config`.
154    #[must_use]
155    pub fn with_config(mut self, config: ConsolidationConfig) -> Self {
156        self.config = config;
157        self
158    }
159
160    /// This request spending at most `budget`.
161    #[must_use]
162    pub fn with_budget(mut self, budget: RunBudget) -> Self {
163        self.budget = Some(budget);
164        self
165    }
166
167    /// This request at clock reading `at`.
168    #[must_use]
169    pub fn at(mut self, at: DateTime<Utc>) -> Self {
170        self.at = Some(at);
171        self
172    }
173}
174
175/// Why a consolidation tick changed a fact's status (spec 3.2 §7.5).
176///
177/// # Example
178///
179/// ```rust
180/// assert_eq!(serde_json::to_value(adk_harness::ChangeReason::Expired).unwrap(), "expired");
181/// ```
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum ChangeReason {
185    /// Pass 1: a newer `Assumed` fact at or above `dedup_score` says the same.
186    Duplicate,
187    /// Pass 1: unused, low-confidence and older than `assumed_ttl`.
188    Expired,
189    /// Pass 2: merged into a new fact.
190    Merged,
191    /// Distillation: a distilled fact names it in `supersedes`, or corrects it.
192    Superseded,
193    /// Distillation: the least-used `Assumed` fact of a full scope.
194    Evicted,
195}
196
197impl ChangeReason {
198    /// The wire name.
199    pub fn as_str(self) -> &'static str {
200        match self {
201            Self::Duplicate => "duplicate",
202            Self::Expired => "expired",
203            Self::Merged => "merged",
204            Self::Superseded => "superseded",
205            Self::Evicted => "evicted",
206        }
207    }
208}
209
210/// One status change a consolidation tick made: always from `Assumed`, which `undo`
211/// restores (spec 3.2 §7.5, K-I22).
212///
213/// # Example
214///
215/// ```rust
216/// use adk_harness::{ChangeReason, FactChange, FactScope, FactStatus};
217///
218/// let change = FactChange {
219///     fact: "01JA".into(),
220///     scope: FactScope::new("app", "alice", None),
221///     to: FactStatus::Forgotten,
222///     reason: ChangeReason::Expired,
223/// };
224/// assert!(!change.to.is_live());
225/// ```
226#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228pub struct FactChange {
229    /// The fact.
230    pub fact: String,
231    /// Its scope.
232    pub scope: FactScope,
233    /// The status the tick gave it.
234    pub to: FactStatus,
235    /// Why.
236    pub reason: ChangeReason,
237}
238
239/// An `Assumed` fact a tick stored beside the `Known` fact it would have superseded, for a
240/// person to confirm or forget (spec 3.2 §7.5, K-I22).
241///
242/// # Example
243///
244/// ```rust
245/// let beside = adk_harness::BesideKnown { fact: "01JB".into(), known: "01JA".into() };
246/// assert_ne!(beside.fact, beside.known);
247/// ```
248#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "camelCase")]
250pub struct BesideKnown {
251    /// The `Assumed` fact.
252    pub fact: String,
253    /// The `Known` fact it stands beside.
254    pub known: String,
255}
256
257/// What one consolidation tick did, kept in the [`FactStore`] so `undo` can revert it
258/// (spec 3.2 §7.5): fact ids and counts, never fact text.
259///
260/// # Example
261///
262/// ```rust
263/// use adk_harness::ConsolidationRecord;
264///
265/// let record = ConsolidationRecord::new("01JT", "app", "alice", "default", chrono::Utc::now());
266/// assert_eq!((record.superseded().count(), record.forgotten().count()), (0, 0));
267/// ```
268#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase")]
270pub struct ConsolidationRecord {
271    /// The tick's id.
272    pub tick_id: String,
273    /// The application.
274    pub app: String,
275    /// The user whose facts it consolidated.
276    pub user: String,
277    /// The partition it ran for.
278    pub partition: String,
279    /// When it ran.
280    pub at: DateTime<Utc>,
281    /// The scopes the passes covered.
282    #[serde(default)]
283    pub scopes: Vec<FactScope>,
284    /// The sessions it distilled.
285    #[serde(default)]
286    pub sessions: Vec<String>,
287    /// The facts its distillation stored, all `Assumed`.
288    #[serde(default)]
289    pub distilled: Vec<String>,
290    /// The facts pass 2 stored, all `Assumed`.
291    #[serde(default)]
292    pub merged: Vec<String>,
293    /// Every status change it made.
294    #[serde(default)]
295    pub changes: Vec<FactChange>,
296    /// The `Assumed` facts it stored beside a `Known` one.
297    #[serde(default)]
298    pub beside_known: Vec<BesideKnown>,
299    /// Why the passes applied nothing: the loss cap.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub refused: Option<String>,
302    /// Model calls made.
303    #[serde(default)]
304    pub model_calls: u64,
305    /// Tokens spent.
306    #[serde(default)]
307    pub total_tokens: u64,
308    /// Cost in millionths of a US dollar.
309    #[serde(default)]
310    pub cost_micro_usd: u64,
311    /// When the tick finished; `None` while it runs, and for one cut off, which its kernel
312    /// runs again.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub finished_at: Option<DateTime<Utc>>,
315    /// When `undo` reverted it.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub undone_at: Option<DateTime<Utc>>,
318}
319
320impl ConsolidationRecord {
321    /// An empty record of tick `tick_id` for `user` of `app` in `partition` at `at`.
322    pub fn new(
323        tick_id: impl Into<String>,
324        app: impl Into<String>,
325        user: impl Into<String>,
326        partition: impl Into<String>,
327        at: DateTime<Utc>,
328    ) -> Self {
329        Self {
330            tick_id: tick_id.into(),
331            app: app.into(),
332            user: user.into(),
333            partition: partition.into(),
334            at,
335            scopes: Vec::new(),
336            sessions: Vec::new(),
337            distilled: Vec::new(),
338            merged: Vec::new(),
339            changes: Vec::new(),
340            beside_known: Vec::new(),
341            refused: None,
342            model_calls: 0,
343            total_tokens: 0,
344            cost_micro_usd: 0,
345            finished_at: None,
346            undone_at: None,
347        }
348    }
349
350    /// The facts it superseded.
351    pub fn superseded(&self) -> impl Iterator<Item = &FactChange> {
352        self.changes.iter().filter(|change| matches!(change.to, FactStatus::Superseded { .. }))
353    }
354
355    /// The facts it forgot.
356    pub fn forgotten(&self) -> impl Iterator<Item = &FactChange> {
357        self.changes.iter().filter(|change| change.to == FactStatus::Forgotten)
358    }
359
360    /// The facts it wrote: distilled and merged.
361    pub fn written(&self) -> impl Iterator<Item = &String> {
362        self.distilled.iter().chain(&self.merged)
363    }
364}
365
366/// What [`undo_consolidation`] reverted (spec 3.2 §7.5).
367///
368/// # Example
369///
370/// ```rust
371/// let report = adk_harness::ConsolidationUndo::default();
372/// assert!(report.restored.is_empty() && report.kept.is_empty());
373/// ```
374#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub struct ConsolidationUndo {
377    /// The tick.
378    pub tick_id: String,
379    /// Facts back to `Assumed`.
380    pub restored: Vec<String>,
381    /// Facts the tick wrote, now `Forgotten`.
382    pub forgotten: Vec<String>,
383    /// Facts left as they are: a person or a later write changed them since the tick.
384    pub kept: Vec<String>,
385}
386
387fn invalid(code: &'static str, message: String) -> AdkError {
388    AdkError::new(ErrorComponent::Agent, ErrorCategory::InvalidInput, code, message)
389}
390
391/// The consolidation record `tick_id` of `user` of `app`: an exact id, or a unique prefix.
392///
393/// # Errors
394///
395/// Returns `harness.memory.tick_not_found` when no record matches, or more than one does,
396/// or the store's error.
397pub async fn find_consolidation(
398    store: &dyn FactStore,
399    app: &str,
400    user: &str,
401    tick_id: &str,
402) -> Result<ConsolidationRecord> {
403    let wanted = tick_id.trim();
404    let records = store.consolidations(app, user).await?;
405    if let Some(record) = records.iter().find(|record| record.tick_id == wanted) {
406        return Ok(record.clone());
407    }
408    let upper = wanted.to_ascii_uppercase();
409    let mut matches = records.into_iter().filter(|record| {
410        !wanted.is_empty()
411            && (record.tick_id.starts_with(wanted) || record.tick_id.starts_with(&upper))
412    });
413    match (matches.next(), matches.next()) {
414        (Some(record), None) => Ok(record),
415        (None, _) => Err(AdkError::new(
416            ErrorComponent::Agent,
417            ErrorCategory::NotFound,
418            "harness.memory.tick_not_found",
419            format!(
420                "there is no consolidation tick '{wanted}'; `adk-rust memory list --source consolidation` lists them"
421            ),
422        )),
423        (Some(_), Some(_)) => Err(invalid(
424            "harness.memory.tick_not_found",
425            format!("'{wanted}' matches more than one consolidation tick; give more of the id"),
426        )),
427    }
428}
429
430/// Reverts consolidation tick `tick_id` of `user` of `app` (spec 3.2 §7.5): each fact the
431/// tick superseded or forgot goes back to `Assumed` with `valid_to` cleared, and each fact
432/// it wrote is forgotten, its history kept. A change a person or a later write has made
433/// since the tick is kept and reported in [`ConsolidationUndo::kept`]. Run right after the
434/// tick, `undo` is the identity on the statuses the facts had before it.
435///
436/// Records the tick as undone; a tick is undone once, and only once it finished, so no
437/// change it makes after the undo escapes it.
438///
439/// # Example
440///
441/// ```rust,ignore
442/// let report = adk_harness::undo_consolidation(store.as_ref(), "adk-rust", "alice", &tick_id, &by).await?;
443/// println!("{} facts restored", report.restored.len());
444/// ```
445///
446/// # Errors
447///
448/// Returns `harness.memory.tick_not_found` for an unknown tick,
449/// `harness.memory.tick_unfinished` for one that has not finished,
450/// `harness.memory.tick_undone` for one already undone, or the store's error.
451pub async fn undo_consolidation(
452    store: &dyn FactStore,
453    app: &str,
454    user: &str,
455    tick_id: &str,
456    by: &SubjectRef,
457) -> Result<ConsolidationUndo> {
458    let mut record = find_consolidation(store, app, user, tick_id).await?;
459    if record.finished_at.is_none() {
460        return Err(AdkError::new(
461            ErrorComponent::Agent,
462            ErrorCategory::Conflict,
463            "harness.memory.tick_unfinished",
464            format!(
465                "consolidation tick '{}' has not finished; undo it once it has (a tick cut off \
466                 is run again by its kernel)",
467                record.tick_id
468            ),
469        ));
470    }
471    if record.undone_at.is_some() {
472        return Err(AdkError::new(
473            ErrorComponent::Agent,
474            ErrorCategory::Conflict,
475            "harness.memory.tick_undone",
476            format!("consolidation tick '{}' was undone already", record.tick_id),
477        ));
478    }
479    let mut report = ConsolidationUndo { tick_id: record.tick_id.clone(), ..Default::default() };
480    // Restore first, then forget what the tick wrote, so no fact is lost in between.
481    for change in record.changes.iter().rev() {
482        let current = store.get(&change.fact).await?;
483        match current {
484            Some(fact) if fact.status == change.to => {
485                store.restore_assumed(&change.fact, by).await?;
486                report.restored.push(change.fact.clone());
487            }
488            _ => report.kept.push(change.fact.clone()),
489        }
490    }
491    for id in record.written() {
492        match store.get(id).await? {
493            Some(fact) if fact.status == FactStatus::Assumed => {
494                store.set_status(id, FactStatus::Forgotten, by).await?;
495                report.forgotten.push(id.clone());
496            }
497            _ => report.kept.push(id.clone()),
498        }
499    }
500    record.undone_at = Some(Utc::now());
501    store.put_consolidation(&record).await?;
502    Ok(report)
503}
504
505/// What [`Harness::distill_sessions`] did (spec 3.2 §10 HK2): the sessions it distilled
506/// and skipped, the facts it stored — every one `Assumed` — and what it spent.
507///
508/// [`Harness::distill_sessions`]: crate::Harness::distill_sessions
509///
510/// # Example
511///
512/// ```rust
513/// let report = adk_harness::SessionDistillation::default();
514/// assert!(report.stored.is_empty());
515/// ```
516#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
517#[serde(rename_all = "camelCase")]
518pub struct SessionDistillation {
519    /// Sessions distilled.
520    pub sessions: Vec<String>,
521    /// Sessions skipped: already distilled up to their last event, still active, due to
522    /// the per-session distiller, in ReadOnly or Plan mode, or not readable.
523    pub skipped: Vec<String>,
524    /// Facts stored, all `Assumed`.
525    pub stored: Vec<String>,
526    /// Candidates refused.
527    pub rejected: usize,
528    /// Status changes the stored facts made: a named `supersedes`, a correction, an
529    /// eviction.
530    pub changes: Vec<FactChange>,
531    /// Facts stored beside a `Known` fact they named.
532    pub beside_known: Vec<BesideKnown>,
533    /// Model calls made.
534    pub model_calls: u64,
535    /// Tokens spent.
536    pub total_tokens: u64,
537    /// Cost in millionths of a US dollar.
538    pub cost_micro_usd: u64,
539}
540
541/// One scope's live facts and their stored vectors, as the passes read them.
542#[cfg(feature = "runner")]
543#[derive(Clone, Debug, Default)]
544pub(crate) struct ScopeFacts {
545    pub(crate) live: Vec<MemoryFact>,
546    pub(crate) vectors: HashMap<String, Vec<f32>>,
547}
548
549#[cfg(feature = "runner")]
550impl ScopeFacts {
551    fn similarity(&self, a: &MemoryFact, b: &MemoryFact) -> Option<f32> {
552        cosine(self.vectors.get(&a.id)?, self.vectors.get(&b.id)?)
553    }
554}
555
556/// Newest first: by `valid_from`, then id (ULIDs sort by time).
557#[cfg(feature = "runner")]
558fn newest_first(facts: &mut [&MemoryFact]) {
559    facts.sort_by(|a, b| b.valid_from.cmp(&a.valid_from).then_with(|| b.id.cmp(&a.id)));
560}
561
562/// Whether pass 1 expires `fact` at `now`: `Assumed`, never used or recalled, a confidence
563/// under `expire_confidence`, and older than `assumed_ttl`. A fact without a confidence is
564/// not expired: its confidence is unknown, not low.
565#[cfg(feature = "runner")]
566pub(crate) fn expires(fact: &MemoryFact, config: &ConsolidationConfig, now: DateTime<Utc>) -> bool {
567    let ttl = chrono::Duration::from_std(config.assumed_ttl).unwrap_or(chrono::Duration::MAX);
568    fact.status == FactStatus::Assumed
569        && fact.uses == 0
570        && fact.last_recalled.is_none()
571        && fact.confidence.is_some_and(|confidence| confidence < config.expire_confidence)
572        && now.signed_duration_since(fact.valid_from) > ttl
573}
574
575/// Pass 1 over one scope (spec 3.2 §7.5): no model call. Expiry first, so an expiring
576/// newer fact never takes a used older one with it; then, per kind and newest first, each
577/// `Assumed` fact at or above `dedup_score` to a newer survivor becomes `Superseded` by the
578/// most similar one. Returns the changes and the `Assumed` survivors.
579#[cfg(feature = "runner")]
580pub(crate) fn pass_one(
581    facts: &ScopeFacts,
582    config: &ConsolidationConfig,
583    now: DateTime<Utc>,
584) -> (Vec<FactChange>, Vec<MemoryFact>) {
585    let mut changes = Vec::new();
586    let mut assumed: Vec<&MemoryFact> =
587        facts.live.iter().filter(|fact| fact.status == FactStatus::Assumed).collect();
588    newest_first(&mut assumed);
589    let mut remaining = Vec::new();
590    for fact in assumed {
591        if expires(fact, config, now) {
592            changes.push(FactChange {
593                fact: fact.id.clone(),
594                scope: fact.scope.clone(),
595                to: FactStatus::Forgotten,
596                reason: ChangeReason::Expired,
597            });
598        } else {
599            remaining.push(fact);
600        }
601    }
602    let mut survivors: Vec<&MemoryFact> = Vec::new();
603    for fact in remaining {
604        let best = survivors
605            .iter()
606            .filter(|survivor| survivor.kind == fact.kind)
607            .filter_map(|survivor| Some((*survivor, facts.similarity(survivor, fact)?)))
608            .filter(|(_, score)| *score >= config.dedup_score)
609            .max_by(|a, b| a.1.total_cmp(&b.1));
610        match best {
611            Some((survivor, _)) => changes.push(FactChange {
612                fact: fact.id.clone(),
613                scope: fact.scope.clone(),
614                to: FactStatus::Superseded { by: survivor.id.clone() },
615                reason: ChangeReason::Duplicate,
616            }),
617            None => survivors.push(fact),
618        }
619    }
620    (changes, survivors.into_iter().cloned().collect())
621}
622
623/// The pass-2 clusters of one scope's survivors (spec 3.2 §7.5): per kind and newest
624/// first, a fact and the older unclustered facts whose similarity to it is at least
625/// [`CONSOLIDATION_CLUSTER_SCORE`] and below `dedup_score`; two facts at least, at most
626/// `limit` clusters.
627#[cfg(feature = "runner")]
628pub(crate) fn clusters(
629    facts: &ScopeFacts,
630    survivors: &[MemoryFact],
631    config: &ConsolidationConfig,
632    limit: usize,
633) -> Vec<Vec<MemoryFact>> {
634    let mut ordered: Vec<&MemoryFact> = survivors.iter().collect();
635    newest_first(&mut ordered);
636    let mut taken = HashSet::new();
637    let mut out = Vec::new();
638    for (i, head) in ordered.iter().enumerate() {
639        if out.len() >= limit {
640            break;
641        }
642        if taken.contains(&head.id) {
643            continue;
644        }
645        let mut cluster = vec![(*head).clone()];
646        for other in &ordered[i + 1..] {
647            if cluster.len() >= CLUSTER_MAX_FACTS {
648                break;
649            }
650            if taken.contains(&other.id) || other.kind != head.kind {
651                continue;
652            }
653            let similar = facts.similarity(head, other).is_some_and(|score| {
654                (CONSOLIDATION_CLUSTER_SCORE..config.dedup_score).contains(&score)
655            });
656            if similar {
657                cluster.push((*other).clone());
658            }
659        }
660        if cluster.len() >= 2 {
661            taken.extend(cluster.iter().map(|fact| fact.id.clone()));
662            out.push(cluster);
663        }
664    }
665    out
666}
667
668/// A model's answer for one pass-2 cluster: `{ merged_text, source_ids, supersedes }`.
669#[cfg(feature = "runner")]
670#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
671pub(crate) struct MergeAnswer {
672    #[serde(default)]
673    pub(crate) merged_text: String,
674    #[serde(default)]
675    pub(crate) source_ids: Vec<String>,
676    #[serde(default)]
677    pub(crate) supersedes: Vec<String>,
678}
679
680/// A merge pass 2 will apply.
681#[cfg(feature = "runner")]
682#[derive(Clone, Debug, PartialEq)]
683pub(crate) enum PlannedMerge {
684    /// A new `Assumed` fact with `text` from `sources`, superseding `supersedes`.
685    New {
686        kind: FactKind,
687        scope: FactScope,
688        text: String,
689        sources: Vec<MemoryFact>,
690        supersedes: Vec<String>,
691    },
692    /// The answer repeated source `into`'s text: it supersedes the others.
693    Into { into: String, supersedes: Vec<String> },
694}
695
696/// Validates a pass-2 answer against its cluster (spec 3.2 §7.5, K-I22): sources and
697/// superseded facts must be the cluster's (`Assumed`, by construction), a merge supersedes
698/// at least one fact, the text passes the fact checks, and a text equal to a live fact
699/// outside the cluster is no merge. `text` is the merged text after redaction, or `None`
700/// when it was refused.
701#[cfg(feature = "runner")]
702pub(crate) fn plan_merge(
703    cluster: &[MemoryFact],
704    answer: &MergeAnswer,
705    text: Option<String>,
706    scope_live: &[MemoryFact],
707) -> Option<PlannedMerge> {
708    let text = text?;
709    let in_cluster = |id: &String| {
710        cluster.iter().any(|fact| fact.id == *id && fact.status == FactStatus::Assumed)
711    };
712    let mut sources: Vec<MemoryFact> = Vec::new();
713    for id in answer.source_ids.iter().filter(|id| in_cluster(id)) {
714        if !sources.iter().any(|fact| fact.id == *id) {
715            sources.extend(cluster.iter().find(|fact| fact.id == *id).cloned());
716        }
717    }
718    let mut supersedes: Vec<String> = Vec::new();
719    for id in &answer.supersedes {
720        if sources.iter().any(|fact| fact.id == *id) && !supersedes.contains(id) {
721            supersedes.push(id.clone());
722        }
723    }
724    let head = cluster.first()?;
725    let digest = fact_digest(&text);
726    if let Some(same) = sources.iter().find(|fact| fact.digest == digest) {
727        supersedes.retain(|id| *id != same.id);
728        return (!supersedes.is_empty())
729            .then(|| PlannedMerge::Into { into: same.id.clone(), supersedes });
730    }
731    if supersedes.is_empty() || scope_live.iter().any(|fact| fact.digest == digest) {
732        return None;
733    }
734    Some(PlannedMerge::New {
735        kind: head.kind,
736        scope: head.scope.clone(),
737        text,
738        sources,
739        supersedes,
740    })
741}
742
743/// The most live facts the passes may lose in a scope of `live` facts (spec 3.2 §7.5):
744/// `max(1, ⌊max_loss_fraction × live⌋)`. The cap stops mass loss; a scope too small for one
745/// loss in its share may still collapse one duplicate.
746#[cfg(feature = "runner")]
747pub(crate) fn loss_cap(live: usize, max_loss_fraction: f32) -> usize {
748    ((max_loss_fraction * live as f32).floor() as usize).max(1)
749}
750
751#[cfg(all(test, feature = "runner"))]
752mod tests {
753    use super::*;
754    use crate::facts::{FactSource, Provenance};
755
756    const DAY: i64 = 24 * 60 * 60;
757
758    fn fact(kind: FactKind, status: FactStatus, age_days: i64, now: DateTime<Utc>) -> MemoryFact {
759        let mut fact = MemoryFact::new(
760            FactScope::new("app", "alice", Some("p".into())),
761            kind,
762            format!("fact {}", uuid::Uuid::new_v4()),
763            status,
764            Provenance::new(FactSource::AgentInferred, "s", "i"),
765        );
766        fact.valid_from = now - chrono::Duration::days(age_days);
767        fact
768    }
769
770    /// Two unit vectors at cosine `score`.
771    fn pair(score: f32) -> (Vec<f32>, Vec<f32>) {
772        (vec![1.0, 0.0], vec![score, (1.0 - score * score).max(0.0).sqrt()])
773    }
774
775    fn scope(facts: Vec<(MemoryFact, Vec<f32>)>) -> ScopeFacts {
776        let mut out = ScopeFacts::default();
777        for (fact, vector) in facts {
778            out.vectors.insert(fact.id.clone(), vector);
779            out.live.push(fact);
780        }
781        out
782    }
783
784    #[test]
785    fn pass_one_supersedes_the_older_at_the_dedup_score_and_not_below() {
786        let now = Utc::now();
787        let config = ConsolidationConfig::default();
788        for (score, superseded) in [(0.92f32, true), (0.9199, false), (0.99, true)] {
789            let (a, b) = pair(score);
790            let older = fact(FactKind::ProjectFact, FactStatus::Assumed, 2, now);
791            let newer = fact(FactKind::ProjectFact, FactStatus::Assumed, 1, now);
792            let facts = scope(vec![(older.clone(), a), (newer.clone(), b)]);
793            let (changes, survivors) = pass_one(&facts, &config, now);
794            if superseded {
795                assert_eq!(
796                    changes,
797                    vec![FactChange {
798                        fact: older.id.clone(),
799                        scope: older.scope.clone(),
800                        to: FactStatus::Superseded { by: newer.id.clone() },
801                        reason: ChangeReason::Duplicate,
802                    }],
803                    "score {score}"
804                );
805                assert_eq!(survivors, vec![newer]);
806            } else {
807                assert!(changes.is_empty(), "score {score}: {changes:?}");
808            }
809        }
810    }
811
812    #[test]
813    fn pass_one_never_touches_known_facts_or_other_kinds() {
814        let now = Utc::now();
815        let (a, b) = pair(1.0);
816        let known = fact(FactKind::ProjectFact, FactStatus::Known, 400, now);
817        let twin = fact(FactKind::ProjectFact, FactStatus::Assumed, 1, now);
818        let other_kind = fact(FactKind::Decision, FactStatus::Assumed, 2, now);
819        let facts =
820            scope(vec![(known, a.clone()), (twin.clone(), b.clone()), (other_kind.clone(), a)]);
821        let (changes, survivors) = pass_one(&facts, &ConsolidationConfig::default(), now);
822        assert!(changes.is_empty(), "{changes:?}");
823        assert_eq!(survivors.len(), 2);
824    }
825
826    #[test]
827    fn expiry_holds_exactly_past_the_thresholds() {
828        let now = Utc::now();
829        let config = ConsolidationConfig::default();
830        let stale = |confidence: f32, age: chrono::Duration| {
831            let mut fact =
832                fact(FactKind::Outcome, FactStatus::Assumed, 0, now).with_confidence(confidence);
833            fact.valid_from = now - age;
834            fact
835        };
836        let ninety = chrono::Duration::seconds(90 * DAY);
837        let second = chrono::Duration::seconds(1);
838        assert!(expires(&stale(0.49, ninety + second), &config, now));
839        assert!(!expires(&stale(0.5, ninety + second), &config, now), "0.5 is not under 0.5");
840        assert!(!expires(&stale(0.49, ninety), &config, now), "90 days is not over 90 days");
841        let mut used = stale(0.1, ninety * 2);
842        used.uses = 1;
843        assert!(!expires(&used, &config, now));
844        let mut recalled = stale(0.1, ninety * 2);
845        recalled.last_recalled = Some(now);
846        assert!(!expires(&recalled, &config, now));
847        let mut unknown = stale(0.1, ninety * 2);
848        unknown.confidence = None;
849        assert!(!expires(&unknown, &config, now), "an unknown confidence is not a low one");
850        let mut known = stale(0.1, ninety * 2);
851        known.status = FactStatus::Known;
852        assert!(!expires(&known, &config, now));
853    }
854
855    #[test]
856    fn clusters_take_the_band_below_the_dedup_score() {
857        let now = Utc::now();
858        let config = ConsolidationConfig::default();
859        let head = fact(FactKind::Procedure, FactStatus::Assumed, 1, now);
860        let near = fact(FactKind::Procedure, FactStatus::Assumed, 2, now);
861        let far = fact(FactKind::Procedure, FactStatus::Assumed, 3, now);
862        let (a, b) = pair(0.85);
863        let (_, c) = pair(0.79);
864        let facts = scope(vec![(head.clone(), a), (near.clone(), b), (far, c)]);
865        let found = clusters(&facts, &facts.live, &config, 20);
866        assert_eq!(found, vec![vec![head, near]]);
867        assert!(clusters(&facts, &facts.live, &config, 0).is_empty());
868    }
869
870    #[test]
871    fn merges_stay_inside_their_cluster() {
872        let now = Utc::now();
873        let a = fact(FactKind::Procedure, FactStatus::Assumed, 1, now);
874        let b = fact(FactKind::Procedure, FactStatus::Assumed, 2, now);
875        let known = fact(FactKind::Procedure, FactStatus::Known, 3, now);
876        let cluster = vec![a.clone(), b.clone()];
877        let live = vec![a.clone(), b.clone(), known.clone()];
878        let answer = |supersedes: Vec<&str>| MergeAnswer {
879            merged_text: "merged".into(),
880            source_ids: vec![a.id.clone(), b.id.clone(), known.id.clone()],
881            supersedes: supersedes.into_iter().map(str::to_string).collect(),
882        };
883        let planned = plan_merge(
884            &cluster,
885            &answer(vec![&a.id, &b.id, &known.id]),
886            Some("merged".into()),
887            &live,
888        )
889        .unwrap();
890        let PlannedMerge::New { supersedes, .. } = planned else {
891            panic!("a new merged fact: {planned:?}");
892        };
893        assert_eq!(supersedes, [a.id.clone(), b.id.clone()], "never the known fact");
894        assert!(plan_merge(&cluster, &answer(vec![]), Some("merged".into()), &live).is_none());
895        assert!(plan_merge(&cluster, &answer(vec![&a.id]), None, &live).is_none(), "refused text");
896        let same = plan_merge(&cluster, &answer(vec![&a.id, &b.id]), Some(a.text.clone()), &live);
897        assert_eq!(
898            same,
899            Some(PlannedMerge::Into { into: a.id.clone(), supersedes: vec![b.id.clone()] })
900        );
901        assert!(
902            plan_merge(&cluster, &answer(vec![&a.id]), Some(known.text.clone()), &live).is_none(),
903            "a text a live fact already holds"
904        );
905    }
906
907    #[test]
908    fn the_loss_cap_is_a_share_of_live_facts_and_at_least_one() {
909        let caps: Vec<usize> =
910            [0, 2, 3, 4, 7, 8, 10, 100].into_iter().map(|live| loss_cap(live, 0.25)).collect();
911        assert_eq!(caps, vec![1, 1, 1, 1, 1, 2, 2, 25]);
912        assert_eq!((loss_cap(10, 0.7), loss_cap(10, 0.0), loss_cap(10, 1.0)), (7, 1, 10));
913    }
914}
915
916#[cfg(feature = "runner")]
917mod tick {
918    use std::sync::Arc;
919
920    use adk_core::audit_log::AuditActor;
921    use adk_core::{BudgetTracker, Result, RunBudget};
922    use chrono::{DateTime, Utc};
923    use serde_json::json;
924
925    use super::{
926        ChangeReason, ConsolidationRecord, ConsolidationRequest, FactChange, PlannedMerge,
927        ScopeFacts, SessionDistillation, clusters, loss_cap, pass_one, plan_merge,
928    };
929    use crate::audit::HarnessAudit;
930    use crate::facts::runtime::{FactsRuntime, harness_subject};
931    use crate::facts::types::{
932        FactFilter, FactScope, FactSource, FactStatus, MemoryFact, Provenance, new_fact_id,
933    };
934    use crate::facts::writer::TickWrites;
935
936    /// One scope's facts, pass-1 changes, pass-2 clusters and planned merges.
937    struct ScopePlan {
938        facts: ScopeFacts,
939        changes: Vec<FactChange>,
940        clusters: Vec<Vec<MemoryFact>>,
941        merges: Vec<PlannedMerge>,
942    }
943
944    fn not_live(error: &adk_core::AdkError) -> bool {
945        error.code == "harness.memory.fact_not_live"
946    }
947
948    impl FactsRuntime {
949        /// The public distillation entry (spec 3.2 §10 HK2) outside a tick.
950        pub(crate) async fn distill_sessions(
951            &self,
952            app: &str,
953            user: &str,
954            sessions: &[String],
955            now: DateTime<Utc>,
956            budget: Option<RunBudget>,
957        ) -> Result<SessionDistillation> {
958            let _one_at_a_time = self.distilling.lock().await;
959            let parent = budget.map(|budget| Arc::new(BudgetTracker::new(budget)));
960            self.distill_unreached(app, user, sessions, now, &TickWrites::new(None), parent).await
961        }
962
963        /// The live facts of exactly `scope` and the vectors of one embedder (spec 3.1
964        /// §7.32, I73): the consolidation embedder's, its `Assumed` facts without one
965        /// embedded first; without an embedder, the embedder most stored vectors carry.
966        async fn scope_facts(&self, scope: &FactScope) -> Result<ScopeFacts> {
967            let live = self
968                .store
969                .list(FactFilter { live_only: true, ..FactFilter::exactly(scope) })
970                .await?;
971            let stored = self.store.embeddings(scope).await?;
972            let id = match &self.embedder {
973                Some(embedder) => crate::facts::embedder_id(embedder.as_ref()),
974                None => {
975                    let mut counts: std::collections::BTreeMap<&str, usize> =
976                        std::collections::BTreeMap::new();
977                    for (_, embedding) in &stored {
978                        *counts.entry(embedding.embedder.as_str()).or_default() += 1;
979                    }
980                    let most = counts.iter().max_by_key(|(_, count)| **count);
981                    most.map(|(id, _)| (*id).to_string()).unwrap_or_default()
982                }
983            };
984            let mut vectors: std::collections::HashMap<String, Vec<f32>> = stored
985                .into_iter()
986                .filter(|(_, embedding)| embedding.is_from(&id))
987                .map(|(fact, embedding)| (fact, embedding.vector))
988                .collect();
989            if let Some(embedder) = &self.embedder {
990                let dimensions = embedder.dimensions();
991                let missing: Vec<&MemoryFact> = live
992                    .iter()
993                    .filter(|fact| fact.status == FactStatus::Assumed)
994                    .filter(|fact| {
995                        vectors.get(&fact.id).is_none_or(|vector| {
996                            vector.is_empty() || (dimensions > 0 && vector.len() != dimensions)
997                        })
998                    })
999                    .collect();
1000                if !missing.is_empty() {
1001                    let texts: Vec<String> = missing.iter().map(|fact| fact.text.clone()).collect();
1002                    match embedder.embed(&texts).await {
1003                        Ok(embedded) => {
1004                            for (fact, vector) in missing.into_iter().zip(embedded) {
1005                                let embedding =
1006                                    crate::facts::FactEmbedding::new(id.clone(), vector.clone());
1007                                if let Err(error) =
1008                                    self.store.put_embedding(&fact.id, embedding).await
1009                                {
1010                                    tracing::debug!(error = %error, "could not store a fact embedding");
1011                                }
1012                                vectors.insert(fact.id.clone(), vector);
1013                            }
1014                        }
1015                        Err(error) => tracing::warn!(
1016                            error = %error,
1017                            "fact embedding failed; consolidation compares the stored vectors only"
1018                        ),
1019                    }
1020                }
1021            }
1022            Ok(ScopeFacts { live, vectors })
1023        }
1024
1025        /// The audit of a tick's writes: the harness's trail outside a run.
1026        fn tick_audit(&self, app: &str, user: &str, tick_id: &str) -> Option<HarnessAudit> {
1027            self.outside_trail().map(|trail| {
1028                HarnessAudit::new(
1029                    trail,
1030                    AuditActor::for_invocation(
1031                        app,
1032                        &format!("{}-consolidator", self.root_agent),
1033                        user,
1034                        tick_id,
1035                    ),
1036                    String::new(),
1037                )
1038            })
1039        }
1040
1041        /// One consolidation tick over `user`'s facts (spec 3.2 §7.5, §10 HK2): the
1042        /// sessions the per-session distiller never reached are distilled with quote
1043        /// promotion off, then the two passes run over the project's and the user-wide
1044        /// scope, all or nothing under the loss cap. The record is written before any
1045        /// change and again after, and one `harness.memory.consolidated` record is audited.
1046        pub(crate) async fn consolidate(
1047            &self,
1048            app: &str,
1049            user: &str,
1050            request: ConsolidationRequest,
1051        ) -> Result<ConsolidationRecord> {
1052            let config = request.config.clone();
1053            let now = request.at.unwrap_or_else(Utc::now);
1054            let tick_id = request
1055                .tick_id
1056                .clone()
1057                .filter(|id| !id.trim().is_empty())
1058                .unwrap_or_else(new_fact_id);
1059            let partition = request.partition.clone().unwrap_or_else(|| "default".to_string());
1060            let _one_at_a_time = self.distilling.lock().await;
1061            let mut record = ConsolidationRecord::new(&tick_id, app, user, &partition, now);
1062            let project = self.scope(app, user);
1063            // A partition's harness reads no user-wide fact, so its tick merges none (K-I15).
1064            record.scopes = if self.confined {
1065                vec![project.clone()]
1066            } else {
1067                vec![project.clone(), project.user_wide()]
1068            };
1069            // Write-ahead; a store that cannot keep the record refuses here, before any change.
1070            self.store.put_consolidation(&record).await?;
1071
1072            let budget = request.budget.clone().unwrap_or_default();
1073            let tokens = budget
1074                .max_total_tokens
1075                .map_or(config.max_tokens_per_tick, |cap| cap.min(config.max_tokens_per_tick));
1076            let tracker = Arc::new(BudgetTracker::new(budget.max_total_tokens(tokens)));
1077
1078            // Distillation of what the per-session distiller never reached (HK2).
1079            let writes = TickWrites::new(Some(tick_id.clone()));
1080            let distilled = self
1081                .distill_unreached(
1082                    app,
1083                    user,
1084                    &request.sessions,
1085                    now,
1086                    &writes,
1087                    Some(tracker.clone()),
1088                )
1089                .await?;
1090            record.sessions = distilled.sessions;
1091            record.distilled = distilled.stored;
1092            record.changes = distilled.changes;
1093            record.beside_known = distilled.beside_known;
1094
1095            // Pass 1, and the clusters pass 2 may merge.
1096            let mut plans = Vec::with_capacity(record.scopes.len());
1097            let mut cluster_room = config.max_clusters_per_tick;
1098            for scope in &record.scopes {
1099                let facts = self.scope_facts(scope).await?;
1100                let (changes, survivors) = pass_one(&facts, &config, now);
1101                let clusters = clusters(&facts, &survivors, &config, cluster_room);
1102                cluster_room = cluster_room.saturating_sub(clusters.len());
1103                plans.push(ScopePlan { facts, changes, clusters, merges: Vec::new() });
1104            }
1105
1106            // Pass 2: one bounded model call per cluster, inside the tick's budget.
1107            'pass_two: for plan in &mut plans {
1108                for cluster in std::mem::take(&mut plan.clusters) {
1109                    if tracker.check().is_err() {
1110                        break 'pass_two;
1111                    }
1112                    match self.run_merge(user, &cluster, Some(tracker.clone())).await {
1113                        Ok((answer, _)) => {
1114                            let text = Some(answer.merged_text.trim())
1115                                .filter(|text| !text.is_empty())
1116                                .and_then(|text| {
1117                                    crate::facts::redact::redact_fact_text(
1118                                        text,
1119                                        self.config.max_fact_chars,
1120                                    )
1121                                    .ok()
1122                                });
1123                            plan.merges.extend(plan_merge(
1124                                &cluster,
1125                                &answer,
1126                                text,
1127                                &plan.facts.live,
1128                            ));
1129                        }
1130                        Err(error) => {
1131                            tracing::warn!(error = %error, "a consolidation merge failed; its facts stay as they are");
1132                            if tracker.check().is_err() {
1133                                break 'pass_two;
1134                            }
1135                        }
1136                    }
1137                }
1138            }
1139
1140            // The loss cap: all or nothing, on the live facts the passes lose. A pass-1
1141            // supersession or expiry loses one; a merge loses the facts it supersedes less
1142            // the one it writes, which keeps their content with provenance.
1143            for plan in &plans {
1144                let live = plan.facts.live.len();
1145                let lost = plan.changes.len()
1146                    + plan
1147                        .merges
1148                        .iter()
1149                        .map(|merge| match merge {
1150                            PlannedMerge::New { supersedes, .. } => {
1151                                supersedes.len().saturating_sub(1)
1152                            }
1153                            PlannedMerge::Into { supersedes, .. } => supersedes.len(),
1154                        })
1155                        .sum::<usize>();
1156                let cap = loss_cap(live, config.max_loss_fraction);
1157                if lost > cap {
1158                    record.refused = Some(format!(
1159                        "the passes would lose {lost} of the {live} live facts of one scope, \
1160                         more than the {cap} max_loss_fraction {} allows",
1161                        config.max_loss_fraction
1162                    ));
1163                    break;
1164                }
1165            }
1166
1167            let audit = self.tick_audit(app, user, &tick_id);
1168            if record.refused.is_none() {
1169                self.apply(&mut record, plans, audit.as_ref(), now).await?;
1170            }
1171            let usage = tracker.usage();
1172            record.model_calls = usage.model_calls;
1173            record.total_tokens = usage.total_tokens;
1174            record.cost_micro_usd = usage.cost_micro_usd;
1175            record.finished_at = Some(Utc::now());
1176            self.store.put_consolidation(&record).await?;
1177            if let Some(audit) = &audit {
1178                let ids = |changes: Vec<&FactChange>| {
1179                    changes.into_iter().map(|change| change.fact.clone()).collect::<Vec<_>>()
1180                };
1181                let superseded = ids(record.superseded().collect());
1182                let forgotten = ids(record.forgotten().collect());
1183                audit
1184                    .record(
1185                        "harness.memory.consolidated",
1186                        json!({
1187                            "tickId": record.tick_id,
1188                            "partition": record.partition,
1189                            "scope": project.project,
1190                            "superseded": superseded,
1191                            "forgotten": forgotten,
1192                            "merged": record.merged,
1193                            "distilled": record.distilled,
1194                            "besideKnown": record
1195                                .beside_known
1196                                .iter()
1197                                .map(|beside| json!({ "fact": beside.fact, "known": beside.known }))
1198                                .collect::<Vec<_>>(),
1199                            "sessions": record.sessions.len(),
1200                            "counts": {
1201                                "superseded": superseded.len(),
1202                                "forgotten": forgotten.len(),
1203                                "merged": record.merged.len(),
1204                                "distilled": record.distilled.len(),
1205                            },
1206                            "refused": record.refused.is_some(),
1207                            "modelCalls": record.model_calls,
1208                            "tokens": record.total_tokens,
1209                            "cost": record.cost_micro_usd,
1210                        }),
1211                    )
1212                    .await?;
1213            }
1214            tracing::info!(
1215                memory.tick = %record.tick_id,
1216                memory.superseded = record.superseded().count(),
1217                memory.forgotten = record.forgotten().count(),
1218                memory.merged = record.merged.len(),
1219                memory.distilled = record.distilled.len(),
1220                memory.refused = record.refused.is_some(),
1221                "memory consolidated"
1222            );
1223            Ok(record)
1224        }
1225
1226        /// Applies the passes' plans. The record lists the plan first, so `undo` reverts a
1227        /// tick a crash interrupted; a fact a concurrent write already changed is skipped.
1228        async fn apply(
1229            &self,
1230            record: &mut ConsolidationRecord,
1231            plans: Vec<ScopePlan>,
1232            audit: Option<&HarnessAudit>,
1233            now: DateTime<Utc>,
1234        ) -> Result<()> {
1235            let tick_id = record.tick_id.clone();
1236            let mut pass_one: Vec<(MemoryFact, FactChange)> = Vec::new();
1237            // (the new fact, or none when a source's text won; the target; what it supersedes)
1238            let mut merges: Vec<(Option<MemoryFact>, String, Vec<MemoryFact>)> = Vec::new();
1239            for plan in plans {
1240                let live =
1241                    |id: &String| plan.facts.live.iter().find(|fact| fact.id == *id).cloned();
1242                for change in plan.changes {
1243                    pass_one.extend(live(&change.fact).map(|fact| (fact, change)));
1244                }
1245                for merge in plan.merges {
1246                    match merge {
1247                        PlannedMerge::New { kind, scope, text, sources, supersedes } => {
1248                            let mut provenance =
1249                                Provenance::new(FactSource::AgentInferred, "", tick_id.clone());
1250                            provenance.at = now;
1251                            provenance.source_ids =
1252                                sources.iter().map(|source| source.id.clone()).collect();
1253                            provenance.tick = Some(tick_id.clone());
1254                            let mut fact =
1255                                MemoryFact::new(scope, kind, text, FactStatus::Assumed, provenance);
1256                            fact.confidence = sources
1257                                .iter()
1258                                .filter_map(|source| source.confidence)
1259                                .reduce(f32::max);
1260                            fact.uses = sources
1261                                .iter()
1262                                .fold(0u32, |uses, source| uses.saturating_add(source.uses));
1263                            fact.last_recalled =
1264                                sources.iter().filter_map(|source| source.last_recalled).max();
1265                            let target = fact.id.clone();
1266                            let superseded = supersedes.iter().filter_map(live).collect();
1267                            merges.push((Some(fact), target, superseded));
1268                        }
1269                        PlannedMerge::Into { into, supersedes } => {
1270                            merges.push((None, into, supersedes.iter().filter_map(live).collect()));
1271                        }
1272                    }
1273                }
1274            }
1275            let merged = |fact: &MemoryFact, target: &str| FactChange {
1276                fact: fact.id.clone(),
1277                scope: fact.scope.clone(),
1278                to: FactStatus::Superseded { by: target.to_string() },
1279                reason: ChangeReason::Merged,
1280            };
1281
1282            // Write-ahead: the whole plan.
1283            let mut planned = record.clone();
1284            planned.changes.extend(pass_one.iter().map(|(_, change)| change.clone()));
1285            for (new, target, superseded) in &merges {
1286                planned.merged.extend(new.as_ref().map(|fact| fact.id.clone()));
1287                planned.changes.extend(superseded.iter().map(|fact| merged(fact, target)));
1288            }
1289            self.store.put_consolidation(&planned).await?;
1290
1291            let by = harness_subject();
1292            let mut changes = pass_one;
1293            for (new, target, superseded) in merges {
1294                let target = match new {
1295                    Some(fact) => {
1296                        if let Some(audit) = audit {
1297                            audit
1298                                .record(
1299                                    "harness.memory.fact.stored",
1300                                    json!({
1301                                        "factId": fact.id,
1302                                        "kind": fact.kind.as_str(),
1303                                        "status": fact.status.label(),
1304                                        "source": fact.provenance.source.as_str(),
1305                                        "project": fact.scope.project,
1306                                        "digest": fact.digest,
1307                                        "sessionId": "",
1308                                        "tickId": tick_id,
1309                                        "sourceIds": fact.provenance.source_ids,
1310                                    }),
1311                                )
1312                                .await?;
1313                        }
1314                        let stored = self.store.put(fact).await?;
1315                        if let Err(error) = self.index.upsert(&stored).await {
1316                            tracing::warn!(error = %error, "could not index a fact; recall by search may miss it");
1317                        }
1318                        record.merged.push(stored.id.clone());
1319                        stored.id
1320                    }
1321                    None => target,
1322                };
1323                changes.extend(superseded.into_iter().map(|fact| {
1324                    let change = merged(&fact, &target);
1325                    (fact, change)
1326                }));
1327            }
1328            for (fact, change) in changes {
1329                let reason = change.reason.as_str();
1330                match self
1331                    .change_status_in(
1332                        audit,
1333                        &fact,
1334                        change.to.clone(),
1335                        &by,
1336                        Some((&tick_id, reason)),
1337                    )
1338                    .await
1339                {
1340                    Ok(()) => record.changes.push(change),
1341                    Err(error) if not_live(&error) => {}
1342                    Err(error) => return Err(error),
1343                }
1344            }
1345            Ok(())
1346        }
1347    }
1348}