1use 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
25pub type SessionStateFilter = Arc<dyn Fn(&dyn adk_session::State) -> bool + Send + Sync>;
27
28#[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 #[must_use]
79 pub fn with_session_filter(mut self, filter: SessionStateFilter) -> Self {
80 self.filter = Some(filter);
81 self
82 }
83
84 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
134fn 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 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#[derive(Clone)]
312pub struct HarnessObservations {
313 facts: Arc<FactsRuntime>,
314 app: String,
315 user: String,
316 partition: Option<PartitionId>,
318}
319
320impl HarnessObservations {
321 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 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 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}