Skip to main content

agentmux_srv_core/registry/
store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Registry` — file-per-agent CRUD on `<root>/<uuid>.json` with
5//! a sibling `retired/<uuid>.json` tombstone tree.
6//!
7//! Concurrency: cross-process safety comes from filesystem atomic
8//! rename. The internal `Mutex` only serializes partial-merge writes
9//! from threads inside the same `srv` so a v1 binary touching
10//! `last_launched_at_ms` doesn't race itself.
11
12use std::path::{Path, PathBuf};
13use std::sync::Mutex;
14
15use serde_json::Value;
16use thiserror::Error;
17
18use super::atomic::{rename_atomic, write_atomic};
19use super::schema::{validate, NamedAgentRecord, ValidationError, MAX_SUPPORTED_SCHEMA, MIN_SUPPORTED_SCHEMA};
20use super::unreadable::{self, UnreadableRecord};
21
22#[derive(Debug, Error)]
23pub enum RegistryError {
24    #[error("io: {0}")]
25    Io(#[from] std::io::Error),
26    #[error("json: {0}")]
27    Json(#[from] serde_json::Error),
28    #[error("validation: {0}")]
29    Validation(#[from] ValidationError),
30}
31
32/// Which records an operation is allowed to touch.
33///
34/// The registry has two ways to say "this record belongs to X": the file
35/// key (`<instance_id>.json`) and the record's own `definition_id`. Since
36/// the agent-concept consolidation those are the same value for an agent —
37/// but only for records `m0026_registry_agent_id_rekey` re-keyed, and that
38/// pass no-ops once `db_agent_instances` is dropped (schema v32), so a real
39/// install still holds launch-keyed records where they differ. Matching
40/// both is what makes Delete actually remove an agent's row
41/// ([`Registry::hard_delete_for_agent`]).
42///
43/// It is also what makes a TEMPLATE dangerous: a template's id is the
44/// `definition_id` of every legacy launch record for the real agents
45/// launched from it, so a wide match would delete/retire/rename THEIR
46/// records along with the template. Hence this type rather than a `bool`
47/// or a per-call-site `if` — ReAgent found the same omission at four
48/// separate call sites on PR #3262 (rounds 3 and 4), which is a sign the
49/// decision belongs in the signature, not in each caller's memory.
50#[derive(Clone, Copy, PartialEq, Eq, Debug)]
51pub enum RecordScope {
52    /// Only the record whose FILE KEY is this id. The correct scope for a
53    /// template: its own record, and nothing belonging to its launches.
54    FileKeyOnly,
55    /// Every record for this agent — file key or `definition_id`.
56    Agent,
57}
58
59pub struct Registry {
60    root: PathBuf,
61    write_lock: Mutex<()>,
62}
63
64impl Registry {
65    /// Open or create the registry rooted at `root`. Ensures the
66    /// active dir and `retired/` subdir both exist.
67    pub fn open(root: PathBuf) -> Result<Self, RegistryError> {
68        std::fs::create_dir_all(&root)?;
69        std::fs::create_dir_all(root.join("retired"))?;
70        super::atomic::sweep_stale_temps(&root, super::atomic::STALE_TEMP_AGE);
71        Ok(Self {
72            root,
73            write_lock: Mutex::new(()),
74        })
75    }
76
77    pub fn root(&self) -> &Path {
78        &self.root
79    }
80
81    /// Resolved `<shared_home>/agents/` — one level above `root`.
82    /// Used by callers that need to express working-directory paths
83    /// as relative subpaths under the shared agents tree. Returns
84    /// `None` if the registry root has no parent (only happens in
85    /// pathological filesystem-root setups; production always nests
86    /// under `~/.agentmux/agents/registry`).
87    pub fn agents_root(&self) -> Option<&Path> {
88        self.root.parent()
89    }
90
91    fn active_path(&self, instance_id: &str) -> PathBuf {
92        self.root.join(format!("{instance_id}.json"))
93    }
94
95    fn retired_path(&self, instance_id: &str) -> PathBuf {
96        self.root.join("retired").join(format!("{instance_id}.json"))
97    }
98
99    /// Insert or update a record. If the file already exists, unknown
100    /// top-level + `data` fields are preserved (forward-compat with
101    /// future schemas that add columns this binary doesn't know).
102    ///
103    /// Forward-compat invariant (spec §6): never write a higher-schema
104    /// row into a lower schema, never overwrite a corrupt/unparseable
105    /// file. Both cases skip the mirror with a warning — the on-disk
106    /// file stays intact for the binary that authored it (or for ops
107    /// triage). Skipping is `Ok(())`: SQLite remains authoritative.
108    pub fn upsert(&self, rec: &NamedAgentRecord) -> Result<(), RegistryError> {
109        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
110        self.upsert_unlocked(rec, SessionWrite::Overwrite)
111    }
112
113    /// [`Self::upsert`], except a `session_id` the record already holds
114    /// wins over `rec`'s. For a mirror that didn't capture a session — a
115    /// launch — whose local row may carry an older session id than the one
116    /// another channel has since written here (#3586). A record without a
117    /// session id still takes `rec`'s.
118    pub fn upsert_keeping_session(&self, rec: &NamedAgentRecord) -> Result<(), RegistryError> {
119        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
120        self.upsert_unlocked(rec, SessionWrite::KeepExisting)
121    }
122
123    /// [`Self::upsert`] without taking `write_lock`, for callers already
124    /// holding it. `write_lock` is a plain `Mutex` — re-entering it from a
125    /// locked section would deadlock, not nest.
126    fn upsert_unlocked(&self, rec: &NamedAgentRecord, session: SessionWrite) -> Result<(), RegistryError> {
127        let path = self.active_path(&rec.data.instance_id);
128        let bytes = match std::fs::read(&path) {
129            Ok(existing) => match merge_for_write(&existing, rec, session)? {
130                Some(b) => b,
131                None => return Ok(()),
132            },
133            Err(e) if e.kind() == std::io::ErrorKind::NotFound => to_pretty(rec)?,
134            Err(e) => return Err(e.into()),
135        };
136        write_atomic(&path, &bytes)?;
137        Ok(())
138    }
139
140    /// Set `instance_name` on every ACTIVE record for `agent_id`. Returns
141    /// how many files changed.
142    ///
143    /// Every record, not just the canonical one, because
144    /// `listrecentsessions` dedupes rows by `(definition_id, instance_name)`
145    /// — renaming one of an agent's records and not the others splits it
146    /// into two picker rows, one under each name. (An agent can hold more
147    /// than one record for the same reason
148    /// [`Self::hard_delete_for_agent`] exists.)
149    ///
150    /// Active tree only: `upsert` writes to the active path, so touching a
151    /// retired record here would resurrect a deliberately-forgotten agent.
152    /// A retired record keeps its old name until `unretire_for_agent`
153    /// brings it back.
154    pub fn set_instance_name_for_agent(
155        &self,
156        agent_id: &str,
157        scope: RecordScope,
158        instance_name: &str,
159    ) -> Result<usize, RegistryError> {
160        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
161        let mut renamed = 0usize;
162        for path in records_for_agent(&self.root, agent_id, scope)? {
163            let Ok(bytes) = std::fs::read(&path) else {
164                continue;
165            };
166            let Ok(mut rec) = serde_json::from_slice::<NamedAgentRecord>(&bytes) else {
167                continue;
168            };
169            // An unnamed record fails validation on READ, so it is already
170            // invisible to the picker — but `upsert` doesn't validate, so
171            // one can sit on disk, and this scan reads raw JSON (matching on
172            // `definition_id` is the whole point). Naming it here would
173            // "repair" it into a visible row for an agent that never had
174            // one. Pinned by
175            // `set_instance_name_for_agent_leaves_an_unnamed_record_invisible`.
176            if rec.data.instance_name.is_empty() || rec.data.instance_name == instance_name {
177                continue;
178            }
179            rec.data.instance_name = instance_name.to_string();
180            self.upsert_unlocked(&rec, SessionWrite::Overwrite)?;
181            renamed += 1;
182        }
183        Ok(renamed)
184    }
185
186    /// Move record into `retired/` (soft delete — keeps the working
187    /// dir intact, drops it from the named-agent lists). Idempotent.
188    pub fn retire(&self, instance_id: &str) -> Result<(), RegistryError> {
189        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
190        let from = self.active_path(instance_id);
191        if !from.exists() {
192            return Ok(());
193        }
194        rename_atomic(&from, &self.retired_path(instance_id))?;
195        Ok(())
196    }
197
198    /// Move record back from `retired/` to active. Idempotent.
199    pub fn unretire(&self, instance_id: &str) -> Result<(), RegistryError> {
200        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
201        let from = self.retired_path(instance_id);
202        if !from.exists() {
203            return Ok(());
204        }
205        rename_atomic(&from, &self.active_path(instance_id))?;
206        Ok(())
207    }
208
209    /// Hard-delete by FILE KEY only (drops both active and retired files),
210    /// returning how many files were removed.
211    ///
212    /// The narrow counterpart of [`Self::hard_delete_for_agent`]. Deleting a
213    /// TEMPLATE needs this one: a template's id can legitimately appear as
214    /// the `definition_id` of a legacy, never-re-keyed launch record
215    /// belonging to a real agent launched from it, and matching on
216    /// `definition_id` would take that agent's record along with the
217    /// template (ReAgent P1 round 3 on PR #3262). A template's own record,
218    /// if it has one, is file-keyed, so this is the complete sweep for one.
219    pub fn hard_delete(&self, instance_id: &str) -> Result<usize, RegistryError> {
220        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
221        let mut removed = 0usize;
222        for p in [self.active_path(instance_id), self.retired_path(instance_id)] {
223            match std::fs::remove_file(&p) {
224                Ok(()) => removed += 1,
225                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
226                Err(e) => return Err(e.into()),
227            }
228        }
229        Ok(removed)
230    }
231
232    /// Drop every record — active AND retired — that belongs to the agent
233    /// `agent_id`, matching on either the record's file key (its instance
234    /// id) or its `definition_id`. Returns how many files were removed.
235    ///
236    /// **Why this exists alongside [`Self::hard_delete`].** That one keys
237    /// only on the file name. Since the agent-concept consolidation an
238    /// agent's instance id and definition id are the same value, so the two
239    /// agree — but only for records this tree has been re-keyed to.
240    /// `m0026_registry_agent_id_rekey` does that re-keying by reading
241    /// `db_agent_instances`, and returns a no-op the moment that legacy
242    /// table is gone (v32 dropped it). An install that consolidated before
243    /// m0026 could run therefore still holds one *launch*-keyed file per
244    /// agent, in addition to the correctly-keyed one.
245    ///
246    /// Deleting such an agent removed only the correctly-keyed file,
247    /// leaving the launch-keyed one active with no definition behind it —
248    /// which `listrecentsessions` still renders as a row (no provider, so
249    /// no icon, and `"(missing definition)"`). The delete looked like it
250    /// half-worked: the icon vanished, the card stayed.
251    ///
252    /// Both keys are checked rather than just `definition_id` because
253    /// callers legitimately hold either one: a consolidated agent id, or
254    /// the launch id of a registry-only row this channel's SQLite has never
255    /// seen. Matching both is a strict superset of [`Self::hard_delete`],
256    /// and a cross-key collision would require the same uuid to name two
257    /// different agents.
258    pub fn hard_delete_for_agent(
259        &self,
260        agent_id: &str,
261        scope: RecordScope,
262    ) -> Result<usize, RegistryError> {
263        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
264        let mut removed = 0usize;
265        for dir in [self.root.clone(), self.root.join("retired")] {
266            for path in records_for_agent(&dir, agent_id, scope)? {
267                match std::fs::remove_file(&path) {
268                    Ok(()) => removed += 1,
269                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
270                    Err(e) => return Err(e.into()),
271                }
272            }
273        }
274        Ok(removed)
275    }
276
277    /// Retire every active record for `agent_id`, matched the same way
278    /// [`Self::hard_delete_for_agent`] matches. A launch-keyed record left
279    /// active by the file-keyed [`Self::retire`] is exactly the "'Forget
280    /// agent' retires the NEW key while the stale file stays active, so the
281    /// forgotten agent reappears" failure `m0026_registry_agent_id_rekey`'s
282    /// own doc comment predicted.
283    pub fn retire_for_agent(&self, agent_id: &str, scope: RecordScope) -> Result<usize, RegistryError> {
284        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
285        self.move_for_agent(agent_id, scope, self.root.clone(), self.root.join("retired"))
286    }
287
288    /// Inverse of [`Self::retire_for_agent`].
289    pub fn unretire_for_agent(&self, agent_id: &str, scope: RecordScope) -> Result<usize, RegistryError> {
290        let _g = self.write_lock.lock().unwrap_or_else(|e| e.into_inner());
291        self.move_for_agent(agent_id, scope, self.root.join("retired"), self.root.clone())
292    }
293
294    /// Move an agent's records between the active and retired trees,
295    /// keeping each file's own name (the instance id) so the record stays
296    /// addressable by [`Self::get`]. Caller holds `write_lock`.
297    fn move_for_agent(
298        &self,
299        agent_id: &str,
300        scope: RecordScope,
301        from_dir: PathBuf,
302        to_dir: PathBuf,
303    ) -> Result<usize, RegistryError> {
304        let mut moved = 0usize;
305        for path in records_for_agent(&from_dir, agent_id, scope)? {
306            let Some(name) = path.file_name() else {
307                continue;
308            };
309            rename_atomic(&path, &to_dir.join(name))?;
310            moved += 1;
311        }
312        Ok(moved)
313    }
314
315    /// Whether an active record exists for `instance_id`. Doesn't
316    /// validate — useful for migration idempotency checks. Use
317    /// [`Self::exists_anywhere`] when retired records should also
318    /// count (e.g. so migration doesn't resurrect a hidden agent).
319    pub fn exists(&self, instance_id: &str) -> bool {
320        self.active_path(instance_id).exists()
321    }
322
323    /// Read a single active record by id, without scanning the whole
324    /// tree. `Ok(None)` when there's no active file for `instance_id`
325    /// (never checks `retired/`). Callers that need to patch a single
326    /// field (e.g. propagating a fresh `session_id`) must read-modify-
327    /// upsert via this rather than constructing a partial record —
328    /// `upsert`'s merge overwrites every field present in the struct,
329    /// so a partially-populated record would clobber the rest with
330    /// defaults.
331    pub fn get(&self, instance_id: &str) -> Result<Option<NamedAgentRecord>, RegistryError> {
332        let path = self.active_path(instance_id);
333        if !path.exists() {
334            return Ok(None);
335        }
336        Ok(Some(read_and_validate(&path, instance_id)?))
337    }
338
339    /// Whether a record exists in either active or retired. Used by
340    /// migration to skip already-tombstoned records (avoid
341    /// resurrecting a user's deliberate "Forget agent" via a
342    /// per-version SQLite row that still has `display_hidden = 0`).
343    pub fn exists_anywhere(&self, instance_id: &str) -> bool {
344        self.active_path(instance_id).exists() || self.retired_path(instance_id).exists()
345    }
346
347    /// Read every valid active record. Invalid files are skipped +
348    /// logged. PR A doesn't wire this into the RPC path; included so
349    /// PR B can swap reads over without further restructuring.
350    pub fn list_active(&self) -> Result<Vec<NamedAgentRecord>, RegistryError> {
351        let mut out = Vec::new();
352        for entry in std::fs::read_dir(&self.root)? {
353            let entry = entry?;
354            let path = entry.path();
355            if !path.is_file() || super::atomic::is_temp_file(&path) {
356                continue;
357            }
358            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
359                continue;
360            };
361            if path.extension().and_then(|s| s.to_str()) != Some("json") {
362                continue;
363            }
364            match read_and_validate(&path, stem) {
365                Ok(rec) => out.push(rec),
366                Err(e) => {
367                    tracing::warn!(
368                        file = %path.display(),
369                        error = %e,
370                        "registry: skipping invalid record"
371                    );
372                }
373            }
374        }
375        Ok(out)
376    }
377}
378
379/// Where an instance record keeps what an unreadable one is explained from.
380const INSTANCE_SHAPE: unreadable::Shape = unreadable::Shape {
381    name_key: "instance_name",
382    provider_key: None,
383    version_keys: &["last_launched_by_version", "created_by_version"],
384    min: MIN_SUPPORTED_SCHEMA,
385    max: MAX_SUPPORTED_SCHEMA,
386};
387
388impl Registry {
389    /// The active instance files [`Self::list_active`] leaves out, each with why. Reads only: the files stay as they are.
390    pub fn list_unreadable(&self) -> Result<Vec<UnreadableRecord>, RegistryError> {
391        let mut out = Vec::new();
392        for entry in std::fs::read_dir(&self.root)? {
393            let path = entry?.path();
394            if !path.is_file() || super::atomic::is_temp_file(&path) || path.extension().and_then(|s| s.to_str()) != Some("json") {
395                continue;
396            }
397            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { continue };
398            let Ok(bytes) = std::fs::read(&path) else { continue };
399            if let Err(e) = read_and_validate_bytes(&bytes, stem) {
400                out.push(unreadable::explain(&bytes, stem, &INSTANCE_SHAPE, &e.to_string()));
401            }
402        }
403        out.sort_by(|a, b| a.id.cmp(&b.id));
404        Ok(out)
405    }
406}
407
408/// Paths of the `*.json` files under `dir` whose record belongs to
409/// `agent_id` — by file key (instance id) or by `definition_id`. A missing
410/// directory yields nothing (the `retired/` tree is created on open, but a
411/// caller may point at a tree that predates it).
412///
413/// Unparseable files are matched on their file key alone and otherwise
414/// skipped, the same way [`Registry::list_active`] skips them: a record
415/// this can't read is also one that can never surface as a row, and
416/// removing it on a guess would destroy whatever newer-schema binary
417/// authored it. The file-key match is kept so an explicitly-addressed
418/// delete still behaves like [`Registry::hard_delete`] did.
419fn records_for_agent(
420    dir: &Path,
421    agent_id: &str,
422    scope: RecordScope,
423) -> Result<Vec<PathBuf>, RegistryError> {
424    let mut out = Vec::new();
425    if scope == RecordScope::FileKeyOnly {
426        let p = dir.join(format!("{agent_id}.json"));
427        if p.is_file() {
428            out.push(p);
429        }
430        return Ok(out);
431    }
432    let entries = match std::fs::read_dir(dir) {
433        Ok(e) => e,
434        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
435        Err(e) => return Err(e.into()),
436    };
437    for entry in entries {
438        let path = entry?.path();
439        if !path.is_file() || path.extension().and_then(|s| s.to_str()) != Some("json") {
440            continue;
441        }
442        if path.file_stem().and_then(|s| s.to_str()) == Some(agent_id) {
443            out.push(path);
444            continue;
445        }
446        let Ok(bytes) = std::fs::read(&path) else {
447            continue;
448        };
449        let Ok(rec) = serde_json::from_slice::<NamedAgentRecord>(&bytes) else {
450            continue;
451        };
452        if rec.data.definition_id == agent_id {
453            out.push(path);
454        }
455    }
456    Ok(out)
457}
458
459fn read_and_validate(path: &Path, stem: &str) -> Result<NamedAgentRecord, RegistryError> {
460    read_and_validate_bytes(&std::fs::read(path)?, stem)
461}
462
463fn read_and_validate_bytes(bytes: &[u8], stem: &str) -> Result<NamedAgentRecord, RegistryError> {
464    let rec: NamedAgentRecord = serde_json::from_slice(bytes)?;
465    validate(stem, &rec)?;
466    Ok(rec)
467}
468
469fn to_pretty(rec: &NamedAgentRecord) -> Result<Vec<u8>, serde_json::Error> {
470    let mut bytes = serde_json::to_vec_pretty(rec)?;
471    bytes.push(b'\n');
472    Ok(bytes)
473}
474
475/// Merge an in-memory record into an on-disk file's raw JSON,
476/// preserving fields beyond this binary's struct shape.
477///
478/// Returns `Ok(None)` when the writer must refuse the merge (corrupt
479/// JSON, missing `schema_version`, or `schema_version` above
480/// `MAX_SUPPORTED_SCHEMA`). The caller treats `None` as a skip and
481/// leaves the on-disk file intact.
482/// Whether an upsert may replace the record's `session_id`.
483#[derive(Clone, Copy, PartialEq, Eq)]
484enum SessionWrite {
485    Overwrite,
486    KeepExisting,
487}
488
489fn merge_for_write(
490    existing: &[u8],
491    rec: &NamedAgentRecord,
492    session: SessionWrite,
493) -> Result<Option<Vec<u8>>, RegistryError> {
494    let on_disk: Value = match serde_json::from_slice(existing) {
495        Ok(v) => v,
496        Err(e) => {
497            tracing::warn!(
498                error = %e,
499                "registry: existing file is unparseable JSON — refusing to overwrite (may be a newer schema)"
500            );
501            return Ok(None);
502        }
503    };
504    // Use `try_from` so any number above `u32::MAX` is treated as
505    // unparseable rather than wrapping into the supported range. A
506    // wrap would let an oversized envelope downgrade-bypass the
507    // forward-compat guard below.
508    let on_disk_version = on_disk
509        .get("schema_version")
510        .and_then(|v| v.as_u64())
511        .and_then(|v| u32::try_from(v).ok());
512    match on_disk_version {
513        Some(v) if v > MAX_SUPPORTED_SCHEMA => {
514            tracing::warn!(
515                on_disk = v,
516                writer_max = MAX_SUPPORTED_SCHEMA,
517                "registry: on-disk schema_version > writer max — refusing downgrade"
518            );
519            return Ok(None);
520        }
521        Some(_) => {}
522        None => {
523            tracing::warn!(
524                "registry: existing file lacks schema_version — refusing to overwrite"
525            );
526            return Ok(None);
527        }
528    }
529    let mut updates = serde_json::to_value(rec)?;
530    let held_session = on_disk
531        .get("data")
532        .and_then(|d| d.get("session_id"))
533        .and_then(Value::as_str)
534        .is_some_and(|s| !s.is_empty());
535    if session == SessionWrite::KeepExisting && held_session {
536        if let Some(data) = updates.get_mut("data").and_then(Value::as_object_mut) {
537            data.remove("session_id");
538        }
539    }
540    let mut merged = on_disk;
541    merge_known(&mut merged, &updates);
542    let mut bytes = serde_json::to_vec_pretty(&merged)?;
543    bytes.push(b'\n');
544    Ok(Some(bytes))
545}
546
547/// Overwrite `target`'s top-level keys with `updates`' keys. Keys in
548/// `target` that aren't in `updates` are preserved. Recurses into
549/// the `data` sub-object so future fields inside `data` also survive.
550fn merge_known(target: &mut Value, updates: &Value) {
551    let (Some(t), Some(u)) = (target.as_object_mut(), updates.as_object()) else {
552        *target = updates.clone();
553        return;
554    };
555    for (k, v) in u {
556        if k == "data" {
557            if let Some(t_data) = t.get_mut("data") {
558                merge_known(t_data, v);
559                continue;
560            }
561        }
562        t.insert(k.clone(), v.clone());
563    }
564}