Skip to main content

agentmux_srv/server/
native_memory_adopt_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agent:memory:adopt` and `agent:memory:release`: what the person confirmed
5//! in the Memory pane, which of an agent's earlier accounts' memory folders to
6//! adopt, or which claimed folder to release
7//! (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2 and §2.1.4).
8//!
9//! Both are **operator-only**: srv takes them only from the AgentMux window,
10//! proven through the host. The shared auth key is in every agent's
11//! environment, so a command an agent can call can't stand for a person's
12//! confirmation. The window asks in a modal over the Memory pane, which an
13//! agent can open but neither read nor answer
14//! (SPEC_AGENT_SPAWN_NOTICE_IN_THE_PANE_2026_11_08.md §6 row 8). The choices
15//! are only `(list_id, index, dir_hash)` from a list the server issued
16//! (`agent:memory:adoption_list`, `agent:memory:claims`), never a path.
17
18use std::sync::Arc;
19
20use crate::backend::memory::adopt::{self, AdoptError, AdoptReport};
21use crate::backend::memory::release::{self, ReleaseError};
22use crate::backend::rpc::engine::WshRpcEngine;
23use crate::backend::rpc_types::{
24    CommandNativeMemoryAdoptData, CommandNativeMemoryReleaseData, NativeMemoryReleaseResult, RpcContext,
25    COMMAND_NATIVE_MEMORY_ADOPT, COMMAND_NATIVE_MEMORY_RELEASE,
26};
27use crate::backend::transcript::damage;
28
29use super::AppState;
30
31const WHY: &str = "only the person adopts memory or releases a memory folder, in the Memory pane";
32
33/// The errors start with a stable word the pane reads: "changed" means list again.
34async fn native_memory_adopt(state: &AppState, cmd: CommandNativeMemoryAdoptData) -> Result<AdoptReport, String> {
35    if cmd.choices.is_empty() {
36        return Err("bad-choice: nothing chosen".to_string());
37    }
38    let fs = damage::global_for(&damage::memory_zone(&cmd.agent_id))
39        .ok_or_else(|| "store: the memory record store is unavailable, or its record is damaged".to_string())?;
40    let mstore = state.mstore.clone();
41    let choices: Vec<(usize, String)> = cmd.choices.into_iter().map(|c| (c.index, c.dir_hash)).collect();
42    let result =
43        tokio::task::spawn_blocking(move || adopt::adopt(&fs, &mstore, &cmd.agent_id, &cmd.list_id, &choices)).await;
44    match result {
45        Ok(Ok(report)) => Ok(report),
46        Ok(Err(AdoptError::Changed { index })) => {
47            Err(format!("changed: folder {index} changed since the list was issued; list again"))
48        }
49        Ok(Err(AdoptError::UnknownList)) => {
50            Err("unknown-list: the list expired or is not this agent's; list again".to_string())
51        }
52        Ok(Err(AdoptError::BadChoice)) => Err("bad-choice".to_string()),
53        Ok(Err(AdoptError::Busy)) => Err("busy: the agent's memory is being synced; try again".to_string()),
54        Ok(Err(AdoptError::Store(e))) => {
55            tracing::warn!("[memory-adopt] adopt failed: {e}");
56            Err("store error".to_string())
57        }
58        Err(e) => Err(format!("agent:memory:adopt: {e}")),
59    }
60}
61
62async fn native_memory_release(cmd: CommandNativeMemoryReleaseData) -> Result<NativeMemoryReleaseResult, String> {
63    let fs = damage::global_for(&damage::memory_zone(&cmd.agent_id))
64        .ok_or_else(|| "store: the memory record store is unavailable, or its record is damaged".to_string())?;
65    let result =
66        tokio::task::spawn_blocking(move || release::release(&fs, &cmd.agent_id, &cmd.list_id, cmd.index)).await;
67    match result {
68        Ok(Ok(released)) => Ok(NativeMemoryReleaseResult { released }),
69        Ok(Err(ReleaseError::UnknownList)) => {
70            Err("unknown-list: the list expired or is not this agent's; list again".to_string())
71        }
72        Ok(Err(ReleaseError::BadChoice)) => Err("bad-choice".to_string()),
73        Ok(Err(ReleaseError::Store(e))) => {
74            tracing::warn!("[memory-adopt] release failed: {e}");
75            Err("store error".to_string())
76        }
77        Err(e) => Err(format!("agent:memory:release: {e}")),
78    }
79}
80
81/// `agent:memory:adopt`, from the window only.
82async fn adopt_from(state: &AppState, ctx: &RpcContext, cmd: CommandNativeMemoryAdoptData) -> Result<AdoptReport, String> {
83    ctx.operator_only(WHY)?;
84    native_memory_adopt(state, cmd).await
85}
86
87/// `agent:memory:release`, from the window only.
88async fn release_from(ctx: &RpcContext, cmd: CommandNativeMemoryReleaseData) -> Result<NativeMemoryReleaseResult, String> {
89    ctx.operator_only(WHY)?;
90    native_memory_release(cmd).await
91}
92
93pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
94    let s = state.clone();
95    engine.register_typed(COMMAND_NATIVE_MEMORY_ADOPT, move |cmd: CommandNativeMemoryAdoptData, ctx| {
96        let s = s.clone();
97        async move { adopt_from(&s, &ctx, cmd).await }
98    });
99    engine.register_typed(COMMAND_NATIVE_MEMORY_RELEASE, |cmd: CommandNativeMemoryReleaseData, ctx| async move {
100        release_from(&ctx, cmd).await
101    });
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::backend::rpc_types::NativeMemoryAdoptChoice;
108    use crate::server::tests::test_state;
109
110    fn adopt_cmd(choices: usize) -> CommandNativeMemoryAdoptData {
111        let choices = (0..choices).map(|index| NativeMemoryAdoptChoice { index, dir_hash: "h".into() }).collect();
112        CommandNativeMemoryAdoptData { agent_id: "a".into(), list_id: "l".into(), choices }
113    }
114
115    fn release_cmd() -> CommandNativeMemoryReleaseData {
116        CommandNativeMemoryReleaseData { agent_id: "a".into(), list_id: "l".into(), index: 0 }
117    }
118
119    /// The attack this closes: an agent holds the instance auth key (every agent's
120    /// environment does) and calls adopt itself, skipping the person's
121    /// confirmation in the Memory pane.
122    #[tokio::test]
123    async fn an_agent_or_an_unproven_connection_cannot_adopt_or_release() {
124        let state = test_state();
125        let agent = RpcContext { agent_id: "worker".to_string(), operator_proven: true, ..Default::default() };
126        for ctx in [agent, RpcContext::default()] {
127            let refused = adopt_from(&state, &ctx, adopt_cmd(1)).await.unwrap_err();
128            assert!(refused.starts_with("FORBIDDEN"), "{refused}");
129            let refused = release_from(&ctx, release_cmd()).await.unwrap_err();
130            assert!(refused.starts_with("FORBIDDEN"), "{refused}");
131        }
132    }
133
134    #[tokio::test]
135    async fn the_window_reaches_adopt_and_release() {
136        let ctx = RpcContext::operator_for_tests();
137        let e = adopt_from(&test_state(), &ctx, adopt_cmd(1)).await.unwrap_err();
138        assert!(!e.starts_with("FORBIDDEN"), "{e}");
139        let e = release_from(&ctx, release_cmd()).await.unwrap_err();
140        assert!(!e.starts_with("FORBIDDEN"), "{e}");
141    }
142
143    #[tokio::test]
144    async fn adopting_nothing_is_refused() {
145        let e = adopt_from(&test_state(), &RpcContext::operator_for_tests(), adopt_cmd(0)).await.unwrap_err();
146        assert_eq!(e, "bad-choice: nothing chosen");
147    }
148}