Skip to main content

kernel/
layout.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4// Copyright (c) 2026 2youg1 and the sprawling contributors
5
6//! Where a city keeps each kind of file on disk: one derivation from
7//! the city root and an address (`crates/kernel/spec/Layout.lean` §8-56).
8//!
9//! Every directory name and file name the city writes is declared here
10//! once, and every path it writes them to is spelled here once, so a
11//! rename reaches every caller and none is left reading an empty
12//! directory.
13//!
14//! Nothing here touches a disk. A `CityLayout` is a value: it answers
15//! where a file would be, and the caller that owns the I/O decides
16//! whether to create it, read it, or refuse. That keeps the layout
17//! inside `kernel`, where the address grammar it rests on already is.
18//!
19//! One rule governs the placement itself: **what governs a scope lives
20//! in that scope's reserved subtree, and no write domain reaches it**
21//! (`Address::is_reserved`). The rules of a building, its configuration
22//! layer and its filters are therefore under [`RESERVED_PREFIX`], while
23//! the documents residents write — the job, the handoff, the urbanite
24//! page, the archive — sit in the open where residents can edit them.
25
26use std::ffi::{OsStr, OsString};
27use std::path::{Path, PathBuf};
28
29use crate::{Address, RESERVED_PREFIX};
30
31/// The append-only history of a city, under the city's reserved subtree.
32pub const LEDGER_DIR: &str = "ledger";
33/// The content-addressed object store, under the city's reserved subtree.
34pub const CAS_DIR: &str = "cas";
35/// What the views held after one ledger line, under the city's reserved
36/// subtree; a projection a start may discard.
37pub const SNAPSHOT_DIR: &str = "snapshot";
38/// The city's shelves of skills, under the city's reserved subtree.
39pub const LIBRARY_DIR: &str = "library";
40/// A building's own shelf of skills, under that building's reserved
41/// subtree: what this building knows and no other building is given.
42pub const BUILDING_SHELF: &str = "skills";
43/// The one document of a skill filed as a directory: a package on a
44/// section shelf, and every skill on a shelf the city mounts from
45/// elsewhere. It is the layout pi, claude and agents all use; the
46/// catalog lists this file's first line, and `read` opens the files
47/// beside it by `<name>/<path>`.
48pub const SKILL_FILE: &str = "SKILL.md";
49/// What one configuration layer declares. The same file name at every
50/// layer, because the layer is the scope it sits in rather than a name.
51pub const CONFIG_FILE: &str = "CONFIG.toml";
52/// What a scope keeps out of the transcript it sends to a model.
53pub const FILTERS_FILE: &str = "FILTERS.toml";
54/// Where a building files work it has finished with, by kind and day.
55pub const ARCHIVE_DIR: &str = "Archive";
56/// The task of one session, in the room it is run from.
57pub const JOB_FILE: &str = "JOB.md";
58/// What the next agent needs before it starts, per room.
59pub const HANDOFF_FILE: &str = "Handoff.md";
60/// Who a standing resident is, in that resident's own directory.
61pub const URBANITE_FILE: &str = "URBANITE.md";
62/// How far the person has got through the first-run guide, under the
63/// city's reserved subtree.
64pub const GUIDE_FILE: &str = "GUIDE.toml";
65/// The extension of what one run saw, written in its room as
66/// `<run>.jsonl`.
67pub const TRANSCRIPT_EXT: &str = "jsonl";
68/// A run id as a git ignore pattern: one `?` for each character of the
69/// hyphenated form a [`crate::RunId`] displays, so a building can keep
70/// every run's transcript out of its history by name.
71pub const RUN_ID_PATTERN: &str = "????????-????-????-????-????????????";
72/// What the remote gate keeps on disk, under the city's reserved subtree.
73pub const REMOTE_DIR: &str = "remote";
74/// The devices paired to reach the city from outside the machine.
75pub const DEVICES_FILE: &str = "devices.toml";
76/// Where residents' playback exports land, under the city's reserved
77/// subtree, one directory per building.
78pub const PLAYBACK_DIR: &str = "playback";
79/// The beat the performance monitor samples at, under the city's
80/// reserved subtree (`crates/sprawling/spec/Monitor.lean` D48).
81pub const MONITOR_FILE: &str = "MONITOR.toml";
82
83/// What the staging file of a document named `name` is called: the
84/// name hidden by a dot and suffixed `.staging`, in the document's own
85/// directory (`crates/kernel/spec/Layout.lean` §8-56).
86///
87/// The whole-or-nothing document writer stages here and renames over
88/// the document; the checkpoint scan refuses this name before git opens
89/// it, because the file can be renamed away between the scan's stat and
90/// its read (storage D30). Both ask this function, so the two spellings
91/// cannot drift apart.
92#[must_use]
93pub fn document_staging_name(name: &OsStr) -> OsString {
94    let mut staged = OsString::from(STAGING_PREFIX);
95    staged.push(name);
96    staged.push(STAGING_SUFFIX);
97    staged
98}
99
100/// Whether `name` is spelled the way [`document_staging_name`] spells
101/// the staging file of some document.
102#[must_use]
103pub fn is_document_staging_name(name: &OsStr) -> bool {
104    let spelled = name.as_encoded_bytes();
105    spelled.len() > STAGING_PREFIX.len().saturating_add(STAGING_SUFFIX.len())
106        && spelled.starts_with(STAGING_PREFIX.as_bytes())
107        && spelled.ends_with(STAGING_SUFFIX.as_bytes())
108}
109
110const STAGING_PREFIX: &str = ".";
111const STAGING_SUFFIX: &str = ".staging";
112
113/// The disk layout of one city, derived from its root.
114///
115/// Construct it once per city root and ask it for paths; the segments
116/// are never joined by hand at a call site.
117#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
118pub struct CityLayout {
119    root: PathBuf,
120}
121
122impl CityLayout {
123    /// The layout of the city rooted at `root`.
124    #[must_use]
125    pub fn new(root: &Path) -> Self {
126        Self {
127            root: root.to_path_buf(),
128        }
129    }
130
131    /// The city root this layout derives from.
132    #[must_use]
133    pub fn root(&self) -> &Path {
134        &self.root
135    }
136
137    /// The directory an address names: the city root with the address's
138    /// segments below it.
139    ///
140    /// Segment by segment rather than one joined string, because a
141    /// city served on Windows and a city served on Linux must lay the
142    /// same address down as the same directory.
143    #[must_use]
144    pub fn scope(&self, addr: &Address) -> PathBuf {
145        let mut path = self.root.clone();
146        for segment in addr.as_str().split('/') {
147            path.push(segment);
148        }
149        path
150    }
151
152    /// The whole city's history.
153    #[must_use]
154    pub fn ledger(&self) -> PathBuf {
155        self.governed_root().join(LEDGER_DIR)
156    }
157
158    /// The snapshot a start resumes the views from.
159    #[must_use]
160    pub fn snapshot(&self) -> PathBuf {
161        self.governed_root().join(SNAPSHOT_DIR)
162    }
163
164    /// The whole city's object store.
165    #[must_use]
166    pub fn cas(&self) -> PathBuf {
167        self.governed_root().join(CAS_DIR)
168    }
169
170    /// The city's shelves of skills.
171    #[must_use]
172    pub fn library(&self) -> PathBuf {
173        self.governed_root().join(LIBRARY_DIR)
174    }
175
176    /// The configuration layer a scope declares.
177    #[must_use]
178    pub fn config(&self, addr: &Address) -> PathBuf {
179        self.governed(addr).join(CONFIG_FILE)
180    }
181
182    /// The configuration layer the city itself declares.
183    ///
184    /// The same rule as [`config`](Self::config) at the root, and a
185    /// method of its own because the root is not an address, and a
186    /// caller without one would otherwise join the two names by hand.
187    #[must_use]
188    pub fn city_config(&self) -> PathBuf {
189        self.governed_root().join(CONFIG_FILE)
190    }
191
192    /// What the city as a whole keeps out of what it sends a model.
193    #[must_use]
194    pub fn city_filters(&self) -> PathBuf {
195        self.governed_root().join(FILTERS_FILE)
196    }
197
198    /// A building's own shelf of skills.
199    #[must_use]
200    pub fn building_skills(&self, addr: &Address) -> PathBuf {
201        self.governed(addr).join(BUILDING_SHELF)
202    }
203
204    /// What a scope keeps out of what it sends a model.
205    #[must_use]
206    pub fn filters(&self, addr: &Address) -> PathBuf {
207        self.governed(addr).join(FILTERS_FILE)
208    }
209
210    /// Where a building files finished work.
211    ///
212    /// In the open rather than under the reserved subtree: residents
213    /// write these documents and read them back.
214    #[must_use]
215    pub fn archive(&self, building: &Address) -> PathBuf {
216        self.scope(building).join(ARCHIVE_DIR)
217    }
218
219    /// The task written for the session run at this address.
220    #[must_use]
221    pub fn job(&self, addr: &Address) -> PathBuf {
222        self.scope(addr).join(JOB_FILE)
223    }
224
225    /// What one room hands to whoever picks it up next.
226    ///
227    /// The room's rather than the building's: two sessions of one
228    /// building can freeze at once, and one file for both would be two
229    /// contents fighting over one name.
230    #[must_use]
231    pub fn handoff(&self, room: &Address) -> PathBuf {
232        self.scope(room).join(HANDOFF_FILE)
233    }
234
235    /// Who the standing resident at this address is.
236    #[must_use]
237    pub fn urbanite(&self, addr: &Address) -> PathBuf {
238        self.scope(addr).join(URBANITE_FILE)
239    }
240
241    /// How far the person has got through this city's first-run guide
242    /// (`crates/wire/Spec.lean` §8-68).
243    ///
244    /// Under the city's reserved subtree, because it decides what this
245    /// city shows a person when it opens, and no write domain reaches it.
246    #[must_use]
247    pub fn guide(&self) -> PathBuf {
248        self.governed_root().join(GUIDE_FILE)
249    }
250
251    /// The devices paired to reach this city from outside the machine.
252    ///
253    /// Under the city's reserved subtree, because the table decides who
254    /// may reach the city and no write domain may change that
255    /// (`crates/kernel/spec/Layout.lean` §8-76).
256    #[must_use]
257    pub fn devices(&self) -> PathBuf {
258        self.governed_root().join(REMOTE_DIR).join(DEVICES_FILE)
259    }
260
261    /// Where residents' playback exports land, one directory per
262    /// building (`crates/accounting/Spec.lean` §8-13, `crates/sprawling/Spec.lean` §8-132).
263    ///
264    /// Under the city's reserved subtree, because no write domain reaches
265    /// it, so a written report is changed only by exporting another; the
266    /// city root's `.gitignore` keeps it out of history; and no worktree
267    /// holds it, so sweeping one loses no report.
268    #[must_use]
269    pub fn playback_exports(&self) -> PathBuf {
270        self.governed_root().join(PLAYBACK_DIR)
271    }
272
273    /// Where this city remembers its monitor's sampling beat: a setting
274    /// of how this machine measures, which no write domain reaches.
275    #[must_use]
276    pub fn monitor(&self) -> PathBuf {
277        self.governed_root().join(MONITOR_FILE)
278    }
279
280    /// The layout whose ledger is `dir`, when `dir` is a city's.
281    ///
282    /// The inverse of [`ledger`](Self::ledger), for the writer that is
283    /// handed the ledger directory and must find the root every other
284    /// path is derived from. `None` for a directory that is not a ledger
285    /// under a reserved prefix: a fixture, a bundle being verified, or a
286    /// store somebody opened directly, none of which is a city.
287    #[must_use]
288    pub fn of_ledger(dir: &Path) -> Option<CityLayout> {
289        if dir.file_name()? != LEDGER_DIR {
290            return None;
291        }
292        let governed = dir.parent()?;
293        if governed.file_name()? != RESERVED_PREFIX {
294            return None;
295        }
296        let root = governed.parent()?;
297        if root.as_os_str().is_empty() {
298            return None;
299        }
300        Some(CityLayout::new(root))
301    }
302
303    /// The city's own name, read from the directory it lives in.
304    ///
305    /// The one address that names the city rather than a room: the
306    /// genesis record carries it so a city can say who it is, and the
307    /// session projection must file it nowhere, because no building is
308    /// named after the city inside itself. Not every directory name is
309    /// an address - a path can hold characters an address may not - and
310    /// a city whose directory cannot be spelled as an address simply has
311    /// no name to show, which is honest and rare.
312    #[must_use]
313    pub fn city_address(&self) -> Option<Address> {
314        self.root
315            .file_name()
316            .and_then(|name| name.to_str())
317            .and_then(|name| Address::parse(name).ok())
318    }
319
320    /// The city root's own reserved subtree.
321    fn governed_root(&self) -> PathBuf {
322        self.root.join(RESERVED_PREFIX)
323    }
324
325    /// A scope's own reserved subtree: what governs that scope, where no
326    /// write domain reaches it.
327    fn governed(&self, addr: &Address) -> PathBuf {
328        self.scope(addr).join(RESERVED_PREFIX)
329    }
330}
331
332#[cfg(test)]
333#[allow(
334    clippy::unwrap_used,
335    clippy::expect_used,
336    clippy::panic,
337    clippy::indexing_slicing,
338    reason = "test code"
339)]
340mod tests;