Skip to main content

aither_sandbox/
subagent.rs

1//! What a subagent's terminal is allowed to write.
2//!
3//! A subagent works in a space of its own inside its launcher's space and can
4//! read, but not write, everything its launcher can write. The launcher widens
5//! that with a [`SubagentGrant`]: directories, usually linked worktrees, the
6//! subagent may write, and the worktrees it may commit in.
7//!
8//! A linked worktree keeps its git data in the main repository, outside the
9//! worktree, so a worktree grant alone leaves `git commit` failing: the
10//! subagent's terminal reads that data ([`crate::GitDirAccess::ReadOnly`]), so `git
11//! status` and `git log` work, and writes none of it. A commit
12//! grant gives the worktree a repository of its own, created by the host when
13//! the grant is first given, that the worktree's `.git` file names: it holds
14//! the worktree's `HEAD`, index, refs and new objects, reads the main object
15//! store as a read-only alternate and includes the main repository's
16//! configuration. It is the only path the grant makes writable, so nothing a
17//! subagent writes can change what the main repository reads. The commits
18//! reach the main repository only through the [`CommitLedger`]'s import, which
19//! packs them inside the subagent's sandbox and verifies the pack on the host
20//! before any ref moves.
21
22mod host_git;
23mod import;
24mod repository;
25mod sandboxed;
26mod space;
27
28use std::io;
29use std::path::{Path, PathBuf};
30use std::sync::Arc;
31use std::sync::atomic::{AtomicU64, Ordering};
32use std::time::Duration;
33
34use futures::future::join_all;
35
36pub use repository::Spelling;
37use sandboxed::Bounds;
38pub use sandboxed::ExportError;
39pub use sandboxed::{SandboxedExit, SandboxedGitImpl, SandboxedRun, SubagentGit};
40pub use space::{
41    AnySubagentSpaces, PreparedSpace, RunSpace, SpacePreparationError, SubagentSpaces,
42};
43
44/// What a launcher grants a subagent beyond its own space.
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct SubagentGrant {
47    worktrees: Vec<WorktreeGrant>,
48}
49
50/// One directory a subagent may write, and whether it may commit there.
51#[derive(Debug, Clone, PartialEq, Eq)]
52struct WorktreeGrant {
53    path: PathBuf,
54    commit: bool,
55}
56
57impl SubagentGrant {
58    /// A grant of nothing beyond the subagent's own space.
59    #[must_use]
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    /// Lets the subagent write the directory `path`, usually a linked worktree
65    /// the launcher created. Its git data stays read-only, so the subagent
66    /// cannot commit there.
67    #[must_use]
68    pub fn with_worktree(mut self, path: impl Into<PathBuf>) -> Self {
69        self.worktrees.push(WorktreeGrant {
70            path: path.into(),
71            commit: false,
72        });
73        self
74    }
75
76    /// Lets the subagent write the linked worktree at `path` and commit in it.
77    ///
78    /// The worktree's branch must lie in a namespace of its own,
79    /// `refs/heads/subagent/<id>/<name>`, holding no other branch when the
80    /// subagent launches: the commit grant covers that namespace and no other
81    /// ref.
82    #[must_use]
83    pub fn with_committing_worktree(mut self, path: impl Into<PathBuf>) -> Self {
84        self.worktrees.push(WorktreeGrant {
85            path: path.into(),
86            commit: true,
87        });
88        self
89    }
90}
91
92/// Why a [`SubagentGrant`] cannot be given.
93#[derive(Debug, thiserror::Error)]
94pub enum SubagentGrantError {
95    /// The launcher cannot write the path, so it cannot hand it on.
96    #[error("{} is not writable by the agent launching the subagent", .0.display())]
97    OutsideAuthority(PathBuf),
98    /// The launcher is a subagent that may not commit in the worktree, so it
99    /// cannot hand that right on.
100    #[error(
101        "the agent launching the subagent may not commit in {}, so it cannot grant commit there",
102        .0.display()
103    )]
104    CommitOutsideAuthority(PathBuf),
105    /// A path of the grant could not be inspected.
106    #[error("cannot inspect {}: {source}", .path.display())]
107    Inspect {
108        /// The path.
109        path: PathBuf,
110        /// The failure.
111        source: io::Error,
112    },
113    /// The granted path holds a repository checkout, whose git data sits inside
114    /// it and so would be writable whatever the commit grant says.
115    #[error(
116        "{} is a repository checkout, not a linked worktree: its git data would be writable without a commit grant",
117        .0.display()
118    )]
119    RepositoryCheckout(PathBuf),
120    /// A linked worktree's `.git` file or its git directory is not what git
121    /// writes for a linked worktree of the repository it names.
122    #[error("malformed git data of worktree {}: {reason}", .path.display())]
123    MalformedGitData {
124        /// The worktree.
125        path: PathBuf,
126        /// What is wrong.
127        reason: &'static str,
128    },
129    /// A commit grant names a path that is not a linked worktree.
130    #[error("{} is not a linked worktree, so there is nothing to commit in", .0.display())]
131    NotAWorktree(PathBuf),
132    /// Git data the commit authorization depends on overlaps a path some
133    /// subagent can write, so a subagent could rewrite it.
134    #[error(
135        "the git data {} of worktree {} overlaps {}, which a subagent can write",
136        .git_data.display(),
137        .worktree.display(),
138        .writable.display()
139    )]
140    GitDataExposed {
141        /// The worktree.
142        worktree: PathBuf,
143        /// Its git directory or repository.
144        git_data: PathBuf,
145        /// The writable path it overlaps.
146        writable: PathBuf,
147    },
148    /// The worktree's branch does not lie in a subagent branch namespace.
149    #[error(
150        "worktree {} must be on a branch `refs/heads/subagent/<id>/<name>` to be granted commit; its HEAD is `{head}`",
151        .worktree.display()
152    )]
153    BranchOutsideNamespace {
154        /// The worktree.
155        worktree: PathBuf,
156        /// What its `HEAD` holds.
157        head: String,
158    },
159    /// The branch namespace of a committing worktree holds other refs, so it
160    /// is not that worktree's own.
161    #[error(
162        "the branch namespace `{namespace}` of worktree {} also holds `{other}`; each committing worktree needs a namespace of its own",
163        .worktree.display()
164    )]
165    SharedNamespace {
166        /// The worktree.
167        worktree: PathBuf,
168        /// The namespace, `refs/heads/subagent/<id>/`.
169        namespace: String,
170        /// A ref in it that is not the worktree's branch.
171        other: String,
172    },
173    /// The repository stores refs in a reftable, which has no per-namespace
174    /// directory a grant could cover.
175    #[error(
176        "the repository {} stores its refs in a reftable, which a commit grant cannot narrow to one branch namespace",
177        .0.display()
178    )]
179    ReftableRepository(PathBuf),
180    /// The refs of a committing worktree could not be read.
181    #[error(transparent)]
182    Ledger(#[from] CommitLedgerError),
183    /// The terminal runs in a container that does not say which host
184    /// directory it mounts, so a subagent's paths have no container spelling.
185    #[error(
186        "the container runtime declares no workspace mount, so a subagent's paths cannot be confined in it"
187    )]
188    NoContainerMount,
189    /// A path the subagent works in is not inside the container's workspace
190    /// mount.
191    #[error("{} has no path inside the container: {source}", .path.display())]
192    OutsideContainerMount {
193        /// The host path.
194        path: PathBuf,
195        /// Why it cannot be mapped.
196        source: crate::MountRootError,
197    },
198    /// The subagent's own space could not be created.
199    #[error("cannot create the subagent space {}: {source}", .path.display())]
200    Space {
201        /// The directory.
202        path: PathBuf,
203        /// The failure.
204        source: io::Error,
205    },
206    /// Every model-facing id is leased, so the subagent's space has no name.
207    #[error(transparent)]
208    SpaceName(#[from] aither_core::IdsExhausted),
209    /// The embedder's [`SubagentSpaces`] could not prepare the subagent's
210    /// space. The space was removed.
211    #[error("cannot prepare the subagent space {}: {source}", .space.display())]
212    Preparation {
213        /// The space.
214        space: PathBuf,
215        /// The embedder's error.
216        source: SpacePreparationError,
217    },
218    /// The embedder named a working copy or an environment directory outside
219    /// the space it prepared. The space was removed.
220    #[error(
221        "the path {} prepared for a subagent is outside its space {}",
222        .path.display(),
223        .space.display()
224    )]
225    PreparedOutsideSpace {
226        /// The working copy or environment directory, by its canonical path.
227        path: PathBuf,
228        /// The space.
229        space: PathBuf,
230    },
231    /// The repository of a committing worktree could not be created.
232    #[error("cannot create the subagent repository at {}: {source}", .path.display())]
233    Repository {
234        /// The path being written.
235        path: PathBuf,
236        /// The failure.
237        source: io::Error,
238    },
239    /// A path the repository of a committing worktree must spell out is not
240    /// text on one line.
241    #[error("{} cannot be written into a subagent repository", .0.display())]
242    UnrepresentablePath(PathBuf),
243    /// A path handed out with a plain grant contains the committing
244    /// worktree, so a subagent holding that grant could replace the worktree
245    /// and make the host write its `.git` file elsewhere.
246    #[error(
247        "{} contains worktree {}, which is granted commit, and is writable by a subagent",
248        .writable.display(),
249        .worktree.display()
250    )]
251    WorktreeExposed {
252        /// The worktree.
253        worktree: PathBuf,
254        /// The writable path that contains it.
255        writable: PathBuf,
256    },
257    /// The git on the host is older than a commit grant works with.
258    #[error("a commit grant needs git 2.29 or later; the host has `{found}`")]
259    GitTooOld {
260        /// What `git --version` printed.
261        found: String,
262    },
263    /// A commit grant was asked for somewhere the terminal can run no git
264    /// shim, so the isolation the grant promises could not be kept.
265    #[error("a commit grant needs a POSIX shell for its git shim; this platform has none")]
266    CommitGrantUnsupported,
267}
268
269/// What a launching terminal may hand on.
270#[derive(Clone, Copy)]
271pub struct Launcher<'a> {
272    /// The canonical paths the launcher can write, its working directory
273    /// included.
274    pub writable: &'a [PathBuf],
275    /// The worktrees a subagent launcher may commit in. `None` for the main
276    /// agent, whose commit grants are read from the repository and need its
277    /// git data inside [`Self::writable`].
278    pub committing: Option<&'a [CommittingWorktree]>,
279    /// The directory every subagent space of the session lives under.
280    pub spaces_root: &'a Path,
281    /// How the subagents' backend spells host paths.
282    pub(crate) spelling: Spelling<'a>,
283}
284
285/// What the main agent's terminal has handed to subagents so far.
286///
287/// Every subagent can write only paths recorded here (or inside a space
288/// under the spaces root), so git data that overlaps none of them cannot have
289/// been rewritten by a subagent. A worktree granted commit once keeps the
290/// git data resolved then, whatever its `.git` file says later.
291#[derive(Debug, Default)]
292pub struct LaunchHistory {
293    /// Every directory handed out with a plain write grant.
294    handed_out: Vec<PathBuf>,
295    /// Every worktree granted commit, with the git data resolved for it.
296    committed: Vec<CommittingWorktree>,
297}
298
299/// The paths a [`SubagentGrant`] resolved to.
300#[derive(Debug)]
301pub struct ResolvedGrant {
302    pub writable: Vec<PathBuf>,
303    pub committing: Vec<CommittingWorktree>,
304}
305
306/// A linked worktree a subagent may commit in, with the git data the grant
307/// covers. Everything here was resolved when the grant was first given and is
308/// never re-read from paths a subagent can write.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct CommittingWorktree {
311    /// The worktree.
312    worktree: PathBuf,
313    /// Its entry in the repository's `worktrees`: git's own files for it,
314    /// `HEAD` mirrored by the import. Nothing in it is granted.
315    git_dir: PathBuf,
316    /// The repository's shared git directory.
317    common_dir: PathBuf,
318    /// The repository the host created for the worktree, inside its entry.
319    /// The one path the commit grant makes writable.
320    repository: PathBuf,
321    /// The `<id>` of the worktree's branch namespace `refs/heads/subagent/<id>/`.
322    namespace: String,
323}
324
325/// The most bytes a subagent's sandbox may send the host while the commits it
326/// made are imported: the pack, and every answer to a question about its
327/// repository.
328///
329/// The budget is an operator setting. Every clone is a handle on the same
330/// value, so a change through any of them applies to the next import of every
331/// terminal that holds one. There is no ceiling, and `0` means the bytes are
332/// not bounded at all.
333#[derive(Debug, Clone)]
334pub struct ImportBudget(Arc<AtomicU64>);
335
336impl ImportBudget {
337    /// A budget of `bytes`; `0` is unbounded.
338    #[must_use]
339    pub fn new(bytes: u64) -> Self {
340        Self(Arc::new(AtomicU64::new(bytes)))
341    }
342
343    /// Changes the budget for every handle; `0` is unbounded.
344    pub fn set(&self, bytes: u64) {
345        self.0.store(bytes, Ordering::Relaxed);
346    }
347
348    /// The budget now, `0` being unbounded.
349    #[must_use]
350    pub fn get(&self) -> u64 {
351        self.0.load(Ordering::Relaxed)
352    }
353
354    /// The byte bound of an import that starts now.
355    fn limit(&self) -> Option<u64> {
356        Some(self.get()).filter(|bytes| *bytes != 0)
357    }
358}
359
360/// What bounds one import of a subagent's commits.
361#[derive(Debug, Clone)]
362pub struct ImportLimits {
363    /// The most bytes of pack, or of any answer, the subagent's sandbox may
364    /// send the host.
365    pub bytes: ImportBudget,
366    /// How long each piece of sandboxed work of an import may take: every
367    /// question to the subagent's repository, the pack, and the tidying after.
368    pub time: Duration,
369}
370
371impl ImportLimits {
372    /// The bounds an import that starts now runs under.
373    fn bounds(&self) -> Bounds {
374        Bounds {
375            bytes: self.bytes.limit(),
376            time: self.time,
377        }
378    }
379}
380
381/// Whether one path lies inside the other.
382fn overlaps(a: &Path, b: &Path) -> bool {
383    a.starts_with(b) || b.starts_with(a)
384}
385
386fn inside_any(path: &Path, roots: &[PathBuf]) -> bool {
387    roots.iter().any(|root| path.starts_with(root))
388}
389
390impl CommittingWorktree {
391    /// The worktree.
392    pub(crate) fn worktree(&self) -> &Path {
393        &self.worktree
394    }
395
396    /// Its entry in the repository's `worktrees`: the host-owned git
397    /// directory a main agent's `git` in the worktree resolves to.
398    pub(crate) fn git_dir(&self) -> &Path {
399        &self.git_dir
400    }
401
402    /// `refs/heads/subagent/<id>/`, as git spells the namespace.
403    fn ref_prefix(&self) -> String {
404        format!("refs/heads/subagent/{}/", self.namespace)
405    }
406
407    /// The directories a commit writes: the worktree's repository, and
408    /// nothing else.
409    pub fn writable(&self) -> Vec<PathBuf> {
410        vec![self.repository.clone()]
411    }
412
413    fn layout(&self) -> repository::Layout<'_> {
414        repository::Layout {
415            worktree: &self.worktree,
416            entry: &self.git_dir,
417            common: &self.common_dir,
418            repository: &self.repository,
419            namespace: &self.namespace,
420        }
421    }
422
423    /// Gives the worktree its repository, if it has none yet, and points the
424    /// worktree's `.git` file at it.
425    async fn prepare(&self, spelling: Spelling<'_>) -> Result<(), SubagentGrantError> {
426        repository::ensure(self.layout(), spelling).await
427    }
428
429    /// Reads the git data of the linked worktree at `worktree` from the
430    /// repository, for a commit grant the main agent gives.
431    ///
432    /// `exposed` are the paths a subagent can write that must not overlap the
433    /// worktree's git data; `plain` those among them that were handed out
434    /// whole, which must not contain the worktree either.
435    async fn discover(
436        worktree: &Path,
437        git: Option<WorktreeGit>,
438        exposed: impl Iterator<Item = &Path>,
439        plain: impl Iterator<Item = &Path>,
440    ) -> Result<Self, SubagentGrantError> {
441        let malformed = |reason| SubagentGrantError::MalformedGitData {
442            path: worktree.to_path_buf(),
443            reason,
444        };
445        let WorktreeGit {
446            git_dir,
447            common_dir,
448            converted,
449        } = git.ok_or_else(|| SubagentGrantError::NotAWorktree(worktree.to_path_buf()))?;
450
451        confirm_back_links(worktree, &git_dir, &common_dir).await?;
452        if async_fs::metadata(common_dir.join("reftable"))
453            .await
454            .is_ok()
455        {
456            return Err(SubagentGrantError::ReftableRepository(common_dir));
457        }
458        for writable in exposed {
459            for git_data in [&git_dir, &common_dir] {
460                if overlaps(writable, git_data) {
461                    return Err(SubagentGrantError::GitDataExposed {
462                        worktree: worktree.to_path_buf(),
463                        git_data: git_data.clone(),
464                        writable: writable.to_path_buf(),
465                    });
466                }
467            }
468        }
469        // The host writes the worktree's `.git` file; a subagent that could
470        // swap the worktree for a symlink first would redirect that write.
471        for writable in plain {
472            if worktree.starts_with(writable) {
473                return Err(SubagentGrantError::WorktreeExposed {
474                    worktree: worktree.to_path_buf(),
475                    writable: writable.to_path_buf(),
476                });
477            }
478        }
479
480        let repository = git_dir.join(repository::REPOSITORY_DIR);
481        if converted {
482            // The namespace was fixed when the repository was created, in a
483            // file only the host writes; the repository itself says what a
484            // subagent made it say.
485            let namespace = read_file(&git_dir.join(repository::NAMESPACE_FILE)).await?;
486            let namespace = namespace.trim();
487            if namespace.is_empty()
488                || namespace.contains('/')
489                || namespace == "."
490                || namespace == ".."
491            {
492                return Err(malformed("its recorded branch namespace is not valid"));
493            }
494            return Ok(Self {
495                worktree: worktree.to_path_buf(),
496                git_dir,
497                common_dir,
498                repository,
499                namespace: namespace.to_string(),
500            });
501        }
502
503        let head = read_file(&git_dir.join("HEAD")).await?;
504        let head = head.trim();
505        let namespace = head
506            .strip_prefix("ref: refs/heads/subagent/")
507            .and_then(|rest| rest.split_once('/'))
508            .filter(|(id, name)| !name.is_empty() && !id.is_empty() && *id != "." && *id != "..")
509            .map(|(id, _)| id.to_string())
510            .ok_or_else(|| SubagentGrantError::BranchOutsideNamespace {
511                worktree: worktree.to_path_buf(),
512                head: head.to_string(),
513            })?;
514        let branch = head.trim_start_matches("ref: ").to_string();
515
516        let worktree = Self {
517            worktree: worktree.to_path_buf(),
518            git_dir,
519            common_dir,
520            repository,
521            namespace,
522        };
523        // The namespace is the worktree's own: nothing else lives in it, so
524        // every ref the subagent moves there is its own work.
525        if let Some(other) = worktree
526            .namespace_refs()
527            .await?
528            .into_iter()
529            .map(|(_, name)| name)
530            .find(|name| *name != branch)
531        {
532            return Err(SubagentGrantError::SharedNamespace {
533                namespace: worktree.ref_prefix(),
534                worktree: worktree.worktree,
535                other,
536            });
537        }
538        Ok(worktree)
539    }
540
541    /// Every ref in the namespace, as `(object id, ref name)`, read from the
542    /// repository.
543    async fn namespace_refs(&self) -> Result<Vec<(String, String)>, CommitLedgerError> {
544        let prefix = self.ref_prefix();
545        let output = host_git::git(
546            &self.common_dir,
547            &[
548                "for-each-ref",
549                "--format=%(objectname)%00%(refname)",
550                prefix.as_str(),
551            ],
552        )
553        .await?;
554        output
555            .lines()
556            .map(|line| {
557                line.split_once('\0')
558                    .and_then(|(id, name)| Some((object_id(id)?.to_string(), name.to_string())))
559                    .ok_or_else(|| CommitLedgerError::Output {
560                        repository: self.common_dir.clone(),
561                        line: line.to_string(),
562                    })
563            })
564            .collect()
565    }
566
567    /// The commits the worktree's refs point at now: every ref in the branch
568    /// namespace and a detached `HEAD`. Both live in the main repository,
569    /// where only the host writes.
570    async fn tips(&self) -> Result<Vec<String>, CommitLedgerError> {
571        let mut tips: Vec<String> = self
572            .namespace_refs()
573            .await?
574            .into_iter()
575            .map(|(id, _)| id)
576            .collect();
577        // `HEAD` is read as plain data: a detached commit id is a tip, a
578        // symbolic ref names a branch that is either in the namespace or not
579        // the subagent's to move.
580        let head_path = self.git_dir.join("HEAD");
581        match async_fs::read_to_string(&head_path).await {
582            Ok(head) => tips.extend(object_id(head.trim()).map(str::to_string)),
583            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
584            Err(source) => {
585                return Err(CommitLedgerError::Read {
586                    path: head_path,
587                    source,
588                });
589            }
590        }
591        tips.sort_unstable();
592        tips.dedup();
593        Ok(tips)
594    }
595
596    /// The commits reachable from `now` and not from `before`, oldest first.
597    async fn commits_between(
598        &self,
599        before: &[String],
600        now: &[String],
601    ) -> Result<Vec<SubagentCommit>, CommitLedgerError> {
602        if now.is_empty() {
603            return Ok(Vec::new());
604        }
605        let mut args = vec![
606            "log",
607            "--no-show-signature",
608            "--no-decorate",
609            "--no-color",
610            "--reverse",
611            "--format=%H%x00%s",
612        ];
613        args.extend(now.iter().map(String::as_str));
614        args.push("--not");
615        args.extend(before.iter().map(String::as_str));
616        let output = host_git::git(&self.common_dir, &args).await?;
617        output
618            .lines()
619            .map(|line| {
620                line.split_once('\0')
621                    .and_then(|(id, subject)| {
622                        Some(SubagentCommit {
623                            worktree: self.worktree.clone(),
624                            commit: object_id(id)?.to_string(),
625                            subject: subject.to_string(),
626                        })
627                    })
628                    .ok_or_else(|| CommitLedgerError::Output {
629                        repository: self.common_dir.clone(),
630                        line: line.to_string(),
631                    })
632            })
633            .collect()
634    }
635}
636
637/// `text` when it is a full hexadecimal object id, SHA-1 or SHA-256.
638fn object_id(text: &str) -> Option<&str> {
639    (matches!(text.len(), 40 | 64) && text.bytes().all(|byte| byte.is_ascii_hexdigit()))
640        .then_some(text)
641}
642
643/// The git data a linked worktree's `.git` file names.
644struct WorktreeGit {
645    /// The per-worktree git directory.
646    git_dir: PathBuf,
647    /// The repository's shared git directory.
648    common_dir: PathBuf,
649    /// Whether the `.git` file names the worktree's own repository inside
650    /// that directory, as a commit grant leaves it, rather than the directory
651    /// itself.
652    converted: bool,
653}
654
655/// `path` resolved to its canonical form, without the Windows verbatim
656/// (`\\?\`) prefix, which git and other tools given these paths cannot read.
657pub async fn canonical(path: &Path) -> Result<PathBuf, SubagentGrantError> {
658    async_fs::canonicalize(path)
659        .await
660        .map(|canonical| dunce::simplified(&canonical).to_path_buf())
661        .map_err(|source| SubagentGrantError::Inspect {
662            path: path.to_path_buf(),
663            source,
664        })
665}
666
667async fn read_file(path: &Path) -> Result<String, SubagentGrantError> {
668    async_fs::read_to_string(path)
669        .await
670        .map_err(|source| SubagentGrantError::Inspect {
671            path: path.to_path_buf(),
672            source,
673        })
674}
675
676/// The most bytes of a worktree's `.git` file the host reads: a `gitdir:` line
677/// holds one path.
678const DOT_GIT_LIMIT: u64 = 16 * 1024;
679
680/// What a worktree's `.git` is.
681enum DotGit {
682    Missing,
683    Directory,
684    /// A regular file and what it holds.
685    File(String),
686}
687
688/// Reads the worktree's `.git`, which a subagent can write, without ever
689/// following a symlink in its place, waiting on a FIFO, or reading more than
690/// [`DOT_GIT_LIMIT`] bytes.
691async fn read_dot_git(dot_git: &Path) -> io::Result<DotGit> {
692    use std::io::Read as _;
693
694    let path = dot_git.to_path_buf();
695    blocking::unblock(move || {
696        let mut options = std::fs::OpenOptions::new();
697        options.read(true);
698        #[cfg(unix)]
699        {
700            use std::os::unix::fs::OpenOptionsExt as _;
701            options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
702        }
703        let file = match options.open(&path) {
704            Ok(file) => file,
705            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(DotGit::Missing),
706            Err(error) => return Err(error),
707        };
708        let metadata = file.metadata()?;
709        if metadata.is_dir() {
710            return Ok(DotGit::Directory);
711        }
712        if !metadata.is_file() {
713            return Err(io::Error::new(
714                io::ErrorKind::InvalidInput,
715                "not a regular file",
716            ));
717        }
718        let mut content = Vec::new();
719        file.take(DOT_GIT_LIMIT + 1).read_to_end(&mut content)?;
720        if u64::try_from(content.len()).map_or(true, |len| len > DOT_GIT_LIMIT) {
721            return Err(io::Error::new(
722                io::ErrorKind::InvalidData,
723                "longer than a gitdir line can be",
724            ));
725        }
726        String::from_utf8(content)
727            .map(DotGit::File)
728            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
729    })
730    .await
731}
732
733/// `path` resolved like [`canonical`], except that its last component may be
734/// missing: the repository of a worktree that was deleted, to be created
735/// again.
736async fn canonical_with_missing_leaf(path: &Path) -> Result<PathBuf, SubagentGrantError> {
737    match canonical(path).await {
738        Err(SubagentGrantError::Inspect { source, .. })
739            if source.kind() == io::ErrorKind::NotFound =>
740        {
741            match (path.parent(), path.file_name()) {
742                (Some(parent), Some(name)) => Ok(canonical(parent).await?.join(name)),
743                _ => canonical(path).await,
744            }
745        }
746        other => other,
747    }
748}
749
750/// Confirms through git's own back-links that the repository at `common_dir`
751/// lists `worktree`: its git directory is an entry of the repository's
752/// `worktrees`, and that entry names this worktree's `.git` file. A `.git`
753/// file is text anyone who can write the worktree can forge, so nothing it
754/// names is trusted before this holds.
755async fn confirm_back_links(
756    worktree: &Path,
757    git_dir: &Path,
758    common_dir: &Path,
759) -> Result<(), SubagentGrantError> {
760    let malformed = |reason| SubagentGrantError::MalformedGitData {
761        path: worktree.to_path_buf(),
762        reason,
763    };
764    if git_dir.parent() != Some(common_dir.join("worktrees").as_path()) {
765        return Err(malformed(
766            "its git directory is not an entry of the repository's `worktrees`",
767        ));
768    }
769    let back = read_file(&git_dir.join("gitdir")).await?;
770    let back = canonical(&git_dir.join(back.trim())).await?;
771    if back != canonical(&worktree.join(".git")).await? {
772        return Err(malformed(
773            "the repository's worktree entry names another worktree",
774        ));
775    }
776    Ok(())
777}
778
779/// The shared git directory of `worktree`, when `worktree` is a linked
780/// worktree its repository confirms by git's back-links; `None` when it is
781/// not a linked worktree or when what its `.git` names is unconfirmed or
782/// unreadable. A worktree holding a repository of its own, as a commit grant
783/// leaves it, has no shared git directory to give.
784pub async fn confirmed_common_dir(worktree: &Path) -> Option<PathBuf> {
785    let git = match read_worktree_git(worktree).await {
786        Ok(Some(git)) if !git.converted => git,
787        Ok(_) => return None,
788        Err(error) => {
789            tracing::debug!(%error, "no common git directory granted");
790            return None;
791        }
792    };
793    match confirm_back_links(worktree, &git.git_dir, &git.common_dir).await {
794        Ok(()) => Some(git.common_dir),
795        Err(error) => {
796            tracing::debug!(%error, "unconfirmed worktree pointer grants nothing");
797            None
798        }
799    }
800}
801
802/// Reads the git data the `.git` file of `worktree` names.
803///
804/// `None` when `worktree` is not a git working tree at all; an error when it is
805/// a repository checkout rather than a linked worktree.
806async fn read_worktree_git(worktree: &Path) -> Result<Option<WorktreeGit>, SubagentGrantError> {
807    let dot_git = worktree.join(".git");
808    let content = match read_dot_git(&dot_git).await {
809        Ok(DotGit::Missing) => return Ok(None),
810        Ok(DotGit::Directory) => {
811            return Err(SubagentGrantError::RepositoryCheckout(
812                worktree.to_path_buf(),
813            ));
814        }
815        Ok(DotGit::File(content)) => content,
816        Err(source) => {
817            return Err(SubagentGrantError::Inspect {
818                path: dot_git,
819                source,
820            });
821        }
822    };
823    let malformed = |reason| SubagentGrantError::MalformedGitData {
824        path: worktree.to_path_buf(),
825        reason,
826    };
827    let git_dir = content
828        .trim()
829        .strip_prefix("gitdir:")
830        .map(str::trim)
831        .ok_or_else(|| malformed("`.git` has no `gitdir:` line"))?;
832    let named = canonical_with_missing_leaf(&worktree.join(git_dir)).await?;
833    // A worktree granted commit names its own repository, which sits inside
834    // its entry in the main repository and has no `commondir` of its own.
835    let (git_dir, converted) = match async_fs::metadata(named.join("commondir")).await {
836        Ok(_) => (named, false),
837        Err(error) if error.kind() == io::ErrorKind::NotFound => {
838            match named
839                .parent()
840                .filter(|_| named.file_name() == Some(repository::REPOSITORY_DIR.as_ref()))
841            {
842                Some(entry) => (entry.to_path_buf(), true),
843                None => return Err(malformed("the git directory has no `commondir`")),
844            }
845        }
846        Err(source) => {
847            return Err(SubagentGrantError::Inspect {
848                path: named.join("commondir"),
849                source,
850            });
851        }
852    };
853    let common_dir = match async_fs::read_to_string(git_dir.join("commondir")).await {
854        Ok(relative) => canonical(&git_dir.join(relative.trim())).await?,
855        Err(error) if error.kind() == io::ErrorKind::NotFound => {
856            return Err(malformed("the git directory has no `commondir`"));
857        }
858        Err(source) => {
859            return Err(SubagentGrantError::Inspect {
860                path: git_dir.join("commondir"),
861                source,
862            });
863        }
864    };
865    Ok(Some(WorktreeGit {
866        git_dir,
867        common_dir,
868        converted,
869    }))
870}
871
872impl CommittingWorktree {
873    /// The committing worktree `launcher` may hand on at `path`: one it holds
874    /// itself when it is a subagent; for the main agent, the one granted
875    /// before or, the first time, the one read from the repository.
876    async fn granted(
877        path: &Path,
878        git: Option<WorktreeGit>,
879        launcher: Launcher<'_>,
880        history: &LaunchHistory,
881        granted: &[PathBuf],
882        plain: &[PathBuf],
883    ) -> Result<Self, SubagentGrantError> {
884        if let Some(held) = launcher.committing {
885            return held
886                .iter()
887                .find(|held| held.worktree == path)
888                .cloned()
889                .ok_or_else(|| SubagentGrantError::CommitOutsideAuthority(path.to_path_buf()));
890        }
891        if let Some(held) = history.committed.iter().find(|held| held.worktree == path) {
892            return Ok(held.clone());
893        }
894        Self::discover(
895            path,
896            git,
897            history
898                .handed_out
899                .iter()
900                .chain(granted)
901                .map(PathBuf::as_path)
902                .chain([launcher.spaces_root]),
903            history
904                .handed_out
905                .iter()
906                .chain(plain)
907                .map(PathBuf::as_path)
908                .chain([launcher.spaces_root]),
909        )
910        .await
911    }
912}
913
914impl SubagentGrant {
915    /// Resolves the grant against what `launcher` may hand on.
916    ///
917    /// Every path the subagent will be able to write, git data included, must
918    /// lie inside what the launcher can write; a subagent launcher hands on
919    /// only the commit grants it holds itself. The main agent's grants are
920    /// recorded in `history`.
921    #[allow(clippy::too_many_lines)]
922    pub(crate) async fn resolve(
923        &self,
924        launcher: Launcher<'_>,
925        history: &mut LaunchHistory,
926    ) -> Result<ResolvedGrant, SubagentGrantError> {
927        let mut paths = Vec::with_capacity(self.worktrees.len());
928        for grant in &self.worktrees {
929            let path = canonical(&grant.path).await?;
930            if !inside_any(&path, launcher.writable) {
931                return Err(SubagentGrantError::OutsideAuthority(path));
932            }
933            paths.push((path, grant.commit));
934        }
935        let granted: Vec<PathBuf> = paths.iter().map(|(path, _)| path.clone()).collect();
936        let plain: Vec<PathBuf> = paths
937            .iter()
938            .filter(|(_, commit)| !commit)
939            .map(|(path, _)| path.clone())
940            .collect();
941
942        let mut writable = Vec::new();
943        let mut committing: Vec<CommittingWorktree> = Vec::new();
944        for (path, commit) in &paths {
945            // A worktree already granted commit has its git data resolved;
946            // its `.git`, which a subagent may have replaced, is not read
947            // again.
948            let known = commit
949                .then(|| {
950                    launcher
951                        .committing
952                        .unwrap_or(&history.committed)
953                        .iter()
954                        .find(|held| held.worktree == *path)
955                })
956                .flatten();
957            let git = if known.is_some() {
958                None
959            } else {
960                read_worktree_git(path).await?
961            };
962            // A worktree's git data inside another granted path would be
963            // writable whatever the commit grant says.
964            let data = known
965                .map(|held| (&held.git_dir, &held.common_dir))
966                .or_else(|| git.as_ref().map(|git| (&git.git_dir, &git.common_dir)));
967            if let Some((git_dir, common_dir)) = data
968                && let Some(exposing) = granted
969                    .iter()
970                    .find(|granted| overlaps(granted, git_dir) || overlaps(granted, common_dir))
971            {
972                return Err(SubagentGrantError::GitDataExposed {
973                    worktree: path.clone(),
974                    git_data: common_dir.clone(),
975                    writable: exposing.clone(),
976                });
977            }
978            if !commit {
979                // A plain write grant never reaches into git data some
980                // subagent's commits are listed from.
981                if let Some(held) = history
982                    .committed
983                    .iter()
984                    .find(|held| overlaps(path, &held.common_dir) || overlaps(path, &held.git_dir))
985                {
986                    return Err(SubagentGrantError::GitDataExposed {
987                        worktree: held.worktree.clone(),
988                        git_data: held.common_dir.clone(),
989                        writable: path.clone(),
990                    });
991                }
992                // Nor does it contain a committing worktree, which a subagent
993                // could then replace under the host's `.git` file.
994                if let Some(held) = history
995                    .committed
996                    .iter()
997                    .find(|held| held.worktree.starts_with(path))
998                {
999                    return Err(SubagentGrantError::WorktreeExposed {
1000                        worktree: held.worktree.clone(),
1001                        writable: path.clone(),
1002                    });
1003                }
1004                writable.push(path.clone());
1005                continue;
1006            }
1007
1008            if launcher.committing.is_none() {
1009                host_git::require_supported_version().await?;
1010            }
1011            let worktree =
1012                CommittingWorktree::granted(path, git, launcher, history, &granted, &plain).await?;
1013            if let Some(part) = worktree
1014                .writable()
1015                .into_iter()
1016                .find(|part| !inside_any(part, launcher.writable))
1017            {
1018                return Err(SubagentGrantError::OutsideAuthority(part));
1019            }
1020            if let Some(shared) = committing.iter().find(|other| {
1021                other.common_dir == worktree.common_dir && other.namespace == worktree.namespace
1022            }) {
1023                return Err(SubagentGrantError::SharedNamespace {
1024                    worktree: worktree.worktree.clone(),
1025                    namespace: worktree.ref_prefix(),
1026                    other: shared.worktree.display().to_string(),
1027                });
1028            }
1029            // Off Unix the terminal runs no `sh`, so nothing guards a
1030            // committing worktree's git data — refused only once every real
1031            // refusal had its say.
1032            if cfg!(unix) {
1033                if launcher.committing.is_none() {
1034                    worktree.prepare(launcher.spelling).await?;
1035                }
1036                writable.push(path.clone());
1037                committing.push(worktree);
1038            } else {
1039                return Err(SubagentGrantError::CommitGrantUnsupported);
1040            }
1041        }
1042
1043        if launcher.committing.is_none() {
1044            history.handed_out.extend(
1045                paths
1046                    .iter()
1047                    .filter(|(_, commit)| !commit)
1048                    .map(|(path, _)| path.clone()),
1049            );
1050            for worktree in &committing {
1051                if !history.committed.contains(worktree) {
1052                    history.committed.push(worktree.clone());
1053                }
1054            }
1055        }
1056        writable.extend(committing.iter().flat_map(CommittingWorktree::writable));
1057        Ok(ResolvedGrant {
1058            writable,
1059            committing,
1060        })
1061    }
1062}
1063
1064/// A commit a subagent made.
1065#[derive(Debug, Clone, PartialEq, Eq)]
1066pub struct SubagentCommit {
1067    /// The worktree it was made in.
1068    pub worktree: PathBuf,
1069    /// The commit id.
1070    pub commit: String,
1071    /// The first line of the commit message.
1072    pub subject: String,
1073}
1074
1075/// Why the commits of a subagent could not be listed.
1076#[derive(Debug, thiserror::Error)]
1077pub enum CommitLedgerError {
1078    /// `git` could not be run.
1079    #[error("cannot run git on {}: {source}", .repository.display())]
1080    Spawn {
1081        /// The repository.
1082        repository: PathBuf,
1083        /// The failure.
1084        source: io::Error,
1085    },
1086    /// `git` failed.
1087    #[error("git failed on {}: {stderr}", .repository.display())]
1088    Git {
1089        /// The repository.
1090        repository: PathBuf,
1091        /// What git printed.
1092        stderr: String,
1093    },
1094    /// `git` printed a line that is not what the query asked for.
1095    #[error("unexpected git output on {}: {line:?}", .repository.display())]
1096    Output {
1097        /// The repository.
1098        repository: PathBuf,
1099        /// The line.
1100        line: String,
1101    },
1102    /// A worktree's `HEAD` could not be read.
1103    #[error("cannot read {}: {source}", .path.display())]
1104    Read {
1105        /// The file.
1106        path: PathBuf,
1107        /// The failure.
1108        source: io::Error,
1109    },
1110    /// A subagent's repository reported a ref or object id that is malformed
1111    /// or lies outside the subagent's branch namespace.
1112    #[error("the subagent repository {} reported {line:?}, which is not a ref of its namespace. {}", .repository.display(), unimported(.repository))]
1113    Report {
1114        /// The subagent's repository.
1115        repository: PathBuf,
1116        /// What it reported.
1117        line: String,
1118    },
1119    /// Git could not run in the subagent's sandbox, failed there, or did not
1120    /// finish in time.
1121    #[error("cannot export from the subagent repository {}: {source}. {}", .repository.display(), unimported(.repository))]
1122    Export {
1123        /// The subagent's repository.
1124        repository: PathBuf,
1125        /// Why.
1126        source: ExportError,
1127    },
1128    /// The pack the subagent's sandbox sent was refused: an object that is
1129    /// not what it claims to be, a broken link, or more than the import
1130    /// allows.
1131    #[error("the pack from the subagent repository {} was refused: {stderr}. {}", .repository.display(), unimported(.repository))]
1132    Rejected {
1133        /// The subagent's repository.
1134        repository: PathBuf,
1135        /// What git said.
1136        stderr: String,
1137    },
1138    /// A tip the subagent reported is missing after indexing, is no commit,
1139    /// or reaches objects that are not there.
1140    #[error("the subagent repository {} reported commits that did not arrive whole: {detail}. {}", .repository.display(), unimported(.repository))]
1141    Incomplete {
1142        /// The subagent's repository.
1143        repository: PathBuf,
1144        /// The object or the git message that says what is missing.
1145        detail: String,
1146    },
1147    /// A ref of the main repository moved while the import was under way.
1148    #[error("`{reference}` moved in the main repository while the commits of {} were imported", .repository.display())]
1149    Moved {
1150        /// The subagent's repository.
1151        repository: PathBuf,
1152        /// The ref.
1153        reference: String,
1154    },
1155    /// The directory a pack is indexed in could not be set up, or the indexed
1156    /// pack could not be moved into the main store.
1157    #[error("cannot use {} to import a pack: {source}", .path.display())]
1158    Quarantine {
1159        /// The path.
1160        path: PathBuf,
1161        /// The failure.
1162        source: io::Error,
1163    },
1164}
1165
1166/// What becomes of commits a repository holds that could not be imported.
1167fn unimported(repository: &Path) -> String {
1168    format!(
1169        "Its commits that were not imported stay in {}; deleting that directory discards them, and granting the worktree again gives it a fresh repository",
1170        repository.display()
1171    )
1172}
1173
1174/// Where a ledger's worktrees stood at one moment: the commits their branch
1175/// namespaces and detached heads pointed at.
1176#[derive(Debug, Clone)]
1177pub struct CommitMark {
1178    tips: Vec<Vec<String>>,
1179    setbacks: Arc<[CommitLedgerError]>,
1180}
1181
1182impl CommitMark {
1183    /// What could not be done to the subagent's repositories before the run.
1184    ///
1185    /// A repository the host cannot refresh or import never keeps a
1186    /// subagent from running; it keeps its commits in itself, out of the main
1187    /// repository, and the run is told here. The commits that failed to
1188    /// import are listed with the next run's when a later import succeeds.
1189    #[must_use]
1190    pub fn setbacks(&self) -> &[CommitLedgerError] {
1191        &self.setbacks
1192    }
1193}
1194
1195/// Lists the commits a subagent holding a commit grant made, and brings them
1196/// into the main repository.
1197///
1198/// The main repository's refs, and so the listing, change only in the import
1199/// that [`Self::since`] runs; it reads nothing a subagent wrote, and the
1200/// subagent's own git runs only inside the subagent's sandbox.
1201#[derive(Debug, Clone)]
1202pub struct CommitLedger {
1203    worktrees: Vec<CommittingWorktree>,
1204    git: SubagentGit,
1205    limits: ImportLimits,
1206}
1207
1208impl CommitLedger {
1209    /// The ledger of `worktrees`; `None` when there are none.
1210    pub(crate) fn new(
1211        worktrees: &[CommittingWorktree],
1212        git: SubagentGit,
1213        limits: ImportLimits,
1214    ) -> Option<Self> {
1215        (!worktrees.is_empty()).then(|| Self {
1216            worktrees: worktrees.to_vec(),
1217            git,
1218            limits,
1219        })
1220    }
1221
1222    /// Starts a run: refreshes each worktree's view of the main repository's
1223    /// refs inside the subagent's sandbox, imports what its repository
1224    /// already holds, then records where every worktree stands. A branch not
1225    /// yet born simply has no tip.
1226    ///
1227    /// What the subagent's repository does or holds never keeps a run from
1228    /// starting. A repository that cannot be refreshed or imported (a stalled
1229    /// or refused one) is left as it is, the run starts from what the main
1230    /// repository holds, and the failure is in [`CommitMark::setbacks`] for the
1231    /// run's report; its commits stay in that repository, which the error
1232    /// names. The mark's tips are always the main repository's, so a later
1233    /// import that succeeds lists the commits an earlier holder left too,
1234    /// never dropping them.
1235    ///
1236    /// # Errors
1237    /// Fails when git cannot list the main repository's refs.
1238    pub async fn mark(&self) -> Result<CommitMark, CommitLedgerError> {
1239        // Every worktree is carried through before an error is looked at, so
1240        // none is dropped partway.
1241        let prepared = join_all(self.worktrees.iter().map(|worktree| async move {
1242            refresh(&self.git, worktree, &self.limits).await?;
1243            // Whatever an earlier holder of the repository left is imported
1244            // now, so it counts as before this run, not as made in it.
1245            worktree.import(&self.git, &self.limits).await
1246        }))
1247        .await;
1248        let setbacks: Vec<CommitLedgerError> =
1249            prepared.into_iter().filter_map(Result::err).collect();
1250        for setback in &setbacks {
1251            tracing::warn!(%setback, "a subagent repository could not be prepared for a run");
1252        }
1253        let tips = join_all(self.worktrees.iter().map(CommittingWorktree::tips))
1254            .await
1255            .into_iter()
1256            .collect::<Result<_, _>>()?;
1257        Ok(CommitMark {
1258            tips,
1259            setbacks: setbacks.into(),
1260        })
1261    }
1262
1263    /// The commits made since `mark`, oldest first per worktree: everything
1264    /// the worktree's branch namespace or detached head reaches now and did
1265    /// not reach then, whatever the subagent did with `HEAD` in between.
1266    ///
1267    /// The subagent's commits are imported into the main repository first.
1268    /// Every worktree's import runs to its end before an error is returned.
1269    ///
1270    /// # Errors
1271    /// Fails when a subagent's commits cannot be imported or git cannot list
1272    /// a worktree's refs or commits.
1273    pub async fn since(&self, mark: &CommitMark) -> Result<Vec<SubagentCommit>, CommitLedgerError> {
1274        let listed = join_all(self.worktrees.iter().zip(&mark.tips).map(
1275            |(worktree, before)| async move {
1276                worktree.import(&self.git, &self.limits).await?;
1277                let now = worktree.tips().await?;
1278                worktree.commits_between(before, &now).await
1279            },
1280        ))
1281        .await;
1282        let mut commits = Vec::new();
1283        for listed in listed {
1284            commits.extend(listed?);
1285        }
1286        Ok(commits)
1287    }
1288}
1289
1290/// Refreshes the subagent repository's snapshot of the main repository's refs
1291/// with a fetch that runs in the subagent's sandbox, so whatever it does stays
1292/// inside what the subagent can write.
1293async fn refresh(
1294    git: &SubagentGit,
1295    worktree: &CommittingWorktree,
1296    limits: &ImportLimits,
1297) -> Result<(), CommitLedgerError> {
1298    git.succeed(
1299        &worktree.repository,
1300        &[
1301            "fetch",
1302            "--quiet",
1303            "--prune",
1304            "--no-write-fetch-head",
1305            "--no-recurse-submodules",
1306            repository::MAIN_REMOTE,
1307        ],
1308        limits.bounds(),
1309    )
1310    .await
1311    .map(drop)
1312    .map_err(|source| CommitLedgerError::Export {
1313        repository: worktree.repository.clone(),
1314        source,
1315    })
1316}
1317
1318/// The null device, which stands in for the global git configuration.
1319#[cfg(windows)]
1320const NULL_DEVICE: &str = "NUL";
1321#[cfg(not(windows))]
1322const NULL_DEVICE: &str = "/dev/null";
1323
1324#[cfg(test)]
1325pub mod tests;