Skip to main content

agentmux_srv/server/app_api/
global_memory.rs

1// Copyright 2024-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Global Memory MuxAPI bodies, moved out of app_api/mod.rs unchanged
5//! (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md item 9).
6
7use super::*;
8use crate::server::api_error::ApiError;
9use crate::backend::storage::bundle_scope::{SCOPE_FLEET, SCOPE_MACHINE};
10
11/// Caller-supplied provenance for a `globalmemory.write` call — same shape
12/// as `MemoryWriteProvenance` above; kept as a distinct type since callers
13/// are conceptually different (an agent writing to a workspace-wide list
14/// every other agent inherits, not its own private memory) even though the
15/// wire shape is identical.
16pub(crate) struct GlobalMemoryWriteProvenance<'a> {
17    pub source: &'a str,
18    pub detail: &'a str,
19}
20
21/// What a write through the agent route records as its source and detail. srv names the source: the labels it uses
22/// itself for who wrote (`human`, `armory-ui`, `revert`, `jekt`, `agent`) are never taken from the caller, so a caller
23/// cannot have its write read as the person's or as a revert. The caller's own label stays what it is for a note
24/// (`agent_inferred` when it gives none), and one of those reserved words moves into the detail as `claimed_source`.
25fn recorded_provenance<'a>(provenance: Option<&'a GlobalMemoryWriteProvenance<'a>>) -> (&'a str, String) {
26    const RESERVED: [&str; 5] = ["human", "armory-ui", "revert", "jekt", "agent"];
27    let Some(p) = provenance else { return ("agent_inferred", "{}".to_string()) };
28    let detail = if p.detail.is_empty() { "{}" } else { p.detail };
29    let label = p.source.trim();
30    if !RESERVED.iter().any(|r| r.eq_ignore_ascii_case(label)) {
31        // Any other label is a note of the caller's, not a claim about who wrote: kept as given.
32        return (label, detail.to_string());
33    }
34    let mut merged = match serde_json::from_str::<serde_json::Value>(detail) {
35        Ok(serde_json::Value::Object(map)) => map,
36        Ok(other) => serde_json::Map::from_iter([("detail".to_string(), other)]),
37        Err(_) => serde_json::Map::new(),
38    };
39    merged.entry("claimed_source").or_insert_with(|| serde_json::Value::String(label.to_string()));
40    ("agent_inferred", serde_json::Value::Object(merged).to_string())
41}
42
43/// Creates a new ordinary Global Memory entry, or updates an existing one
44/// by `id`. Backs the `GlobalMemoryWrite` MCP tool.
45pub(crate) fn global_memory_write_impl(
46    state: &AppState,
47    agent_id: &str,
48    written_by_uid: &str,
49    id: Option<&str>,
50    name: &str,
51    content: &str,
52    provenance: Option<GlobalMemoryWriteProvenance<'_>>,
53) -> Result<serde_json::Value, ApiError> {
54    global_memory_write_inner(state, agent_id, written_by_uid, id, name, content, provenance, None)
55}
56
57/// What a write does with the entry's id once it is known and before the entry is saved.
58type BeforeWrite<'a> = Option<&'a dyn Fn(&str) -> Result<(), String>>;
59
60/// [`global_memory_write_impl`], running `before_write` with the entry's id (the existing one, or
61/// the new one) just before the entry is saved. If it fails, nothing is saved.
62#[allow(clippy::too_many_arguments)]
63pub(crate) fn global_memory_write_inner(
64    state: &AppState,
65    agent_id: &str,
66    written_by_uid: &str,
67    id: Option<&str>,
68    name: &str,
69    content: &str,
70    provenance: Option<GlobalMemoryWriteProvenance<'_>>,
71    before_write: BeforeWrite<'_>,
72) -> Result<serde_json::Value, ApiError> {
73    let name = name.trim();
74    if name.is_empty() {
75        return Err(ApiError::bad_request("globalmemory.write: name is required"));
76    }
77    // Generous but bounded — Global Memory entries are meant to be readable
78    // instructions text, not arbitrary file storage (memory.write's own
79    // 10MB cap is for markdown notes files; this is an order of magnitude
80    // tighter since every agent's launch has to parse and inject this).
81    const MAX: usize = 1024 * 1024;
82    if content.len() > MAX {
83        return Err(ApiError::bad_request(format!("globalmemory.write: content too large ({} bytes, max {MAX})", content.len())));
84    }
85
86    let now = agentmux_common::time::now_ms();
87    let is_new = id.map(|v| v.is_empty()).unwrap_or(true);
88    let bundle = match id {
89        Some(existing_id) if !existing_id.is_empty() => {
90            let mut existing = state.id_store.bundle_get(existing_id)
91                .map_err(|e| format!("globalmemory.write: {e}"))?
92                .ok_or_else(|| ApiError::not_found(format!("globalmemory.write: not found id={existing_id}")))?;
93            // Belt-and-suspenders with bundle_upsert's own guard (see this
94            // section's top-of-block comment) — refuse here too, before
95            // even attempting the write, so the error message is specific
96            // to this API rather than bundle_upsert's generic one.
97            if existing.is_system {
98                return Err(ApiError::refused("globalmemory.write: cannot modify a system Global Memory entry through this API"));
99            }
100            // reagent P0, PR #3237: `id` is caller-supplied and bundle ids
101            // for EVERY bundle in the system (not just global ones) are
102            // already enumerable by any agent via PresetList
103            // (bundle_list_impl, unfiltered). Without these two checks, an
104            // agent could target any other agent's private preset — or the
105            // seeded 'blank' singleton — by id, rename/replace its content,
106            // and force it into is_global=true, hijacking it into every
107            // agent's launch instructions workspace-wide. Mirrors
108            // upsertmemory's own already-fixed blank-singleton guard
109            // (agent_handlers/bundle.rs, reagent P1, 2026-05-08) and adds
110            // the is_global check that guard alone doesn't cover: this API
111            // may only ever EDIT an entry that was already a Global Memory
112            // entry BEFORE this call, never silently promote/adopt an
113            // unrelated bundle into one.
114            if existing.is_blank || existing.id == "blank" {
115                return Err(ApiError::refused("globalmemory.write: cannot mutate the blank Bundle singleton"));
116            }
117            if !existing.is_global {
118                return Err(ApiError::not_found(format!(
119                    "globalmemory.write: id={existing_id} is not a Global Memory entry — this API cannot adopt an unrelated bundle, only create a new entry (omit id) or edit an existing Global Memory one"
120                )));
121            }
122            existing.name = name.to_string();
123            existing.instructions = content.to_string();
124            existing.is_global = true;
125            existing.updated_at = now;
126            existing
127        }
128        _ => Bundle {
129            id: uuid::Uuid::new_v4().to_string(),
130            name: name.to_string(),
131            description: String::new(),
132            is_blank: false,
133            is_global: true,
134            provider: String::new(),
135            model: String::new(),
136            instructions: content.to_string(),
137            instructions_by_provider: "{}".to_string(),
138            context_files: "[]".to_string(),
139            mcp_servers: "[]".to_string(),
140            skills: "[]".to_string(),
141            sort_order: 0,
142            is_system: false,
143            created_at: now,
144            updated_at: now,
145        },
146    };
147
148    // `written_by` is the TRUSTED `agent_id` this function received
149    // (agentmux-mcp's own AGENTMUX_AGENT_ID, unforgeable from the agent's
150    // PTY — see this section's top-of-block comment) — never taken from
151    // caller-supplied `source`/`source_detail`, which stay free-form
152    // annotation. bundle_upsert_with_version records both, atomically with
153    // the bundle write itself (codex P2, PR #3237 — see that method's own
154    // doc comment for why two separate calls here would have been unsafe
155    // under concurrent writers). `written_by_uid` is the writer's UID from
156    // the request's `Caller` (identity M4c-1, spec §6.5.9) — its token,
157    // never a body field; `""` when Unattributed.
158    let (source, source_detail) = recorded_provenance(provenance.as_ref());
159    let source_detail = source_detail.as_str();
160    if let Some(before_write) = before_write {
161        before_write(&bundle.id)?;
162    }
163    state.id_store
164        .bundle_upsert_with_version(&bundle, agent_id, written_by_uid, source, source_detail)
165        .map_err(|e| format!("globalmemory.write: {e}"))?;
166
167    // New entries sort LAST, matching Memory → Global's own "+ New section"
168    // behavior (global-bundle-model.ts's saveEdit) — without this, a fresh
169    // bundle_id defaults to sort_order=0 and could land ambiguously
170    // interleaved with any other 0-sort_order row instead of visibly
171    // appended at the end of the order the operator/agent expects.
172    if is_new {
173        append_to_order(state, agent_id, &bundle.id, "globalmemory.write")?;
174    }
175
176    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
177    tracing::info!(agent_id, bundle_id = %bundle.id, name = %bundle.name, "globalmemory.write");
178    Ok(with_peers_not_in_step(json!({ "id": bundle.id, "name": bundle.name })))
179}
180
181/// A write's answer, with the machines the last sync did not bring up to date (one that could not be
182/// reached, one that kept an entry back and why): this write may not reach them either. Said here,
183/// not only in `list`. Nothing is added when every machine is in step.
184fn with_peers_not_in_step(mut answer: serde_json::Value) -> serde_json::Value {
185    let behind = crate::server::remote_ops::fleet_sync::status::global().not_in_step();
186    if behind.as_object().is_some_and(|peers| !peers.is_empty()) {
187        answer["peers_not_in_step"] = behind;
188    }
189    answer
190}
191
192/// Puts `bundle_id` last in the Global Memory order, as Memory → Global's own
193/// "+ New section" does for a new entry and a restored one. A failed reorder
194/// is logged, not fatal: the entry is saved either way.
195fn append_to_order(state: &AppState, agent_id: &str, bundle_id: &str, verb: &str) -> Result<(), String> {
196    append_to_global_order(&state.id_store, agent_id, bundle_id, verb)
197}
198
199/// [`append_to_order`] on a store, for the window-side restore too.
200pub(crate) fn append_to_global_order(store: &Store, agent_id: &str, bundle_id: &str, verb: &str) -> Result<(), String> {
201    let ordinary_ids: Vec<String> = store.bundle_list_global()
202        .map_err(|e| format!("{verb}: {e}"))?
203        .into_iter()
204        .filter(|b| !b.is_system && b.id != bundle_id)
205        .map(|b| b.id)
206        .chain(std::iter::once(bundle_id.to_string()))
207        .collect();
208    if let Err(e) = store.bundle_reorder(&ordinary_ids) {
209        tracing::warn!(agent_id, bundle_id, error = %e, "{verb}: append-to-order failed (non-fatal)");
210    }
211    Ok(())
212}
213
214/// The entries taken out of Global Memory and not restored, most recently
215/// removed first, each with the `remove` version that records it: who removed
216/// it and when. Shared by `list`'s `removed` and the window's
217/// `globalmemory:removed`.
218pub(crate) fn removed_global_entries(store: &Store) -> Result<Vec<crate::backend::rpc_types::GlobalMemoryRemovedEntry>, String> {
219    let bundles = store.bundle_list_removed_global().map_err(|e| format!("removed Global Memory entries: {e}"))?;
220    let mut out = Vec::with_capacity(bundles.len());
221    for b in bundles {
222        // The query selected on the newest version being a removal, so there is one.
223        let Some(v) = store.bundle_version_latest(&b.id).map_err(|e| format!("removed Global Memory entries: {e}"))? else { continue };
224        out.push(crate::backend::rpc_types::GlobalMemoryRemovedEntry {
225            id: b.id,
226            name: b.name,
227            version_id: v.id,
228            removed_at: v.created_at,
229            removed_by: v.written_by,
230        });
231    }
232    Ok(out)
233}
234
235/// Where an entry goes: `fleet` (every proven machine, last write wins) or `machine` (this one only).
236/// AgentMux's own system entries never leave the machine.
237fn reach_of(b: &Bundle, machine_only: &std::collections::HashSet<String>) -> &'static str {
238    if b.is_system || machine_only.contains(&b.id) { SCOPE_MACHINE } else { SCOPE_FLEET }
239}
240
241/// Every Global Memory entry Memory → Global shows — id/name/updated_at/system,
242/// no content (mirrors `memory_list_impl`'s summary shape), system rows first
243/// as `bundle_list_global` orders them. System-tier rows are listed so an empty
244/// result means "nothing" and not "nothing you may touch" (the pane lists them
245/// too, and their content is already injected into every agent's context); what
246/// stays structural is that read, write and remove refuse a system id. `removed`
247/// lists the entries taken out of Global Memory and not restored, most recent
248/// first, with when and by whom: each one's id works with `history`, `diff` and
249/// `revert`. Backs the `GlobalMemoryList` MCP tool.
250/// docs/specs/SPEC_GLOBAL_MEMORY_LIST_SYSTEM_ROWS_2026_10_02.md
251pub(crate) fn global_memory_list_impl(state: &AppState) -> Result<serde_json::Value, ApiError> {
252    let machine_only = state.id_store.bundle_scope_machine_ids().map_err(|e| format!("globalmemory.list: {e}"))?;
253    let entries: Vec<_> = state.id_store.bundle_list_global()
254        .map_err(|e| format!("globalmemory.list: {e}"))?
255        .into_iter()
256        .map(|b| json!({ "id": b.id, "name": b.name, "updated_at": b.updated_at, "system": b.is_system, "reach": reach_of(&b, &machine_only) }))
257        .collect();
258    let removed: Vec<_> = removed_global_entries(&state.id_store)
259        .map_err(|e| format!("globalmemory.list: {e}"))?
260        .into_iter()
261        .map(|r| json!({ "id": r.id, "name": r.name, "removed_at": r.removed_at, "removed_by": r.removed_by }))
262        .collect();
263    // What the fleet sync did with each peer, and what a newer write from the fleet replaced here.
264    let sync = crate::server::remote_ops::fleet_sync::status::global().snapshot();
265    Ok(json!({ "entries": entries, "removed": removed, "sync": sync }))
266}
267
268/// Every Global Memory entry's reach, for the Memory pane. Backs `globalmemory:reach_list`.
269pub(crate) fn global_memory_reaches(store: &Store) -> Result<Vec<crate::backend::rpc_types::GlobalMemoryReachEntry>, String> {
270    let machine_only = store.bundle_scope_machine_ids().map_err(|e| format!("globalmemory.reach: {e}"))?;
271    Ok(store
272        .bundle_list_global()
273        .map_err(|e| format!("globalmemory.reach: {e}"))?
274        .into_iter()
275        .map(|b| crate::backend::rpc_types::GlobalMemoryReachEntry { reach: reach_of(&b, &machine_only).to_string(), id: b.id })
276        .collect())
277}
278
279/// Full content of one ordinary Global Memory entry by id. Refuses a
280/// system-tier id, same reasoning as write. Backs the `GlobalMemoryRead`
281/// MCP tool.
282pub(crate) fn global_memory_read_impl(state: &AppState, id: &str) -> Result<serde_json::Value, ApiError> {
283    let bundle = state.id_store.bundle_get(id)
284        .map_err(|e| format!("globalmemory.read: {e}"))?
285        .ok_or_else(|| ApiError::not_found(format!("globalmemory.read: not found id={id}")))?;
286    if bundle.is_system {
287        return Err(ApiError::refused("globalmemory.read: cannot read a system Global Memory entry through this API"));
288    }
289    if !bundle.is_global {
290        return Err(ApiError::not_found(format!("globalmemory.read: {id} is not a Global Memory entry")));
291    }
292    let machine_only = state.id_store.bundle_scope_machine_ids().map_err(|e| format!("globalmemory.read: {e}"))?;
293    Ok(json!({ "id": bundle.id, "name": bundle.name, "content": bundle.instructions, "reach": reach_of(&bundle, &machine_only) }))
294}
295
296/// `reach` as a Global Memory write or the reach action takes it, or why not.
297pub(crate) fn check_reach(reach: &str) -> Result<&'static str, ApiError> {
298    match reach {
299        SCOPE_FLEET => Ok(SCOPE_FLEET),
300        SCOPE_MACHINE => Ok(SCOPE_MACHINE),
301        other => Err(ApiError::bad_request(format!("globalmemory: reach must be \"fleet\" or \"machine\", not {other:?}"))),
302    }
303}
304
305/// [`global_memory_write_impl`], with the entry's reach set when the caller gave one. The reach is
306/// checked first, so a bad one writes nothing, and it is set **before** the entry is saved: an entry
307/// with no reach row counts as `fleet`, so setting it afterwards would leave a `machine` entry
308/// visible to the fleet in between, and for good if setting it then failed.
309#[allow(clippy::too_many_arguments)]
310pub(crate) fn global_memory_write_with_reach_impl(
311    state: &AppState,
312    agent_id: &str,
313    written_by_uid: &str,
314    id: Option<&str>,
315    name: &str,
316    content: &str,
317    provenance: Option<GlobalMemoryWriteProvenance<'_>>,
318    reach: Option<&str>,
319) -> Result<serde_json::Value, ApiError> {
320    let Some(reach) = reach.map(check_reach).transpose()? else {
321        return global_memory_write_impl(state, agent_id, written_by_uid, id, name, content, provenance);
322    };
323    // What the entry's reach was, to put back if the save then fails: the text is untouched in that
324    // case, so a changed reach would be the only trace of a write that reported an error.
325    let undo: std::cell::RefCell<Option<(String, String)>> = std::cell::RefCell::new(None);
326    let set_reach = |entry_id: &str| {
327        let was = state.id_store.bundle_scope_get(entry_id).map_err(|e| format!("globalmemory.write: reach: {e}"))?;
328        state.id_store.bundle_scope_set(entry_id, reach).map_err(|e| format!("globalmemory.write: reach: {e}"))?;
329        *undo.borrow_mut() = Some((entry_id.to_string(), was));
330        Ok(())
331    };
332    let mut result = match global_memory_write_inner(state, agent_id, written_by_uid, id, name, content, provenance, Some(&set_reach)) {
333        Ok(result) => result,
334        Err(e) => {
335            if let Some((entry_id, was)) = undo.take() {
336                if let Err(undo_err) = state.id_store.bundle_scope_set(&entry_id, &was) {
337                    tracing::warn!(bundle_id = %entry_id, error = %undo_err, "globalmemory.write: could not put the reach back after a failed save");
338                }
339            }
340            return Err(e);
341        }
342    };
343    result["reach"] = json!(reach);
344    Ok(result)
345}
346
347/// Sets where an existing ordinary Global Memory entry goes, without touching its text: `fleet`
348/// (pushed to every proven machine, last write wins) or `machine` (stays here; a copy another
349/// machine pushes is skipped). Same ownership guards as write and remove. Backs the `reach` action
350/// of the Memory tool.
351pub(crate) fn global_memory_reach_impl(state: &AppState, agent_id: &str, id: &str, reach: &str) -> Result<serde_json::Value, ApiError> {
352    let reach = check_reach(reach)?;
353    let bundle = state.id_store.bundle_get(id)
354        .map_err(|e| format!("globalmemory.reach: {e}"))?
355        .ok_or_else(|| ApiError::not_found(format!("globalmemory.reach: not found id={id}")))?;
356    if bundle.is_system {
357        return Err(ApiError::refused("globalmemory.reach: a system Global Memory entry stays on this machine and cannot be changed through this API"));
358    }
359    if bundle.is_blank || bundle.id == "blank" {
360        return Err(ApiError::refused("globalmemory.reach: cannot mutate the blank Bundle singleton"));
361    }
362    if !bundle.is_global {
363        return Err(ApiError::not_found(format!("globalmemory.reach: id={id} is not a Global Memory entry")));
364    }
365    state.id_store.bundle_scope_set(id, reach).map_err(|e| format!("globalmemory.reach: {e}"))?;
366    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
367    tracing::info!(agent_id, bundle_id = %id, reach, "globalmemory.reach");
368    Ok(json!({ "id": id, "reach": reach }))
369}
370
371/// Demotes a Global Memory entry (clears `is_global`) — matches Memory →
372/// Global's own "Remove" semantics: the bundle row itself survives (still
373/// available in Memory → Bundles), only its Global Memory membership is
374/// cleared. Refuses a system-tier id, the blank singleton, or any id that
375/// wasn't ALREADY a Global Memory entry before this call — same ownership
376/// guards as `global_memory_write_impl`, for the identical reason: bundle
377/// ids are enumerable via `PresetList` regardless of `is_global`.
378///
379/// The removal is a version too: the store records a `remove` version holding
380/// the content the entry had, written by `agent_id` (the agent its token names,
381/// proven by the handler) with `written_by_uid`, in the same transaction as the
382/// flag. `history`, `diff` and `revert` still reach the entry afterwards, and a
383/// revert restores it. Backs the `GlobalMemoryRemove` MCP tool.
384pub(crate) fn global_memory_remove_impl(
385    state: &AppState,
386    agent_id: &str,
387    written_by_uid: &str,
388    id: &str,
389) -> Result<serde_json::Value, ApiError> {
390    let mut bundle = state.id_store.bundle_get(id)
391        .map_err(|e| format!("globalmemory.remove: {e}"))?
392        .ok_or_else(|| ApiError::not_found(format!("globalmemory.remove: not found id={id}")))?;
393    if bundle.is_system {
394        return Err(ApiError::refused("globalmemory.remove: cannot remove a system Global Memory entry through this API"));
395    }
396    // reagent P1, PR #3237 (re-review): same missing-ownership-check bug
397    // already fixed for write above, left unfixed here. Bundle ids for
398    // every bundle are enumerable via PresetList (unfiltered), so without
399    // this an agent could call GlobalMemoryRemove with another agent's
400    // private preset id (or 'blank') — is_global is already false so the
401    // flag write is a no-op, but bundle_upsert still rewrites the row and
402    // bumps updated_at on a bundle this API has no business touching at
403    // all. This API may only ever act on an entry that was already Global
404    // Memory before the call.
405    if bundle.is_blank || bundle.id == "blank" {
406        return Err(ApiError::refused("globalmemory.remove: cannot mutate the blank Bundle singleton"));
407    }
408    if !bundle.is_global {
409        return Err(ApiError::not_found(format!("globalmemory.remove: id={id} is not a Global Memory entry")));
410    }
411    bundle.is_global = false;
412    bundle.updated_at = agentmux_common::time::now_ms();
413    let tombstone = state.id_store
414        .bundle_upsert_with_version(&bundle, agent_id, written_by_uid, crate::backend::storage::bundles::REMOVE_SOURCE, "{}")
415        .map_err(|e| format!("globalmemory.remove: {e}"))?
416        // Only `None` when the entry stopped being Global Memory between the
417        // read above and the write (another remove got there first).
418        .ok_or_else(|| ApiError::not_found(format!("globalmemory.remove: id={id} is not a Global Memory entry")))?;
419    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
420    tracing::info!(agent_id, bundle_id = %id, "globalmemory.remove");
421    Ok(json!({
422        "ok": true,
423        "version": version_meta_json(crate::server::agent_handlers::bundle::version_meta(tombstone)),
424    }))
425}
426
427/// A version's metadata as JSON: `GlobalMemoryVersionMeta`, the same shape
428/// `globalmemory:history` sends the pane, with no `name`/`instructions`.
429fn version_meta_json(meta: crate::backend::rpc_types::GlobalMemoryVersionMeta) -> serde_json::Value {
430    serde_json::to_value(meta).unwrap_or_default()
431}
432
433/// Loads `id`'s bundle and refuses it unless it is (a) not the blank
434/// singleton, (b) not a system-tier entry, and (c) a Global Memory entry
435/// (`is_global`) or one removed from Global Memory and not restored since (its
436/// newest version is a `remove` one, which only a removal writes) — the guard
437/// `global_memory_write_impl`/`global_memory_remove_impl` apply, plus the
438/// removed case so a removal can be inspected and undone. Bundle
439/// ids for EVERY bundle in the system (not just global ones) are enumerable
440/// via `PresetList` (reagent P0/P1, PR #3237) — without this, an agent could
441/// point any of these three new routes at another agent's private preset, or
442/// at AgentMux's own system-tier entries, and read/restore content that was
443/// never meant to be reachable through this API.
444fn load_ordinary_global_bundle(state: &AppState, id: &str, verb: &str) -> Result<Bundle, ApiError> {
445    let bundle = state.id_store.bundle_get(id)
446        .map_err(|e| format!("globalmemory.{verb}: {e}"))?
447        .ok_or_else(|| ApiError::not_found(format!("globalmemory.{verb}: not found id={id}")))?;
448    if bundle.is_system {
449        return Err(ApiError::refused(format!("globalmemory.{verb}: cannot {verb} a system Global Memory entry through this API")));
450    }
451    if bundle.is_blank || bundle.id == "blank" {
452        return Err(ApiError::refused(format!("globalmemory.{verb}: cannot {verb} the blank Bundle singleton")));
453    }
454    if !bundle.is_global
455        && !state.id_store.bundle_is_removed_global(id).map_err(|e| format!("globalmemory.{verb}: store: {e}"))?
456    {
457        return Err(ApiError::not_found(format!("globalmemory.{verb}: id={id} is not a Global Memory entry")));
458    }
459    Ok(bundle)
460}
461
462/// Version history for one Global Memory entry, newest first — metadata
463/// only, no `name`/`instructions` (mirrors `memory_history_impl`'s summary
464/// shape and `global_memory_list_impl`'s "no content" posture). Refuses a
465/// system-tier, blank, or non-global id via `load_ordinary_global_bundle` —
466/// structurally the same exclusion `list`/`read`/`remove` already apply, so
467/// there is no path here that can ever surface a system-tier row's history.
468/// Backs the `GlobalMemoryHistory` MCP tool.
469pub(crate) fn global_memory_history_impl(state: &AppState, id: &str) -> Result<serde_json::Value, ApiError> {
470    load_ordinary_global_bundle(state, id, "history")?;
471    let versions: Vec<_> = state.id_store.bundle_version_list(id)
472        .map_err(|e| format!("globalmemory.history: store: {e}"))?
473        .into_iter()
474        .map(|v| version_meta_json(crate::server::agent_handlers::bundle::version_summary_meta(v)))
475        .collect();
476    Ok(json!({ "versions": versions }))
477}
478
479/// A line-based diff between two recorded versions of one Global Memory
480/// entry (mirrors `memory_diff_impl`). Both versions must belong to `id` —
481/// reagent P1 in `memory_diff_impl` fixed the identical "diff across two
482/// unrelated owners" gap for native memory; the same check applies here
483/// since a `version_id` alone does not otherwise prove which bundle (and
484/// therefore whether a system-tier one) it came from. A name change is
485/// surfaced as its own two-line entry ahead of the instructions diff, since
486/// `content_hash` is computed over `name` + `instructions` together
487/// (`bundle_versions.rs`'s own `content_hash` doc comment) — a rename with
488/// unchanged body would otherwise produce a "no differences" instructions
489/// diff that silently hid the one thing that actually changed. Backs the
490/// `GlobalMemoryDiff` MCP tool.
491pub(crate) fn global_memory_diff_impl(
492    state: &AppState,
493    id: &str,
494    from_version_id: &str,
495    to_version_id: &str,
496) -> Result<serde_json::Value, ApiError> {
497    load_ordinary_global_bundle(state, id, "diff")?;
498    let from = state.id_store.bundle_version_get(from_version_id)
499        .map_err(|e| format!("globalmemory.diff: store: {e}"))?
500        .ok_or_else(|| ApiError::not_found(format!("globalmemory.diff: version {from_version_id} not found")))?;
501    let to = state.id_store.bundle_version_get(to_version_id)
502        .map_err(|e| format!("globalmemory.diff: store: {e}"))?
503        .ok_or_else(|| ApiError::not_found(format!("globalmemory.diff: version {to_version_id} not found")))?;
504    if from.bundle_id != id || to.bundle_id != id {
505        return Err(ApiError::bad_request(format!("globalmemory.diff: one or both versions do not belong to {id}")));
506    }
507    Ok(json!({ "diff": bundle_version_diff(&from, &to) }))
508}
509
510/// The diff text `global_memory_diff_impl` returns — a `- name:`/`+ name:`
511/// pair when the name changed (see that function's doc comment for why),
512/// then `line_diff` over the instructions. Shared with Memory → Global's
513/// `globalmemory:diff` WebSocket command (`agent_handlers/bundle.rs`) so the
514/// MCP tool and the UI can never render the same pair of versions two ways.
515pub(crate) fn bundle_version_diff(
516    from: &crate::backend::storage::BundleVersion,
517    to: &crate::backend::storage::BundleVersion,
518) -> String {
519    let mut diff = String::new();
520    if from.name != to.name {
521        diff.push_str(&format!("- name: {}\n+ name: {}\n", from.name, to.name));
522    }
523    diff.push_str(&crate::server::native_memory_handlers::line_diff(&from.instructions, &to.instructions));
524    diff
525}
526
527/// Restores a Global Memory entry's live `name`/`instructions` to a prior
528/// recorded version — same "revert never rewrites history, it records a new
529/// version" semantics as `memory_revert_impl` (`source: "revert"`, chained
530/// onto whatever the current latest version is). Reuses
531/// `Store::bundle_upsert_with_version` — the SAME primitive
532/// `global_memory_write_impl` already uses — so the live row and its new
533/// version are written atomically, in one transaction, exactly as that
534/// method's own doc comment requires (codex P2, PR #3237). `agent_id` is the
535/// TRUSTED caller identity (an agent's real `AGENTMUX_AGENT_ID`, resolved by
536/// `agentmux-mcp` from its own env, never caller-suppliable) recorded as
537/// `written_by` — never inferred from anything in the request body.
538/// `written_by_uid` is recorded beside it: the request's `Caller` UID
539/// (identity M4c-1), `""` when Unattributed. Backs the `GlobalMemoryRevert`
540/// MCP tool.
541pub(crate) fn global_memory_revert_impl(
542    state: &AppState,
543    agent_id: &str,
544    written_by_uid: &str,
545    id: &str,
546    version_id: &str,
547) -> Result<serde_json::Value, ApiError> {
548    let mut bundle = load_ordinary_global_bundle(state, id, "revert")?;
549    let target = state.id_store.bundle_version_get(version_id)
550        .map_err(|e| format!("globalmemory.revert: store: {e}"))?
551        .ok_or_else(|| ApiError::not_found(format!("globalmemory.revert: version {version_id} not found")))?;
552    if target.bundle_id != id {
553        return Err(ApiError::bad_request(format!("globalmemory.revert: version {version_id} does not belong to {id}")));
554    }
555
556    // A removed entry comes back as Global Memory, last in the order.
557    let restoring = !bundle.is_global;
558    bundle.is_global = true;
559    bundle.name = target.name.clone();
560    bundle.instructions = target.instructions.clone();
561    bundle.updated_at = agentmux_common::time::now_ms();
562
563    let detail = json!({ "reverted_to": version_id }).to_string();
564    let new_version = state.id_store
565        .bundle_upsert_with_version(&bundle, agent_id, written_by_uid, "revert", &detail)
566        .map_err(|e| format!("globalmemory.revert: {e}"))?
567        // `bundle.is_global` is set true above, and `bundle_upsert_with_version`
568        // returns `None` only for a row that stays non-global — so this branch is
569        // unreachable in practice, but
570        // failing loudly beats silently reporting success with no new version.
571        .ok_or_else(|| ApiError::internal("globalmemory.revert: no version was recorded (unexpected: entry is not global)"))?;
572    if restoring {
573        append_to_order(state, agent_id, id, "globalmemory.revert")?;
574    }
575
576    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
577    tracing::info!(agent_id, bundle_id = %id, version_id, "globalmemory.revert");
578    Ok(json!({ "version": version_meta_json(crate::server::agent_handlers::bundle::version_meta(new_version)) }))
579}