Skip to main content

adk_kernel/control/
memory.rs

1//! What the agents remember, and the person's corrections (spec 3.3 §10 K5, §5.1 "What your
2//! agents remember", §8.1, §8.2).
3//!
4//! The kernel holds no facts: the harness does (spec 3.1 §7.15.2). A [`MemoryBook`] is what
5//! the harness gives the kernel, so the control plane can list the facts with their
6//! provenance and apply a person's correction; `adk-rust up` builds one over each area's
7//! harness.
8//!
9//! | Route (under `/api`) | Caller | Does |
10//! |---|---|---|
11//! | `GET /kernel/memory` | operator, or a device with `read` | The facts of the caller, live ones only, and the overnight tidy-ups ([`MemoryResponse`]) |
12//! | `POST /kernel/memory/facts/{id}/confirm` | the person, no device | "That's right": a guess becomes "You said this" |
13//! | `POST /kernel/memory/facts/{id}/fix` | the person, no device | "Fix it": the fact is replaced by the person's words ([`FixRequest`]) |
14//! | `POST /kernel/memory/facts/{id}/forget` | the person, no device | "Forget it": never recalled again |
15//! | `POST /kernel/memory/undo` | the person, no device | "Undo": reverts the latest overnight tidy-up, or the one named ([`UndoRequest`]) |
16//!
17//! Each change is recorded as `kernel.control` (`memory.confirm`, `memory.fix`,
18//! `memory.forget`, `memory.undo`, the fact or tidy-up as its target) before it is applied;
19//! the record carries ids, never a fact's text.
20
21use 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/// Where a remembered fact came from, in the home's words (spec 3.3 §8.1): a known fact
39/// reads "You said this", whether the person said it or confirmed or corrected a guess, and
40/// an assumed one "A guess".
41///
42/// # Example
43///
44/// ```rust
45/// use adk_kernel::control::FactOrigin;
46///
47/// assert_eq!(serde_json::to_value(FactOrigin::YouSaidThis).unwrap(), "youSaidThis");
48/// assert_eq!(FactOrigin::YouConfirmedThis.label(), "You said this");
49/// assert_eq!(FactOrigin::Guess.label(), "A guess");
50/// ```
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53#[non_exhaustive]
54pub enum FactOrigin {
55    /// The person's own words: a verified quote (`Known`, `UserStated`).
56    YouSaidThis,
57    /// A person confirmed or corrected it (`Known`, `UserConfirmed`); it reads "You said
58    /// this" (spec 3.3 §8.1).
59    YouConfirmedThis,
60    /// The agents inferred or read it; it can be confirmed, fixed or forgotten (`Assumed`).
61    Guess,
62}
63
64impl FactOrigin {
65    /// The words the home shows (spec 3.3 §8.1): "You said this" for a known fact, "A
66    /// guess" for an assumed one.
67    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/// One fact the agents remember (spec 3.3 §5.1 "What your agents remember").
76///
77/// # Example
78///
79/// ```rust
80/// use adk_kernel::control::{FactOrigin, RememberedFact};
81///
82/// let fact = RememberedFact::new("01JB", "You send invoices on the last working day.", FactOrigin::Guess, chrono::Utc::now())
83///     .with_noticed_by("finance");
84/// assert_eq!(serde_json::to_value(&fact).unwrap()["noticedBy"], "finance");
85/// ```
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88#[non_exhaustive]
89pub struct RememberedFact {
90    /// The fact's id.
91    pub id: String,
92    /// The fact, redacted as the harness stores it. Escape it before display (S-I9).
93    pub text: String,
94    /// Where it came from.
95    pub origin: FactOrigin,
96    /// What it is about: `preference`, `project_fact`, `procedure`, `outcome`, `decision`,
97    /// `correction`.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub kind: Option<String>,
100    /// The area whose agents remember it; `None` for every area.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub area: Option<PartitionId>,
103    /// The agent that noticed a guess.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub noticed_by: Option<String>,
106    /// When it was learned.
107    pub learned_at: DateTime<Utc>,
108    /// The overnight tidy-up that wrote it, when one did.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub tidy_up: Option<String>,
111}
112
113impl RememberedFact {
114    /// A fact `id` with `text` from `origin`, learned at `learned_at`.
115    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    /// Sets what it is about.
134    #[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    /// Sets the area.
141    #[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    /// Sets the agent that noticed it.
148    #[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    /// Sets the tidy-up that wrote it.
155    #[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/// One overnight tidy-up of the memory: a consolidation tick (spec 3.2 §7.5, spec 3.3 §8.2
163/// "Undo").
164///
165/// # Example
166///
167/// ```rust
168/// use adk_kernel::control::TidyUp;
169///
170/// let tick = TidyUp::new("01JT", "default", chrono::Utc::now()).with_counts(1, 2, 0, 0);
171/// assert_eq!((tick.merged, tick.superseded), (1, 2));
172/// assert!(!tick.undoable(), "an unfinished tidy-up cannot be undone");
173/// ```
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "camelCase")]
176#[non_exhaustive]
177pub struct TidyUp {
178    /// The tick's id.
179    pub id: String,
180    /// The area it tidied.
181    pub area: PartitionId,
182    /// When it ran.
183    pub at: DateTime<Utc>,
184    /// When it finished; a tidy-up still running or cut off has none.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub finished_at: Option<DateTime<Utc>>,
187    /// When it was undone.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub undone_at: Option<DateTime<Utc>>,
190    /// Facts it wrote by merging others.
191    pub merged: usize,
192    /// Facts it replaced by a merged one.
193    pub superseded: usize,
194    /// Facts it forgot.
195    pub forgotten: usize,
196    /// Facts it learned from sessions nobody had read.
197    pub distilled: usize,
198}
199
200impl TidyUp {
201    /// A tidy-up `id` of `area` at `at`, unfinished, that changed nothing.
202    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    /// Sets what it changed.
217    #[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    /// Sets when it finished.
231    #[must_use]
232    pub fn finished(mut self, at: DateTime<Utc>) -> Self {
233        self.finished_at = Some(at);
234        self
235    }
236
237    /// Sets when it was undone.
238    #[must_use]
239    pub fn undone(mut self, at: DateTime<Utc>) -> Self {
240        self.undone_at = Some(at);
241        self
242    }
243
244    /// Whether "Undo" applies: it finished, changed something, and was not undone.
245    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/// What undoing a tidy-up did (spec 3.3 §8.2 "Undo").
253#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub struct TidyUpUndo {
257    /// The tidy-up.
258    pub id: String,
259    /// Facts it had replaced or forgotten, back as guesses.
260    pub restored: Vec<String>,
261    /// Facts it had written, now forgotten.
262    pub forgotten: Vec<String>,
263    /// Facts left as they are: a person or a later write changed them since.
264    pub kept: Vec<String>,
265}
266
267impl TidyUpUndo {
268    /// The undo of tidy-up `id`, with the facts it restored, forgot and kept.
269    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/// What the harness gives the kernel so the control plane can show and correct the agents'
280/// memory (spec 3.3 §10 K5). `user` is the caller; a book answers only that person's facts,
281/// as `fact_not_found` for anyone else's.
282///
283/// # Example
284///
285/// ```rust
286/// use adk_core::principal::SubjectRef;
287/// use adk_kernel::control::{FactOrigin, MemoryBook, RememberedFact, TidyUp, TidyUpUndo};
288///
289/// struct Nothing;
290///
291/// #[async_trait::async_trait]
292/// impl MemoryBook for Nothing {
293///     async fn facts(&self, _: &str, _: Option<&adk_kernel::PartitionId>) -> adk_kernel::Result<Vec<RememberedFact>> { Ok(vec![]) }
294///     async fn confirm(&self, _: &str, id: &str, _: &SubjectRef) -> adk_kernel::Result<RememberedFact> { Err(adk_kernel::KernelError::NotFound { pid: id.into() }) }
295///     async fn fix(&self, _: &str, id: &str, _: &str, _: &SubjectRef) -> adk_kernel::Result<RememberedFact> { Err(adk_kernel::KernelError::NotFound { pid: id.into() }) }
296///     async fn forget(&self, _: &str, id: &str, _: &SubjectRef) -> adk_kernel::Result<()> { Err(adk_kernel::KernelError::NotFound { pid: id.into() }) }
297///     async fn tidy_ups(&self, _: &str) -> adk_kernel::Result<Vec<TidyUp>> { Ok(vec![]) }
298///     async fn undo_tidy_up(&self, _: &str, id: &str, _: &SubjectRef) -> adk_kernel::Result<TidyUpUndo> { Err(adk_kernel::KernelError::NotFound { pid: id.into() }) }
299/// }
300/// ```
301#[async_trait]
302pub trait MemoryBook: Send + Sync {
303    /// The live facts of `user`, of `area` when one is named, newest first.
304    ///
305    /// # Errors
306    ///
307    /// The book's error.
308    async fn facts(&self, user: &str, area: Option<&PartitionId>) -> Result<Vec<RememberedFact>>;
309
310    /// "That's right": `user`'s fact `id` becomes "You said this".
311    ///
312    /// # Errors
313    ///
314    /// A `NotFound` error for a fact that is not `user`'s or not live, or the book's error.
315    async fn confirm(&self, user: &str, id: &str, by: &SubjectRef) -> Result<RememberedFact>;
316
317    /// "Fix it": `user`'s fact `id` is replaced by `text`, which reads "You said this"; the
318    /// old one is kept in the history.
319    ///
320    /// # Errors
321    ///
322    /// As [`confirm`](Self::confirm), and an `InvalidInput` error for a text the harness
323    /// refuses (empty, too long, a secret).
324    async fn fix(
325        &self,
326        user: &str,
327        id: &str,
328        text: &str,
329        by: &SubjectRef,
330    ) -> Result<RememberedFact>;
331
332    /// "Forget it": `user`'s fact `id` is never recalled again.
333    ///
334    /// # Errors
335    ///
336    /// As [`confirm`](Self::confirm).
337    async fn forget(&self, user: &str, id: &str, by: &SubjectRef) -> Result<()>;
338
339    /// The tidy-ups of `user`'s memory, newest first.
340    ///
341    /// # Errors
342    ///
343    /// The book's error.
344    async fn tidy_ups(&self, user: &str) -> Result<Vec<TidyUp>>;
345
346    /// "Undo": reverts tidy-up `id` of `user`'s memory.
347    ///
348    /// # Errors
349    ///
350    /// A `NotFound` error for an unknown tidy-up, a `Conflict` for one unfinished or
351    /// already undone, or the book's error.
352    async fn undo_tidy_up(&self, user: &str, id: &str, by: &SubjectRef) -> Result<TidyUpUndo>;
353}
354
355/// `GET /kernel/memory` query (spec 3.3 §10 K5).
356#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct MemoryQuery {
359    /// Only facts of this area.
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub area: Option<PartitionId>,
362}
363
364/// `GET /kernel/memory` answer (spec 3.3 §10 K5).
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase")]
367pub struct MemoryResponse {
368    /// The live facts, newest first.
369    pub facts: Vec<RememberedFact>,
370    /// The tidy-ups, newest first.
371    pub tidy_ups: Vec<TidyUp>,
372}
373
374/// The answer of "That's right" and "Fix it": the fact after it.
375#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(rename_all = "camelCase")]
377pub struct FactResponse {
378    /// The fact.
379    pub fact: RememberedFact,
380}
381
382/// `POST /kernel/memory/facts/{id}/fix` body (spec 3.3 §8.2 "Fix it").
383#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
384#[serde(rename_all = "camelCase")]
385pub struct FixRequest {
386    /// The person's words.
387    pub text: String,
388}
389
390/// The answer of "Forget it".
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392#[serde(rename_all = "camelCase")]
393pub struct ForgetResponse {
394    /// The forgotten fact's id.
395    pub forgotten: String,
396}
397
398/// `POST /kernel/memory/undo` body (spec 3.3 §8.2 "Undo").
399#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401pub struct UndoRequest {
402    /// The tidy-up to undo; the latest undoable one when absent.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub tidy_up: Option<String>,
405}
406
407type Backend = State<Arc<dyn ControlBackend>>;
408
409/// The routes, relative to `/api`, over the backend in their state.
410pub(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
419/// The memory book of `backend`, or a `Config` error naming why there is none.
420fn 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}