Skip to main content

adk_harness/facts/
kernel_tick.rs

1//! The harness's side of the kernel's consolidation tick (spec 3.2 §7.5, §10 HK2; features
2//! `kernel` and `memory`): [`HarnessConsolidator`] reports a partition's new material and
3//! runs a tick through [`Harness::consolidate_memory`]. [`HarnessObservations`] is the
4//! person the kernel's `/proc` observations are put to, and remembers the ones they confirm
5//! (spec 3.2 §7.10).
6
7use std::sync::Arc;
8
9use adk_core::UserId;
10use adk_core::principal::SubjectRef;
11use adk_kernel::{
12    AgendaItem, Consolidator, ObservationAudience, PartitionId, PartitionMode, TickMaterial,
13    TickOutcome, TickProposal, TickRun, TickSpend,
14};
15use adk_session::{ListRequest, SessionService};
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18
19use super::consolidate::{ConsolidationConfig, ConsolidationRecord, ConsolidationRequest};
20use super::runtime::FactsRuntime;
21use super::types::{FactFilter, FactKind, FactScope};
22use crate::harness::Harness;
23use crate::mode::HarnessMode;
24
25/// Which sessions a [`HarnessConsolidator`] distils: true keeps one, read from its state.
26pub type SessionStateFilter = Arc<dyn Fn(&dyn adk_session::State) -> bool + Send + Sync>;
27
28/// The [`Consolidator`] of one user of a harness (spec 3.2 §7.5, §10 HK2), registered with
29/// `KernelBuilder::consolidator`.
30///
31/// | Material | Read from |
32/// |---|---|
33/// | The last tick and what today's ticks spent | the user's consolidation records in the fact store |
34/// | Distilled sessions since the last tick | the store's distillation cursor: sessions read past the last tick |
35/// | New facts since the last tick | the project's and the user-wide facts, the ticks' own aside |
36/// | Latest activity and the sessions to distil | the user's sessions updated since the last tick, kept by the session filter |
37/// | Mode | the harness's mode, as the partition's |
38///
39/// A tick runs [`Harness::consolidate_memory`] with the tick's thresholds and budget, and
40/// proposes one agenda item when it stored assumptions beside known facts, so a person
41/// confirms or forgets them (K-I22, K-I23).
42///
43/// # Example
44///
45/// ```rust,ignore
46/// let consolidator = harness
47///     .consolidator(&user)?
48///     .with_session_filter(Arc::new(|state| state.get("harness:workspace").is_some()));
49/// let kernel = harness
50///     .kernel()
51///     .config(KernelConfig::default().with_proactivity(
52///         ProactivityPolicy::default().with_consolidation(ConsolidationTick::default()),
53///     ))
54///     .consolidator(PartitionId::default(), Arc::new(consolidator))
55///     .build()?;
56/// ```
57#[derive(Clone)]
58pub struct HarnessConsolidator {
59    facts: Arc<FactsRuntime>,
60    sessions: Arc<dyn SessionService>,
61    app: String,
62    user: String,
63    filter: Option<SessionStateFilter>,
64}
65
66impl std::fmt::Debug for HarnessConsolidator {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("HarnessConsolidator")
69            .field("app", &self.app)
70            .field("filter", &self.filter.is_some())
71            .finish_non_exhaustive()
72    }
73}
74
75impl HarnessConsolidator {
76    /// Distils only the sessions whose state `filter` keeps; the CLI keeps the sessions of
77    /// its workspace.
78    #[must_use]
79    pub fn with_session_filter(mut self, filter: SessionStateFilter) -> Self {
80        self.filter = Some(filter);
81        self
82    }
83
84    /// The user's sessions updated after `since`, kept by the filter, with their last update.
85    async fn sessions_since(
86        &self,
87        since: Option<DateTime<Utc>>,
88    ) -> adk_core::Result<Vec<(String, DateTime<Utc>)>> {
89        let listed = self
90            .sessions
91            .list(ListRequest {
92                app_name: self.app.clone(),
93                user_id: self.user.clone(),
94                limit: None,
95                offset: None,
96            })
97            .await?;
98        let mut out = Vec::new();
99        for session in listed {
100            let updated = session.last_update_time();
101            if since.is_some_and(|since| updated <= since) {
102                continue;
103            }
104            if let Some(filter) = &self.filter {
105                let full = self
106                    .sessions
107                    .get(adk_session::GetRequest {
108                        app_name: self.app.clone(),
109                        user_id: self.user.clone(),
110                        session_id: session.id().to_string(),
111                        num_recent_events: Some(1),
112                        after: None,
113                    })
114                    .await?;
115                if !filter(full.state()) {
116                    continue;
117                }
118            }
119            out.push((session.id().to_string(), updated));
120        }
121        Ok(out)
122    }
123}
124
125fn partition_mode(mode: HarnessMode) -> PartitionMode {
126    match mode {
127        HarnessMode::ReadOnly => PartitionMode::ReadOnly,
128        HarnessMode::Plan => PartitionMode::Plan,
129        HarnessMode::Ask => PartitionMode::Ask,
130        HarnessMode::Auto => PartitionMode::Auto,
131    }
132}
133
134/// The agenda item for the assumptions a tick stored beside known facts: ids only.
135fn beside_known_proposal(record: &ConsolidationRecord) -> Option<TickProposal> {
136    if record.beside_known.is_empty() {
137        return None;
138    }
139    let pairs: Vec<String> = record
140        .beside_known
141        .iter()
142        .map(|beside| format!("{} beside {}", beside.fact, beside.known))
143        .collect();
144    Some(TickProposal::new(
145        format!(
146            "Confirm or forget {} remembered assumption(s) that disagree with known facts",
147            pairs.len()
148        ),
149        format!(
150            "Consolidation tick {} stored assumptions beside the known facts they would \
151             replace: {}. `adk-rust memory accept ID` confirms one; `adk-rust memory forget ID` \
152             drops it.",
153            record.tick_id,
154            pairs.join("; ")
155        ),
156    ))
157}
158
159#[async_trait]
160impl Consolidator for HarnessConsolidator {
161    async fn material(
162        &self,
163        _partition: &PartitionId,
164        now: DateTime<Utc>,
165    ) -> adk_kernel::Result<TickMaterial> {
166        let records = self.facts.store.consolidations(&self.app, &self.user).await?;
167        let last_tick = records.iter().map(|record| record.at).max();
168        let today = now.date_naive();
169        let spent = records.iter().filter(|record| record.at.date_naive() == today).fold(
170            TickSpend::default(),
171            |spent, record| {
172                TickSpend::new(
173                    spent.cost_micro_usd.saturating_add(record.cost_micro_usd),
174                    spent.total_tokens.saturating_add(record.total_tokens),
175                    spent.model_calls.saturating_add(record.model_calls),
176                )
177            },
178        );
179        let new_sessions = self
180            .facts
181            .store
182            .distilled_sessions(&self.app, &self.user)
183            .await?
184            .into_iter()
185            .filter(|(_, upto)| last_tick.is_none_or(|last| *upto > last))
186            .count();
187        let scope = self.facts.scope(&self.app, &self.user);
188        let readable = if self.facts.confined {
189            FactFilter::exactly(&scope)
190        } else {
191            FactFilter::recall(&scope)
192        };
193        let new_facts = self
194            .facts
195            .store
196            .list(FactFilter { live_only: false, since: last_tick, ..readable })
197            .await?
198            .into_iter()
199            .filter(|fact| fact.provenance.tick.is_none())
200            .filter(|fact| last_tick.is_none_or(|last| fact.valid_from > last))
201            .count();
202        let sessions = self.sessions_since(last_tick).await?;
203        let mut material = TickMaterial::new(&self.user, partition_mode(self.facts.default_mode))
204            .with_new_material(new_sessions, new_facts)
205            .with_sessions(sessions.iter().map(|(id, _)| id.clone()))
206            .with_spent_today(spent);
207        if let Some(last) = last_tick {
208            material = material.with_last_tick(last);
209        }
210        if let Some(active) = sessions.iter().map(|(_, at)| *at).max() {
211            material = material.with_last_activity(active);
212        }
213        Ok(material)
214    }
215
216    async fn consolidate(&self, run: TickRun) -> adk_kernel::Result<TickOutcome> {
217        let tick = &run.tick;
218        let config = ConsolidationConfig {
219            dedup_score: tick.dedup_score,
220            expire_confidence: tick.expire_confidence,
221            assumed_ttl: tick.assumed_ttl,
222            max_clusters_per_tick: tick.max_clusters_per_tick,
223            max_loss_fraction: tick.max_loss_fraction,
224            max_tokens_per_tick: tick.max_tokens_per_tick,
225        };
226        let request = ConsolidationRequest::new()
227            .with_tick_id(&run.tick_id)
228            .with_partition(run.partition.as_str())
229            .with_sessions(run.sessions.clone())
230            .with_config(config)
231            .with_budget(run.budget.clone())
232            .at(run.at);
233        let record = self.facts.consolidate(&self.app, &self.user, request).await?;
234        let mut outcome = TickOutcome::new(&record.tick_id)
235            .with_counts(
236                record.superseded().count(),
237                record.forgotten().count(),
238                record.merged.len(),
239                record.distilled.len(),
240            )
241            .with_spend(TickSpend::new(
242                record.cost_micro_usd,
243                record.total_tokens,
244                record.model_calls,
245            ));
246        if let Some(refused) = &record.refused {
247            outcome = outcome.with_refused(refused.clone());
248        }
249        if let Some(proposal) = beside_known_proposal(&record) {
250            outcome = outcome.with_proposal(proposal);
251        }
252        Ok(outcome)
253    }
254}
255
256impl Harness {
257    /// The kernel's [`Consolidator`] for `user`'s memory in this harness (spec 3.2 §7.5,
258    /// §10 HK2): register it with `KernelBuilder::consolidator` and turn the tick on with
259    /// `ProactivityPolicy::consolidation`. The tick is off unless both are set: it is on in
260    /// the CLI's Ask and Auto partitions, off in the library and on servers.
261    ///
262    /// # Example
263    ///
264    /// ```rust,ignore
265    /// let kernel = harness
266    ///     .kernel()
267    ///     .consolidator(adk_kernel::PartitionId::default(), Arc::new(harness.consolidator(&user)?))
268    ///     .build()?;
269    /// ```
270    ///
271    /// # Errors
272    ///
273    /// Returns a configuration error when long-term memory is off.
274    pub fn consolidator(&self, user: &UserId) -> adk_core::Result<HarnessConsolidator> {
275        let facts = self.agent().runtime().toolset().facts().cloned().ok_or_else(|| {
276            adk_core::AdkError::config(
277                "the consolidation tick works on long-term memory, which is off for this \
278                 harness; turn it on with HarnessAgentBuilder::long_term_memory",
279            )
280        })?;
281        Ok(HarnessConsolidator {
282            facts,
283            sessions: self.sessions().clone(),
284            app: self.app_name().to_string(),
285            user: user.to_string(),
286            filter: None,
287        })
288    }
289}
290
291/// The [`ObservationAudience`] of one user of a harness (spec 3.2 §7.10), registered with
292/// `KernelBuilder::observation_audience`: the kernel puts the partition's observations to
293/// this user, in the harness's mode, and a person's confirmation becomes a user-wide
294/// `Preference` fact, `Known` with source `UserConfirmed` (spec 3.1 §7.15). The same text
295/// already remembered is promoted to `Known` rather than stored twice; a rejected
296/// observation records nothing, so any related fact stays as it was.
297///
298/// A partition's harness is the audience of its own partition only (spec 3.2 §7.8,
299/// K-I15): it answers no one for another partition's observations, refuses to confirm one,
300/// and remembers a confirmed observation in the partition's `memory_scope`, where no other
301/// partition reads it.
302///
303/// # Example
304///
305/// ```rust,ignore
306/// let kernel = harness
307///     .kernel()
308///     .observation_audience(PartitionId::default(), Arc::new(harness.observation_audience(&user)?))
309///     .build()?;
310/// ```
311#[derive(Clone)]
312pub struct HarnessObservations {
313    facts: Arc<FactsRuntime>,
314    app: String,
315    user: String,
316    /// The partition of a partition's harness.
317    partition: Option<PartitionId>,
318}
319
320impl HarnessObservations {
321    /// Whether `partition`'s observations are this audience's: any partition's for a
322    /// harness without one, else its own only.
323    fn serves(&self, partition: &PartitionId) -> bool {
324        self.partition.as_ref().is_none_or(|own| own == partition)
325    }
326}
327
328impl std::fmt::Debug for HarnessObservations {
329    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
330        f.debug_struct("HarnessObservations").field("app", &self.app).finish_non_exhaustive()
331    }
332}
333
334#[async_trait]
335impl ObservationAudience for HarnessObservations {
336    async fn audience(
337        &self,
338        partition: &PartitionId,
339    ) -> adk_kernel::Result<Option<(SubjectRef, PartitionMode)>> {
340        if !self.serves(partition) {
341            return Ok(None);
342        }
343        Ok(Some((SubjectRef::human(&self.user), partition_mode(self.facts.default_mode))))
344    }
345
346    async fn confirm(&self, item: &AgendaItem, by: &SubjectRef) -> adk_kernel::Result<String> {
347        if !self.serves(&item.partition) {
348            return Err(adk_kernel::KernelError::Config {
349                reason: format!(
350                    "agenda item {} is an observation of partition `{}`, which this harness \
351                     does not run; only its own partition's harness remembers it (spec 3.2 \
352                     K-I15)",
353                    item.id, item.partition
354                ),
355            });
356        }
357        if item.subject.id != self.user {
358            return Err(adk_kernel::KernelError::Config {
359                reason: format!(
360                    "agenda item {} asks {}, but this harness remembers for {}; register the \
361                     audience of that user",
362                    item.id, item.subject.id, self.user
363                ),
364            });
365        }
366        // User-wide, or a partition's memory scope (spec 3.2 §7.8).
367        let scope = FactScope::new(
368            self.app.clone(),
369            self.user.clone(),
370            self.facts.project_of(FactKind::Preference),
371        );
372        let fact = self.facts.confirm(by, scope, FactKind::Preference, &item.rationale).await?;
373        Ok(fact.id)
374    }
375}
376
377impl Harness {
378    /// The kernel's [`ObservationAudience`] for `user` in this harness (spec 3.2 §7.10):
379    /// register it with `KernelBuilder::observation_audience` so the daily baseline pass
380    /// puts its observations to `user` as agenda questions and a confirmed one is
381    /// remembered as known.
382    ///
383    /// # Example
384    ///
385    /// ```rust,ignore
386    /// let audience = harness.observation_audience(&user)?;
387    /// let kernel = harness
388    ///     .kernel()
389    ///     .observation_audience(adk_kernel::PartitionId::default(), Arc::new(audience))
390    ///     .build()?;
391    /// ```
392    ///
393    /// # Errors
394    ///
395    /// Returns a configuration error when long-term memory is off.
396    pub fn observation_audience(&self, user: &UserId) -> adk_core::Result<HarnessObservations> {
397        let facts = self.agent().runtime().toolset().facts().cloned().ok_or_else(|| {
398            adk_core::AdkError::config(
399                "a confirmed observation is remembered in long-term memory, which is off for \
400                 this harness; turn it on with HarnessAgentBuilder::long_term_memory",
401            )
402        })?;
403        Ok(HarnessObservations {
404            facts,
405            app: self.app_name().to_string(),
406            user: user.to_string(),
407            partition: self.partition().map(|partition| partition.id.clone()),
408        })
409    }
410}