1use 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
45pub const FLEET_SOURCE: &str = "fleet";
47
48const BASELINE_SOURCE: &str = "fleet-baseline";
50
51const MAX_INSTRUCTIONS: usize = 1024 * 1024;
53
54const 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#[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 pub updated_at: i64,
80 #[serde(default)]
84 pub edited_by: String,
85}
86
87impl FleetEntry {
88 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct FleetRemoval {
106 pub id: String,
107 pub removed_at: i64,
109 #[serde(default)]
111 pub edited_by: String,
112}
113
114#[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#[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 Restored,
137 Adopted,
140 Removed,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum Skipped {
145 Same,
147 Older,
149 MachineScope,
151 Protected,
153 NotMemory,
155 NameTaken,
159 AlreadyRemoved,
161 Unknown,
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum Outcome {
167 Applied(Applied),
168 Skipped(Skipped),
169}
170
171impl Outcome {
172 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 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
218fn 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
223fn 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
239pub 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
259pub 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
280pub 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
294pub 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#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum Push {
303 Put { id: String },
304 Remove { id: String, removed_at: i64 },
305}
306
307pub 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 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
333pub 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 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 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
428pub 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
459fn keep_current_text(store: &Store, current: &Bundle) -> Result<(), StoreError> {
462 let held = crate::backend::storage::bundle_versions::content_hash(¤t.name, ¤t.instructions);
463 if store.bundle_version_latest(¤t.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
471fn 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
502fn 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;