Skip to main content

agentmux_srv_core/backend/memory/
fleet.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One Global Memory for the fleet
5//! (task #12439, "agents operate other machines", section 4.6).
6//!
7//! A Global Memory entry with scope `fleet` (see `storage::bundle_scope`) is
8//! pushed to every proven machine with the remote ops `memory.global.put` and
9//! `memory.global.remove`, and a machine lists what it holds with
10//! `memory.global.list` so the other side can catch it up. This module is the
11//! machine-independent part: what an entry carries over the wire, which write
12//! wins, and applying a received write to the local store. The transport that
13//! carries the ops is `server::remote_ops`.
14//!
15//! **Last write wins.** An entry's `updated_at` is stamped by the machine that
16//! wrote it and kept as is on every machine that applies it, so all machines
17//! agree on it. The newer `updated_at` wins; on a tie the larger content hash
18//! wins, so every machine picks the same side. A removal is a write too: it
19//! carries the time it happened and wins or loses the same way, so an entry
20//! removed on one machine and edited later on another comes back.
21//!
22//! **What is not carried.** `skills`, `provider` and `model` name things that
23//! exist per machine, `sort_order` is a position on one machine's list, and
24//! `mcp_servers` is always empty. AgentMux's own entries (system tier, `seed-`
25//! ids) and the blank bundle never leave or enter. A write for an entry that is
26//! `machine` scope here is skipped, so a machine keeps what its owner kept. The
27//! exception is an entry whose `machine` row is only the default the scope table
28//! gave what existed when it was made (`storage::bundle_scope`): a newer write
29//! replaces that one, the entry follows the fleet from then on, and the old text
30//! stays in its history. The write is answered `adopted` so the sender, and this
31//! machine's sync state, can say which entries changed.
32//!
33//! **No echo.** A write applied from another machine is recorded with source
34//! [`FLEET_SOURCE`]; the push on change (a later PR) does not push those back.
35
36use std::collections::HashMap;
37
38use serde::{Deserialize, Serialize};
39use sha2::{Digest, Sha256};
40
41use crate::backend::storage::bundles::REMOVE_SOURCE;
42use crate::backend::storage::error::StoreError;
43use crate::backend::storage::store::{Bundle, Store};
44
45/// The `db_bundle_versions.source` of a write that came from another machine.
46pub const FLEET_SOURCE: &str = "fleet";
47
48/// The `source` of the version that keeps the text a fleet write is about to replace.
49const BASELINE_SOURCE: &str = "fleet-baseline";
50
51/// Same bound as `globalmemory.write`: every agent's launch parses and injects this.
52const MAX_INSTRUCTIONS: usize = 1024 * 1024;
53
54/// The hash a removal carries, so a removal and an edit with the same
55/// timestamp resolve the same way on every machine.
56const REMOVED_HASH: &str = "removed";
57
58fn default_json_object() -> String {
59    "{}".to_string()
60}
61
62fn default_json_array() -> String {
63    "[]".to_string()
64}
65
66/// A Global Memory entry as it travels between machines: `memory.global.put`'s params.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub struct FleetEntry {
69    pub id: String,
70    pub name: String,
71    #[serde(default)]
72    pub description: String,
73    pub instructions: String,
74    #[serde(default = "default_json_object")]
75    pub instructions_by_provider: String,
76    #[serde(default = "default_json_array")]
77    pub context_files: String,
78    /// When the writing machine saved it (ms since the epoch).
79    pub updated_at: i64,
80    /// Who last wrote it where it was written (`armory-ui` for the Memory pane, an agent's id, or
81    /// `slug@machine` for a copy that came from elsewhere). Shown in the history; not part of the
82    /// content, so it is not hashed, and never an authority.
83    #[serde(default)]
84    pub edited_by: String,
85}
86
87impl FleetEntry {
88    /// The entry's content hash: what differs between two copies.
89    pub fn hash(&self) -> String {
90        content_hash(&self.name, &self.description, &self.instructions, &self.instructions_by_provider, &self.context_files)
91    }
92}
93
94fn content_hash(name: &str, description: &str, instructions: &str, by_provider: &str, context_files: &str) -> String {
95    let mut hasher = Sha256::new();
96    for part in [name, description, instructions, by_provider, context_files] {
97        hasher.update(part.as_bytes());
98        hasher.update(b"\0");
99    }
100    hex::encode(hasher.finalize())
101}
102
103/// `memory.global.remove`'s params.
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct FleetRemoval {
106    pub id: String,
107    /// When the writing machine removed it.
108    pub removed_at: i64,
109    /// Who removed it there; see [`FleetEntry::edited_by`].
110    #[serde(default)]
111    pub edited_by: String,
112}
113
114/// What a machine holds for one entry, without its text: `memory.global.list`'s rows.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct FleetMeta {
117    pub id: String,
118    pub updated_at: i64,
119    pub hash: String,
120    pub removed: bool,
121}
122
123/// Who a write is attributed to on this machine: the remote agent as
124/// `slug@machine`, and its uid when the transport knows it. Never the operator.
125#[derive(Debug, Clone, Copy)]
126pub struct Actor<'a> {
127    pub label: &'a str,
128    pub uid: &'a str,
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Applied {
133    Created,
134    Updated,
135    /// The entry had been removed here; the newer write brought it back.
136    Restored,
137    /// The entry was `machine` here only by default; it now follows the fleet, and the newer
138    /// write replaced its text (the old text is in its history).
139    Adopted,
140    Removed,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum Skipped {
145    /// The same content is already here.
146    Same,
147    /// What is here is newer.
148    Older,
149    /// This machine keeps the entry to itself.
150    MachineScope,
151    /// AgentMux's own entry, the blank bundle, or an id the fleet never carries.
152    Protected,
153    /// The id belongs to a bundle that is not Global Memory (an agent's own preset).
154    NotMemory,
155    /// Another entry here (a different id) already holds this name, and it is live: an entry copied
156    /// by hand, or one of this machine's own. Names are unique, so the two cannot both be kept; a
157    /// person on this machine says which stays (rename or remove one).
158    NameTaken,
159    /// A removal for an entry this machine already removed.
160    AlreadyRemoved,
161    /// A removal for an entry this machine never had.
162    Unknown,
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum Outcome {
167    Applied(Applied),
168    Skipped(Skipped),
169}
170
171impl Outcome {
172    /// What the remote op answers: `{"outcome": ..., "reason": ...}` (a reason only for a skip).
173    pub fn to_json(self) -> serde_json::Value {
174        match self {
175            Outcome::Applied(a) => serde_json::json!({ "outcome": match a {
176                Applied::Created => "created",
177                Applied::Updated => "updated",
178                Applied::Restored => "restored",
179                Applied::Adopted => "adopted",
180                Applied::Removed => "removed",
181            } }),
182            Outcome::Skipped(s) => serde_json::json!({ "outcome": "skipped", "reason": match s {
183                Skipped::Same => "same",
184                Skipped::Older => "older",
185                Skipped::MachineScope => "machine_scope",
186                Skipped::Protected => "protected",
187                Skipped::NotMemory => "not_memory",
188                Skipped::NameTaken => "name_taken",
189                Skipped::AlreadyRemoved => "already_removed",
190                Skipped::Unknown => "unknown",
191            } }),
192        }
193    }
194}
195
196#[derive(Debug)]
197pub enum FleetError {
198    /// The request is malformed; nothing was written.
199    Invalid(String),
200    Store(StoreError),
201}
202
203impl std::fmt::Display for FleetError {
204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205        match self {
206            FleetError::Invalid(m) => f.write_str(m),
207            FleetError::Store(e) => write!(f, "{e}"),
208        }
209    }
210}
211
212impl From<StoreError> for FleetError {
213    fn from(e: StoreError) -> Self {
214        FleetError::Store(e)
215    }
216}
217
218/// Whether a write with `(incoming_at, incoming_hash)` replaces what is here.
219fn wins(incoming_at: i64, incoming_hash: &str, local_at: i64, local_hash: &str) -> bool {
220    incoming_at > local_at || (incoming_at == local_at && incoming_hash > local_hash)
221}
222
223/// An id the fleet never carries: the blank bundle and AgentMux's re-seeded entries.
224fn is_fleet_id(id: &str) -> bool {
225    !id.is_empty() && id != "blank" && !id.starts_with("seed-")
226}
227
228fn validate_id(id: &str) -> Result<(), FleetError> {
229    if id.is_empty() || id.len() > 200 {
230        return Err(FleetError::Invalid("memory.global: id is required (at most 200 characters)".to_string()));
231    }
232    Ok(())
233}
234
235fn bundle_hash(b: &Bundle) -> String {
236    content_hash(&b.name, &b.description, &b.instructions, &b.instructions_by_provider, &b.context_files)
237}
238
239/// The entries that follow the fleet, including those removed here since:
240/// `memory.global.list`'s answer.
241pub fn list_meta(store: &Store) -> Result<Vec<FleetMeta>, StoreError> {
242    let machine_only = store.bundle_scope_machine_ids()?;
243    let carried = |b: &Bundle| is_fleet_id(&b.id) && !b.is_system && !b.is_blank && !machine_only.contains(&b.id);
244    let mut out: Vec<FleetMeta> = store
245        .bundle_list_global()?
246        .into_iter()
247        .filter(carried)
248        .map(|b| FleetMeta { hash: bundle_hash(&b), id: b.id, updated_at: b.updated_at, removed: false })
249        .collect();
250    out.extend(store.bundle_list_removed_global()?.into_iter().filter(carried).map(|b| FleetMeta {
251        id: b.id,
252        updated_at: b.updated_at,
253        hash: REMOVED_HASH.to_string(),
254        removed: true,
255    }));
256    Ok(out)
257}
258
259/// One entry to send, if it follows the fleet and is still Global Memory.
260pub fn entry_for_push(store: &Store, id: &str) -> Result<Option<FleetEntry>, StoreError> {
261    if !is_fleet_id(id) || store.bundle_scope_get(id)? != crate::backend::storage::bundle_scope::SCOPE_FLEET {
262        return Ok(None);
263    }
264    let Some(b) = store.bundle_get(id)?.filter(|b| b.is_global && !b.is_system && !b.is_blank) else {
265        return Ok(None);
266    };
267    let edited_by = store.bundle_version_latest(id)?.map(|v| v.written_by).unwrap_or_default();
268    Ok(Some(FleetEntry {
269        id: b.id,
270        name: b.name,
271        description: b.description,
272        instructions: b.instructions,
273        instructions_by_provider: b.instructions_by_provider,
274        context_files: b.context_files,
275        updated_at: b.updated_at,
276        edited_by,
277    }))
278}
279
280/// A short fingerprint of what a machine lists: it changes when an entry is added, edited or
281/// removed, so the sync only talks to a peer when there is something new for it.
282pub fn fingerprint(metas: &[FleetMeta]) -> String {
283    let mut rows: Vec<String> = metas.iter().map(|m| format!("{}:{}:{}:{}", m.id, m.updated_at, m.hash, m.removed)).collect();
284    rows.sort();
285    let mut hasher = Sha256::new();
286    for row in rows {
287        hasher.update(row.as_bytes());
288        hasher.update(b"
289");
290    }
291    hex::encode(hasher.finalize())
292}
293
294/// The removal of `id` to send, with who removed it here.
295pub fn removal_for_push(store: &Store, id: &str, removed_at: i64) -> Result<FleetRemoval, StoreError> {
296    let edited_by = store.bundle_version_latest(id)?.map(|v| v.written_by).unwrap_or_default();
297    Ok(FleetRemoval { id: id.to_string(), removed_at, edited_by })
298}
299
300/// One thing to send a machine that is behind.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum Push {
303    Put { id: String },
304    Remove { id: String, removed_at: i64 },
305}
306
307/// What to send a machine, given what each side lists, so it catches up: the
308/// entries it lacks or holds an older copy of, and the removals it has not
309/// seen. Newest first. What the other machine holds newer is that machine's to
310/// push when it sees this one.
311pub fn to_push(local: &[FleetMeta], remote: &[FleetMeta]) -> Vec<Push> {
312    let theirs: HashMap<&str, &FleetMeta> = remote.iter().map(|m| (m.id.as_str(), m)).collect();
313    let mut out: Vec<(i64, Push)> = Vec::new();
314    for mine in local {
315        match theirs.get(mine.id.as_str()) {
316            Some(t) if t.hash == mine.hash => continue,
317            Some(t) if !wins(mine.updated_at, &mine.hash, t.updated_at, &t.hash) => continue,
318            // Nothing to tell a machine that never had an entry that is gone.
319            None if mine.removed => continue,
320            _ => {}
321        }
322        let push = if mine.removed {
323            Push::Remove { id: mine.id.clone(), removed_at: mine.updated_at }
324        } else {
325            Push::Put { id: mine.id.clone() }
326        };
327        out.push((mine.updated_at, push));
328    }
329    out.sort_by(|a, b| b.0.cmp(&a.0));
330    out.into_iter().map(|(_, p)| p).collect()
331}
332
333/// Apply a write received from another machine.
334pub fn apply_put(store: &Store, entry: &FleetEntry, actor: Actor<'_>) -> Result<Outcome, FleetError> {
335    validate_id(&entry.id)?;
336    if entry.name.trim().is_empty() {
337        return Err(FleetError::Invalid("memory.global.put: name is required".to_string()));
338    }
339    if entry.instructions.len() > MAX_INSTRUCTIONS {
340        return Err(FleetError::Invalid(format!(
341            "memory.global.put: content too large ({} bytes, max {MAX_INSTRUCTIONS})",
342            entry.instructions.len()
343        )));
344    }
345    for (field, value) in [("instructions_by_provider", &entry.instructions_by_provider), ("context_files", &entry.context_files)] {
346        if serde_json::from_str::<serde_json::Value>(value).is_err() {
347            return Err(FleetError::Invalid(format!("memory.global.put: {field} is not valid JSON")));
348        }
349    }
350    if !is_fleet_id(&entry.id) {
351        return Ok(Outcome::Skipped(Skipped::Protected));
352    }
353    let local = store.bundle_get(&entry.id)?;
354    if let Some(b) = &local {
355        if b.is_system || b.is_blank {
356            return Ok(Outcome::Skipped(Skipped::Protected));
357        }
358    }
359    // `machine` here: kept, unless the row is only the default the scope table gave it.
360    let mut lifts_default = false;
361    if store.bundle_scope_get(&entry.id)? != crate::backend::storage::bundle_scope::SCOPE_FLEET {
362        if !store.bundle_scope_is_default_machine(&entry.id)? {
363            return Ok(Outcome::Skipped(Skipped::MachineScope));
364        }
365        lifts_default = true;
366    }
367
368    let incoming_hash = entry.hash();
369    let (mut applied, mut bundle) = match local {
370        None => (Applied::Created, new_bundle(entry)),
371        Some(b) if b.is_global => {
372            let local_hash = bundle_hash(&b);
373            if local_hash == incoming_hash {
374                if lifts_default {
375                    store.bundle_scope_follow_fleet(&entry.id)?;
376                    return Ok(Outcome::Applied(Applied::Adopted));
377                }
378                return Ok(Outcome::Skipped(Skipped::Same));
379            }
380            if !wins(entry.updated_at, &incoming_hash, b.updated_at, &local_hash) {
381                return Ok(Outcome::Skipped(Skipped::Older));
382            }
383            (Applied::Updated, b)
384        }
385        Some(b) if store.bundle_is_removed_global(&b.id)? => {
386            if !wins(entry.updated_at, &incoming_hash, b.updated_at, REMOVED_HASH) {
387                return Ok(Outcome::Skipped(Skipped::Older));
388            }
389            (Applied::Restored, b)
390        }
391        Some(_) => return Ok(Outcome::Skipped(Skipped::NotMemory)),
392    };
393    // `db_bundles.name` is unique, and the fleet carries entries by id. A different id that holds
394    // this name is either an entry removed here (its name is dead: free it) or a live one, which a
395    // person here has to sort out; the sync says so and goes on with the others.
396    if let Some(holder) = store.bundle_get_by_name(entry.name.trim())? {
397        if holder.id != entry.id {
398            if holder.is_global || holder.is_system || holder.is_blank || !store.bundle_is_removed_global(&holder.id)? {
399                return Ok(Outcome::Skipped(Skipped::NameTaken));
400            }
401            let short: String = holder.id.chars().take(8).collect();
402            store.bundle_rename_removed(&holder.id, &format!("{} (removed {short})", holder.name))?;
403        }
404    }
405    if lifts_default && applied == Applied::Updated {
406        keep_current_text(store, &bundle)?;
407    }
408    bundle.name = entry.name.trim().to_string();
409    bundle.description = entry.description.clone();
410    bundle.instructions = entry.instructions.clone();
411    bundle.instructions_by_provider = entry.instructions_by_provider.clone();
412    bundle.context_files = entry.context_files.clone();
413    bundle.is_global = true;
414    bundle.updated_at = entry.updated_at;
415    store.bundle_upsert_with_version(&bundle, actor.label, actor.uid, FLEET_SOURCE, &source_detail(actor, &entry.edited_by, lifts_default))?;
416    if lifts_default {
417        store.bundle_scope_follow_fleet(&bundle.id)?;
418        if applied == Applied::Updated {
419            applied = Applied::Adopted;
420        }
421    }
422    if !matches!(applied, Applied::Updated | Applied::Adopted) {
423        append_to_order(store, &bundle.id);
424    }
425    Ok(Outcome::Applied(applied))
426}
427
428/// Apply a removal received from another machine.
429pub fn apply_remove(store: &Store, removal: &FleetRemoval, actor: Actor<'_>) -> Result<Outcome, FleetError> {
430    validate_id(&removal.id)?;
431    if !is_fleet_id(&removal.id) {
432        return Ok(Outcome::Skipped(Skipped::Protected));
433    }
434    let Some(mut bundle) = store.bundle_get(&removal.id)? else {
435        return Ok(Outcome::Skipped(Skipped::Unknown));
436    };
437    if bundle.is_system || bundle.is_blank {
438        return Ok(Outcome::Skipped(Skipped::Protected));
439    }
440    if store.bundle_scope_get(&removal.id)? != crate::backend::storage::bundle_scope::SCOPE_FLEET {
441        return Ok(Outcome::Skipped(Skipped::MachineScope));
442    }
443    if !bundle.is_global {
444        return Ok(Outcome::Skipped(if store.bundle_is_removed_global(&removal.id)? {
445            Skipped::AlreadyRemoved
446        } else {
447            Skipped::NotMemory
448        }));
449    }
450    if !wins(removal.removed_at, REMOVED_HASH, bundle.updated_at, &bundle_hash(&bundle)) {
451        return Ok(Outcome::Skipped(Skipped::Older));
452    }
453    bundle.is_global = false;
454    bundle.updated_at = removal.removed_at;
455    store.bundle_upsert_with_version(&bundle, actor.label, actor.uid, REMOVE_SOURCE, &source_detail(actor, &removal.edited_by, false))?;
456    Ok(Outcome::Applied(Applied::Removed))
457}
458
459/// Make sure the text an entry holds now is in its history before a fleet write replaces it: an
460/// entry that was copied by hand may have no version at all, and a revert needs one.
461fn keep_current_text(store: &Store, current: &Bundle) -> Result<(), StoreError> {
462    let held = crate::backend::storage::bundle_versions::content_hash(&current.name, &current.instructions);
463    if store.bundle_version_latest(&current.id)?.is_some_and(|v| v.content_hash == held) {
464        return Ok(());
465    }
466    let detail = serde_json::json!({ "why": "the text before a newer fleet write replaced it" }).to_string();
467    store.bundle_upsert_with_version(current, "agentmux", "", BASELINE_SOURCE, &detail)?;
468    Ok(())
469}
470
471/// The version's `source_detail`. `lifted_machine_default` says the write replaced an entry that was
472/// `machine` here only by default, so history shows why this entry changed on its own.
473fn source_detail(actor: Actor<'_>, edited_by: &str, lifted_machine_default: bool) -> String {
474    let mut detail = serde_json::json!({ "fleet_from": actor.label, "edited_by": edited_by });
475    if lifted_machine_default {
476        detail["lifted_machine_default"] = serde_json::Value::Bool(true);
477    }
478    detail.to_string()
479}
480
481fn new_bundle(entry: &FleetEntry) -> Bundle {
482    Bundle {
483        id: entry.id.clone(),
484        name: entry.name.trim().to_string(),
485        description: entry.description.clone(),
486        is_blank: false,
487        is_global: true,
488        provider: String::new(),
489        model: String::new(),
490        instructions: entry.instructions.clone(),
491        instructions_by_provider: entry.instructions_by_provider.clone(),
492        context_files: entry.context_files.clone(),
493        mcp_servers: "[]".to_string(),
494        skills: "[]".to_string(),
495        sort_order: 0,
496        is_system: false,
497        created_at: agentmux_common::time::now_ms(),
498        updated_at: entry.updated_at,
499    }
500}
501
502/// Put a new or restored entry last in the Global Memory order, as Memory →
503/// Global's "+ New section" does. A failed reorder is logged, not fatal.
504fn append_to_order(store: &Store, id: &str) {
505    let ids: Result<Vec<String>, StoreError> = store.bundle_list_global().map(|bundles| {
506        bundles
507            .into_iter()
508            .filter(|b| !b.is_system && b.id != id)
509            .map(|b| b.id)
510            .chain(std::iter::once(id.to_string()))
511            .collect()
512    });
513    match ids.and_then(|ids| store.bundle_reorder(&ids)) {
514        Ok(_) => {}
515        Err(e) => tracing::warn!(bundle_id = id, error = %e, "fleet memory: append-to-order failed (non-fatal)"),
516    }
517}
518
519#[cfg(test)]
520mod tests;