Skip to main content

vitrify_cli/
layout.rs

1//! Where vitrify keeps its working copies, and what it calls them.
2//!
3//! Two places. `<repo>/.vitrify/` is scratch nothing is ever built in:
4//! transaction worktrees, logs, `run.json`, the repo-level config. The unit
5//! worktrees and the integration checkouts — where workers build and gate
6//! commands run — live **outside the working tree**, by default under the
7//! vitrify home, so that no ignore file of the repository (its own
8//! `.gitignore`, or the `*` vitrify writes into `.vitrify/`) is an ancestor
9//! of the files being checked. Tools that honour parent ignore files would
10//! otherwise treat every source file as ignored and pass without looking.
11//!
12//! Branch and worktree names carry the SDD's slug: several SDDs in one
13//! repository all have a `U-001`, and their work must never share a name.
14//! So do a run's lanes — one per SDD: each has its own integration
15//! checkout and lock, its own head checkout, and its own records under the
16//! job's logs, so runs of different SDDs never wait on each other's gate.
17
18use std::path::{Path, PathBuf};
19
20use vitrify_core::CoreError;
21use vitrify_core::model::{Instance, Meta, Shape};
22use vitrify_core::trace::hash12;
23
24use crate::git::Git;
25
26/// The directories of one repository's vitrify state.
27#[derive(Debug, Clone)]
28pub struct Layout {
29    /// The primary checkout.
30    pub primary: PathBuf,
31    /// `<primary>/.vitrify` — transactions, logs, `run.json`.
32    pub scratch: PathBuf,
33    /// Root of the unit worktrees and the integration checkouts.
34    pub wt_root: PathBuf,
35}
36
37impl Layout {
38    /// The layout for `primary`. `worktree_dir` is `run.worktree_dir`: empty
39    /// puts the worktrees under the vitrify home (`home`), keyed by the
40    /// repository; a relative path is taken from the repository root.
41    pub fn resolve(
42        primary: &Path,
43        home: Option<&Path>,
44        worktree_dir: &str,
45    ) -> Result<Layout, CoreError> {
46        let wt_root = if worktree_dir.trim().is_empty() {
47            let Some(home) = home else {
48                return Err(CoreError::refusal(
49                    1,
50                    "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
51                ));
52            };
53            let name = primary
54                .file_name()
55                .map(|n| ref_part(&n.to_string_lossy()))
56                .unwrap_or_else(|| "repo".to_string());
57            let key = hash12(&primary.to_string_lossy());
58            home.join("worktrees").join(format!("{name}-{}", &key[..8]))
59        } else {
60            let p = PathBuf::from(worktree_dir.trim());
61            if p.is_absolute() { p } else { primary.join(p) }
62        };
63        Ok(Layout::at(primary, &wt_root))
64    }
65
66    /// An explicit layout (tests, and callers that already know the root).
67    pub fn at(primary: &Path, wt_root: &Path) -> Layout {
68        Layout {
69            primary: primary.to_path_buf(),
70            scratch: primary.join(".vitrify"),
71            wt_root: normalize(wt_root),
72        }
73    }
74
75    /// The integration checkout of the SDD `slug`: a detached worktree of
76    /// the mainline head, where its gates and §5 commands run.
77    pub fn mainline(&self, slug: &str) -> PathBuf {
78        self.wt_root.join(format!("mainline-{slug}"))
79    }
80
81    /// The lock on that checkout: runs of one SDD gate one at a time,
82    /// across processes; runs of different SDDs gate side by side. (A slug
83    /// never ends in `.lock`, so no checkout is ever named like a lock.)
84    pub fn mainline_lock(&self, slug: &str) -> PathBuf {
85        self.wt_root.join(format!("mainline-{slug}.lock"))
86    }
87
88    /// The checkout where the lane of the SDD `slug` runs a gate's failing
89    /// rows again on the gate's base, apart from its integration checkout.
90    pub fn base_checkout(&self, slug: &str) -> PathBuf {
91        self.wt_root.join(format!("base-{slug}"))
92    }
93
94    /// This process's detached checkout of the mainline head for the SDD
95    /// `slug`, where the run reads spec state.
96    pub fn head_checkout(&self, slug: &str) -> PathBuf {
97        self.scratch
98            .join(format!("tx-{}-{slug}-head", std::process::id()))
99    }
100
101    /// `.vitrify/logs/<job>/`: the job's own records — its `run.json`,
102    /// `project.json`, `events.jsonl` and final report.
103    pub fn job_logs(&self, job: &str) -> PathBuf {
104        self.scratch.join("logs").join(job)
105    }
106
107    /// `.vitrify/logs/<job>/<slug>/`: one lane's records — its worker logs
108    /// and prompts, its gate board, its escalations.
109    pub fn lane_logs(&self, job: &str, slug: &str) -> PathBuf {
110        self.job_logs(job).join(slug)
111    }
112
113    /// One claim's worktree.
114    pub fn unit_worktree(&self, slug: &str, unit: &str, seq: i64) -> PathBuf {
115        self.wt_root.join(format!("{slug}-{unit}-c{seq}"))
116    }
117
118    /// The worktree root relative to the primary checkout, when it lies
119    /// inside it.
120    pub fn in_tree(&self) -> Option<PathBuf> {
121        self.wt_root
122            .strip_prefix(&self.primary)
123            .ok()
124            .map(Path::to_path_buf)
125    }
126
127    /// Create `.vitrify/` with the ignore file that keeps it out of the
128    /// repository. Nothing is built under it, so the `*` hides nothing a
129    /// tool needs to see.
130    pub fn ensure_scratch(&self) -> Result<(), CoreError> {
131        ensure_scratch(&self.primary).map(|_| ())
132    }
133
134    /// Create the worktree root. A root inside the working tree is added to
135    /// `.git/info/exclude`, and refused when one of the repository's own
136    /// ignore files already covers it — the case in which ignore-aware
137    /// tools check nothing there.
138    pub fn ensure_worktree_root(&self, primary: &Git) -> Result<(), CoreError> {
139        std::fs::create_dir_all(&self.wt_root).map_err(|source| CoreError::Io {
140            path: self.wt_root.clone(),
141            source,
142        })?;
143        let Some(rel) = self.in_tree() else {
144            return Ok(());
145        };
146        let rel = rel.to_string_lossy().replace('\\', "/");
147        if rel.is_empty() {
148            return Err(CoreError::refusal(
149                2,
150                "error: run.worktree_dir is the repository root itself — name a directory",
151            ));
152        }
153        primary
154            .exclude_locally(&format!("/{rel}/"))
155            .map_err(CoreError::from)?;
156        if let Some(source) = primary
157            .ignored_by(&format!("{rel}/probe"))
158            .map_err(CoreError::from)?
159            && !source.contains("info/exclude")
160        {
161            return Err(CoreError::refusal(
162                2,
163                format!(
164                    "error: the worktree directory {rel}/ is ignored by {source} — tools that honour parent ignore files would check nothing in vitrify's worktrees; remove that pattern, or point run.worktree_dir elsewhere"
165                ),
166            ));
167        }
168        Ok(())
169    }
170}
171
172/// `path` with `.` and `..` resolved by name alone (the directory need not
173/// exist yet): `../repo-wt` beside the repository is outside it, whatever
174/// the spelling.
175fn normalize(path: &Path) -> PathBuf {
176    use std::path::Component;
177    let mut out = PathBuf::new();
178    for part in path.components() {
179        match part {
180            Component::CurDir => {}
181            Component::ParentDir => {
182                if !out.pop() {
183                    out.push("..");
184                }
185            }
186            other => out.push(other.as_os_str()),
187        }
188    }
189    out
190}
191
192/// Create `<primary>/.vitrify` and its ignore file; returns the directory.
193pub fn ensure_scratch(primary: &Path) -> Result<PathBuf, CoreError> {
194    let scratch = primary.join(".vitrify");
195    std::fs::create_dir_all(&scratch).map_err(|source| CoreError::Io {
196        path: scratch.clone(),
197        source,
198    })?;
199    let _ = std::fs::write(scratch.join(".gitignore"), "*\n");
200    Ok(scratch)
201}
202
203/// `s` as one component of a git ref or a directory name: anything outside
204/// `[A-Za-z0-9._-]` becomes `-`, leading dots and dashes go, and a `.lock`
205/// suffix (which git forbids) is defused.
206pub fn ref_part(s: &str) -> String {
207    let mut out: String = s
208        .chars()
209        .map(|c| {
210            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
211                c
212            } else {
213                '-'
214            }
215        })
216        .collect();
217    while out.contains("..") {
218        out = out.replace("..", ".");
219    }
220    let mut out = out
221        .trim_start_matches(['.', '-'])
222        .trim_end_matches('.')
223        .to_string();
224    if out.ends_with(".lock") {
225        out.push('-');
226    }
227    if out.is_empty() {
228        out.push_str("sdd");
229    }
230    out
231}
232
233/// The SDD's name in branch and worktree names: its `sdd:` slug, else the
234/// name of its directory (bundle) or file (single).
235pub fn slug_of(meta: &Meta, root: &Path, shape: Shape) -> String {
236    let named = meta.get_str("sdd").map(str::trim).unwrap_or("");
237    if !named.is_empty() {
238        return ref_part(named);
239    }
240    let stem = match shape {
241        Shape::Bundle => root.file_name().map(|n| n.to_string_lossy().to_string()),
242        Shape::Single => root.file_name().map(|n| {
243            let n = n.to_string_lossy();
244            n.strip_suffix(".sdd.md")
245                .or_else(|| n.strip_suffix(".md"))
246                .unwrap_or(&n)
247                .to_string()
248        }),
249    };
250    ref_part(&stem.unwrap_or_default())
251}
252
253pub fn sdd_slug(inst: &Instance) -> String {
254    slug_of(&inst.meta, &inst.root, inst.shape)
255}
256
257/// `sdd/<slug>/<unit>/` — every attempt branch of one unit.
258pub fn branch_prefix(slug: &str, unit: &str) -> String {
259    format!("sdd/{slug}/{}/", ref_part(unit))
260}
261
262/// `sdd/<slug>/<unit>/c<seq>` — the branch name carries the fencing token.
263pub fn unit_branch(slug: &str, unit: &str, seq: i64) -> String {
264    format!("{}c{seq}", branch_prefix(slug, unit))
265}
266
267/// The claim sequence a branch name carries (`…/c<seq>`).
268pub fn branch_seq(branch: &str) -> Option<i64> {
269    branch.rsplit('/').next()?.strip_prefix('c')?.parse().ok()
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn names_carry_the_slug_and_the_token() {
278        assert_eq!(
279            unit_branch("shop-cart", "U-001", 3),
280            "sdd/shop-cart/U-001/c3"
281        );
282        assert_eq!(branch_seq("sdd/shop-cart/U-001/c3"), Some(3));
283        assert_eq!(branch_seq("sdd/shop-cart/U-001/x3"), None);
284        let l = Layout::at(Path::new("/r"), Path::new("/w"));
285        assert_eq!(
286            l.unit_worktree("shop-cart", "U-001", 3),
287            PathBuf::from("/w/shop-cart-U-001-c3")
288        );
289        assert_eq!(
290            l.mainline("shop-cart"),
291            PathBuf::from("/w/mainline-shop-cart")
292        );
293        assert_eq!(
294            l.mainline_lock("shop-cart"),
295            PathBuf::from("/w/mainline-shop-cart.lock")
296        );
297        assert_eq!(
298            l.lane_logs("run-x", "shop-cart"),
299            PathBuf::from("/r/.vitrify/logs/run-x/shop-cart")
300        );
301        assert_eq!(
302            l.head_checkout("shop-cart"),
303            PathBuf::from(format!(
304                "/r/.vitrify/tx-{}-shop-cart-head",
305                std::process::id()
306            ))
307        );
308        assert!(l.in_tree().is_none());
309        assert_eq!(
310            Layout::at(Path::new("/r"), Path::new("/r/wt")).in_tree(),
311            Some(PathBuf::from("wt"))
312        );
313    }
314
315    #[test]
316    fn ref_part_is_always_a_legal_component() {
317        assert_eq!(ref_part("shop-cart"), "shop-cart");
318        assert_eq!(ref_part("my sdd/v2"), "my-sdd-v2");
319        assert_eq!(ref_part("..hidden"), "hidden");
320        assert_eq!(ref_part("a..b"), "a.b");
321        assert_eq!(ref_part("x.lock"), "x.lock-");
322        assert_eq!(ref_part("~^:"), "sdd");
323    }
324
325    #[test]
326    fn default_root_is_outside_the_working_tree_and_keyed_by_repository() {
327        let a = Layout::resolve(Path::new("/src/app"), Some(Path::new("/h")), "").unwrap();
328        let b = Layout::resolve(Path::new("/other/app"), Some(Path::new("/h")), "").unwrap();
329        assert!(a.wt_root.starts_with("/h/worktrees"));
330        assert!(a.in_tree().is_none());
331        assert_ne!(a.wt_root, b.wt_root, "same name, different repository");
332        // an explicit directory: absolute as given, relative from the root
333        let c = Layout::resolve(Path::new("/src/app"), None, "/big/disk").unwrap();
334        assert_eq!(c.wt_root, PathBuf::from("/big/disk"));
335        let d = Layout::resolve(Path::new("/src/app"), None, "vitrify-wt").unwrap();
336        assert_eq!(d.in_tree(), Some(PathBuf::from("vitrify-wt")));
337        // beside the repository is outside it, however it is spelled
338        let e = Layout::resolve(Path::new("/src/app"), None, "../app-wt").unwrap();
339        assert_eq!(e.wt_root, PathBuf::from("/src/app-wt"));
340        assert!(e.in_tree().is_none());
341        let f = Layout::resolve(Path::new("/src/app"), None, "./a/../wt").unwrap();
342        assert_eq!(f.in_tree(), Some(PathBuf::from("wt")));
343        // no home and no directory: nowhere to put them
344        assert!(Layout::resolve(Path::new("/src/app"), None, "").is_err());
345    }
346}