Skip to main content

agentmux_srv_core/registry/
def_store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `DefinitionStore` โ€” file-per-definition CRUD on `<root>/<id>.json`
5//! with a sibling `retired/<id>.json` tombstone tree.
6//!
7//! Sibling of `store.rs` (the named-*instance* `Registry`). Same on-disk
8//! discipline: atomic rename for cross-process safety, a forward-compat
9//! merge that preserves unknown fields, refuses schema downgrades, and
10//! never clobbers an unparseable file. Holds the GLOBAL agent-definition
11//! roster so any channel/version sees the same agents (P0.2 of
12//! `docs/specs/SPEC_CROSS_CHANNEL_AGENT_PERSISTENCE_2026-06-13.md`).
13//!
14//! The forward-compat merge helpers below intentionally parallel the
15//! private ones in `store.rs`. They are kept separate (not shared) so
16//! this addition is fully isolated from the in-production instance
17//! registry; a later cleanup can extract a generic file-store both use.
18
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22use serde_json::Value;
23use thiserror::Error;
24
25use super::atomic::{rename_atomic, write_atomic};
26use super::def_slug_index::{SlugEntry, SlugIndex};
27use super::def_schema::{validate, AgentSeat, DefValidationError, Handover, DefinitionRecord, DEF_MAX_SUPPORTED_SCHEMA, DEF_MIN_SUPPORTED_SCHEMA};
28use super::unreadable::{self, UnreadableRecord};
29
30#[derive(Debug, Error)]
31pub enum DefStoreError {
32    #[error("io: {0}")]
33    Io(#[from] std::io::Error),
34    #[error("json: {0}")]
35    Json(#[from] serde_json::Error),
36    #[error("validation: {0}")]
37    Validation(#[from] DefValidationError),
38    #[error("definition {id} is being written by another process (waited {waited_ms} ms); try again")]
39    Locked { id: String, waited_ms: u64 },
40}
41
42pub struct DefinitionStore {
43    root: PathBuf,
44    /// How long a writer waits for a record's lock ([`Self::with_record_locked`]).
45    lock_timeout: Duration,
46    /// Every record's slug, parsed once per change ([`Self::slug_index`]).
47    slugs: SlugIndex,
48}
49
50impl DefinitionStore {
51    /// Open or create the store rooted at `root`. Ensures the active dir
52    /// and `retired/` subdir both exist.
53    pub fn open(root: PathBuf) -> Result<Self, DefStoreError> {
54        std::fs::create_dir_all(&root)?;
55        std::fs::create_dir_all(root.join("retired"))?;
56        super::atomic::sweep_stale_temps(&root, super::atomic::STALE_TEMP_AGE);
57        Ok(Self {
58            root,
59            lock_timeout: super::def_record_lock::LOCK_TIMEOUT,
60            slugs: SlugIndex::default(),
61        })
62    }
63
64    pub fn root(&self) -> &Path {
65        &self.root
66    }
67
68    fn active_path(&self, id: &str) -> PathBuf {
69        self.root.join(format!("{id}.json"))
70    }
71
72    fn retired_path(&self, id: &str) -> PathBuf {
73        self.root.join("retired").join(format!("{id}.json"))
74    }
75
76    /// Run `f` with record `id` locked against every other writer, in this
77    /// process or another (`def_record_lock`): a read, merge and write inside
78    /// it can't interleave with another one. Every write below takes it;
79    /// a rename that has to read and rewrite the record takes it too. Waits
80    /// up to the store's lock timeout, then fails with
81    /// [`DefStoreError::Locked`] having written nothing.
82    pub fn with_record_locked<T>(
83        &self,
84        id: &str,
85        f: impl FnOnce(&LockedRecord<'_>) -> Result<T, DefStoreError>,
86    ) -> Result<T, DefStoreError> {
87        let lock = super::def_record_lock::lock_record(&self.root, id, self.lock_timeout)?;
88        let out = f(&LockedRecord { store: self, id: id.to_string() });
89        drop(lock);
90        out
91    }
92
93    /// The host-wide slug allocation lock, held until the guard drops. A
94    /// new agent's slug is picked against every slug the shared store holds
95    /// and then published by mirroring its record: whoever inserts holds this
96    /// across both, so two channels or instances creating agents at once
97    /// can't both pick the same free slug. Same bounded wait as a record's
98    /// lock; [`DefStoreError::Locked`] names it.
99    pub fn lock_slug_allocation(&self) -> Result<SlugAllocationLock, DefStoreError> {
100        let file = super::def_record_lock::lock_record(&self.root, super::def_record_lock::SLUG_ALLOCATION, self.lock_timeout)?;
101        Ok(SlugAllocationLock { _file: file })
102    }
103
104    /// The host-wide seat lock, held until the guard drops. A seat's lead is
105    /// checked against every other agent's (no cycles) and then written: two
106    /// clients setting reciprocal leads at once could each pass the check
107    /// before the other wrote, so a writer holds this across both.
108    pub fn lock_seat_graph(&self) -> Result<SlugAllocationLock, DefStoreError> {
109        let file = super::def_record_lock::lock_record(&self.root, super::def_record_lock::SEAT_GRAPH, self.lock_timeout)?;
110        Ok(SlugAllocationLock { _file: file })
111    }
112
113    #[cfg(test)]
114    pub(crate) fn set_lock_timeout(&mut self, timeout: Duration) {
115        self.lock_timeout = timeout;
116    }
117
118    /// Insert or update a definition. Preserves unknown top-level + `data`
119    /// fields on an existing file (forward-compat); refuses to overwrite a
120    /// corrupt or higher-schema file. An existing record's slug and former
121    /// slugs are kept ([`keep_slug_and_former_slugs`]): a rename is not an
122    /// update. Holds the record's lock across the read, merge and write.
123    pub fn upsert(&self, rec: &DefinitionRecord) -> Result<(), DefStoreError> {
124        self.with_record_locked(&rec.data.id, |locked| locked.upsert(rec))
125    }
126
127    /// [`Self::upsert`]'s body; the caller holds the record's lock.
128    fn upsert_locked(&self, rec: &DefinitionRecord) -> Result<(), DefStoreError> {
129        let path = self.active_path(&rec.data.id);
130        let bytes = match std::fs::read(&path) {
131            Ok(existing) => match merge_for_write(&existing, rec)? {
132                Some(b) => b,
133                None => return Ok(()),
134            },
135            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
136                // Don't resurrect a tombstoned definition: a missing active
137                // file plus an existing `retired/<id>.json` means the agent
138                // was deliberately deleted (possibly in another channel). A
139                // stale cross-channel mirror calling `upsert` must NOT recreate
140                // it; the caller must `unretire` first to bring it back.
141                // (codex P1 on #1384.)
142                if self.retired_path(&rec.data.id).exists() {
143                    return Ok(());
144                }
145                to_pretty(rec)?
146            }
147            Err(e) => return Err(e.into()),
148        };
149        write_atomic(&path, &bytes)?;
150        self.slugs.invalidate(&rec.data.id);
151        Ok(())
152    }
153
154    /// Soft-delete โ†’ move into `retired/` (tombstone). Idempotent. The
155    /// tombstone prevents another channel's migration from resurrecting an
156    /// agent the user deliberately deleted.
157    pub fn retire(&self, id: &str) -> Result<(), DefStoreError> {
158        self.with_record_locked(id, |_| {
159            let from = self.active_path(id);
160            if from.exists() {
161                rename_atomic(&from, &self.retired_path(id))?;
162                self.slugs.invalidate(id);
163            }
164            Ok(())
165        })
166    }
167
168    /// Move a record back from `retired/` to active. Idempotent.
169    pub fn unretire(&self, id: &str) -> Result<(), DefStoreError> {
170        self.with_record_locked(id, |_| {
171            let from = self.retired_path(id);
172            if from.exists() {
173                rename_atomic(&from, &self.active_path(id))?;
174                self.slugs.invalidate(id);
175            }
176            Ok(())
177        })
178    }
179
180    /// Hard-delete (drops both active and retired files). Mirrors SQLite
181    /// `agent_def_delete`. Use [`Self::retire`] when a resurrection-proof
182    /// tombstone is wanted instead.
183    pub fn hard_delete(&self, id: &str) -> Result<(), DefStoreError> {
184        self.with_record_locked(id, |_| {
185            for p in [self.active_path(id), self.retired_path(id)] {
186                match std::fs::remove_file(&p) {
187                    Ok(()) => {}
188                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
189                    Err(e) => return Err(e.into()),
190                }
191            }
192            self.slugs.invalidate(id);
193            Ok(())
194        })
195    }
196
197    pub fn exists(&self, id: &str) -> bool {
198        self.active_path(id).exists()
199    }
200
201    pub fn exists_anywhere(&self, id: &str) -> bool {
202        self.active_path(id).exists() || self.retired_path(id).exists()
203    }
204
205    /// Read a single active definition record by id. `None` if absent;
206    /// invalid/corrupt files surface as an error (caller logs + falls back).
207    pub fn get(&self, id: &str) -> Result<Option<DefinitionRecord>, DefStoreError> {
208        match std::fs::read(self.active_path(id)) {
209            Ok(bytes) => {
210                let rec: DefinitionRecord = serde_json::from_slice(&bytes)?;
211                validate(id, &rec)?;
212                Ok(Some(rec))
213            }
214            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
215            Err(e) => Err(e.into()),
216        }
217    }
218
219    /// Read every valid active definition. Invalid files are skipped +
220    /// logged (left on disk for ops triage).
221    pub fn list_active(&self) -> Result<Vec<DefinitionRecord>, DefStoreError> {
222        let mut out = Vec::new();
223        for entry in std::fs::read_dir(&self.root)? {
224            let entry = entry?;
225            let path = entry.path();
226            if !path.is_file() || super::atomic::is_temp_file(&path) {
227                continue;
228            }
229            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
230                continue;
231            };
232            if path.extension().and_then(|s| s.to_str()) != Some("json") {
233                continue;
234            }
235            match read_and_validate(&path, stem) {
236                Ok(rec) => out.push(rec),
237                Err(e) => {
238                    tracing::warn!(
239                        file = %path.display(),
240                        error = %e,
241                        "def registry: skipping invalid record"
242                    );
243                }
244            }
245        }
246        Ok(out)
247    }
248
249    /// The active definition files [`Self::list_active`] leaves out, each with why (a newer AgentMux wrote it, it is damaged, it
250    /// is incomplete). Reads only: the files stay as they are, so a build that can read them reads them back unchanged.
251    pub fn list_unreadable(&self) -> Result<Vec<UnreadableRecord>, DefStoreError> {
252        let mut out = Vec::new();
253        for entry in std::fs::read_dir(&self.root)? {
254            let path = entry?.path();
255            let Some(stem) = record_stem(&path) else { continue };
256            let Ok(bytes) = std::fs::read(&path) else { continue };
257            if let Err(e) = parse_and_validate(&bytes, stem) {
258                out.push(unreadable::explain(&bytes, stem, &DEF_SHAPE, &e.to_string()));
259            }
260        }
261        out.sort_by(|a, b| a.id.cmp(&b.id));
262        Ok(out)
263    }
264
265    /// Why the active definition `id` cannot be used by this build, or `None` when it is absent or reads fine.
266    pub fn unreadable_reason(&self, id: &str) -> Option<String> {
267        let bytes = std::fs::read(self.active_path(id)).ok()?;
268        let e = parse_and_validate(&bytes, id).err()?;
269        Some(unreadable::explain(&bytes, id, &DEF_SHAPE, &e.to_string()).reason)
270    }
271
272    /// Every valid active record's slug and former slugs, by id: what
273    /// [`Self::list_active`] would give, without reading a file that hasn't
274    /// changed since the last call (`def_slug_index`). For lookups that run
275    /// per message.
276    pub fn slug_index(&self) -> Result<std::sync::Arc<std::collections::HashMap<String, SlugEntry>>, DefStoreError> {
277        Ok(self.slugs.all(&self.root)?)
278    }
279
280    /// One active record's slug and former slugs, read from its file now,
281    /// for a caller that must not act on a guess (deleting the agent). `None`
282    /// only when there is no active file. A file that can't be read, or whose
283    /// slug fields can't be (`def_slug_index::slug_fields`), is an error. A
284    /// record this build otherwise can't load (a newer schema, a missing name
285    /// or provider) still answers when its slug fields can be read.
286    pub fn slug_of_strict(&self, id: &str) -> Result<Option<SlugEntry>, DefStoreError> {
287        let bytes = match std::fs::read(self.active_path(id)) {
288            Ok(b) => b,
289            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
290            Err(e) => return Err(e.into()),
291        };
292        super::def_slug_index::slug_fields(id, &bytes)
293            .map(Some)
294            .map_err(|why| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{id}.json: {why}")).into())
295    }
296
297    /// Every active record's slug and former slugs, for allocating a new
298    /// slug: [`Self::slug_index`]'s cache, but every record counts, newer
299    /// schemas included, and anything that can't be read (the directory, a
300    /// file, a record's slug fields) is an error rather than skipped.
301    pub fn slug_index_strict(&self) -> Result<std::collections::HashMap<String, SlugEntry>, DefStoreError> {
302        self.slugs
303            .all_strict(&self.root)
304            .map_err(|why| std::io::Error::new(std::io::ErrorKind::InvalidData, why).into())
305    }
306
307    /// One active record's slug and former slugs, from the same cache;
308    /// stats only that record's file.
309    pub fn slug_of(&self, id: &str) -> Result<Option<SlugEntry>, DefStoreError> {
310        Ok(self.slugs.one(&self.root, id)?)
311    }
312
313    /// Set (`Some`) or remove (`None`) record `id`'s seat, leaving every other
314    /// field, known to this build or not, as it is on disk. The one writer of
315    /// `seat`: [`Self::upsert`] keeps the file's copy, so a mirror write can't
316    /// clear it. `Ok(false)` when there is no active record. A record this
317    /// build can't write (unparseable, a newer schema) is an error, not
318    /// overwritten.
319    pub fn set_seat(&self, id: &str, seat: Option<&AgentSeat>) -> Result<bool, DefStoreError> {
320        self.with_record_locked(id, |locked| {
321            let Some(raw) = locked.raw()? else { return Ok(false) };
322            let mut value: Value = serde_json::from_slice(&raw)?;
323            let data = value
324                .get_mut("data")
325                .and_then(Value::as_object_mut)
326                .ok_or(DefValidationError::MissingField("data"))?;
327            match seat {
328                Some(seat) => {
329                    data.insert("seat".to_string(), serde_json::to_value(seat)?);
330                }
331                None => {
332                    data.remove("seat");
333                }
334            }
335            locked.replace_raw(&record_bytes(&value)?)?;
336            Ok(true)
337        })
338    }
339}
340
341impl DefinitionStore {
342    /// Record `id`'s hand-over mark, read so that it fails closed: from the file's own JSON, whatever else in the record
343    /// this build can or cannot read (a newer schema, a field it does not know). `Ok(None)`: no record, or a record
344    /// with no mark. `Err`: the file could not be read or parsed, so nobody can say the agent is not handed over.
345    pub fn handover_of(&self, id: &str) -> Result<Option<Handover>, DefStoreError> {
346        let raw = match std::fs::read(self.active_path(id)) {
347            Ok(raw) => raw,
348            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
349            Err(e) => return Err(e.into()),
350        };
351        let value: Value = serde_json::from_slice(&raw)?;
352        let Some(mark) = value.pointer("/data/handover").filter(|m| !m.is_null()) else { return Ok(None) };
353        Ok(Some(match serde_json::from_value::<Handover>(mark.clone()) {
354            Ok(h) if !h.state.is_empty() => h,
355            _ => Handover { state: Handover::HANDED_OVER.to_string(), ..Handover::default() },
356        }))
357    }
358
359    /// Set (`Some`) or remove (`None`) record `id`'s hand-over mark, leaving every other field as it is on disk. The one
360    /// writer of `handover`: [`Self::upsert`] keeps the file's copy, so a mirror write can't clear it. `Ok(false)` when
361    /// there is no active record.
362    pub fn set_handover(&self, id: &str, mark: Option<&Handover>) -> Result<bool, DefStoreError> {
363        self.with_record_locked(id, |locked| {
364            let Some(raw) = locked.raw()? else { return Ok(false) };
365            let mut value: Value = serde_json::from_slice(&raw)?;
366            let data = value
367                .get_mut("data")
368                .and_then(Value::as_object_mut)
369                .ok_or(DefValidationError::MissingField("data"))?;
370            match mark {
371                Some(mark) => {
372                    data.insert("handover".to_string(), serde_json::to_value(mark)?);
373                }
374                None => {
375                    data.remove("handover");
376                }
377            }
378            locked.replace_raw(&record_bytes(&value)?)?;
379            Ok(true)
380        })
381    }
382}
383
384/// A held host-wide lock: slug allocation ([`DefinitionStore::lock_slug_allocation`])
385/// or seat changes ([`DefinitionStore::lock_seat_graph`]).
386pub struct SlugAllocationLock {
387    _file: std::fs::File,
388}
389
390/// One definition record, locked by [`DefinitionStore::with_record_locked`].
391pub struct LockedRecord<'a> {
392    store: &'a DefinitionStore,
393    id: String,
394}
395
396impl LockedRecord<'_> {
397    /// The active record, as [`DefinitionStore::get`] reads it.
398    pub fn get(&self) -> Result<Option<DefinitionRecord>, DefStoreError> {
399        self.store.get(&self.id)
400    }
401
402    /// [`DefinitionStore::upsert`] of this record, under the lock already held.
403    pub fn upsert(&self, rec: &DefinitionRecord) -> Result<(), DefStoreError> {
404        if rec.data.id != self.id {
405            return Err(DefValidationError::IdMismatch { filename: self.id.clone(), id: rec.data.id.clone() }.into());
406        }
407        self.store.upsert_locked(rec)
408    }
409
410    /// The active file's bytes, as they are on disk; `None` if there is none.
411    pub fn raw(&self) -> Result<Option<Vec<u8>>, DefStoreError> {
412        match std::fs::read(self.store.active_path(&self.id)) {
413            Ok(bytes) => Ok(Some(bytes)),
414            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
415            Err(e) => Err(e.into()),
416        }
417    }
418
419    /// Replace the active file with `bytes`, as they are: the one write that
420    /// may change a non-empty slug, which [`Self::upsert`] never does. For
421    /// the fork slug migration's rename and its undo
422    /// (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` ยง4 Phase 2, S1). `bytes`
423    /// must be a record of this id and a schema this build writes; nothing is
424    /// written otherwise, and a missing active file (a deleted agent) is not
425    /// recreated.
426    pub fn replace_raw(&self, bytes: &[u8]) -> Result<(), DefStoreError> {
427        let path = self.store.active_path(&self.id);
428        if !path.exists() {
429            return Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("{}.json is not active", self.id)).into());
430        }
431        let value: Value = serde_json::from_slice(bytes)?;
432        let version = value.get("schema_version").and_then(Value::as_u64).unwrap_or(0);
433        if version == 0 || version > u64::from(DEF_MAX_SUPPORTED_SCHEMA) {
434            return Err(DefValidationError::UnsupportedSchema {
435                version: version as u32,
436                min: super::def_schema::DEF_MIN_SUPPORTED_SCHEMA,
437                max: DEF_MAX_SUPPORTED_SCHEMA,
438            }
439            .into());
440        }
441        if value.pointer("/data/id").and_then(Value::as_str) != Some(self.id.as_str()) {
442            let id = value.pointer("/data/id").and_then(Value::as_str).unwrap_or("").to_string();
443            return Err(DefValidationError::IdMismatch { filename: self.id.clone(), id }.into());
444        }
445        write_atomic(&path, bytes)?;
446        self.store.slugs.invalidate(&self.id);
447        Ok(())
448    }
449}
450
451/// A definition record as [`DefinitionStore`] writes one after a merge:
452/// pretty JSON and a trailing newline.
453pub fn record_bytes(value: &Value) -> Result<Vec<u8>, serde_json::Error> {
454    let mut bytes = serde_json::to_vec_pretty(value)?;
455    bytes.push(b'\n');
456    Ok(bytes)
457}
458
459/// Where a definition record keeps what an unreadable one is explained from.
460const DEF_SHAPE: unreadable::Shape = unreadable::Shape {
461    name_key: "name",
462    provider_key: Some("provider"),
463    version_keys: &[],
464    min: DEF_MIN_SUPPORTED_SCHEMA,
465    max: DEF_MAX_SUPPORTED_SCHEMA,
466};
467
468/// The id a record file stands for: its name without `.json`; `None` for a directory, a write temp file or anything else.
469fn record_stem(path: &Path) -> Option<&str> {
470    if !path.is_file() || super::atomic::is_temp_file(path) || path.extension().and_then(|s| s.to_str()) != Some("json") {
471        return None;
472    }
473    path.file_stem().and_then(|s| s.to_str())
474}
475
476fn read_and_validate(path: &Path, stem: &str) -> Result<DefinitionRecord, DefStoreError> {
477    parse_and_validate(&std::fs::read(path)?, stem)
478}
479
480pub(super) fn parse_and_validate(bytes: &[u8], stem: &str) -> Result<DefinitionRecord, DefStoreError> {
481    let rec: DefinitionRecord = serde_json::from_slice(bytes)?;
482    validate(stem, &rec)?;
483    Ok(rec)
484}
485
486fn to_pretty(rec: &DefinitionRecord) -> Result<Vec<u8>, serde_json::Error> {
487    let mut bytes = serde_json::to_vec_pretty(rec)?;
488    bytes.push(b'\n');
489    Ok(bytes)
490}
491
492/// Merge an in-memory record into an on-disk file's raw JSON, preserving
493/// fields beyond this binary's struct shape. Returns `Ok(None)` (skip,
494/// leave file intact) on corrupt JSON, missing `schema_version`, or
495/// `schema_version` above `DEF_MAX_SUPPORTED_SCHEMA`. Parallels
496/// `store.rs::merge_for_write` (see module docs).
497fn merge_for_write(
498    existing: &[u8],
499    rec: &DefinitionRecord,
500) -> Result<Option<Vec<u8>>, DefStoreError> {
501    let on_disk: Value = match serde_json::from_slice(existing) {
502        Ok(v) => v,
503        Err(e) => {
504            tracing::warn!(
505                error = %e,
506                "def registry: existing file is unparseable JSON โ€” refusing to overwrite"
507            );
508            return Ok(None);
509        }
510    };
511    // `try_from` so a number above u32::MAX is treated as unparseable
512    // rather than wrapping past the forward-compat guard.
513    let on_disk_version = on_disk
514        .get("schema_version")
515        .and_then(|v| v.as_u64())
516        .and_then(|v| u32::try_from(v).ok());
517    match on_disk_version {
518        Some(v) if v > DEF_MAX_SUPPORTED_SCHEMA => {
519            tracing::warn!(
520                on_disk = v,
521                writer_max = DEF_MAX_SUPPORTED_SCHEMA,
522                "def registry: on-disk schema_version > writer max โ€” refusing downgrade"
523            );
524            return Ok(None);
525        }
526        Some(_) => {}
527        None => {
528            tracing::warn!("def registry: existing file lacks schema_version โ€” refusing to overwrite");
529            return Ok(None);
530        }
531    }
532    let mut merged = on_disk;
533    let mut updates = serde_json::to_value(rec)?;
534    keep_slug_and_former_slugs(&merged, &mut updates);
535    merge_known(&mut merged, &updates);
536    let mut bytes = serde_json::to_vec_pretty(&merged)?;
537    bytes.push(b'\n');
538    Ok(Some(bytes))
539}
540
541/// A shared definition's slug is never changed by an update
542/// (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` P0.2). Every channel and version
543/// keeps its own copy of the slug in its `objects.db`, and the copy a writer
544/// mirrors back may be one this record has moved on from (a former slug), or
545/// a local collision suffix. So a non-empty slug on disk is kept whatever the
546/// update carries, and its `former_slugs` are kept too, with any new ones the
547/// update carries appended. An empty slug on disk takes the update's.
548fn keep_slug_and_former_slugs(on_disk: &Value, updates: &mut Value) {
549    let disk_slug = on_disk
550        .pointer("/data/slug")
551        .and_then(Value::as_str)
552        .filter(|s| !s.trim().is_empty());
553    let disk_former: Vec<Value> = on_disk
554        .pointer("/data/former_slugs")
555        .and_then(Value::as_array)
556        .cloned()
557        .unwrap_or_default();
558    let Some(data) = updates.get_mut("data").and_then(Value::as_object_mut) else {
559        return;
560    };
561    if let Some(disk_slug) = disk_slug {
562        let incoming = data.get("slug").and_then(Value::as_str).unwrap_or("").to_string();
563        if incoming != disk_slug {
564            let retired = disk_former
565                .iter()
566                .any(|f| f.get("slug").and_then(Value::as_str) == Some(incoming.as_str()));
567            let def_id = data.get("id").and_then(Value::as_str).unwrap_or("").to_string();
568            tracing::warn!(
569                def_id = %def_id,
570                shared_slug = disk_slug,
571                refused_slug = %incoming,
572                refused_is_former = retired,
573                "def registry: an update carried a different slug; the shared record's is kept"
574            );
575            data.insert("slug".to_string(), Value::String(disk_slug.to_string()));
576        }
577    }
578    if !disk_former.is_empty() {
579        let mut all = disk_former;
580        for f in data.get("former_slugs").and_then(Value::as_array).into_iter().flatten() {
581            if !all.iter().any(|g| g.get("slug") == f.get("slug")) {
582                all.push(f.clone());
583            }
584        }
585        data.insert("former_slugs".to_string(), Value::Array(all));
586    }
587}
588
589/// Overwrite `target`'s top-level keys with `updates`' keys, preserving
590/// keys absent from `updates`; recurses into `data`.
591fn merge_known(target: &mut Value, updates: &Value) {
592    let (Some(t), Some(u)) = (target.as_object_mut(), updates.as_object()) else {
593        *target = updates.clone();
594        return;
595    };
596    for (k, v) in u {
597        if k == "data" {
598            if let Some(t_data) = t.get_mut("data") {
599                merge_known(t_data, v);
600                continue;
601            }
602        }
603        t.insert(k.clone(), v.clone());
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use crate::registry::DefinitionRecordV1;
611
612    fn store() -> (tempfile::TempDir, DefinitionStore) {
613        let tmp = tempfile::tempdir().unwrap();
614        let s = DefinitionStore::open(tmp.path().join("definitions")).unwrap();
615        (tmp, s)
616    }
617
618    fn rec(id: &str, name: &str) -> DefinitionRecord {
619        DefinitionRecord {
620            schema_version: 1,
621            data: DefinitionRecordV1 {
622                id: id.to_string(),
623                slug: id.to_string(),
624                name: name.to_string(),
625                icon: "โœฆ".to_string(),
626                provider: "claude".to_string(),
627                description: String::new(),
628                working_directory: String::new(),
629                shell: String::new(),
630                provider_flags: String::new(),
631                auto_start: 0,
632                restart_on_crash: 0,
633                idle_timeout_minutes: 0,
634                created_at: 1,
635                agent_type: "host".to_string(),
636                environment: String::new(),
637                agent_bus_id: String::new(),
638                is_seeded: 0,
639                accounts: String::new(),
640                parent_id: String::new(),
641                branch_label: String::new(),
642                updated_at: 1,
643                user_hidden: 0,
644                container_image: String::new(),
645                container_volumes: "[]".to_string(),
646                container_name: String::new(),
647                use_ambient_login: 0,
648                former_slugs: Vec::new(),
649                seat: None,
650                handover: None,
651                content: Vec::new(),
652                skills: Vec::new(),
653            },
654        }
655    }
656
657    fn former(slug: &str, retired_at: i64) -> crate::registry::FormerSlug {
658        crate::registry::FormerSlug { slug: slug.to_string(), retired_at }
659    }
660
661    /// A temp file left by an interrupted write is no record: listing and the slug
662    /// index pass over it without a warning or a failed strict read, and opening
663    /// the store removes it once it is old.
664    #[test]
665    fn a_leftover_write_temp_file_is_not_a_record_and_is_swept_when_old() {
666        let (tmp, s) = store();
667        s.upsert(&rec("aaa", "Loap")).unwrap();
668        let temp = s.root().join(".registry-tmp-AbC123.json");
669        std::fs::write(&temp, b"{\"half\":").unwrap();
670
671        let listed = s.list_active().unwrap();
672        assert_eq!(listed.len(), 1);
673        assert_eq!(s.slug_index().unwrap().len(), 1);
674        assert_eq!(s.slug_index_strict().unwrap().len(), 1, "a strict read must not trip on it");
675        assert!(temp.exists(), "a fresh temp file may be a write in flight: left alone");
676
677        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
678        std::fs::OpenOptions::new().write(true).open(&temp).unwrap().set_modified(old).unwrap();
679        let reopened = DefinitionStore::open(tmp.path().join("definitions")).unwrap();
680        assert!(!temp.exists(), "an old one is removed when the store opens");
681        assert!(reopened.exists("aaa"), "the record is untouched");
682    }
683
684    /// P0.2: a channel whose `objects.db` still holds a slug the shared
685    /// record has retired mirrors an edit back. The edit lands; the slug and
686    /// the former slugs don't change.
687    #[test]
688    fn an_update_cannot_put_back_a_former_slug() {
689        let (_t, s) = store();
690        let mut renamed = rec("aaa", "Loap #3");
691        renamed.data.slug = "loap-3".to_string();
692        renamed.data.former_slugs = vec![former("loap-loap-2-loap-3", 5)];
693        s.upsert(&renamed).unwrap();
694
695        let mut stale = rec("aaa", "Loap #3 (edited)");
696        stale.data.slug = "loap-loap-2-loap-3".to_string();
697        s.upsert(&stale).unwrap();
698
699        let got = s.get("aaa").unwrap().unwrap();
700        assert_eq!(got.data.name, "Loap #3 (edited)", "the edit itself still mirrors");
701        assert_eq!(got.data.slug, "loap-3");
702        assert_eq!(got.data.former_slugs, vec![former("loap-loap-2-loap-3", 5)]);
703    }
704
705    /// Any other slug is refused the same way (a local collision suffix), and
706    /// an empty slug on disk takes the update's.
707    #[test]
708    fn an_update_keeps_the_shared_slug_unless_it_is_empty() {
709        let (_t, s) = store();
710        let mut first = rec("aaa", "Foo");
711        first.data.slug = "foo".to_string();
712        s.upsert(&first).unwrap();
713        let mut suffixed = first.clone();
714        suffixed.data.slug = "foo-2".to_string();
715        s.upsert(&suffixed).unwrap();
716        assert_eq!(s.get("aaa").unwrap().unwrap().data.slug, "foo");
717
718        let mut blank = rec("bbb", "Bar");
719        blank.data.slug = String::new();
720        s.upsert(&blank).unwrap();
721        blank.data.slug = "bar".to_string();
722        s.upsert(&blank).unwrap();
723        assert_eq!(s.get("bbb").unwrap().unwrap().data.slug, "bar");
724    }
725
726    /// Former slugs are never dropped: neither by a writer that doesn't know
727    /// the field (an older build, whose update has none) nor by one carrying
728    /// an older copy of the list; new entries are appended.
729    #[test]
730    fn former_slugs_only_grow() {
731        let (_t, s) = store();
732        let path = s.root().join("aaa.json");
733        let raw = serde_json::json!({
734            "schema_version": 1,
735            "data": {
736                "id": "aaa", "name": "Demo", "provider": "claude", "slug": "c",
737                "former_slugs": [{ "slug": "a", "retired_at": 1 }, { "slug": "b", "retired_at": 2 }]
738            }
739        });
740        std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
741
742        s.upsert(&rec("aaa", "Renamed")).unwrap();
743        let got = s.get("aaa").unwrap().unwrap();
744        assert_eq!(got.data.former_slugs, vec![former("a", 1), former("b", 2)]);
745
746        let mut partial = got.clone();
747        partial.data.former_slugs = vec![former("a", 1), former("z", 9)];
748        s.upsert(&partial).unwrap();
749        let got = s.get("aaa").unwrap().unwrap();
750        assert_eq!(got.data.former_slugs, vec![former("a", 1), former("b", 2), former("z", 9)]);
751        assert_eq!(got.data.slug, "c");
752    }
753
754    fn seat(role: &str) -> AgentSeat {
755        AgentSeat { role: role.to_string(), area: Some("docs".into()), set_at_ms: 3, ..Default::default() }
756    }
757
758    /// `set_seat` sets and removes the seat and leaves every other field,
759    /// one this build doesn't know included, as it was.
760    #[test]
761    fn set_seat_sets_and_clears_only_the_seat() {
762        let (_t, s) = store();
763        let path = s.root().join("aaa.json");
764        let raw = serde_json::json!({
765            "schema_version": 1,
766            "future": 1,
767            "data": { "id": "aaa", "name": "Demo", "provider": "claude", "slug": "demo", "future_field": "kept" }
768        });
769        std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
770
771        assert!(s.set_seat("aaa", Some(&seat("leader"))).unwrap());
772        assert_eq!(s.get("aaa").unwrap().unwrap().data.seat, Some(seat("leader")));
773        let on_disk: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
774        assert_eq!(on_disk.pointer("/data/future_field"), Some(&serde_json::json!("kept")));
775        assert_eq!(on_disk.get("future"), Some(&serde_json::json!(1)));
776
777        assert!(s.set_seat("aaa", None).unwrap());
778        let on_disk: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
779        assert!(on_disk.pointer("/data/seat").is_none(), "clearing removes the key");
780        assert_eq!(on_disk.pointer("/data/future_field"), Some(&serde_json::json!("kept")));
781        assert_eq!(on_disk.pointer("/data/slug"), Some(&serde_json::json!("demo")));
782
783        assert!(!s.set_seat("missing", Some(&seat("leader"))).unwrap(), "no record, nothing written");
784        assert!(!s.root().join("missing.json").exists());
785    }
786
787    /// `handover_of` fails closed: a mark is found in a record this build cannot otherwise read (a newer schema), and a
788    /// record that cannot be read at all is an error, never "no mark".
789    #[test]
790    fn the_handover_read_fails_closed() {
791        let (_t, s) = store();
792        assert_eq!(s.handover_of("missing").unwrap(), None, "no record: nothing is marked");
793        let newer = r#"{"schema_version":99,"data":{"id":"bbb","name":"B","handover":{"state":"moved","to":"Starpower"}}}"#;
794        std::fs::write(s.root().join("bbb.json"), newer).unwrap();
795        assert_eq!(s.handover_of("bbb").unwrap().map(|h| h.state), Some("moved".to_string()));
796        let plain = r#"{"schema_version":99,"data":{"id":"ccc","name":"C"}}"#;
797        std::fs::write(s.root().join("ccc.json"), plain).unwrap();
798        assert_eq!(s.handover_of("ccc").unwrap(), None);
799        std::fs::write(s.root().join("ddd.json"), b"{ not json").unwrap();
800        assert!(s.handover_of("ddd").is_err(), "an unreadable record is not permission to start");
801    }
802
803    fn mark(state: &str) -> Handover {
804        Handover { state: state.to_string(), to: "Starpower".into(), at_ms: 5, manifest_hash: "ab".repeat(32) }
805    }
806
807    /// The hand-over mark is set and cleared by `set_handover` alone: a mirror write that carries none keeps it, and a
808    /// mark this build cannot read stays a refusal to start (never an absent mark).
809    #[test]
810    fn the_handover_mark_is_set_cleared_kept_by_upserts_and_never_lost_to_a_bad_value() {
811        let (_t, s) = store();
812        let path = s.root().join("aaa.json");
813        let raw = serde_json::json!({
814            "schema_version": 1,
815            "data": { "id": "aaa", "name": "Demo", "provider": "claude", "slug": "demo", "future_field": "kept" }
816        });
817        std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
818        assert!(s.set_handover("aaa", Some(&mark(Handover::HANDED_OVER))).unwrap());
819        assert_eq!(s.get("aaa").unwrap().unwrap().data.handover, Some(mark(Handover::HANDED_OVER)));
820
821        let mut mirror = s.get("aaa").unwrap().unwrap();
822        mirror.data.handover = None;
823        mirror.data.name = "Renamed".into();
824        s.upsert(&mirror).unwrap();
825        let got = s.get("aaa").unwrap().unwrap();
826        assert_eq!((got.data.name.as_str(), got.data.handover.clone()), ("Renamed", Some(mark(Handover::HANDED_OVER))), "a write that does not know the mark keeps it");
827
828        let on_disk: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
829        assert_eq!(on_disk.pointer("/data/future_field"), Some(&serde_json::json!("kept")));
830
831        // A newer build's mark of a shape this one cannot read still refuses a start.
832        let mut value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
833        value["data"]["handover"] = serde_json::json!("sealed");
834        std::fs::write(&path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
835        let bad = s.get("aaa").unwrap().unwrap().data.handover.expect("an unreadable mark is not dropped");
836        assert_eq!(bad.state, Handover::HANDED_OVER);
837
838        assert!(s.set_handover("aaa", None).unwrap());
839        assert_eq!(s.get("aaa").unwrap().unwrap().data.handover, None);
840        assert!(!s.set_handover("missing", Some(&mark(Handover::MOVED))).unwrap(), "no record, nothing written");
841    }
842
843    /// A write that carries no seat, from this build's mirror or from an
844    /// older build that doesn't know the field, keeps the one on disk.
845    #[test]
846    fn an_upsert_without_a_seat_keeps_the_stored_one() {
847        let (_t, s) = store();
848        s.upsert(&rec("aaa", "Demo")).unwrap();
849        s.set_seat("aaa", Some(&seat("specialist"))).unwrap();
850
851        s.upsert(&rec("aaa", "Renamed")).unwrap();
852        let got = s.get("aaa").unwrap().unwrap();
853        assert_eq!(got.data.name, "Renamed");
854        assert_eq!(got.data.seat, Some(seat("specialist")));
855
856        // An older build's record: its JSON has no `seat` key at all.
857        let mut older = serde_json::to_value(rec("aaa", "Older")).unwrap();
858        older["data"].as_object_mut().unwrap().remove("seat");
859        let older: DefinitionRecord = serde_json::from_value(older).unwrap();
860        s.upsert(&older).unwrap();
861        assert_eq!(s.get("aaa").unwrap().unwrap().data.seat, Some(seat("specialist")));
862    }
863
864    /// A newer schema's file isn't rewritten by `set_seat`.
865    #[test]
866    fn set_seat_refuses_a_newer_schema() {
867        let (_t, s) = store();
868        let path = s.root().join("bbb.json");
869        let future = r#"{"schema_version":99,"data":{"id":"bbb","name":"B","provider":"claude"}}"#;
870        std::fs::write(&path, future).unwrap();
871        assert!(s.set_seat("bbb", Some(&seat("leader"))).is_err());
872        assert_eq!(std::fs::read_to_string(&path).unwrap(), future);
873    }
874
875    /// Backdate a record's file, as an index built a while after the last
876    /// write sees it (out of the racy window).
877    fn age(s: &DefinitionStore, id: &str, secs: u64) {
878        let file = std::fs::File::options().write(true).open(s.root().join(format!("{id}.json"))).unwrap();
879        file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap();
880    }
881
882    fn with_slug(id: &str, slug: &str) -> DefinitionRecord {
883        let mut r = rec(id, "Demo");
884        r.data.slug = slug.to_string();
885        r
886    }
887
888    /// Once warm, a lookup parses nothing: not for the whole index, and not
889    /// for one record.
890    #[test]
891    fn a_warm_slug_index_parses_no_file() {
892        let (_t, s) = store();
893        for i in 0..5 {
894            let id = format!("id-{i}");
895            s.upsert(&with_slug(&id, &format!("slug-{i}"))).unwrap();
896            age(&s, &id, 60);
897        }
898        let first = s.slug_index().unwrap();
899        assert_eq!(first.len(), 5);
900        assert_eq!(s.slugs.parses(), 5);
901        for _ in 0..20 {
902            assert_eq!(s.slug_index().unwrap().get("id-3").map(|e| e.slug.as_str()), Some("slug-3"));
903            assert_eq!(s.slug_of("id-1").unwrap().map(|e| e.slug), Some("slug-1".to_string()));
904        }
905        assert_eq!(s.slugs.parses(), 5, "nothing reparsed");
906        assert!(std::sync::Arc::ptr_eq(&first, &s.slug_index().unwrap()), "the same map is handed out");
907    }
908
909    /// A write through this store invalidates its record: the next lookup
910    /// reparses that file only. A retired record leaves the index.
911    #[test]
912    fn an_in_process_write_invalidates_the_slug_index() {
913        let (_t, s) = store();
914        for id in ["aaa", "bbb"] {
915            s.upsert(&with_slug(id, id)).unwrap();
916            age(&s, id, 60);
917        }
918        s.slug_index().unwrap();
919        let warm = s.slugs.parses();
920
921        // A same-size edit, then the old timestamp put back: the file's
922        // stamp is unchanged, so only the invalidation can trigger a reparse.
923        let path = s.root().join("aaa.json");
924        let before = std::fs::metadata(&path).unwrap();
925        let mut edited = with_slug("aaa", "aaa");
926        edited.data.name = "Dema".to_string();
927        s.upsert(&edited).unwrap();
928        std::fs::File::options().write(true).open(&path).unwrap().set_modified(before.modified().unwrap()).unwrap();
929        assert_eq!(std::fs::metadata(&path).unwrap().len(), before.len());
930        s.slug_index().unwrap();
931        assert_eq!(s.slugs.parses(), warm + 1, "only the written record is reparsed");
932
933        let mut renamed = with_slug("aaa", "aaa");
934        renamed.data.former_slugs = vec![former("aaa-old", 1)];
935        s.upsert(&renamed).unwrap();
936        s.retire("bbb").unwrap();
937        let index = s.slug_index().unwrap();
938        assert_eq!(index["aaa"].former, vec!["aaa-old".to_string()]);
939        assert!(!index.contains_key("bbb"));
940    }
941
942    /// Another process's write is picked up from the file's stamp: a new
943    /// file, a changed one, and a removed one. A same-size rewrite within
944    /// the racy window of the last parse is caught too.
945    #[test]
946    fn an_out_of_process_change_reaches_the_slug_index() {
947        let (_t, s) = store();
948        s.upsert(&with_slug("aaa", "loap-loap-2")).unwrap();
949        age(&s, "aaa", 60);
950        assert_eq!(s.slug_index().unwrap()["aaa"].slug, "loap-loap-2");
951
952        // Another instance renames it and adds an agent, writing the files directly.
953        let mut moved = with_slug("aaa", "loap-2");
954        moved.data.former_slugs = vec![former("loap-loap-2", 1)];
955        std::fs::write(s.root().join("aaa.json"), serde_json::to_vec_pretty(&moved).unwrap()).unwrap();
956        age(&s, "aaa", 30);
957        std::fs::write(s.root().join("ccc.json"), serde_json::to_vec_pretty(&with_slug("ccc", "c")).unwrap()).unwrap();
958        let index = s.slug_index().unwrap();
959        assert_eq!(index["aaa"].slug, "loap-2");
960        assert_eq!(index["aaa"].former, vec!["loap-loap-2".to_string()]);
961        assert_eq!(s.slug_of("ccc").unwrap().map(|e| e.slug), Some("c".to_string()));
962
963        std::fs::remove_file(s.root().join("ccc.json")).unwrap();
964        assert!(!s.slug_index().unwrap().contains_key("ccc"));
965        assert_eq!(s.slug_of("ccc").unwrap(), None);
966
967        // Racy: parsed just after a write, then rewritten with the same size
968        // and the same timestamp. The stamp alone can't tell; the index
969        // doesn't trust it yet.
970        let path = s.root().join("ddd.json");
971        std::fs::write(&path, serde_json::to_vec(&with_slug("ddd", "d-one")).unwrap()).unwrap();
972        let stamp = std::fs::metadata(&path).unwrap().modified().unwrap();
973        assert_eq!(s.slug_of("ddd").unwrap().unwrap().slug, "d-one");
974        std::fs::write(&path, serde_json::to_vec(&with_slug("ddd", "d-two")).unwrap()).unwrap();
975        std::fs::File::options().write(true).open(&path).unwrap().set_modified(stamp).unwrap();
976        assert_eq!(s.slug_of("ddd").unwrap().unwrap().slug, "d-two");
977    }
978
979    /// P0.2 across stores: two `DefinitionStore`s on one directory, as two
980    /// channels have. While one holds the record's lock for a rename (the
981    /// slug and a former slug written directly, as Phase 2's will be), the
982    /// other's update waits, then merges onto the renamed record: the slug is
983    /// not reverted and the former slug is not dropped.
984    #[test]
985    fn an_update_from_another_store_waits_for_the_record_lock() {
986        let tmp = tempfile::tempdir().unwrap();
987        let root = tmp.path().join("definitions");
988        let a = std::sync::Arc::new(DefinitionStore::open(root.clone()).unwrap());
989        let b = DefinitionStore::open(root).unwrap();
990        a.upsert(&with_slug("aaa", "loap-loap-2")).unwrap();
991
992        let (tx, rx) = std::sync::mpsc::channel();
993        let holder = {
994            let a = a.clone();
995            std::thread::spawn(move || {
996                a.with_record_locked("aaa", |locked| {
997                    let mut rec = locked.get()?.unwrap();
998                    tx.send(()).unwrap();
999                    std::thread::sleep(std::time::Duration::from_millis(300));
1000                    rec.data.slug = "loap-2".to_string();
1001                    rec.data.former_slugs = vec![former("loap-loap-2", 1)];
1002                    Ok(std::fs::write(a.root().join("aaa.json"), serde_json::to_vec_pretty(&rec)?)?)
1003                })
1004            })
1005        };
1006        rx.recv().unwrap();
1007        let started = std::time::Instant::now();
1008        let mut stale = with_slug("aaa", "loap-loap-2");
1009        stale.data.name = "Edited".to_string();
1010        b.upsert(&stale).unwrap();
1011        assert!(started.elapsed() >= std::time::Duration::from_millis(200), "the update waited for the lock");
1012        holder.join().unwrap().unwrap();
1013
1014        let got = b.get("aaa").unwrap().unwrap();
1015        assert_eq!(got.data.name, "Edited");
1016        assert_eq!(got.data.slug, "loap-2");
1017        assert_eq!(got.data.former_slugs, vec![former("loap-loap-2", 1)]);
1018    }
1019
1020    /// A writer that can't get the lock in time fails with `Locked` and
1021    /// writes nothing.
1022    #[test]
1023    fn a_lock_timeout_fails_and_writes_nothing() {
1024        let tmp = tempfile::tempdir().unwrap();
1025        let root = tmp.path().join("definitions");
1026        let a = std::sync::Arc::new(DefinitionStore::open(root.clone()).unwrap());
1027        let mut b = DefinitionStore::open(root).unwrap();
1028        b.set_lock_timeout(std::time::Duration::from_millis(100));
1029        a.upsert(&with_slug("aaa", "aaa")).unwrap();
1030        let before = std::fs::read(a.root().join("aaa.json")).unwrap();
1031
1032        let (tx, rx) = std::sync::mpsc::channel();
1033        let holder = {
1034            let a = a.clone();
1035            std::thread::spawn(move || {
1036                a.with_record_locked("aaa", |_| {
1037                    tx.send(()).unwrap();
1038                    std::thread::sleep(std::time::Duration::from_millis(600));
1039                    Ok(())
1040                })
1041            })
1042        };
1043        rx.recv().unwrap();
1044        let mut edit = with_slug("aaa", "aaa");
1045        edit.data.name = "Changed".to_string();
1046        assert!(matches!(b.upsert(&edit), Err(DefStoreError::Locked { .. })));
1047        assert!(matches!(b.retire("aaa"), Err(DefStoreError::Locked { .. })));
1048        assert_eq!(std::fs::read(a.root().join("aaa.json")).unwrap(), before, "nothing written");
1049        holder.join().unwrap().unwrap();
1050    }
1051
1052    /// The strict index fails when the directory can't be listed or a
1053    /// record's slug fields can't be read, and reads a newer schema's.
1054    #[test]
1055    fn the_strict_slug_index_fails_closed_and_reads_newer_schemas() {
1056        let (_t, s) = store();
1057        s.upsert(&with_slug("aaa", "a")).unwrap();
1058        let future = r#"{"schema_version":99,"data":{"id":"bbb","slug":"b","former_slugs":[{"slug":"b-old"}]}}"#;
1059        std::fs::write(s.root().join("bbb.json"), future).unwrap();
1060        let strict = s.slug_index_strict().unwrap();
1061        assert_eq!(strict["bbb"].former, vec!["b-old".to_string()]);
1062        assert!(!s.slug_index().unwrap().contains_key("bbb"), "the lenient index lists what list_active does");
1063
1064        for bad in [r#"{"data":{"id":"ccc","former_slugs":"x"}}"#, "{", r#"{"data":{"id":"other"}}"#] {
1065            std::fs::write(s.root().join("ccc.json"), bad).unwrap();
1066            assert!(s.slug_index_strict().is_err(), "{bad}");
1067        }
1068        std::fs::remove_file(s.root().join("ccc.json")).unwrap();
1069        assert!(s.slug_index_strict().is_ok());
1070
1071        std::fs::remove_dir_all(s.root()).unwrap();
1072        assert!(s.slug_index_strict().is_err(), "an unlistable directory");
1073    }
1074
1075    /// Slug allocation is one host-wide lock: a second store waits for it,
1076    /// then fails with `Locked`; once released it is free again.
1077    #[test]
1078    fn slug_allocation_is_exclusive_and_bounded() {
1079        let tmp = tempfile::tempdir().unwrap();
1080        let root = tmp.path().join("definitions");
1081        let a = DefinitionStore::open(root.clone()).unwrap();
1082        let mut b = DefinitionStore::open(root).unwrap();
1083        b.set_lock_timeout(std::time::Duration::from_millis(100));
1084        let held = a.lock_slug_allocation().unwrap();
1085        assert!(matches!(b.lock_slug_allocation(), Err(DefStoreError::Locked { .. })));
1086        drop(held);
1087        assert!(b.lock_slug_allocation().is_ok());
1088    }
1089
1090    /// Seat changes are one host-wide lock too, apart from slug allocation.
1091    #[test]
1092    fn the_seat_lock_is_exclusive_and_separate() {
1093        let tmp = tempfile::tempdir().unwrap();
1094        let root = tmp.path().join("definitions");
1095        let a = DefinitionStore::open(root.clone()).unwrap();
1096        let mut b = DefinitionStore::open(root).unwrap();
1097        b.set_lock_timeout(std::time::Duration::from_millis(100));
1098        let held = a.lock_seat_graph().unwrap();
1099        assert!(matches!(b.lock_seat_graph(), Err(DefStoreError::Locked { .. })));
1100        assert!(b.lock_slug_allocation().is_ok(), "slug allocation isn't blocked by it");
1101        drop(held);
1102        assert!(b.lock_seat_graph().is_ok());
1103    }
1104
1105    #[test]
1106    fn upsert_then_list() {
1107        let (_t, s) = store();
1108        s.upsert(&rec("aaa", "Demo")).unwrap();
1109        let listed = s.list_active().unwrap();
1110        assert_eq!(listed.len(), 1);
1111        assert_eq!(listed[0].data.name, "Demo");
1112    }
1113
1114    #[test]
1115    fn upsert_update_replaces_known_fields() {
1116        let (_t, s) = store();
1117        s.upsert(&rec("aaa", "Demo")).unwrap();
1118        s.upsert(&rec("aaa", "Renamed")).unwrap();
1119        let listed = s.list_active().unwrap();
1120        assert_eq!(listed.len(), 1);
1121        assert_eq!(listed[0].data.name, "Renamed");
1122    }
1123
1124    #[test]
1125    fn retire_then_unretire_round_trips() {
1126        let (_t, s) = store();
1127        s.upsert(&rec("aaa", "Demo")).unwrap();
1128        s.retire("aaa").unwrap();
1129        assert!(s.list_active().unwrap().is_empty());
1130        assert!(s.exists_anywhere("aaa"));
1131        s.unretire("aaa").unwrap();
1132        assert_eq!(s.list_active().unwrap().len(), 1);
1133    }
1134
1135    #[test]
1136    fn hard_delete_removes_both_paths() {
1137        let (_t, s) = store();
1138        s.upsert(&rec("aaa", "Demo")).unwrap();
1139        s.retire("aaa").unwrap();
1140        s.upsert(&rec("bbb", "Demo2")).unwrap();
1141        s.hard_delete("aaa").unwrap();
1142        s.hard_delete("bbb").unwrap();
1143        assert!(!s.exists_anywhere("aaa"));
1144        assert!(!s.exists_anywhere("bbb"));
1145    }
1146
1147    #[test]
1148    fn unknown_field_survives_older_writer_update() {
1149        let (_t, s) = store();
1150        // Write a record carrying a future field directly to disk.
1151        let path = s.root().join("aaa.json");
1152        let raw = serde_json::json!({
1153            "schema_version": 1,
1154            "data": {
1155                "id": "aaa", "name": "Demo", "provider": "claude",
1156                "tags": ["keep-me"]
1157            }
1158        });
1159        std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap();
1160        // An older binary updates a known field.
1161        s.upsert(&rec("aaa", "Renamed")).unwrap();
1162        let on_disk: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
1163        assert_eq!(on_disk.pointer("/data/tags"), Some(&serde_json::json!(["keep-me"])));
1164        assert_eq!(on_disk.pointer("/data/name"), Some(&serde_json::json!("Renamed")));
1165    }
1166
1167    #[test]
1168    fn refuses_to_downgrade_higher_schema_on_disk() {
1169        let (_t, s) = store();
1170        let path = s.root().join("aaa.json");
1171        let v999 = serde_json::json!({
1172            "schema_version": 999,
1173            "data": { "id": "aaa", "future_only": "field" }
1174        });
1175        std::fs::write(&path, serde_json::to_vec_pretty(&v999).unwrap()).unwrap();
1176        s.upsert(&rec("aaa", "Renamed")).unwrap();
1177        let after: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
1178        assert_eq!(after.pointer("/schema_version"), Some(&serde_json::json!(999)));
1179        assert_eq!(after.pointer("/data/future_only"), Some(&serde_json::json!("field")));
1180    }
1181
1182    #[test]
1183    fn upsert_does_not_resurrect_a_tombstoned_definition() {
1184        let (_t, s) = store();
1185        s.upsert(&rec("aaa", "Demo")).unwrap();
1186        s.retire("aaa").unwrap();
1187        // A stale cross-channel mirror upserts the same id.
1188        s.upsert(&rec("aaa", "Resurrected")).unwrap();
1189        // Tombstone respected: still not active, not resurrected.
1190        assert!(
1191            s.list_active().unwrap().is_empty(),
1192            "tombstoned definition must not be resurrected by upsert"
1193        );
1194        assert!(s.exists_anywhere("aaa"), "tombstone file still present");
1195        // An explicit unretire is required to bring it back.
1196        s.unretire("aaa").unwrap();
1197        assert_eq!(s.list_active().unwrap().len(), 1);
1198    }
1199}