1use super::*;
8use crate::server::api_error::ApiError;
9use crate::backend::storage::bundle_scope::{SCOPE_FLEET, SCOPE_MACHINE};
10
11pub(crate) struct GlobalMemoryWriteProvenance<'a> {
17 pub source: &'a str,
18 pub detail: &'a str,
19}
20
21fn 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 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
43pub(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
57type BeforeWrite<'a> = Option<&'a dyn Fn(&str) -> Result<(), String>>;
59
60#[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 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 if existing.is_system {
98 return Err(ApiError::refused("globalmemory.write: cannot modify a system Global Memory entry through this API"));
99 }
100 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 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 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
181fn 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
192fn 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
199pub(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
214pub(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 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
235fn 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
241pub(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 let sync = crate::server::remote_ops::fleet_sync::status::global().snapshot();
265 Ok(json!({ "entries": entries, "removed": removed, "sync": sync }))
266}
267
268pub(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
279pub(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
296pub(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#[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 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
347pub(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
371pub(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 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 .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
427fn version_meta_json(meta: crate::backend::rpc_types::GlobalMemoryVersionMeta) -> serde_json::Value {
430 serde_json::to_value(meta).unwrap_or_default()
431}
432
433fn 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
462pub(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
479pub(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
510pub(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
527pub(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 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 .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}