Skip to main content

agentmux_srv/server/remote_ops/
memory.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `memory.global.put`, `memory.global.remove` and `memory.global.list`: one Global Memory for
5//! the fleet (task #12439, section 4.6). The rules for which write wins and what is never touched
6//! are in `backend::memory::fleet`; these are the thin handlers the transport calls.
7//!
8//! A write is attributed to the remote agent as `slug@machine`, never to the operator, and with
9//! no uid: the caller's uid is signed but not tied to its key, so it describes and never proves.
10
11use serde::de::DeserializeOwned;
12use serde_json::{json, Value};
13
14use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
15use crate::backend::memory::fleet::{self, Actor, FleetEntry, FleetError, FleetRemoval, Outcome};
16use crate::backend::storage::store::Store;
17
18/// The most params bytes `memory.global.put` takes: the 1 MiB an entry's text may be, plus its
19/// JSON escaping and the other fields.
20pub(super) const MAX_PUT_PARAMS: usize = 1_200_000;
21
22fn parse<T: DeserializeOwned>(op: &str, params: Value) -> Result<T, RemoteRefusal> {
23    serde_json::from_value(params).map_err(|e| RemoteRefusal::new("bad_params", format!("{op}: {e}")))
24}
25
26/// Run a store write off the async threads and tell the Memory pane when it changed something.
27async fn write(
28    state: &AppState,
29    caller: &RemoteCaller,
30    run: impl FnOnce(&Store, Actor<'_>) -> Result<Outcome, FleetError> + Send + 'static,
31) -> RemoteResult {
32    let store = state.id_store.clone();
33    let label = caller.actor();
34    let outcome = tokio::task::spawn_blocking(move || run(&store, Actor { label: &label, uid: "" }))
35        .await
36        .map_err(|e| RemoteRefusal::failed(format!("the write did not finish: {e}")))?
37        .map_err(|e| match e {
38            FleetError::Invalid(message) => RemoteRefusal::new("bad_params", message),
39            FleetError::Store(e) => RemoteRefusal::failed(e.to_string()),
40        })?;
41    if matches!(outcome, Outcome::Applied(_)) {
42        state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
43        tracing::info!(actor = %caller.actor(), outcome = %outcome.to_json(), "fleet memory: applied a write from another machine");
44    }
45    Ok(outcome.to_json())
46}
47
48pub(super) async fn put(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
49    let entry: FleetEntry = parse("memory.global.put", params)?;
50    let (id, name) = (entry.id.clone(), entry.name.clone());
51    let answer = write(state, caller, move |store, actor| fleet::apply_put(store, &entry, actor)).await?;
52    // An entry that was `machine` here only by default now follows the fleet: say which one, so a
53    // steward can see it and revert it from the entry's history.
54    if answer.get("outcome").and_then(Value::as_str) == Some("adopted") {
55        let from = caller.actor();
56        tracing::warn!(entry = %id, name = %name, from = %from, "fleet memory: replaced an entry that was machine-only by default; its old text is in its history");
57        super::fleet_sync::status::global().adopted(&id, &name, &from, agentmux_common::time::now_ms());
58    }
59    Ok(answer)
60}
61
62pub(super) async fn remove(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
63    let removal: FleetRemoval = parse("memory.global.remove", params)?;
64    write(state, caller, move |store, actor| fleet::apply_remove(store, &removal, actor)).await
65}
66
67/// What this machine holds for the fleet, without any text: the ids, when each was written, a hash
68/// of its content and whether it was removed, so the caller can tell what to send.
69pub(super) async fn list(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
70    let store = state.id_store.clone();
71    let entries = tokio::task::spawn_blocking(move || fleet::list_meta(&store))
72        .await
73        .map_err(|e| RemoteRefusal::failed(format!("the listing did not finish: {e}")))?
74        .map_err(|e| RemoteRefusal::failed(e.to_string()))?;
75    Ok(json!({ "entries": entries }))
76}
77
78#[cfg(test)]
79mod tests;