Skip to main content

agentmux_srv/server/agent_handlers/
bundle.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7use serde_json::json;
8
9use crate::backend::rpc::engine::WshRpcEngine;
10use crate::backend::rpc_types::{
11    RpcContext, COMMAND_LIST_MEMORIES, COMMAND_GET_MEMORY,
12    COMMAND_GET_AGENT_BUNDLES, COMMAND_SET_AGENT_BUNDLES,
13    AgentBundlesResult, CommandGetAgentBundlesData, CommandSetAgentBundlesData,
14    COMMAND_UPSERT_MEMORY, COMMAND_DELETE_MEMORY, COMMAND_REORDER_GLOBAL_BRAIN,
15    COMMAND_UPSERT_SYSTEM_MEMORY, COMMAND_DELETE_SYSTEM_MEMORY,
16    COMMAND_GET_CLAUDE_GLOBAL_CONFIG,
17    COMMAND_GLOBAL_MEMORY_HISTORY, COMMAND_GLOBAL_MEMORY_DIFF, COMMAND_GLOBAL_MEMORY_REVERT,
18    COMMAND_GLOBAL_MEMORY_REMOVED, CommandGlobalMemoryRemovedData, GlobalMemoryRemovedResult,
19    COMMAND_GLOBAL_MEMORY_REACH_LIST, COMMAND_GLOBAL_MEMORY_SET_REACH, CommandGlobalMemoryReachListData,
20    CommandGlobalMemorySetReachData, GlobalMemoryReachListResult,
21    COMMAND_GLOBAL_MEMORY_IMPORT_SOURCES, COMMAND_GLOBAL_MEMORY_IMPORT, COMMAND_GLOBAL_MEMORY_SECTIONS,
22    CommandGlobalMemoryImportSourcesData, CommandGlobalMemoryImportData, CommandGlobalMemorySectionsData,
23    CommandGetBundleData, CommandDeleteBundleData, DeleteBundleResult, CommandReorderGlobalBundlesData,
24    CommandListBundlesData, CommandGetClaudeGlobalConfigData, ReorderGlobalBundlesResult,
25    CommandUpsertBundleData, CommandGlobalMemoryHistoryData, CommandGlobalMemoryDiffData,
26    CommandGlobalMemoryRevertData, GlobalMemoryDiffResult, GlobalMemoryHistoryResult,
27    GlobalMemoryRevertResult, GlobalMemoryVersionMeta,
28};
29use crate::backend::storage::store::{Bundle, Store};
30use crate::backend::storage::{BundleVersion, BundleVersionSummary};
31
32use super::super::AppState;
33
34// ---- Bundle CRUD ----
35
36/// `listmemories`.
37pub(crate) fn list_memories(state: &AppState) -> Result<Vec<Bundle>, String> {
38    let memories = state
39        .id_store
40        .bundle_list()
41        .map_err(|e| format!("listmemories: {e}"))?;
42    Ok(memories)
43}
44
45/// `getmemory`.
46pub(crate) fn get_memory(state: &AppState, cmd: CommandGetBundleData) -> Result<Bundle, String> {
47    match state
48        .id_store
49        .bundle_get(&cmd.id)
50        .map_err(|e| format!("getmemory: {e}"))?
51    {
52        Some(m) => Ok(m),
53        None => Err(format!("getmemory: not found id={}", cmd.id)),
54    }
55}
56
57/// `upsertmemory`.
58pub(crate) fn upsert_memory(state: &AppState, ctx: &RpcContext, req: CommandUpsertBundleData) -> Result<Bundle, String> {
59    let CommandUpsertBundleData { bundle: mut memory, base_sha256 } = req;
60    // Guard on BOTH client-supplied is_blank AND id == "blank".
61    // Without the id check a caller could send
62    // {id:"blank", is_blank:false, name:"evil"} and the
63    // ON CONFLICT(id) DO UPDATE path would rename/re-describe
64    // the seeded singleton. (reagent P1, 2026-05-08).
65    if memory.is_blank || memory.id == "blank" {
66        return Err("upsertmemory: cannot mutate the blank singleton".to_string());
67    }
68    if memory.id.is_empty() {
69        memory.id = uuid::Uuid::new_v4().to_string();
70    }
71    let now = agentmux_common::time::now_ms();
72    if memory.created_at == 0 {
73        memory.created_at = now;
74    }
75    memory.updated_at = now;
76    // bundle_upsert_with_version, not bundle_upsert — this is
77    // the actual Memory → Global save path (frontend's
78    // UpsertBundleCommand -> "upsertmemory"; also used by the
79    // per-agent Bundle editor, which is fine: versioning only
80    // fires when memory.is_global is true either way). Without
81    // this, a human edit in Memory → Global was invisible to
82    // db_bundle_versions entirely — only agent-originated
83    // writes through GlobalMemoryWrite recorded a version, so a
84    // future history/diff view would present a false sequence
85    // with operator edits silently missing from it (codex P2,
86    // PR #3237). "armory-ui" as written_by: a connection that did
87    // not register as an agent is the window, which has no
88    // per-request trusted AGENT identity the way the REST/MCP
89    // path does (see BundleVersion::written_by's own doc
90    // comment). No writer UID either (identity M4c-1): the
91    // WebSocket is always Unattributed.
92    // `base_sha256` (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md
93    // §2.4): the Memory editor says which content its draft
94    // started from, so a concurrent write (an agent's
95    // GlobalMemoryWrite, another window) becomes a `conflict:`
96    // refusal instead of being silently overwritten. Absent =
97    // the unconditional save every other caller still gets.
98    // A write made by a registered agent is recorded as that agent,
99    // never as the person at the window.
100    let (written_by, source) = writer_of(ctx, "human");
101    state
102        .id_store
103        .bundle_upsert_with_version_based(&memory, written_by, "", source, "{}", base_sha256.as_deref())
104        .map_err(|e| format!("upsertmemory: {e}"))?;
105    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
106    Ok(memory)
107}
108
109/// `deletememory`.
110pub(crate) fn delete_memory(state: &AppState, cmd: CommandDeleteBundleData) -> Result<DeleteBundleResult, String> {
111    let deleted = state
112        .id_store
113        .bundle_delete(&cmd.id)
114        .map_err(|e| format!("deletememory: {e}"))?;
115    if deleted {
116        // This is the delete Memory actually calls
117        // (`rpc-api/bundle.ts`), so the ref purge has to live here
118        // too — fixing only `bundle.delete` left the product path
119        // orphaning refs (Codex, PR #3153). Shared helper, not a
120        // second copy of the logic.
121        crate::server::app_api::bundle::purge_bundle_component_refs(
122            &state.mstore,
123            &cmd.id,
124        );
125        state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
126    }
127    Ok(DeleteBundleResult { deleted })
128}
129
130/// `reorderglobalbrain`.
131pub(crate) fn reorder_global_bundles(
132    state: &AppState,
133    cmd: CommandReorderGlobalBundlesData,
134) -> Result<ReorderGlobalBundlesResult, String> {
135    let updated = state
136        .id_store
137        .bundle_reorder(&cmd.ids)
138        .map_err(|e| format!("reorderglobalbrain: {e}"))?;
139    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
140    Ok(ReorderGlobalBundlesResult { updated })
141}
142
143// ---- System-tier Global Bundle — see
144// docs/specs/SPEC_GLOBAL_MEMORY_SYSTEM_TIER_2026_08_24.md. Deliberately
145// separate commands from the four above (never wired to any MCP tool)
146// so the ordinary Global Bundle editor and every other generic
147// bundle-writing surface can never reach an is_system row.
148
149/// `upsertsystemmemory`.
150pub(crate) fn upsert_system_memory(state: &AppState, ctx: &RpcContext, req: CommandUpsertBundleData) -> Result<Bundle, String> {
151    let mstore = &state.id_store;
152    let CommandUpsertBundleData { bundle: mut memory, base_sha256 } = req;
153    if memory.id.is_empty() {
154        memory.id = uuid::Uuid::new_v4().to_string();
155    }
156    let now = agentmux_common::time::now_ms();
157    if memory.created_at == 0 {
158        memory.created_at = now;
159    }
160    memory.updated_at = now;
161    // bundle_upsert_system_if_changed atomically compares against
162    // the current row and skips recording a version
163    // for a byte-identical save (operator opens a seeded entry
164    // and hits Save without changing anything — the UI does not
165    // suppress this request) — recording one would permanently
166    // mark the row as human-owned even though nothing actually
167    // changed, so a future Operator Config manifest update would
168    // be skipped forever instead of just once. A REAL edit is
169    // stamped with its writer ("armory-ui" for the window, the
170    // agent's id for a registered agent), so the next startup's
171    // reseed correctly leaves it alone. The
172    // read-decide-write happens in one transaction, not as a
173    // separate bundle_get + conditional call here — an earlier
174    // revision raced a concurrent writer (e.g. another AgentMux
175    // instance's own reseed) between the read and the write.
176    // Codex P1/P2, ReAgent P2, PR #3244.
177    // Same optional base check as `upsertmemory` above.
178    // A registered agent's save is recorded as that agent, never as the person's.
179    let (written_by, source) = writer_of(ctx, "human");
180    mstore
181        .bundle_upsert_system_if_changed_based(&memory, written_by, source, "{}", base_sha256.as_deref())
182        .map_err(|e| format!("upsertsystemmemory: {e}"))?;
183    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
184    // Return the row actually persisted, not the client-supplied
185    // struct — bundle_upsert_system hardcodes
186    // is_blank/is_global/is_system server-side regardless of
187    // what `memory` carried (e.g. the frontend's saveSystemEdit
188    // sends only id/name/instructions, so `memory.is_global`/
189    // `is_system` deserialize to false via #[serde(default)]).
190    // Echoing `memory` back would misreport both to any caller
191    // that trusts the response instead of refetching. reagent
192    // P2, PR #2782.
193    let saved = mstore
194        .bundle_get(&memory.id)
195        .map_err(|e| format!("upsertsystemmemory: {e}"))?
196        .ok_or_else(|| format!("upsertsystemmemory: row {} vanished after upsert", memory.id))?;
197    Ok(saved)
198}
199
200/// `deletesystemmemory`.
201pub(crate) fn delete_system_memory(state: &AppState, cmd: CommandDeleteBundleData) -> Result<DeleteBundleResult, String> {
202    let deleted = state
203        .id_store
204        .bundle_delete_system(&cmd.id)
205        .map_err(|e| format!("deletesystemmemory: {e}"))?;
206    if deleted {
207        state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
208    }
209    Ok(DeleteBundleResult { deleted })
210}
211
212/// `globalmemory:revert`.
213pub(crate) fn global_memory_revert(
214    state: &AppState,
215    ctx: &RpcContext,
216    cmd: CommandGlobalMemoryRevertData,
217) -> Result<GlobalMemoryRevertResult, String> {
218    let result = global_memory_ui_revert(&state.id_store, &cmd, writer_of(ctx, "revert").0)?;
219    state.broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
220    Ok(result)
221}
222
223/// `globalmemory:removed`: the entries taken out of Global Memory, so the pane
224/// can offer to restore them: a restore is `globalmemory:revert` to the
225/// version listed here.
226pub(crate) fn global_memory_removed(state: &AppState) -> Result<GlobalMemoryRemovedResult, String> {
227    crate::server::app_api::removed_global_entries(&state.id_store)
228        .map(|entries| GlobalMemoryRemovedResult { entries })
229        .map_err(|e| format!("globalmemory:removed: {e}"))
230}
231
232/// `globalmemory:reach_list`: where each entry goes, for the pane's switch.
233pub(crate) fn global_memory_reach_list(state: &AppState) -> Result<GlobalMemoryReachListResult, String> {
234    crate::server::app_api::global_memory_reaches(&state.id_store)
235        .map(|entries| GlobalMemoryReachListResult { entries })
236        .map_err(|e| format!("globalmemory:reach_list: {e}"))
237}
238
239/// `globalmemory:set_reach`: the pane's switch. The change is the MCP tool's
240/// (`global_memory_reach_impl`: same guards, same event), made by the window;
241/// the entry's text is not touched.
242pub(crate) fn global_memory_set_reach(
243    state: &AppState,
244    ctx: &RpcContext,
245    cmd: CommandGlobalMemorySetReachData,
246) -> Result<crate::backend::rpc_types::GlobalMemoryReachEntry, String> {
247    let by = writer_of(ctx, "set_reach").0.to_string();
248    let answer = crate::server::app_api::global_memory_reach_impl(state, &by, &cmd.id, &cmd.reach).map_err(|e| e.to_string())?;
249    Ok(crate::backend::rpc_types::GlobalMemoryReachEntry {
250        id: cmd.id,
251        reach: answer["reach"].as_str().unwrap_or_default().to_string(),
252    })
253}
254
255pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
256    register_global_memory_import(engine, state);
257    register_global_memory_sections(engine, state);
258    register_agent_bundles(engine, state);
259    register_bundle_crud(engine, state);
260    register_global_memory_ui(engine, state);
261}
262
263fn register_bundle_crud(engine: &Arc<WshRpcEngine>, state: &AppState) {
264    let s = state.clone();
265    engine.register_typed(COMMAND_LIST_MEMORIES, move |_req: CommandListBundlesData, _ctx| {
266        let s = s.clone();
267        async move { list_memories(&s) }
268    });
269
270    let s = state.clone();
271    engine.register_typed(COMMAND_GET_MEMORY, move |cmd: CommandGetBundleData, _ctx| {
272        let s = s.clone();
273        async move { get_memory(&s, cmd) }
274    });
275
276    let s = state.clone();
277    engine.register_typed(COMMAND_UPSERT_MEMORY, move |req: CommandUpsertBundleData, ctx| {
278        let s = s.clone();
279        async move { upsert_memory(&s, &ctx, req) }
280    });
281
282    let s = state.clone();
283    engine.register_typed(COMMAND_DELETE_MEMORY, move |cmd: CommandDeleteBundleData, _ctx| {
284        let s = s.clone();
285        async move { delete_memory(&s, cmd) }
286    });
287
288    let s = state.clone();
289    engine.register_typed(COMMAND_REORDER_GLOBAL_BRAIN, move |cmd: CommandReorderGlobalBundlesData, _ctx| {
290        let s = s.clone();
291        async move { reorder_global_bundles(&s, cmd) }
292    });
293
294    let s = state.clone();
295    engine.register_typed(COMMAND_UPSERT_SYSTEM_MEMORY, move |req: CommandUpsertBundleData, ctx| {
296        let s = s.clone();
297        async move { upsert_system_memory(&s, &ctx, req) }
298    });
299
300    let s = state.clone();
301    engine.register_typed(COMMAND_DELETE_SYSTEM_MEMORY, move |cmd: CommandDeleteBundleData, _ctx| {
302        let s = s.clone();
303        async move { delete_system_memory(&s, cmd) }
304    });
305
306    // ---- Read-only: the CLAUDE.md at AgentMux's shared Claude provider
307    // config dir — see docs/specs/SPEC_SURFACE_CLAUDE_GLOBAL_CONFIG_2026_08_24.md
308    // §5 (post-review revision). No parameters (fixed path, not
309    // caller-supplied), no write counterpart.
310    engine.register_typed(
311        COMMAND_GET_CLAUDE_GLOBAL_CONFIG,
312        move |_req: CommandGetClaudeGlobalConfigData, _ctx| async move {
313            let claude_dir = resolve_shared_claude_provider_dir();
314            read_claude_global_config(&claude_dir)
315                .map_err(|e| format!("getclaudeglobalconfig: {e}"))
316        },
317    );
318}
319
320// ---- Global Memory version history for Memory → Global
321// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.3). Same rows, same
322// diff, same "revert records a new version" rule as the MCP tools in
323// app_api/mod.rs (global_memory_{history,diff,revert}_impl) — the
324// difference is the guard: Memory → Global can already edit and delete
325// system-tier entries through upsertsystemmemory/deletesystemmemory, so
326// their history is not hidden from it the way it is from agents.
327fn register_global_memory_ui(engine: &Arc<WshRpcEngine>, state: &AppState) {
328    let mstore = state.id_store.clone();
329    engine.register_typed(
330        COMMAND_GLOBAL_MEMORY_HISTORY,
331        move |cmd: CommandGlobalMemoryHistoryData, _ctx| {
332            let mstore = mstore.clone();
333            async move { global_memory_ui_history(&mstore, &cmd.id) }
334        },
335    );
336
337    let mstore = state.id_store.clone();
338    engine.register_typed(
339        COMMAND_GLOBAL_MEMORY_DIFF,
340        move |cmd: CommandGlobalMemoryDiffData, _ctx| {
341            let mstore = mstore.clone();
342            async move { global_memory_ui_diff(&mstore, &cmd) }
343        },
344    );
345
346    let s = state.clone();
347    engine.register_typed(COMMAND_GLOBAL_MEMORY_REVERT, move |cmd: CommandGlobalMemoryRevertData, ctx| {
348        let s = s.clone();
349        async move { global_memory_revert(&s, &ctx, cmd) }
350    });
351
352    let s = state.clone();
353    engine.register_typed(COMMAND_GLOBAL_MEMORY_REMOVED, move |_cmd: CommandGlobalMemoryRemovedData, _ctx| {
354        let s = s.clone();
355        async move { global_memory_removed(&s) }
356    });
357
358    let s = state.clone();
359    engine.register_typed(COMMAND_GLOBAL_MEMORY_REACH_LIST, move |_cmd: CommandGlobalMemoryReachListData, _ctx| {
360        let s = s.clone();
361        async move { global_memory_reach_list(&s) }
362    });
363    let s = state.clone();
364    engine.register_typed(COMMAND_GLOBAL_MEMORY_SET_REACH, move |cmd: CommandGlobalMemorySetReachData, ctx| {
365        let s = s.clone();
366        async move { global_memory_set_reach(&s, &ctx, cmd) }
367    });
368}
369
370/// `getagentbundles` / `setagentbundles`: an agent's Bundles list, the
371/// bundles picked for it in order (`Store::agent_bundle_ids`). Window-scoped, like
372/// `setagentcontent`: the new-agent form and the Stash call
373/// these before the agent runs.
374fn register_agent_bundles(engine: &WshRpcEngine, state: &AppState) {
375    let mstore = state.mstore.clone();
376    engine.register_typed(COMMAND_GET_AGENT_BUNDLES, move |cmd: CommandGetAgentBundlesData, _ctx| {
377        let mstore = mstore.clone();
378        async move {
379            let bundle_ids = mstore
380                .agent_bundle_ids(&cmd.agent_id)
381                .map_err(|e| format!("getagentbundles: {e}"))?;
382            Ok(AgentBundlesResult { bundle_ids })
383        }
384    });
385    let mstore = state.mstore.clone();
386    engine.register_typed(COMMAND_SET_AGENT_BUNDLES, move |cmd: CommandSetAgentBundlesData, _ctx| {
387        let mstore = mstore.clone();
388        async move {
389            let bundle_ids = mstore
390                .agent_bundles_set(&cmd.agent_id, &cmd.bundle_ids)
391                .map_err(|e| format!("setagentbundles: {e}"))?;
392            Ok(AgentBundlesResult { bundle_ids })
393        }
394    });
395}
396
397/// `globalmemory:sections`' `agent_kind`, for a caller with no pane: `host`
398/// when absent.
399fn requested_agent_kind(agent_kind: Option<&str>) -> Result<&'static str, String> {
400    match agent_kind {
401        None | Some("host") => Ok("host"),
402        Some("container") => Ok("container"),
403        Some(other) => Err(format!("globalmemory:sections: agent_kind must be host or container, not {other:?}")),
404    }
405}
406
407/// Memory → Global's "Bring Global Memory from…" step for an isolated channel
408/// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.6). Registered with the
409/// others below.
410/// `globalmemory:sections`: the Global Memory block an agent's startup file
411/// carries, from the same store (`id_store`) and formatter the startup-file
412/// writers use — so memory reinjection re-delivers it byte for byte,
413/// Operator Config included (SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P1).
414pub(crate) fn register_global_memory_sections(engine: &WshRpcEngine, state: &AppState) {
415    let id_store = state.id_store.clone();
416    let mstore = state.mstore.clone();
417    engine.register_typed(
418        COMMAND_GLOBAL_MEMORY_SECTIONS,
419        move |cmd: CommandGlobalMemorySectionsData, _ctx| {
420            let store = id_store.clone();
421            let mstore = mstore.clone();
422            async move {
423                let bundles = store.bundle_list_global().map_err(|e| format!("globalmemory:sections: {e}"))?;
424                // The same entries the pane's startup file got: Operator
425                // Config targeted at another agent kind is left out.
426                let agent_mode = match cmd.block_id.as_deref() {
427                    Some(b) => crate::backend::operator_config_seed::agent_mode_of_block(&mstore, b),
428                    None => requested_agent_kind(cmd.agent_kind.as_deref())?.to_string(),
429                };
430                let bundles = crate::backend::operator_config_seed::global_bundles_for_agent(bundles, &agent_mode);
431                Ok::<Vec<crate::backend::storage::GlobalMemorySection>, String>(
432                    crate::backend::storage::global_bundle_sections(&bundles),
433                )
434            }
435        },
436    );
437}
438
439pub(crate) fn register_global_memory_import(engine: &WshRpcEngine, state: &AppState) {
440    let id_store = state.id_store.clone();
441    engine.register_typed(
442        COMMAND_GLOBAL_MEMORY_IMPORT_SOURCES,
443        move |_cmd: CommandGlobalMemoryImportSourcesData, _ctx| {
444            let store = id_store.clone();
445            async move {
446                let fs = crate::backend::agent_session::global_transcript_store()
447                    .ok_or_else(|| "globalmemory:import_sources: record store unavailable".to_string())?;
448                tokio::task::spawn_blocking(move || crate::backend::memory::global_record::import_sources_checked(fs, &store))
449                    .await
450                    .map_err(|e| format!("globalmemory:import_sources: {e}"))?
451                    .map_err(|e| format!("globalmemory:import_sources: {e}"))
452            }
453        },
454    );
455    let id_store = state.id_store.clone();
456    let broker = state.broker.clone();
457    engine.register_typed(
458        COMMAND_GLOBAL_MEMORY_IMPORT,
459        move |cmd: CommandGlobalMemoryImportData, _ctx| {
460            let store = id_store.clone();
461            let broker = broker.clone();
462            async move {
463                let fs = crate::backend::agent_session::global_transcript_store()
464                    .ok_or_else(|| "globalmemory:import: record store unavailable".to_string())?;
465                let report = tokio::task::spawn_blocking(move || {
466                    crate::backend::memory::global_record::import_checked(fs, &store, &cmd.list_id, cmd.index)
467                })
468                .await
469                .map_err(|e| format!("globalmemory:import: {e}"))?
470                .map_err(|e| format!("globalmemory:import: {e}"))?;
471                broker.publish_event::<crate::backend::mps_events::MemoriesChanged>(&(), vec![], 0);
472                Ok(report)
473            }
474        },
475    );
476}
477
478/// Loads a Global Memory entry for Memory → Global's history commands: it must
479/// exist, be `is_global` (or removed from Global Memory and not restored since,
480/// so it can be inspected and restored), and not be the blank singleton.
481/// System-tier rows are allowed (see the comment above the registrations).
482fn load_global_bundle_for_ui(store: &Store, id: &str, verb: &str) -> Result<Bundle, String> {
483    let bundle = store
484        .bundle_get(id)
485        .map_err(|e| format!("globalmemory:{verb}: {e}"))?
486        .ok_or_else(|| format!("globalmemory:{verb}: not found id={id}"))?;
487    if bundle.is_blank || bundle.id == "blank" {
488        return Err(format!("globalmemory:{verb}: cannot {verb} the blank Bundle singleton"));
489    }
490    if !bundle.is_global
491        && (bundle.is_system || !store.bundle_is_removed_global(id).map_err(|e| format!("globalmemory:{verb}: store: {e}"))?)
492    {
493        return Err(format!("globalmemory:{verb}: id={id} is not a Global Memory entry"));
494    }
495    Ok(bundle)
496}
497
498/// A history row as the wire's version metadata. Shared with the
499/// `GlobalMemoryHistory` / `GlobalMemoryRevert` MCP tools (`app_api/global_memory.rs`),
500/// so both surfaces carry the same fields.
501pub(crate) fn version_summary_meta(v: BundleVersionSummary) -> GlobalMemoryVersionMeta {
502    GlobalMemoryVersionMeta {
503        id: v.id,
504        content_hash: v.content_hash,
505        parent_version_id: v.parent_version_id,
506        source: v.source,
507        source_detail: v.source_detail,
508        written_by: v.written_by,
509        written_by_uid: v.written_by_uid,
510        created_at: v.created_at,
511        size_bytes: v.size_bytes,
512        tokens_est: v.tokens_est,
513    }
514}
515
516/// A full version as the wire's version metadata, counted from its instructions.
517pub(crate) fn version_meta(v: BundleVersion) -> GlobalMemoryVersionMeta {
518    GlobalMemoryVersionMeta {
519        size_bytes: v.instructions.len() as u64,
520        tokens_est: agentmux_common::tokens::estimate_tokens(&v.instructions),
521        id: v.id,
522        content_hash: v.content_hash,
523        parent_version_id: v.parent_version_id,
524        source: v.source,
525        source_detail: v.source_detail,
526        written_by: v.written_by,
527        written_by_uid: v.written_by_uid,
528        created_at: v.created_at,
529    }
530}
531
532fn global_memory_ui_history(store: &Store, id: &str) -> Result<GlobalMemoryHistoryResult, String> {
533    load_global_bundle_for_ui(store, id, "history")?;
534    let versions = store
535        .bundle_version_list(id)
536        .map_err(|e| format!("globalmemory:history: store: {e}"))?
537        .into_iter()
538        .map(version_summary_meta)
539        .collect();
540    Ok(GlobalMemoryHistoryResult { versions })
541}
542
543fn global_memory_ui_diff(store: &Store, cmd: &CommandGlobalMemoryDiffData) -> Result<GlobalMemoryDiffResult, String> {
544    load_global_bundle_for_ui(store, &cmd.id, "diff")?;
545    let get = |vid: &str| {
546        store
547            .bundle_version_get(vid)
548            .map_err(|e| format!("globalmemory:diff: store: {e}"))?
549            .ok_or_else(|| format!("globalmemory:diff: version {vid} not found"))
550    };
551    let from = get(&cmd.from_version_id)?;
552    let to = get(&cmd.to_version_id)?;
553    // Both versions must belong to this entry — a version id alone does not
554    // prove which bundle it came from (same check as the MCP diff).
555    if from.bundle_id != cmd.id || to.bundle_id != cmd.id {
556        return Err(format!("globalmemory:diff: one or both versions do not belong to {}", cmd.id));
557    }
558    Ok(GlobalMemoryDiffResult { diff: crate::server::app_api::bundle_version_diff(&from, &to) })
559}
560
561/// Who a websocket Global Memory write is recorded as: the agent when the connection registered as one, the window
562/// (`armory-ui`, with `window_source`) only when the connection is the person's proven window, and `unproven` for a
563/// connection that holds the instance key and proved nothing more. A write is never recorded as the person's unless their
564/// window made it.
565fn writer_of<'a>(ctx: &'a RpcContext, window_source: &'a str) -> (&'a str, &'a str) {
566    use crate::backend::rpc::actor::{actor_of, Actor};
567    match actor_of(ctx) {
568        Actor::Agent(_) => (ctx.agent_id.as_str(), "agent"),
569        Actor::Operator | Actor::Person(_) => ("armory-ui", window_source),
570        Actor::Unproven | Actor::Srv => ("unproven", "unproven"),
571    }
572}
573
574/// Restores `name` + `instructions` from `target_version_id` as a NEW
575/// version (`source: "revert"`, `written_by`: `writer`, which is `armory-ui`
576/// for the window), through the same atomic upsert-plus-version primitive
577/// each tier's ordinary save uses.
578fn global_memory_ui_revert(store: &Store, cmd: &CommandGlobalMemoryRevertData, writer: &str) -> Result<GlobalMemoryRevertResult, String> {
579    let mut bundle = load_global_bundle_for_ui(store, &cmd.id, "revert")?;
580    let target = store
581        .bundle_version_get(&cmd.target_version_id)
582        .map_err(|e| format!("globalmemory:revert: store: {e}"))?
583        .ok_or_else(|| format!("globalmemory:revert: version {} not found", cmd.target_version_id))?;
584    if target.bundle_id != cmd.id {
585        return Err(format!(
586            "globalmemory:revert: version {} does not belong to {}",
587            cmd.target_version_id, cmd.id
588        ));
589    }
590    // An entry removed from Global Memory comes back as Global Memory, last in
591    // the order.
592    let restoring = !bundle.is_global;
593    bundle.is_global = true;
594    bundle.name = target.name;
595    bundle.instructions = target.instructions;
596    bundle.updated_at = agentmux_common::time::now_ms();
597    let detail = json!({ "reverted_to": cmd.target_version_id }).to_string();
598    let version = if bundle.is_system {
599        // Reverting to text AgentMux itself seeded hands the entry back to
600        // the seeder, so it keeps receiving Operator Config updates;
601        // recording it as a human edit would opt it out of them for good
602        // (`bundle_reseed_system_if_owned` skips any non-seeder last writer).
603        let seeder = crate::backend::operator_config_seed::WRITTEN_BY;
604        let written_by = if target.written_by == seeder { seeder } else { writer };
605        store.bundle_upsert_system_if_changed(&bundle, written_by, "revert", &detail)
606    } else {
607        store.bundle_upsert_with_version(&bundle, writer, "", "revert", &detail)
608    }
609    .map_err(|e| format!("globalmemory:revert: {e}"))?;
610    if restoring {
611        crate::server::app_api::append_to_global_order(store, writer, &cmd.id, "globalmemory:revert")?;
612    }
613    tracing::info!(bundle_id = %cmd.id, version_id = %cmd.target_version_id, "globalmemory:revert");
614    Ok(GlobalMemoryRevertResult { version: version.map(version_meta) })
615}
616
617/// The directory a spawned Claude agent's `CLAUDE_CONFIG_DIR` env var
618/// points at by DEFAULT (agents not bound to an account — the common
619/// case; an agent bound to an account uses that account's own dir, which
620/// this does not cover). Mirrors `agent_open.rs`'s own `auth_dir`
621/// resolution exactly — `DataPaths::provider_auth_dir("claude")`, with the
622/// identical `~/.agentmux/shared/providers/claude` fallback when
623/// `DataPaths::from_env()` fails — so the path shown here is genuinely the
624/// one AgentMux itself uses when launching a Claude agent, not a guess.
625/// codex P1, PR #2794: the original version read `~/.claude/CLAUDE.md`
626/// directly, which `SPEC_PROVIDER_ISOLATION_2026_06_20.md`
627/// §5b confirms is NOT what a `CLAUDE_CONFIG_DIR`-redirected spawned agent
628/// actually loads as its "user CLAUDE.md" — `CLAUDE_CONFIG_DIR` relocates
629/// Claude Code's entire home, `<CLAUDE_CONFIG_DIR>/CLAUDE.md` included.
630fn resolve_shared_claude_provider_dir() -> std::path::PathBuf {
631    agentmux_common::DataPaths::from_env()
632        .map(|p| p.provider_auth_dir("claude"))
633        .unwrap_or_else(|| {
634            crate::backend::base::get_home_dir()
635                .join(".agentmux")
636                .join("shared")
637                .join("providers")
638                .join("claude")
639        })
640}
641
642/// The resolved shared-provider-dir's `CLAUDE.md` path + content,
643/// read-only. `claude_dir` is injected (not resolved internally) so this
644/// is testable against a tempdir. `content: None, exists: false` for a
645/// genuinely missing file (the common case — no AgentMux-spawned Claude
646/// agent on this host has one today, confirmed 2026-08-24) — real I/O
647/// errors (permission denied, etc.) still propagate as `Err`, not
648/// silently folded into "missing."
649#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
650#[ts(export, export_to = "../../../frontend/types/rpc/")]
651pub struct ClaudeGlobalConfig {
652    pub path: String,
653    /// Genuinely `string | null`, not an optional property: a plain
654    /// `Option<String>` with no `skip_serializing_if`, so the key is always
655    /// present and carries `null` when the file does not exist. That
656    /// distinction is load-bearing here — `exists: false` with
657    /// `content: null` is the meaningful "no file" answer, not an absent key.
658    pub content: Option<String>,
659    pub exists: bool,
660}
661
662fn read_claude_global_config(claude_dir: &std::path::Path) -> std::io::Result<ClaudeGlobalConfig> {
663    let path = claude_dir.join("CLAUDE.md");
664    let (content, exists) = match std::fs::read_to_string(&path) {
665        Ok(c) => (Some(c), true),
666        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, false),
667        Err(e) => return Err(e),
668    };
669    Ok(ClaudeGlobalConfig { path: path.to_string_lossy().into_owned(), content, exists })
670}
671
672// Covers getclaudeglobalconfig (resolve_shared_claude_provider_dir).
673// The sibling getclaudehostconfig (~/.claude) handler was removed
674// 2026-09-01 — SPEC_ARMORY_DROP_HOST_CLI_CONFIG_BLOCK_2026_09_01.md.
675// See docs/specs/SPEC_SURFACE_CLAUDE_GLOBAL_CONFIG_2026_08_24.md §5.
676#[cfg(test)]
677mod global_memory_sections_tests {
678    use super::requested_agent_kind;
679
680    #[test]
681    fn the_agent_kind_is_host_or_container_and_host_by_default() {
682        assert_eq!(requested_agent_kind(None), Ok("host"));
683        assert_eq!(requested_agent_kind(Some("host")), Ok("host"));
684        assert_eq!(requested_agent_kind(Some("container")), Ok("container"));
685        assert!(requested_agent_kind(Some("vm")).is_err());
686    }
687}
688
689#[cfg(test)]
690mod claude_global_config_tests {
691    use super::*;
692
693    #[test]
694    fn returns_content_and_exists_true_when_the_file_is_present() {
695        let dir = tempfile::tempdir().unwrap();
696        std::fs::write(dir.path().join("CLAUDE.md"), "# My global rules\n").unwrap();
697
698        let result = read_claude_global_config(dir.path()).unwrap();
699        assert!(result.exists);
700        assert_eq!(result.content.as_deref(), Some("# My global rules\n"));
701        assert_eq!(result.path, dir.path().join("CLAUDE.md").to_string_lossy());
702    }
703
704    #[test]
705    fn returns_none_content_and_exists_false_when_the_file_is_missing_not_an_error() {
706        let dir = tempfile::tempdir().unwrap();
707        // Deliberately no CLAUDE.md written — the common case on a host
708        // where the user never created one.
709
710        let result = read_claude_global_config(dir.path()).unwrap();
711        assert!(!result.exists);
712        assert!(result.content.is_none());
713        // The path is still reported even when nothing exists there yet —
714        // useful information on its own (SPEC_SURFACE_CLAUDE_GLOBAL_CONFIG_2026_08_24.md §2.3).
715        assert_eq!(result.path, dir.path().join("CLAUDE.md").to_string_lossy());
716    }
717
718    #[test]
719    fn returns_content_for_an_empty_file_not_treated_as_missing() {
720        let dir = tempfile::tempdir().unwrap();
721        std::fs::write(dir.path().join("CLAUDE.md"), "").unwrap();
722
723        let result = read_claude_global_config(dir.path()).unwrap();
724        assert!(result.exists);
725        assert_eq!(result.content.as_deref(), Some(""));
726    }
727}
728
729#[cfg(test)]
730mod delete_memory_tests {
731    use super::*;
732    use crate::backend::rpc_types::{RpcMessage, COMMAND_DELETE_MEMORY, COMMAND_DELETE_SYSTEM_MEMORY};
733    use crate::server::tests::test_state;
734
735    fn seed_memory(state: &AppState, id: &str, is_system: bool) {
736        let now = agentmux_common::time::now_ms();
737        let memory = Bundle {
738            id: id.to_string(),
739            name: "Test Bundle".to_string(),
740            description: String::new(),
741            is_blank: false,
742            is_global: false,
743            provider: String::new(),
744            model: String::new(),
745            instructions: String::new(),
746            instructions_by_provider: "{}".to_string(),
747            context_files: "[]".to_string(),
748            mcp_servers: "[]".to_string(),
749            skills: "[]".to_string(),
750            sort_order: 0,
751            created_at: now,
752            updated_at: now,
753            is_system,
754        };
755        if is_system {
756            state.id_store.bundle_upsert_system(&memory).unwrap();
757        } else {
758            state.id_store.bundle_upsert(&memory).unwrap();
759        }
760    }
761
762    async fn send(engine: &Arc<WshRpcEngine>, output_rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>, command: &str, id: &str) -> RpcMessage {
763        engine.handle_message(RpcMessage {
764            command: command.to_string(),
765            reqid: format!("req-{command}"),
766            data: Some(serde_json::json!({ "id": id })),
767            ..Default::default()
768        });
769        tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
770            .await
771            .unwrap()
772            .unwrap()
773    }
774
775    /// The wire behaviour a caller depends on is unchanged by the migration:
776    /// deleting a real row answers `{ deleted: true }`, and the schema now
777    /// records the exact type names ts-rs generated bindings from.
778    #[tokio::test]
779    async fn deletememory_deletes_a_real_row_and_reports_it() {
780        let state = test_state();
781        seed_memory(&state, "mem-1", false);
782        let (engine, mut output_rx) = WshRpcEngine::new();
783        register(&engine, &state);
784
785        let resp = send(&engine, &mut output_rx, COMMAND_DELETE_MEMORY, "mem-1").await;
786        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
787        let result: DeleteBundleResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
788        assert!(result.deleted);
789
790        assert!(state.id_store.bundle_get("mem-1").unwrap().is_none());
791    }
792
793    /// Deleting an id that never existed is not an error — it answers
794    /// `{ deleted: false }`, same as the pre-migration `json!({"deleted": ..})`
795    /// body did.
796    #[tokio::test]
797    async fn deletememory_reports_false_for_an_unknown_id() {
798        let state = test_state();
799        let (engine, mut output_rx) = WshRpcEngine::new();
800        register(&engine, &state);
801
802        let resp = send(&engine, &mut output_rx, COMMAND_DELETE_MEMORY, "does-not-exist").await;
803        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
804        let result: DeleteBundleResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
805        assert!(!result.deleted);
806    }
807
808    #[tokio::test]
809    async fn deletesystemmemory_deletes_a_real_system_row_and_reports_it() {
810        let state = test_state();
811        seed_memory(&state, "sysmem-1", true);
812        let (engine, mut output_rx) = WshRpcEngine::new();
813        register(&engine, &state);
814
815        let resp = send(&engine, &mut output_rx, COMMAND_DELETE_SYSTEM_MEMORY, "sysmem-1").await;
816        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
817        let result: DeleteBundleResult = serde_json::from_value(resp.data.expect("expected result data")).unwrap();
818        assert!(result.deleted);
819    }
820
821    /// Both commands are recorded in the engine's schema with their exact
822    /// type names, and share ONE response type (DeleteBundleResult) the
823    /// same way they already shared CommandDeleteBundleData as a request.
824    #[tokio::test]
825    async fn register_typed_records_both_delete_commands_sharing_one_response_type() {
826        let state = test_state();
827        let (engine, _rx) = WshRpcEngine::new();
828        register(&engine, &state);
829        let schema = engine.schema_json();
830        let rows = schema.as_array().unwrap();
831        for cmd in [COMMAND_DELETE_MEMORY, COMMAND_DELETE_SYSTEM_MEMORY] {
832            let row = rows
833                .iter()
834                .find(|r| r["command"] == cmd)
835                .unwrap_or_else(|| panic!("{cmd} missing from the schema"));
836            assert_eq!(row["requestName"], "CommandDeleteBundleData");
837            assert_eq!(row["responseName"], "DeleteBundleResult");
838        }
839        // The rest of the bundle CRUD surface is now migrated too. This block
840        // previously asserted these five were ABSENT from the schema, which was
841        // a statement about a temporary state ("not migrated yet"), not an
842        // invariant -- so migrating them correctly made it fail. It now asserts
843        // what each one actually records, which is the thing worth pinning.
844        //
845        // `upsertmemory`/`upsertsystemmemory` take `CommandUpsertBundleData`:
846        // the storage `Bundle` itself, flattened (the upsert body IS the
847        // entity), plus an optional `base_sha256`. Only `id` and `name` are
848        // required on the wire (every other field has a serde default), which
849        // is what `BundleUpsertInput` expresses on the frontend side.
850        for (cmd, req, resp) in [
851            (COMMAND_GET_MEMORY, "CommandGetBundleData", "Bundle"),
852            (COMMAND_UPSERT_MEMORY, "CommandUpsertBundleData", "Bundle"),
853            (COMMAND_UPSERT_SYSTEM_MEMORY, "CommandUpsertBundleData", "Bundle"),
854            (COMMAND_GLOBAL_MEMORY_HISTORY, "CommandGlobalMemoryHistoryData", "GlobalMemoryHistoryResult"),
855            (COMMAND_GLOBAL_MEMORY_DIFF, "CommandGlobalMemoryDiffData", "GlobalMemoryDiffResult"),
856            (COMMAND_GLOBAL_MEMORY_REVERT, "CommandGlobalMemoryRevertData", "GlobalMemoryRevertResult"),
857            (COMMAND_GLOBAL_MEMORY_REMOVED, "CommandGlobalMemoryRemovedData", "GlobalMemoryRemovedResult"),
858            (COMMAND_GLOBAL_MEMORY_REACH_LIST, "CommandGlobalMemoryReachListData", "GlobalMemoryReachListResult"),
859            (COMMAND_GLOBAL_MEMORY_SET_REACH, "CommandGlobalMemorySetReachData", "GlobalMemoryReachEntry"),
860            (
861                COMMAND_REORDER_GLOBAL_BRAIN,
862                "CommandReorderGlobalBundlesData",
863                "ReorderGlobalBundlesResult",
864            ),
865            (
866                COMMAND_GET_CLAUDE_GLOBAL_CONFIG,
867                "CommandGetClaudeGlobalConfigData",
868                "ClaudeGlobalConfig",
869            ),
870        ] {
871            let row = rows
872                .iter()
873                .find(|r| r["command"] == cmd)
874                .unwrap_or_else(|| panic!("{cmd} missing from the schema"));
875            assert_eq!(row["requestName"], req, "{cmd} request");
876            assert_eq!(row["responseName"], resp, "{cmd} response");
877        }
878
879        // `listmemories` answers with `Vec<Bundle>`. `short_name` deliberately
880        // leaves a generic whole (truncating `Vec<a::B>` at the last `::`
881        // would yield `B>`, which names nothing), so match on the shape rather
882        // than pinning the full crate path.
883        let list = rows
884            .iter()
885            .find(|r| r["command"] == COMMAND_LIST_MEMORIES)
886            .expect("listmemories missing from the schema");
887        assert_eq!(list["requestName"], "CommandListBundlesData");
888        let list_resp = list["responseName"].as_str().unwrap_or_default();
889        assert!(
890            list_resp.starts_with("alloc::vec::Vec<") && list_resp.ends_with("::Bundle>"),
891            "listmemories should answer with a Vec of Bundle, got {list_resp}"
892        );
893    }
894}
895
896// Conditional saves (`base_sha256`) and Memory → Global's history
897// commands — SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.3/§2.4.
898#[cfg(test)]
899mod global_memory_ui_tests {
900    use super::*;
901    use crate::backend::rpc_types::RpcMessage;
902    use crate::backend::rpc_types::GlobalMemoryReachEntry;
903    use crate::server::tests::test_state;
904
905    async fn call(
906        engine: &Arc<WshRpcEngine>,
907        rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
908        command: &str,
909        data: serde_json::Value,
910    ) -> RpcMessage {
911        let reqid = format!("req-{}", uuid::Uuid::new_v4());
912        engine.handle_message(RpcMessage {
913            command: command.to_string(),
914            reqid: reqid.clone(),
915            data: Some(data),
916            ..Default::default()
917        });
918        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
919            .await
920            .unwrap()
921            .unwrap();
922        assert_eq!(resp.resid, reqid);
923        resp
924    }
925
926    async fn ok<T: serde::de::DeserializeOwned>(
927        engine: &Arc<WshRpcEngine>,
928        rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
929        command: &str,
930        data: serde_json::Value,
931    ) -> T {
932        let resp = call(engine, rx, command, data).await;
933        assert!(resp.error.is_empty(), "{command}: unexpected error: {}", resp.error);
934        serde_json::from_value(resp.data.unwrap_or(serde_json::Value::Null)).unwrap()
935    }
936
937    fn hash(name: &str, instructions: &str) -> String {
938        crate::backend::storage::bundle_versions::content_hash(name, instructions)
939    }
940
941    /// Creates an ordinary Global Memory entry through the real save path
942    /// and returns its id.
943    async fn create_entry(
944        engine: &Arc<WshRpcEngine>,
945        rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
946        name: &str,
947        instructions: &str,
948    ) -> String {
949        let saved: Bundle = ok(engine, rx, COMMAND_UPSERT_MEMORY, json!({
950            "id": "", "name": name, "is_global": true, "instructions": instructions,
951        }))
952        .await;
953        saved.id
954    }
955
956    #[tokio::test]
957    async fn upsertmemory_with_a_matching_base_saves() {
958        let state = test_state();
959        let (engine, mut rx) = WshRpcEngine::new();
960        register(&engine, &state);
961        let id = create_entry(&engine, &mut rx, "Rules", "v1").await;
962
963        let resp = call(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
964            "id": id, "name": "Rules", "is_global": true, "instructions": "v2",
965            "base_sha256": hash("Rules", "v1"),
966        }))
967        .await;
968        assert!(resp.error.is_empty(), "unexpected error: {}", resp.error);
969        assert_eq!(state.id_store.bundle_get(&id).unwrap().unwrap().instructions, "v2");
970    }
971
972    #[tokio::test]
973    async fn upsertmemory_with_a_stale_base_is_a_conflict_and_changes_nothing() {
974        let state = test_state();
975        let (engine, mut rx) = WshRpcEngine::new();
976        register(&engine, &state);
977        let id = create_entry(&engine, &mut rx, "Rules", "v1").await;
978        // Someone else saves while the human's draft is still based on v1.
979        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
980            "id": id, "name": "Rules", "is_global": true, "instructions": "agent edit",
981        }))
982        .await;
983        let versions_before = state.id_store.bundle_version_list(&id).unwrap().len();
984
985        let resp = call(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
986            "id": id, "name": "Rules", "is_global": true, "instructions": "human draft",
987            "base_sha256": hash("Rules", "v1"),
988        }))
989        .await;
990        assert!(resp.error.contains("conflict:"), "expected a conflict, got {:?}", resp.error);
991        assert_eq!(state.id_store.bundle_get(&id).unwrap().unwrap().instructions, "agent edit");
992        assert_eq!(state.id_store.bundle_version_list(&id).unwrap().len(), versions_before);
993    }
994
995    #[tokio::test]
996    async fn upsertmemory_without_a_base_behaves_as_before() {
997        let state = test_state();
998        let (engine, mut rx) = WshRpcEngine::new();
999        register(&engine, &state);
1000        let id = create_entry(&engine, &mut rx, "Rules", "v1").await;
1001        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
1002            "id": id, "name": "Rules", "is_global": true, "instructions": "v2",
1003        }))
1004        .await;
1005        assert_eq!(state.id_store.bundle_get(&id).unwrap().unwrap().instructions, "v2");
1006    }
1007
1008    #[tokio::test]
1009    async fn upsertsystemmemory_honours_the_base_too() {
1010        let state = test_state();
1011        let (engine, mut rx) = WshRpcEngine::new();
1012        register(&engine, &state);
1013        let saved: Bundle = ok(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1014            "id": "sys-base", "name": "Policy", "instructions": "v1",
1015        }))
1016        .await;
1017        let resp = call(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1018            "id": saved.id, "name": "Policy", "instructions": "draft",
1019            "base_sha256": hash("Policy", "something else"),
1020        }))
1021        .await;
1022        assert!(resp.error.contains("conflict:"), "expected a conflict, got {:?}", resp.error);
1023        assert_eq!(state.id_store.bundle_get("sys-base").unwrap().unwrap().instructions, "v1");
1024
1025        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1026            "id": "sys-base", "name": "Policy", "instructions": "v2",
1027            "base_sha256": hash("Policy", "v1"),
1028        }))
1029        .await;
1030        assert_eq!(state.id_store.bundle_get("sys-base").unwrap().unwrap().instructions, "v2");
1031    }
1032
1033    /// A system-tier save by a registered agent is recorded as that agent, not the window; both are non-seeder writers.
1034    #[tokio::test]
1035    async fn upsertsystemmemory_records_an_agent_as_the_agent() {
1036        use crate::backend::rpc_types::RpcContext;
1037        let state = test_state();
1038        let (engine, mut rx) = WshRpcEngine::new();
1039        register(&engine, &state);
1040        engine.set_rpc_context(RpcContext { agent_id: "sys-writer".to_string(), ..Default::default() });
1041        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1042            "id": "sys-attr", "name": "Policy", "instructions": "v1",
1043        }))
1044        .await;
1045        let versions = state.id_store.bundle_version_list("sys-attr").unwrap();
1046        assert_eq!((versions[0].written_by.as_str(), versions[0].source.as_str()), ("sys-writer", "agent"));
1047        engine.set_rpc_context(RpcContext::operator_for_tests());
1048        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1049            "id": "sys-attr", "name": "Policy", "instructions": "v2",
1050        }))
1051        .await;
1052        let versions = state.id_store.bundle_version_list("sys-attr").unwrap();
1053        assert_eq!((versions[0].written_by.as_str(), versions[0].source.as_str()), ("armory-ui", "human"));
1054    }
1055
1056    #[tokio::test]
1057    async fn history_diff_and_revert_round_trip() {
1058        let state = test_state();
1059        let (engine, mut rx) = WshRpcEngine::new();
1060        register(&engine, &state);
1061        assert!(engine.mark_operator_proven());
1062        let id = create_entry(&engine, &mut rx, "Rules", "line one\n").await;
1063        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
1064            "id": id, "name": "Rules", "is_global": true, "instructions": "line one\nline two\n",
1065        }))
1066        .await;
1067
1068        let history: GlobalMemoryHistoryResult =
1069            ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_HISTORY, json!({ "id": id })).await;
1070        assert_eq!(history.versions.len(), 2);
1071        let (newest, oldest) = (history.versions[0].clone(), history.versions[1].clone());
1072        assert_eq!(newest.written_by, "armory-ui");
1073        // The latest version's hash is what the editor sends as its base.
1074        assert_eq!(newest.content_hash, hash("Rules", "line one\nline two\n"));
1075
1076        let diff: GlobalMemoryDiffResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_DIFF, json!({
1077            "id": id, "from_version_id": oldest.id, "to_version_id": newest.id,
1078        }))
1079        .await;
1080        assert_eq!(diff.diff, "  line one\n+ line two\n");
1081
1082        let reverted: GlobalMemoryRevertResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1083            "id": id, "target_version_id": oldest.id,
1084        }))
1085        .await;
1086        let v = reverted.version.expect("an ordinary revert always records a version");
1087        assert_eq!(v.source, "revert");
1088        assert_eq!(v.written_by, "armory-ui");
1089        assert!(v.source_detail.contains(&oldest.id));
1090        assert_eq!(state.id_store.bundle_get(&id).unwrap().unwrap().instructions, "line one\n");
1091        assert_eq!(state.id_store.bundle_version_list(&id).unwrap().len(), 3, "revert appends, never rewrites");
1092    }
1093
1094    #[tokio::test]
1095    async fn diff_refuses_a_version_from_another_entry() {
1096        let state = test_state();
1097        let (engine, mut rx) = WshRpcEngine::new();
1098        register(&engine, &state);
1099        let a = create_entry(&engine, &mut rx, "A", "a").await;
1100        let b = create_entry(&engine, &mut rx, "B", "b").await;
1101        let va = state.id_store.bundle_version_list(&a).unwrap()[0].id.clone();
1102        let vb = state.id_store.bundle_version_list(&b).unwrap()[0].id.clone();
1103        let resp = call(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_DIFF, json!({
1104            "id": a, "from_version_id": va, "to_version_id": vb,
1105        }))
1106        .await;
1107        assert!(resp.error.contains("do not belong"), "got {:?}", resp.error);
1108        let resp = call(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1109            "id": a, "target_version_id": vb,
1110        }))
1111        .await;
1112        assert!(resp.error.contains("does not belong"), "got {:?}", resp.error);
1113    }
1114
1115    #[tokio::test]
1116    async fn history_refuses_a_non_global_bundle() {
1117        let state = test_state();
1118        let (engine, mut rx) = WshRpcEngine::new();
1119        register(&engine, &state);
1120        let saved: Bundle = ok(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
1121            "id": "", "name": "Private preset", "is_global": false, "instructions": "x",
1122        }))
1123        .await;
1124        let resp = call(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_HISTORY, json!({ "id": saved.id })).await;
1125        assert!(resp.error.contains("not a Global Memory entry"), "got {:?}", resp.error);
1126    }
1127
1128    // The pane's Remove leaves a record; the removed entry is listed with who
1129    // removed it, and `globalmemory:revert` to that record restores it as
1130    // Global Memory, last in the order (it would sort first by name).
1131    #[tokio::test]
1132    async fn a_removed_entry_is_listed_and_restored_through_revert() {
1133        let state = test_state();
1134        let (engine, mut rx) = WshRpcEngine::new();
1135        register(&engine, &state);
1136        assert!(engine.mark_operator_proven());
1137        let id = create_entry(&engine, &mut rx, "Alpha", "the rules").await;
1138        let other = create_entry(&engine, &mut rx, "Zed", "other rules").await;
1139        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_MEMORY, json!({
1140            "id": id, "name": "Alpha", "is_global": false, "instructions": "the rules",
1141        }))
1142        .await;
1143
1144        let removed: GlobalMemoryRemovedResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REMOVED, json!({})).await;
1145        assert_eq!(removed.entries.len(), 1);
1146        let entry = removed.entries[0].clone();
1147        assert_eq!((entry.id.as_str(), entry.name.as_str(), entry.removed_by.as_str()), (id.as_str(), "Alpha", "armory-ui"));
1148        assert!(entry.removed_at > 0);
1149
1150        // Its history is still reachable, and says what happened.
1151        let history: GlobalMemoryHistoryResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_HISTORY, json!({ "id": id })).await;
1152        assert_eq!((history.versions[0].id.as_str(), history.versions[0].source.as_str()), (entry.version_id.as_str(), "remove"));
1153
1154        let restored: GlobalMemoryRevertResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1155            "id": id, "target_version_id": entry.version_id,
1156        }))
1157        .await;
1158        assert_eq!(restored.version.expect("a restore records a version").source, "revert");
1159        let row = state.id_store.bundle_get(&id).unwrap().unwrap();
1160        assert!(row.is_global);
1161        assert_eq!(row.instructions, "the rules");
1162        let order: Vec<String> = state.id_store.bundle_list_global().unwrap().into_iter().map(|b| b.id).collect();
1163        assert_eq!(order, [other, id], "restored last");
1164        let after: GlobalMemoryRemovedResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REMOVED, json!({})).await;
1165        assert!(after.entries.is_empty());
1166    }
1167
1168    // The pane's reach switch: an entry that existed before reach stays on this machine, the
1169    // switch sends it to the fleet and back, and the entry's text and time are left alone.
1170    #[tokio::test]
1171    async fn the_pane_lists_and_switches_an_entrys_reach() {
1172        let state = test_state();
1173        state.id_store.bundle_scope_ensure().unwrap();
1174        let (engine, mut rx) = WshRpcEngine::new();
1175        register(&engine, &state);
1176        let id = create_entry(&engine, &mut rx, "Alpha", "the rules").await;
1177        let before = state.id_store.bundle_get(&id).unwrap().unwrap();
1178
1179        let reach_of = |list: &GlobalMemoryReachListResult, id: &str| {
1180            list.entries.iter().find(|e| e.id == id).map(|e| e.reach.clone())
1181        };
1182        let list: GlobalMemoryReachListResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REACH_LIST, json!({})).await;
1183        assert_eq!(reach_of(&list, &id).as_deref(), Some("fleet"), "a new entry follows the fleet");
1184
1185        let set: GlobalMemoryReachEntry = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_SET_REACH, json!({ "id": id, "reach": "machine" })).await;
1186        assert_eq!((set.id.as_str(), set.reach.as_str()), (id.as_str(), "machine"));
1187        let list: GlobalMemoryReachListResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REACH_LIST, json!({})).await;
1188        assert_eq!(reach_of(&list, &id).as_deref(), Some("machine"));
1189        let after = state.id_store.bundle_get(&id).unwrap().unwrap();
1190        assert_eq!((after.instructions, after.updated_at), (before.instructions, before.updated_at), "the text and its time are untouched");
1191
1192        ok::<GlobalMemoryReachEntry>(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_SET_REACH, json!({ "id": id, "reach": "fleet" })).await;
1193        let list: GlobalMemoryReachListResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REACH_LIST, json!({})).await;
1194        assert_eq!(reach_of(&list, &id).as_deref(), Some("fleet"));
1195    }
1196
1197    // The switch refuses what the MCP tool refuses: a system entry stays on this machine, and
1198    // a reach is one of two words.
1199    #[tokio::test]
1200    async fn the_pane_cannot_send_a_system_entry_away_or_set_a_made_up_reach() {
1201        let state = test_state();
1202        state.id_store.bundle_scope_ensure().unwrap();
1203        let mut sys: Bundle = serde_json::from_value(json!({ "id": "sys-reach", "name": "Sys", "instructions": "x", "is_global": true, "is_system": true })).unwrap();
1204        sys.is_system = true;
1205        state.id_store.bundle_upsert_system(&sys).unwrap();
1206        let (engine, mut rx) = WshRpcEngine::new();
1207        register(&engine, &state);
1208        let id = create_entry(&engine, &mut rx, "Alpha", "the rules").await;
1209
1210        let list: GlobalMemoryReachListResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REACH_LIST, json!({})).await;
1211        assert!(list.entries.iter().all(|e| e.id != "sys-reach" || e.reach == "machine"));
1212        let sys = call(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_SET_REACH, json!({ "id": "sys-reach", "reach": "fleet" })).await;
1213        assert!(sys.error.contains("system"), "a system entry cannot be sent to the fleet");
1214        let bad = call(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_SET_REACH, json!({ "id": id, "reach": "everywhere" })).await;
1215        assert!(bad.error.contains("reach must be"), "a reach is fleet or machine");
1216    }
1217
1218    // Unlike the MCP tools, Memory → Global sees system-tier history — it can
1219    // already edit those entries. A no-op revert of one records nothing.
1220    #[tokio::test]
1221    async fn system_entries_have_history_and_a_no_op_revert_records_nothing() {
1222        let state = test_state();
1223        let (engine, mut rx) = WshRpcEngine::new();
1224        register(&engine, &state);
1225        for body in ["v1", "v2"] {
1226            ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1227                "id": "sys-hist", "name": "Policy", "instructions": body,
1228            }))
1229            .await;
1230        }
1231        let history: GlobalMemoryHistoryResult =
1232            ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_HISTORY, json!({ "id": "sys-hist" })).await;
1233        assert_eq!(history.versions.len(), 2);
1234
1235        let latest = history.versions[0].id.clone();
1236        let reverted: GlobalMemoryRevertResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1237            "id": "sys-hist", "target_version_id": latest,
1238        }))
1239        .await;
1240        assert!(reverted.version.is_none());
1241
1242        let oldest = history.versions[1].id.clone();
1243        let reverted: GlobalMemoryRevertResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1244            "id": "sys-hist", "target_version_id": oldest,
1245        }))
1246        .await;
1247        assert_eq!(reverted.version.expect("a real revert records a version").source, "revert");
1248        let row = state.id_store.bundle_get("sys-hist").unwrap().unwrap();
1249        assert_eq!(row.instructions, "v1");
1250        assert!(row.is_system, "reverting must not demote a system entry");
1251    }
1252
1253    // Reverting a system entry to the text AgentMux seeded hands it back to
1254    // the seeder: later Operator Config updates apply again.
1255    #[tokio::test]
1256    async fn reverting_a_system_entry_to_seeded_text_restores_seeder_ownership() {
1257        use crate::backend::operator_config_seed::WRITTEN_BY;
1258        let state = test_state();
1259        let (engine, mut rx) = WshRpcEngine::new();
1260        register(&engine, &state);
1261        let mut seeded = Bundle {
1262            id: "sys-own".into(),
1263            name: "Policy".into(),
1264            description: String::new(),
1265            is_blank: false,
1266            is_global: true,
1267            provider: String::new(),
1268            model: String::new(),
1269            instructions: "seeded v1".into(),
1270            instructions_by_provider: "{}".into(),
1271            context_files: "[]".into(),
1272            mcp_servers: "[]".into(),
1273            skills: "[]".into(),
1274            sort_order: 0,
1275            created_at: 1,
1276            updated_at: 1,
1277            is_system: true,
1278        };
1279        state.id_store.bundle_reseed_system_if_owned(&seeded, WRITTEN_BY, "test_seed", "{}").unwrap();
1280        ok::<Bundle>(&engine, &mut rx, COMMAND_UPSERT_SYSTEM_MEMORY, json!({
1281            "id": "sys-own", "name": "Policy", "instructions": "local edit",
1282        }))
1283        .await;
1284
1285        let history: GlobalMemoryHistoryResult =
1286            ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_HISTORY, json!({ "id": "sys-own" })).await;
1287        let seeded_version = history.versions.iter().find(|v| v.written_by == WRITTEN_BY).unwrap().id.clone();
1288        let reverted: GlobalMemoryRevertResult = ok(&engine, &mut rx, COMMAND_GLOBAL_MEMORY_REVERT, json!({
1289            "id": "sys-own", "target_version_id": seeded_version,
1290        }))
1291        .await;
1292        assert_eq!(reverted.version.unwrap().written_by, WRITTEN_BY);
1293
1294        seeded.instructions = "seeded v2".into();
1295        let outcome = state.id_store.bundle_reseed_system_if_owned(&seeded, WRITTEN_BY, "test_seed", "{}").unwrap();
1296        assert!(!matches!(outcome, crate::backend::storage::BundleReseedOutcome::SkippedLocalEdit), "{outcome:?}");
1297        assert_eq!(state.id_store.bundle_get("sys-own").unwrap().unwrap().instructions, "seeded v2");
1298    }
1299}
1300
1301#[cfg(test)]
1302#[path = "bundle_handler_tests.rs"]
1303mod bundle_handler_tests;