1use std::sync::Arc;
22
23use adk_core::principal::SubjectRef;
24use async_trait::async_trait;
25use axum::Json;
26use axum::Router;
27use axum::extract::{Path as UrlPath, Query, State};
28use axum::routing::{get, post};
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31
32use super::paths;
33use super::routes::{Caller, ControlBackend, record};
34use super::settings::require_owner;
35use crate::error::{KernelError, Result};
36use crate::partition::PartitionId;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53#[non_exhaustive]
54pub enum FactOrigin {
55 YouSaidThis,
57 YouConfirmedThis,
60 Guess,
62}
63
64impl FactOrigin {
65 pub fn label(self) -> &'static str {
68 match self {
69 Self::YouSaidThis | Self::YouConfirmedThis => "You said this",
70 Self::Guess => "A guess",
71 }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88#[non_exhaustive]
89pub struct RememberedFact {
90 pub id: String,
92 pub text: String,
94 pub origin: FactOrigin,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub kind: Option<String>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub area: Option<PartitionId>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub noticed_by: Option<String>,
106 pub learned_at: DateTime<Utc>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub tidy_up: Option<String>,
111}
112
113impl RememberedFact {
114 pub fn new(
116 id: impl Into<String>,
117 text: impl Into<String>,
118 origin: FactOrigin,
119 learned_at: DateTime<Utc>,
120 ) -> Self {
121 Self {
122 id: id.into(),
123 text: text.into(),
124 origin,
125 kind: None,
126 area: None,
127 noticed_by: None,
128 learned_at,
129 tidy_up: None,
130 }
131 }
132
133 #[must_use]
135 pub fn with_kind(mut self, kind: impl Into<String>) -> Self {
136 self.kind = Some(kind.into());
137 self
138 }
139
140 #[must_use]
142 pub fn with_area(mut self, area: impl Into<PartitionId>) -> Self {
143 self.area = Some(area.into());
144 self
145 }
146
147 #[must_use]
149 pub fn with_noticed_by(mut self, agent: impl Into<String>) -> Self {
150 self.noticed_by = Some(agent.into());
151 self
152 }
153
154 #[must_use]
156 pub fn with_tidy_up(mut self, tick: impl Into<String>) -> Self {
157 self.tidy_up = Some(tick.into());
158 self
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "camelCase")]
176#[non_exhaustive]
177pub struct TidyUp {
178 pub id: String,
180 pub area: PartitionId,
182 pub at: DateTime<Utc>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub finished_at: Option<DateTime<Utc>>,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub undone_at: Option<DateTime<Utc>>,
190 pub merged: usize,
192 pub superseded: usize,
194 pub forgotten: usize,
196 pub distilled: usize,
198}
199
200impl TidyUp {
201 pub fn new(id: impl Into<String>, area: impl Into<PartitionId>, at: DateTime<Utc>) -> Self {
203 Self {
204 id: id.into(),
205 area: area.into(),
206 at,
207 finished_at: None,
208 undone_at: None,
209 merged: 0,
210 superseded: 0,
211 forgotten: 0,
212 distilled: 0,
213 }
214 }
215
216 #[must_use]
218 pub fn with_counts(
219 mut self,
220 merged: usize,
221 superseded: usize,
222 forgotten: usize,
223 distilled: usize,
224 ) -> Self {
225 (self.merged, self.superseded, self.forgotten, self.distilled) =
226 (merged, superseded, forgotten, distilled);
227 self
228 }
229
230 #[must_use]
232 pub fn finished(mut self, at: DateTime<Utc>) -> Self {
233 self.finished_at = Some(at);
234 self
235 }
236
237 #[must_use]
239 pub fn undone(mut self, at: DateTime<Utc>) -> Self {
240 self.undone_at = Some(at);
241 self
242 }
243
244 pub fn undoable(&self) -> bool {
246 self.finished_at.is_some()
247 && self.undone_at.is_none()
248 && self.merged + self.superseded + self.forgotten + self.distilled > 0
249 }
250}
251
252#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub struct TidyUpUndo {
257 pub id: String,
259 pub restored: Vec<String>,
261 pub forgotten: Vec<String>,
263 pub kept: Vec<String>,
265}
266
267impl TidyUpUndo {
268 pub fn new(
270 id: impl Into<String>,
271 restored: Vec<String>,
272 forgotten: Vec<String>,
273 kept: Vec<String>,
274 ) -> Self {
275 Self { id: id.into(), restored, forgotten, kept }
276 }
277}
278
279#[async_trait]
302pub trait MemoryBook: Send + Sync {
303 async fn facts(&self, user: &str, area: Option<&PartitionId>) -> Result<Vec<RememberedFact>>;
309
310 async fn confirm(&self, user: &str, id: &str, by: &SubjectRef) -> Result<RememberedFact>;
316
317 async fn fix(
325 &self,
326 user: &str,
327 id: &str,
328 text: &str,
329 by: &SubjectRef,
330 ) -> Result<RememberedFact>;
331
332 async fn forget(&self, user: &str, id: &str, by: &SubjectRef) -> Result<()>;
338
339 async fn tidy_ups(&self, user: &str) -> Result<Vec<TidyUp>>;
345
346 async fn undo_tidy_up(&self, user: &str, id: &str, by: &SubjectRef) -> Result<TidyUpUndo>;
353}
354
355#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct MemoryQuery {
359 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub area: Option<PartitionId>,
362}
363
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase")]
367pub struct MemoryResponse {
368 pub facts: Vec<RememberedFact>,
370 pub tidy_ups: Vec<TidyUp>,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(rename_all = "camelCase")]
377pub struct FactResponse {
378 pub fact: RememberedFact,
380}
381
382#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
384#[serde(rename_all = "camelCase")]
385pub struct FixRequest {
386 pub text: String,
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392#[serde(rename_all = "camelCase")]
393pub struct ForgetResponse {
394 pub forgotten: String,
396}
397
398#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401pub struct UndoRequest {
402 #[serde(default, skip_serializing_if = "Option::is_none")]
404 pub tidy_up: Option<String>,
405}
406
407type Backend = State<Arc<dyn ControlBackend>>;
408
409pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
411 Router::new()
412 .route(paths::MEMORY, get(list))
413 .route(paths::FACT_CONFIRM, post(confirm))
414 .route(paths::FACT_FIX, post(fix))
415 .route(paths::FACT_FORGET, post(forget))
416 .route(paths::MEMORY_UNDO, post(undo))
417}
418
419fn book_of(backend: &dyn ControlBackend) -> Result<Arc<dyn MemoryBook>> {
421 backend.kernel().and_then(|kernel| kernel.config().control.memory.clone()).ok_or_else(|| {
422 KernelError::Config {
423 reason: "this kernel shows no memory: set ControlPlaneConfig::with_memory, as \
424 `adk-rust up` does with long-term memory on"
425 .into(),
426 }
427 })
428}
429
430async fn list(
431 State(backend): Backend,
432 caller: Caller,
433 Query(query): Query<MemoryQuery>,
434) -> Result<Json<MemoryResponse>> {
435 caller.require_operator("read what the agents remember")?;
436 let book = book_of(backend.as_ref())?;
437 let user = &caller.context.user_id;
438 let facts = book.facts(user, query.area.as_ref()).await?;
439 let tidy_ups = book.tidy_ups(user).await?;
440 Ok(Json(MemoryResponse { facts, tidy_ups }))
441}
442
443async fn confirm(
444 State(backend): Backend,
445 caller: Caller,
446 UrlPath(id): UrlPath<String>,
447) -> Result<Json<FactResponse>> {
448 require_owner(&caller, "confirm what the agents remember")?;
449 let book = book_of(backend.as_ref())?;
450 record(backend.as_ref(), &caller, "memory.confirm", Some(&id), &[]).await?;
451 let fact = book.confirm(&caller.context.user_id, &id, &caller.subject()).await?;
452 Ok(Json(FactResponse { fact }))
453}
454
455async fn fix(
456 State(backend): Backend,
457 caller: Caller,
458 UrlPath(id): UrlPath<String>,
459 Json(request): Json<FixRequest>,
460) -> Result<Json<FactResponse>> {
461 require_owner(&caller, "fix what the agents remember")?;
462 let book = book_of(backend.as_ref())?;
463 record(backend.as_ref(), &caller, "memory.fix", Some(&id), &[]).await?;
464 let fact = book.fix(&caller.context.user_id, &id, &request.text, &caller.subject()).await?;
465 Ok(Json(FactResponse { fact }))
466}
467
468async fn forget(
469 State(backend): Backend,
470 caller: Caller,
471 UrlPath(id): UrlPath<String>,
472) -> Result<Json<ForgetResponse>> {
473 require_owner(&caller, "make the agents forget")?;
474 let book = book_of(backend.as_ref())?;
475 record(backend.as_ref(), &caller, "memory.forget", Some(&id), &[]).await?;
476 book.forget(&caller.context.user_id, &id, &caller.subject()).await?;
477 Ok(Json(ForgetResponse { forgotten: id }))
478}
479
480async fn undo(
481 State(backend): Backend,
482 caller: Caller,
483 Json(request): Json<UndoRequest>,
484) -> Result<Json<TidyUpUndo>> {
485 require_owner(&caller, "undo a tidy-up of the memory")?;
486 let book = book_of(backend.as_ref())?;
487 let user = &caller.context.user_id;
488 let id = match request.tidy_up {
489 Some(id) => id,
490 None => book
491 .tidy_ups(user)
492 .await?
493 .into_iter()
494 .find(TidyUp::undoable)
495 .map(|tidy_up| tidy_up.id)
496 .ok_or_else(|| {
497 KernelError::Core(adk_core::AdkError::new(
498 adk_core::ErrorComponent::Server,
499 adk_core::ErrorCategory::NotFound,
500 crate::error::NOT_FOUND_CODE,
501 "no overnight tidy-up of the memory is left to undo",
502 ))
503 })?,
504 };
505 record(backend.as_ref(), &caller, "memory.undo", Some(&id), &[]).await?;
506 Ok(Json(book.undo_tidy_up(user, &id, &caller.subject()).await?))
507}