Skip to main content

agentmux_srv/server/
dreams_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agent:memory:dreams_list` and `agent:memory:dream_get`: the Dreams record, read by the Memory pane
5//! (docs/specs/SPEC_DREAMS_BACKGROUND_MEMORY_ORGANIZING_2026_11_27.md ยง9).
6//!
7//! `agent:memory:dream_apply`, `dream_reject` and `dream_revert` are what the person decides about a dream there.
8//!
9//! All are **window-only**, like adopting memory: an opened dream holds quotes from the agent's sessions and the text of
10//! memory files, which is the person's to read and not another agent's.
11
12use std::sync::Arc;
13
14use crate::backend::rpc::engine::WshRpcEngine;
15use crate::backend::rpc_types::{
16    CommandDreamApplyData, CommandDreamGetData, CommandDreamNowData, CommandDreamRejectData, CommandDreamRevertData, CommandDreamsListData,
17    DreamDecisionResult, DreamGetResult, DreamNowResult, DreamsListResult, RpcContext, COMMAND_DREAMS_LIST,
18    COMMAND_DREAM_APPLY, COMMAND_DREAM_GET, COMMAND_DREAM_NOW, COMMAND_DREAM_REJECT, COMMAND_DREAM_REVERT,
19};
20use crate::backend::storage::dreams::trigger;
21use crate::server::app_api::dream_run;
22use crate::server::app_api::dream_exec::{dream_apply_impl, dream_reject_impl, dream_revert_impl, Ran};
23
24use super::AppState;
25
26const WHY: &str = "only the person reads the record of Dreams, in the Memory pane";
27const WHY_DECIDE: &str = "only the person decides about a dream, in the Memory pane";
28/// The most dreams a page holds, and what a list with no limit returns.
29const PAGE: u32 = 50;
30
31fn dreams_list(state: &AppState, ctx: &RpcContext, cmd: CommandDreamsListData) -> Result<DreamsListResult, String> {
32    ctx.operator_only(WHY)?;
33    let before = match (cmd.before_ms, cmd.before_id.as_deref()) {
34        (Some(ms), Some(id)) => Some((ms, id)),
35        (None, None) => None,
36        _ => return Err("agent:memory:dreams_list: before_ms and before_id come together".to_string()),
37    };
38    let dreams = state
39        .id_store
40        .dream_list(cmd.memory_kind.as_deref(), cmd.agent_id.as_deref(), before, cmd.limit.unwrap_or(PAGE).min(PAGE) as usize)
41        .map_err(|e| format!("agent:memory:dreams_list: {e}"))?;
42    Ok(DreamsListResult { dreams: dreams.into_iter().map(Into::into).collect() })
43}
44
45fn dream_get(state: &AppState, ctx: &RpcContext, cmd: CommandDreamGetData) -> Result<DreamGetResult, String> {
46    ctx.operator_only(WHY)?;
47    let dream = state
48        .id_store
49        .dream_get(&cmd.id)
50        .map_err(|e| format!("agent:memory:dream_get: {e}"))?
51        .ok_or_else(|| format!("not-found: no dream {}", cmd.id))?;
52    let ops = state.id_store.dream_ops(&cmd.id).map_err(|e| format!("agent:memory:dream_get: {e}"))?;
53    Ok(DreamGetResult { dream: dream.into(), ops: ops.into_iter().map(Into::into).collect() })
54}
55
56/// What the person decided, from the dream's state after it: the files a plan could not run on, or the new state.
57fn decision(state: &AppState, id: &str, ran: Result<Ran, String>) -> Result<DreamDecisionResult, String> {
58    let now = |state: &AppState| -> Result<String, String> {
59        Ok(state.id_store.dream_get(id).map_err(|e| format!("store: {e}"))?.map(|d| d.state).unwrap_or_default())
60    };
61    match ran? {
62        Ran::Done { steps } => Ok(DreamDecisionResult { state: now(state)?, steps: steps as u32, stale: Vec::new() }),
63        Ran::Stale(files) => Ok(DreamDecisionResult { state: now(state)?, steps: 0, stale: files }),
64    }
65}
66
67/// The three decisions run on a blocking thread: they read and write files and the record.
68async fn decide(
69    state: &AppState,
70    ctx: &RpcContext,
71    id: String,
72    run: fn(&AppState, &str, &str, i64) -> Result<Ran, String>,
73) -> Result<DreamDecisionResult, String> {
74    ctx.operator_only(WHY_DECIDE)?;
75    let s = state.clone();
76    tokio::task::spawn_blocking(move || {
77        let ran = run(&s, &id, trigger::PERSON, agentmux_common::time::now_ms());
78        decision(&s, &id, ran)
79    })
80    .await
81    .map_err(|e| format!("agent:memory:dream: {e}"))?
82}
83
84async fn dream_reject(state: &AppState, ctx: &RpcContext, cmd: CommandDreamRejectData) -> Result<DreamDecisionResult, String> {
85    ctx.operator_only(WHY_DECIDE)?;
86    let s = state.clone();
87    tokio::task::spawn_blocking(move || {
88        let ran = dream_reject_impl(&s, &cmd.id, trigger::PERSON, agentmux_common::time::now_ms()).map(|()| Ran::Done { steps: 0 });
89        decision(&s, &cmd.id, ran)
90    })
91    .await
92    .map_err(|e| format!("agent:memory:dream_reject: {e}"))?
93}
94
95/// Queue a dream of one agent's memory (the pass itself runs in the loop).
96fn dream_now(state: &AppState, ctx: &RpcContext, cmd: CommandDreamNowData) -> Result<DreamNowResult, String> {
97    ctx.operator_only(WHY_DECIDE)?;
98    dream_run::dream_now(state, &cmd.agent_id, agentmux_common::time::now_ms()).map(|id| DreamNowResult { id })
99}
100
101pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
102    dream_run::start_loop(state);
103    let s = state.clone();
104    engine.register_typed(COMMAND_DREAMS_LIST, move |cmd: CommandDreamsListData, ctx| {
105        let s = s.clone();
106        async move { dreams_list(&s, &ctx, cmd) }
107    });
108    let s = state.clone();
109    engine.register_typed(COMMAND_DREAM_GET, move |cmd: CommandDreamGetData, ctx| {
110        let s = s.clone();
111        async move { dream_get(&s, &ctx, cmd) }
112    });
113    let s = state.clone();
114    engine.register_typed(COMMAND_DREAM_NOW, move |cmd: CommandDreamNowData, ctx| {
115        let s = s.clone();
116        async move { dream_now(&s, &ctx, cmd) }
117    });
118    let s = state.clone();
119    engine.register_typed(COMMAND_DREAM_APPLY, move |cmd: CommandDreamApplyData, ctx| {
120        let s = s.clone();
121        async move { decide(&s, &ctx, cmd.id, dream_apply_impl).await }
122    });
123    let s = state.clone();
124    engine.register_typed(COMMAND_DREAM_REJECT, move |cmd: CommandDreamRejectData, ctx| {
125        let s = s.clone();
126        async move { dream_reject(&s, &ctx, cmd).await }
127    });
128    let s = state.clone();
129    engine.register_typed(COMMAND_DREAM_REVERT, move |cmd: CommandDreamRevertData, ctx| {
130        let s = s.clone();
131        async move { decide(&s, &ctx, cmd.id, dream_revert_impl).await }
132    });
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::backend::storage::dreams::{memory_kind, op, trigger, Dream, DreamOp};
139    use crate::server::tests::test_state;
140
141    fn put(state: &AppState, id: &str, agent: &str, at: i64) {
142        state.id_store.dream_insert(&Dream::queued(id, memory_kind::PERSONAL, agent, trigger::NIGHTLY, at)).unwrap();
143    }
144
145    fn list(state: &AppState, cmd: CommandDreamsListData) -> Vec<String> {
146        dreams_list(state, &RpcContext::operator_for_tests(), cmd).unwrap().dreams.into_iter().map(|d| d.id).collect()
147    }
148
149    /// An agent holds the instance auth key like everything else in its environment: it cannot read the record.
150    #[tokio::test]
151    async fn an_agent_or_an_unproven_connection_cannot_read_the_record() {
152        let state = test_state();
153        put(&state, "d1", "a", 1);
154        let agent = RpcContext { agent_id: "worker".to_string(), operator_proven: true, ..Default::default() };
155        for ctx in [agent, RpcContext::default()] {
156            let e = dreams_list(&state, &ctx, CommandDreamsListData::default()).unwrap_err();
157            assert!(e.starts_with("FORBIDDEN"), "{e}");
158            let e = dream_get(&state, &ctx, CommandDreamGetData { id: "d1".into() }).unwrap_err();
159            assert!(e.starts_with("FORBIDDEN"), "{e}");
160        }
161    }
162
163    #[tokio::test]
164    async fn the_window_pages_through_the_list_newest_first_and_narrows_it() {
165        let state = test_state();
166        for (id, agent, at) in [("d1", "a", 5), ("d2", "b", 5), ("d3", "a", 5), ("d4", "a", 9)] {
167            put(&state, id, agent, at);
168        }
169        assert_eq!(list(&state, CommandDreamsListData::default()), ["d4", "d3", "d2", "d1"]);
170        let page = |before_id: &str| CommandDreamsListData {
171            limit: Some(2),
172            before_ms: Some(5),
173            before_id: Some(before_id.into()),
174            ..Default::default()
175        };
176        assert_eq!(list(&state, CommandDreamsListData { limit: Some(2), ..Default::default() }), ["d4", "d3"]);
177        assert_eq!(list(&state, page("d3")), ["d2", "d1"], "same-millisecond dreams are not skipped");
178        assert_eq!(list(&state, CommandDreamsListData { agent_id: Some("a".into()), ..Default::default() }), ["d4", "d3", "d1"]);
179    }
180
181    #[tokio::test]
182    async fn a_cursor_needs_both_halves() {
183        let e = dreams_list(&test_state(), &RpcContext::operator_for_tests(), CommandDreamsListData { before_ms: Some(1), ..Default::default() })
184            .unwrap_err();
185        assert!(e.contains("come together"), "{e}");
186    }
187
188    #[tokio::test]
189    async fn an_opened_dream_carries_its_operations_in_order() {
190        let state = test_state();
191        put(&state, "d1", "a", 1);
192        let mk = |id: &str, file: &str| DreamOp {
193            id: id.into(),
194            dream_id: String::new(),
195            seq: 0,
196            op: op::REWRITE.into(),
197            filename: file.into(),
198            merged_from: "[]".into(),
199            base_hash: "h".into(),
200            base_text: "old".into(),
201            new_text: "new".into(),
202            reason: "stale".into(),
203            evidence: "[]".into(),
204            flags: "[]".into(),
205            applied_version_id: String::new(),
206            merged_bases: "[]".into(),
207        };
208        state.id_store.dream_ops_insert("d1", &[mk("o1", "b.md"), mk("o2", "a.md")]).unwrap();
209        let got = dream_get(&state, &RpcContext::operator_for_tests(), CommandDreamGetData { id: "d1".into() }).unwrap();
210        assert_eq!(got.dream.id, "d1");
211        assert_eq!(got.ops.iter().map(|o| (o.id.as_str(), o.seq, o.filename.as_str())).collect::<Vec<_>>(), [("o1", 0, "b.md"), ("o2", 1, "a.md")]);
212        assert_eq!((got.ops[0].base_text.as_str(), got.ops[0].new_text.as_str()), ("old", "new"));
213        let e = dream_get(&state, &RpcContext::operator_for_tests(), CommandDreamGetData { id: "nope".into() }).unwrap_err();
214        assert!(e.starts_with("not-found"), "{e}");
215    }
216
217    /// An agent holds the instance auth key like everything else in its environment: it cannot decide about a dream.
218    #[tokio::test]
219    async fn an_agent_or_an_unproven_connection_cannot_decide() {
220        let state = test_state();
221        put(&state, "d1", "a", 1);
222        let agent = RpcContext { agent_id: "worker".to_string(), operator_proven: true, ..Default::default() };
223        for ctx in [agent, RpcContext::default()] {
224            let e = decide(&state, &ctx, "d1".into(), dream_apply_impl).await.unwrap_err();
225            assert!(e.starts_with("FORBIDDEN"), "{e}");
226            let e = decide(&state, &ctx, "d1".into(), dream_revert_impl).await.unwrap_err();
227            assert!(e.starts_with("FORBIDDEN"), "{e}");
228            let e = dream_reject(&state, &ctx, CommandDreamRejectData { id: "d1".into() }).await.unwrap_err();
229            assert!(e.starts_with("FORBIDDEN"), "{e}");
230        }
231    }
232
233    #[tokio::test]
234    async fn only_the_person_can_ask_for_a_dream_now() {
235        let state = test_state();
236        let agent = RpcContext { agent_id: "worker".to_string(), operator_proven: true, ..Default::default() };
237        for ctx in [agent, RpcContext::default()] {
238            let e = dream_now(&state, &ctx, CommandDreamNowData { agent_id: "a".into() }).unwrap_err();
239            assert!(e.starts_with("FORBIDDEN"), "{e}");
240        }
241        let e = dream_now(&state, &RpcContext::operator_for_tests(), CommandDreamNowData { agent_id: "nobody".into() }).unwrap_err();
242        assert!(e.contains("no agent"), "{e}");
243    }
244
245    #[tokio::test]
246    async fn the_person_rejects_a_ready_dream_and_the_record_says_who() {
247        use crate::backend::storage::dreams::state as dstate;
248        let state = test_state();
249        put(&state, "d1", "a", 1);
250        for (from, to) in [(dstate::QUEUED, dstate::RUNNING), (dstate::RUNNING, dstate::READY)] {
251            assert!(state.id_store.dream_move("d1", from, to, "", "", 2).unwrap());
252        }
253        let got = dream_reject(&state, &RpcContext::operator_for_tests(), CommandDreamRejectData { id: "d1".into() }).await.unwrap();
254        assert_eq!(got, DreamDecisionResult { state: dstate::REJECTED.into(), steps: 0, stale: vec![] });
255        let d = state.id_store.dream_get("d1").unwrap().unwrap();
256        assert_eq!((d.state.as_str(), d.decided_by.as_str()), (dstate::REJECTED, trigger::PERSON));
257    }
258
259    #[tokio::test]
260    async fn a_dream_that_is_not_ready_is_not_applied_and_an_unknown_one_is_not_found() {
261        let state = test_state();
262        put(&state, "d1", "a", 1);
263        let ctx = RpcContext::operator_for_tests();
264        let e = decide(&state, &ctx, "d1".into(), dream_apply_impl).await.unwrap_err();
265        assert!(e.contains("not ready"), "{e}");
266        let e = decide(&state, &ctx, "nope".into(), dream_revert_impl).await.unwrap_err();
267        assert!(e.contains("not found"), "{e}");
268    }
269}