Skip to main content

agentmux_srv_core/registry/
def_slug_index.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A cached index of every shared definition's slug and former slugs, for
5//! the slug-to-uid reads that run on every message
6//! (`docs/specs/SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` P0.1).
7//!
8//! A file is parsed again only when it may have changed. Each lookup stats
9//! the files (no reads) and reparses one whose modification time or size
10//! differs from what was cached, or that this process wrote since
11//! ([`SlugIndex::invalidate`]). Other channels and instances write these
12//! files too, so the on-disk stamp, not an in-process signal, is what keeps
13//! the cache current. A stamp is trusted only once the file is older than
14//! [`RACY_WINDOW`] at parse time, as git does for its index: a filesystem with
15//! coarse timestamps could otherwise give a quick rewrite of the same size
16//! the same stamp.
17//!
18//! Two views of one cache. [`SlugIndex::all`] is the records `list_active`
19//! would list, for resolving names. [`SlugIndex::all_strict`] is every record
20//! whose slug fields can be read, newer schemas included (`slug_fields`), and
21//! fails when any file or the directory can't be: allocating a new slug
22//! against an incomplete view could take one an unseen agent holds.
23
24use std::collections::{HashMap, HashSet};
25use std::path::Path;
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, SystemTime};
28
29use serde_json::Value;
30
31/// The slug and former slugs of one active shared definition, and the
32/// display names it goes by now (its `name` and `branch_label`, non-empty),
33/// which a former display name of another agent never outranks.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct SlugEntry {
36    pub slug: String,
37    pub former: Vec<String>,
38    pub display: Vec<String>,
39}
40
41/// Wider than the coarsest common timestamp granularity (FAT's 2 s).
42const RACY_WINDOW: Duration = Duration::from_secs(3);
43
44/// What a file looked like when it was parsed.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46struct Stamp {
47    modified: Option<SystemTime>,
48    len: u64,
49}
50
51impl Stamp {
52    fn of(meta: &std::fs::Metadata) -> Stamp {
53        Stamp { modified: meta.modified().ok(), len: meta.len() }
54    }
55}
56
57struct Cached {
58    stamp: Stamp,
59    /// The stamp was taken too close to a write to rule out a second one.
60    racy: bool,
61    /// Its slug fields, or why they can't be read.
62    slugs: Result<SlugEntry, String>,
63    /// Whether the whole record validates (`list_active` would list it).
64    valid: bool,
65}
66
67#[derive(Default)]
68struct State {
69    by_id: HashMap<String, Cached>,
70    /// Files seen but not statted on the last scan, for the strict view.
71    unstatted: Vec<String>,
72    /// Rebuilt from `by_id` when a file changed; `None` until then.
73    snapshot: Option<Arc<HashMap<String, SlugEntry>>>,
74    #[cfg(any(test, feature = "test-support"))]
75    parses: usize,
76}
77
78/// Owned by a `DefinitionStore`; one lock, held for a lookup's stats and any
79/// reparse, so concurrent readers never see a half-updated index.
80#[derive(Default)]
81pub(super) struct SlugIndex(Mutex<State>);
82
83impl SlugIndex {
84    /// Forget `id`, after this process wrote, retired or deleted its file.
85    pub fn invalidate(&self, id: &str) {
86        let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
87        s.by_id.remove(id);
88        s.snapshot = None;
89    }
90
91    /// Every valid active definition in `root`, by id.
92    pub fn all(&self, root: &Path) -> std::io::Result<Arc<HashMap<String, SlugEntry>>> {
93        let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
94        s.scan(root)?;
95        Ok(s.snapshot())
96    }
97
98    /// Every active definition's slug fields, or an error naming what can't
99    /// be read: the directory, a file, or a record's slug fields.
100    pub fn all_strict(&self, root: &Path) -> Result<HashMap<String, SlugEntry>, String> {
101        let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
102        s.scan(root).map_err(|e| format!("{} can't be listed: {e}", root.display()))?;
103        if let Some(file) = s.unstatted.first() {
104            return Err(format!("{file} can't be read"));
105        }
106        s.by_id
107            .iter()
108            .map(|(id, c)| match &c.slugs {
109                Ok(entry) => Ok((id.clone(), entry.clone())),
110                Err(why) => Err(format!("{id}.json: {why}")),
111            })
112            .collect()
113    }
114
115    /// One definition, statting only its own file.
116    pub fn one(&self, root: &Path, id: &str) -> std::io::Result<Option<SlugEntry>> {
117        let path = root.join(format!("{id}.json"));
118        let meta = match std::fs::metadata(&path) {
119            Ok(m) if m.is_file() => m,
120            Ok(_) => return Ok(None),
121            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
122                self.invalidate(id);
123                return Ok(None);
124            }
125            Err(e) => return Err(e),
126        };
127        let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
128        s.refresh(id, &path, Stamp::of(&meta));
129        Ok(s.by_id.get(id).filter(|c| c.valid).and_then(|c| c.slugs.clone().ok()))
130    }
131
132    #[cfg(test)]
133    pub fn parses(&self) -> usize {
134        self.0.lock().unwrap().parses
135    }
136}
137
138impl State {
139    /// Stat every `.json` file in `root`, reparse the changed ones, and drop
140    /// the ones that are gone.
141    fn scan(&mut self, root: &Path) -> std::io::Result<()> {
142        let mut seen = HashSet::new();
143        self.unstatted.clear();
144        for dirent in std::fs::read_dir(root)? {
145            let path = dirent?.path();
146            if path.extension().and_then(|e| e.to_str()) != Some("json") || super::atomic::is_temp_file(&path) {
147                continue;
148            }
149            let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_string) else {
150                continue;
151            };
152            // A real stat, not the directory listing's copy of it.
153            let meta = match std::fs::metadata(&path) {
154                Ok(meta) => meta,
155                Err(e) => {
156                    self.unstatted.push(format!("{} ({e})", path.display()));
157                    continue;
158                }
159            };
160            if !meta.is_file() {
161                continue;
162            }
163            self.refresh(&id, &path, Stamp::of(&meta));
164            seen.insert(id);
165        }
166        let before = self.by_id.len();
167        self.by_id.retain(|id, _| seen.contains(id));
168        if self.by_id.len() != before {
169            self.snapshot = None;
170        }
171        Ok(())
172    }
173
174    fn refresh(&mut self, id: &str, path: &Path, stamp: Stamp) {
175        if matches!(self.by_id.get(id), Some(c) if c.stamp == stamp && !c.racy) {
176            return;
177        }
178        let parsed_at = SystemTime::now();
179        let (slugs, valid) = match std::fs::read(path) {
180            Ok(bytes) => {
181                let valid = match super::def_store::parse_and_validate(&bytes, id) {
182                    Ok(_) => true,
183                    Err(e) => {
184                        tracing::warn!(file = %path.display(), error = %e, "def registry: skipping invalid record");
185                        false
186                    }
187                };
188                (slug_fields(id, &bytes), valid)
189            }
190            Err(e) => (Err(format!("can't be read: {e}")), false),
191        };
192        #[cfg(any(test, feature = "test-support"))]
193        {
194            self.parses += 1;
195        }
196        let racy = stamp.modified.is_none_or(|m| parsed_at.duration_since(m).map_or(true, |age| age < RACY_WINDOW));
197        let changed = self.by_id.get(id).is_none_or(|c| c.slugs != slugs || c.valid != valid);
198        self.by_id.insert(id.to_string(), Cached { stamp, racy, slugs, valid });
199        if changed {
200            self.snapshot = None;
201        }
202    }
203
204    fn snapshot(&mut self) -> Arc<HashMap<String, SlugEntry>> {
205        self.snapshot
206            .get_or_insert_with(|| {
207                Arc::new(
208                    self.by_id
209                        .iter()
210                        .filter(|(_, c)| c.valid)
211                        .filter_map(|(id, c)| c.slugs.clone().ok().map(|e| (id.clone(), e)))
212                        .collect(),
213                )
214            })
215            .clone()
216    }
217}
218
219/// A record's slug and former slugs, read from its raw JSON so that a record
220/// this build can't otherwise load (a newer schema, a field it doesn't know)
221/// still answers, as long as these fields are where this build puts them:
222/// `data.id` naming the file, `data.slug` a string (absent reads as empty),
223/// `data.former_slugs` a list of objects with a string `slug` (absent reads as
224/// none). Anything else is an error naming what is wrong. The display names
225/// (`data.name`, `data.branch_label`) are read when they are strings and
226/// skipped otherwise: they never make a record's slugs unreadable.
227pub(super) fn slug_fields(id: &str, bytes: &[u8]) -> Result<SlugEntry, String> {
228    let json: Value = serde_json::from_slice(bytes).map_err(|e| format!("not JSON ({e})"))?;
229    let data = json.get("data").and_then(Value::as_object).ok_or("no `data` object")?;
230    if data.get("id").and_then(Value::as_str) != Some(id) {
231        return Err("its `data.id` doesn't name this file".to_string());
232    }
233    let slug = match data.get("slug") {
234        None | Some(Value::Null) => String::new(),
235        Some(Value::String(s)) => s.clone(),
236        Some(_) => return Err("`data.slug` isn't a string".to_string()),
237    };
238    let former = match data.get("former_slugs") {
239        None | Some(Value::Null) => Vec::new(),
240        Some(Value::Array(entries)) => entries
241            .iter()
242            .map(|f| f.get("slug").and_then(Value::as_str).map(str::to_string))
243            .collect::<Option<Vec<_>>>()
244            .ok_or("a `data.former_slugs` entry has no string `slug`")?,
245        Some(_) => return Err("`data.former_slugs` isn't a list".to_string()),
246    };
247    let display = ["name", "branch_label"]
248        .iter()
249        .filter_map(|k| data.get(*k).and_then(Value::as_str))
250        .filter(|s| !s.trim().is_empty())
251        .map(str::to_string)
252        .collect();
253    Ok(SlugEntry { slug, former, display })
254}