mod host_git;
mod import;
mod repository;
mod sandboxed;
mod space;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use futures::future::join_all;
pub use repository::Spelling;
use sandboxed::Bounds;
pub use sandboxed::ExportError;
pub use sandboxed::{SandboxedExit, SandboxedGitImpl, SandboxedRun, SubagentGit};
pub use space::{
AnySubagentSpaces, PreparedSpace, RunSpace, SpacePreparationError, SubagentSpaces,
};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SubagentGrant {
worktrees: Vec<WorktreeGrant>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct WorktreeGrant {
path: PathBuf,
commit: bool,
}
impl SubagentGrant {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_worktree(mut self, path: impl Into<PathBuf>) -> Self {
self.worktrees.push(WorktreeGrant {
path: path.into(),
commit: false,
});
self
}
#[must_use]
pub fn with_committing_worktree(mut self, path: impl Into<PathBuf>) -> Self {
self.worktrees.push(WorktreeGrant {
path: path.into(),
commit: true,
});
self
}
}
#[derive(Debug, thiserror::Error)]
pub enum SubagentGrantError {
#[error("{} is not writable by the agent launching the subagent", .0.display())]
OutsideAuthority(PathBuf),
#[error(
"the agent launching the subagent may not commit in {}, so it cannot grant commit there",
.0.display()
)]
CommitOutsideAuthority(PathBuf),
#[error("cannot inspect {}: {source}", .path.display())]
Inspect {
path: PathBuf,
source: io::Error,
},
#[error(
"{} is a repository checkout, not a linked worktree: its git data would be writable without a commit grant",
.0.display()
)]
RepositoryCheckout(PathBuf),
#[error("malformed git data of worktree {}: {reason}", .path.display())]
MalformedGitData {
path: PathBuf,
reason: &'static str,
},
#[error("{} is not a linked worktree, so there is nothing to commit in", .0.display())]
NotAWorktree(PathBuf),
#[error(
"the git data {} of worktree {} overlaps {}, which a subagent can write",
.git_data.display(),
.worktree.display(),
.writable.display()
)]
GitDataExposed {
worktree: PathBuf,
git_data: PathBuf,
writable: PathBuf,
},
#[error(
"worktree {} must be on a branch `refs/heads/subagent/<id>/<name>` to be granted commit; its HEAD is `{head}`",
.worktree.display()
)]
BranchOutsideNamespace {
worktree: PathBuf,
head: String,
},
#[error(
"the branch namespace `{namespace}` of worktree {} also holds `{other}`; each committing worktree needs a namespace of its own",
.worktree.display()
)]
SharedNamespace {
worktree: PathBuf,
namespace: String,
other: String,
},
#[error(
"the repository {} stores its refs in a reftable, which a commit grant cannot narrow to one branch namespace",
.0.display()
)]
ReftableRepository(PathBuf),
#[error(transparent)]
Ledger(#[from] CommitLedgerError),
#[error(
"the container runtime declares no workspace mount, so a subagent's paths cannot be confined in it"
)]
NoContainerMount,
#[error("{} has no path inside the container: {source}", .path.display())]
OutsideContainerMount {
path: PathBuf,
source: crate::MountRootError,
},
#[error("cannot create the subagent space {}: {source}", .path.display())]
Space {
path: PathBuf,
source: io::Error,
},
#[error(transparent)]
SpaceName(#[from] aither_core::IdsExhausted),
#[error("cannot prepare the subagent space {}: {source}", .space.display())]
Preparation {
space: PathBuf,
source: SpacePreparationError,
},
#[error(
"the path {} prepared for a subagent is outside its space {}",
.path.display(),
.space.display()
)]
PreparedOutsideSpace {
path: PathBuf,
space: PathBuf,
},
#[error("cannot create the subagent repository at {}: {source}", .path.display())]
Repository {
path: PathBuf,
source: io::Error,
},
#[error("{} cannot be written into a subagent repository", .0.display())]
UnrepresentablePath(PathBuf),
#[error(
"{} contains worktree {}, which is granted commit, and is writable by a subagent",
.writable.display(),
.worktree.display()
)]
WorktreeExposed {
worktree: PathBuf,
writable: PathBuf,
},
#[error("a commit grant needs git 2.29 or later; the host has `{found}`")]
GitTooOld {
found: String,
},
#[error("a commit grant needs a POSIX shell for its git shim; this platform has none")]
CommitGrantUnsupported,
}
#[derive(Clone, Copy)]
pub struct Launcher<'a> {
pub writable: &'a [PathBuf],
pub committing: Option<&'a [CommittingWorktree]>,
pub spaces_root: &'a Path,
pub(crate) spelling: Spelling<'a>,
}
#[derive(Debug, Default)]
pub struct LaunchHistory {
handed_out: Vec<PathBuf>,
committed: Vec<CommittingWorktree>,
}
#[derive(Debug)]
pub struct ResolvedGrant {
pub writable: Vec<PathBuf>,
pub committing: Vec<CommittingWorktree>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommittingWorktree {
worktree: PathBuf,
git_dir: PathBuf,
common_dir: PathBuf,
repository: PathBuf,
namespace: String,
}
#[derive(Debug, Clone)]
pub struct ImportBudget(Arc<AtomicU64>);
impl ImportBudget {
#[must_use]
pub fn new(bytes: u64) -> Self {
Self(Arc::new(AtomicU64::new(bytes)))
}
pub fn set(&self, bytes: u64) {
self.0.store(bytes, Ordering::Relaxed);
}
#[must_use]
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
fn limit(&self) -> Option<u64> {
Some(self.get()).filter(|bytes| *bytes != 0)
}
}
#[derive(Debug, Clone)]
pub struct ImportLimits {
pub bytes: ImportBudget,
pub time: Duration,
}
impl ImportLimits {
fn bounds(&self) -> Bounds {
Bounds {
bytes: self.bytes.limit(),
time: self.time,
}
}
}
fn overlaps(a: &Path, b: &Path) -> bool {
a.starts_with(b) || b.starts_with(a)
}
fn inside_any(path: &Path, roots: &[PathBuf]) -> bool {
roots.iter().any(|root| path.starts_with(root))
}
impl CommittingWorktree {
pub(crate) fn worktree(&self) -> &Path {
&self.worktree
}
pub(crate) fn git_dir(&self) -> &Path {
&self.git_dir
}
fn ref_prefix(&self) -> String {
format!("refs/heads/subagent/{}/", self.namespace)
}
pub fn writable(&self) -> Vec<PathBuf> {
vec![self.repository.clone()]
}
fn layout(&self) -> repository::Layout<'_> {
repository::Layout {
worktree: &self.worktree,
entry: &self.git_dir,
common: &self.common_dir,
repository: &self.repository,
namespace: &self.namespace,
}
}
async fn prepare(&self, spelling: Spelling<'_>) -> Result<(), SubagentGrantError> {
repository::ensure(self.layout(), spelling).await
}
async fn discover(
worktree: &Path,
git: Option<WorktreeGit>,
exposed: impl Iterator<Item = &Path>,
plain: impl Iterator<Item = &Path>,
) -> Result<Self, SubagentGrantError> {
let malformed = |reason| SubagentGrantError::MalformedGitData {
path: worktree.to_path_buf(),
reason,
};
let WorktreeGit {
git_dir,
common_dir,
converted,
} = git.ok_or_else(|| SubagentGrantError::NotAWorktree(worktree.to_path_buf()))?;
confirm_back_links(worktree, &git_dir, &common_dir).await?;
if async_fs::metadata(common_dir.join("reftable"))
.await
.is_ok()
{
return Err(SubagentGrantError::ReftableRepository(common_dir));
}
for writable in exposed {
for git_data in [&git_dir, &common_dir] {
if overlaps(writable, git_data) {
return Err(SubagentGrantError::GitDataExposed {
worktree: worktree.to_path_buf(),
git_data: git_data.clone(),
writable: writable.to_path_buf(),
});
}
}
}
for writable in plain {
if worktree.starts_with(writable) {
return Err(SubagentGrantError::WorktreeExposed {
worktree: worktree.to_path_buf(),
writable: writable.to_path_buf(),
});
}
}
let repository = git_dir.join(repository::REPOSITORY_DIR);
if converted {
let namespace = read_file(&git_dir.join(repository::NAMESPACE_FILE)).await?;
let namespace = namespace.trim();
if namespace.is_empty()
|| namespace.contains('/')
|| namespace == "."
|| namespace == ".."
{
return Err(malformed("its recorded branch namespace is not valid"));
}
return Ok(Self {
worktree: worktree.to_path_buf(),
git_dir,
common_dir,
repository,
namespace: namespace.to_string(),
});
}
let head = read_file(&git_dir.join("HEAD")).await?;
let head = head.trim();
let namespace = head
.strip_prefix("ref: refs/heads/subagent/")
.and_then(|rest| rest.split_once('/'))
.filter(|(id, name)| !name.is_empty() && !id.is_empty() && *id != "." && *id != "..")
.map(|(id, _)| id.to_string())
.ok_or_else(|| SubagentGrantError::BranchOutsideNamespace {
worktree: worktree.to_path_buf(),
head: head.to_string(),
})?;
let branch = head.trim_start_matches("ref: ").to_string();
let worktree = Self {
worktree: worktree.to_path_buf(),
git_dir,
common_dir,
repository,
namespace,
};
if let Some(other) = worktree
.namespace_refs()
.await?
.into_iter()
.map(|(_, name)| name)
.find(|name| *name != branch)
{
return Err(SubagentGrantError::SharedNamespace {
namespace: worktree.ref_prefix(),
worktree: worktree.worktree,
other,
});
}
Ok(worktree)
}
async fn namespace_refs(&self) -> Result<Vec<(String, String)>, CommitLedgerError> {
let prefix = self.ref_prefix();
let output = host_git::git(
&self.common_dir,
&[
"for-each-ref",
"--format=%(objectname)%00%(refname)",
prefix.as_str(),
],
)
.await?;
output
.lines()
.map(|line| {
line.split_once('\0')
.and_then(|(id, name)| Some((object_id(id)?.to_string(), name.to_string())))
.ok_or_else(|| CommitLedgerError::Output {
repository: self.common_dir.clone(),
line: line.to_string(),
})
})
.collect()
}
async fn tips(&self) -> Result<Vec<String>, CommitLedgerError> {
let mut tips: Vec<String> = self
.namespace_refs()
.await?
.into_iter()
.map(|(id, _)| id)
.collect();
let head_path = self.git_dir.join("HEAD");
match async_fs::read_to_string(&head_path).await {
Ok(head) => tips.extend(object_id(head.trim()).map(str::to_string)),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(source) => {
return Err(CommitLedgerError::Read {
path: head_path,
source,
});
}
}
tips.sort_unstable();
tips.dedup();
Ok(tips)
}
async fn commits_between(
&self,
before: &[String],
now: &[String],
) -> Result<Vec<SubagentCommit>, CommitLedgerError> {
if now.is_empty() {
return Ok(Vec::new());
}
let mut args = vec![
"log",
"--no-show-signature",
"--no-decorate",
"--no-color",
"--reverse",
"--format=%H%x00%s",
];
args.extend(now.iter().map(String::as_str));
args.push("--not");
args.extend(before.iter().map(String::as_str));
let output = host_git::git(&self.common_dir, &args).await?;
output
.lines()
.map(|line| {
line.split_once('\0')
.and_then(|(id, subject)| {
Some(SubagentCommit {
worktree: self.worktree.clone(),
commit: object_id(id)?.to_string(),
subject: subject.to_string(),
})
})
.ok_or_else(|| CommitLedgerError::Output {
repository: self.common_dir.clone(),
line: line.to_string(),
})
})
.collect()
}
}
fn object_id(text: &str) -> Option<&str> {
(matches!(text.len(), 40 | 64) && text.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then_some(text)
}
struct WorktreeGit {
git_dir: PathBuf,
common_dir: PathBuf,
converted: bool,
}
pub async fn canonical(path: &Path) -> Result<PathBuf, SubagentGrantError> {
async_fs::canonicalize(path)
.await
.map(|canonical| dunce::simplified(&canonical).to_path_buf())
.map_err(|source| SubagentGrantError::Inspect {
path: path.to_path_buf(),
source,
})
}
async fn read_file(path: &Path) -> Result<String, SubagentGrantError> {
async_fs::read_to_string(path)
.await
.map_err(|source| SubagentGrantError::Inspect {
path: path.to_path_buf(),
source,
})
}
const DOT_GIT_LIMIT: u64 = 16 * 1024;
enum DotGit {
Missing,
Directory,
File(String),
}
async fn read_dot_git(dot_git: &Path) -> io::Result<DotGit> {
use std::io::Read as _;
let path = dot_git.to_path_buf();
blocking::unblock(move || {
let mut options = std::fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = match options.open(&path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(DotGit::Missing),
Err(error) => return Err(error),
};
let metadata = file.metadata()?;
if metadata.is_dir() {
return Ok(DotGit::Directory);
}
if !metadata.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a regular file",
));
}
let mut content = Vec::new();
file.take(DOT_GIT_LIMIT + 1).read_to_end(&mut content)?;
if u64::try_from(content.len()).map_or(true, |len| len > DOT_GIT_LIMIT) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"longer than a gitdir line can be",
));
}
String::from_utf8(content)
.map(DotGit::File)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
})
.await
}
async fn canonical_with_missing_leaf(path: &Path) -> Result<PathBuf, SubagentGrantError> {
match canonical(path).await {
Err(SubagentGrantError::Inspect { source, .. })
if source.kind() == io::ErrorKind::NotFound =>
{
match (path.parent(), path.file_name()) {
(Some(parent), Some(name)) => Ok(canonical(parent).await?.join(name)),
_ => canonical(path).await,
}
}
other => other,
}
}
async fn confirm_back_links(
worktree: &Path,
git_dir: &Path,
common_dir: &Path,
) -> Result<(), SubagentGrantError> {
let malformed = |reason| SubagentGrantError::MalformedGitData {
path: worktree.to_path_buf(),
reason,
};
if git_dir.parent() != Some(common_dir.join("worktrees").as_path()) {
return Err(malformed(
"its git directory is not an entry of the repository's `worktrees`",
));
}
let back = read_file(&git_dir.join("gitdir")).await?;
let back = canonical(&git_dir.join(back.trim())).await?;
if back != canonical(&worktree.join(".git")).await? {
return Err(malformed(
"the repository's worktree entry names another worktree",
));
}
Ok(())
}
pub async fn confirmed_common_dir(worktree: &Path) -> Option<PathBuf> {
let git = match read_worktree_git(worktree).await {
Ok(Some(git)) if !git.converted => git,
Ok(_) => return None,
Err(error) => {
tracing::debug!(%error, "no common git directory granted");
return None;
}
};
match confirm_back_links(worktree, &git.git_dir, &git.common_dir).await {
Ok(()) => Some(git.common_dir),
Err(error) => {
tracing::debug!(%error, "unconfirmed worktree pointer grants nothing");
None
}
}
}
async fn read_worktree_git(worktree: &Path) -> Result<Option<WorktreeGit>, SubagentGrantError> {
let dot_git = worktree.join(".git");
let content = match read_dot_git(&dot_git).await {
Ok(DotGit::Missing) => return Ok(None),
Ok(DotGit::Directory) => {
return Err(SubagentGrantError::RepositoryCheckout(
worktree.to_path_buf(),
));
}
Ok(DotGit::File(content)) => content,
Err(source) => {
return Err(SubagentGrantError::Inspect {
path: dot_git,
source,
});
}
};
let malformed = |reason| SubagentGrantError::MalformedGitData {
path: worktree.to_path_buf(),
reason,
};
let git_dir = content
.trim()
.strip_prefix("gitdir:")
.map(str::trim)
.ok_or_else(|| malformed("`.git` has no `gitdir:` line"))?;
let named = canonical_with_missing_leaf(&worktree.join(git_dir)).await?;
let (git_dir, converted) = match async_fs::metadata(named.join("commondir")).await {
Ok(_) => (named, false),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
match named
.parent()
.filter(|_| named.file_name() == Some(repository::REPOSITORY_DIR.as_ref()))
{
Some(entry) => (entry.to_path_buf(), true),
None => return Err(malformed("the git directory has no `commondir`")),
}
}
Err(source) => {
return Err(SubagentGrantError::Inspect {
path: named.join("commondir"),
source,
});
}
};
let common_dir = match async_fs::read_to_string(git_dir.join("commondir")).await {
Ok(relative) => canonical(&git_dir.join(relative.trim())).await?,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Err(malformed("the git directory has no `commondir`"));
}
Err(source) => {
return Err(SubagentGrantError::Inspect {
path: git_dir.join("commondir"),
source,
});
}
};
Ok(Some(WorktreeGit {
git_dir,
common_dir,
converted,
}))
}
impl CommittingWorktree {
async fn granted(
path: &Path,
git: Option<WorktreeGit>,
launcher: Launcher<'_>,
history: &LaunchHistory,
granted: &[PathBuf],
plain: &[PathBuf],
) -> Result<Self, SubagentGrantError> {
if let Some(held) = launcher.committing {
return held
.iter()
.find(|held| held.worktree == path)
.cloned()
.ok_or_else(|| SubagentGrantError::CommitOutsideAuthority(path.to_path_buf()));
}
if let Some(held) = history.committed.iter().find(|held| held.worktree == path) {
return Ok(held.clone());
}
Self::discover(
path,
git,
history
.handed_out
.iter()
.chain(granted)
.map(PathBuf::as_path)
.chain([launcher.spaces_root]),
history
.handed_out
.iter()
.chain(plain)
.map(PathBuf::as_path)
.chain([launcher.spaces_root]),
)
.await
}
}
impl SubagentGrant {
#[allow(clippy::too_many_lines)]
pub(crate) async fn resolve(
&self,
launcher: Launcher<'_>,
history: &mut LaunchHistory,
) -> Result<ResolvedGrant, SubagentGrantError> {
let mut paths = Vec::with_capacity(self.worktrees.len());
for grant in &self.worktrees {
let path = canonical(&grant.path).await?;
if !inside_any(&path, launcher.writable) {
return Err(SubagentGrantError::OutsideAuthority(path));
}
paths.push((path, grant.commit));
}
let granted: Vec<PathBuf> = paths.iter().map(|(path, _)| path.clone()).collect();
let plain: Vec<PathBuf> = paths
.iter()
.filter(|(_, commit)| !commit)
.map(|(path, _)| path.clone())
.collect();
let mut writable = Vec::new();
let mut committing: Vec<CommittingWorktree> = Vec::new();
for (path, commit) in &paths {
let known = commit
.then(|| {
launcher
.committing
.unwrap_or(&history.committed)
.iter()
.find(|held| held.worktree == *path)
})
.flatten();
let git = if known.is_some() {
None
} else {
read_worktree_git(path).await?
};
let data = known
.map(|held| (&held.git_dir, &held.common_dir))
.or_else(|| git.as_ref().map(|git| (&git.git_dir, &git.common_dir)));
if let Some((git_dir, common_dir)) = data
&& let Some(exposing) = granted
.iter()
.find(|granted| overlaps(granted, git_dir) || overlaps(granted, common_dir))
{
return Err(SubagentGrantError::GitDataExposed {
worktree: path.clone(),
git_data: common_dir.clone(),
writable: exposing.clone(),
});
}
if !commit {
if let Some(held) = history
.committed
.iter()
.find(|held| overlaps(path, &held.common_dir) || overlaps(path, &held.git_dir))
{
return Err(SubagentGrantError::GitDataExposed {
worktree: held.worktree.clone(),
git_data: held.common_dir.clone(),
writable: path.clone(),
});
}
if let Some(held) = history
.committed
.iter()
.find(|held| held.worktree.starts_with(path))
{
return Err(SubagentGrantError::WorktreeExposed {
worktree: held.worktree.clone(),
writable: path.clone(),
});
}
writable.push(path.clone());
continue;
}
if launcher.committing.is_none() {
host_git::require_supported_version().await?;
}
let worktree =
CommittingWorktree::granted(path, git, launcher, history, &granted, &plain).await?;
if let Some(part) = worktree
.writable()
.into_iter()
.find(|part| !inside_any(part, launcher.writable))
{
return Err(SubagentGrantError::OutsideAuthority(part));
}
if let Some(shared) = committing.iter().find(|other| {
other.common_dir == worktree.common_dir && other.namespace == worktree.namespace
}) {
return Err(SubagentGrantError::SharedNamespace {
worktree: worktree.worktree.clone(),
namespace: worktree.ref_prefix(),
other: shared.worktree.display().to_string(),
});
}
if cfg!(unix) {
if launcher.committing.is_none() {
worktree.prepare(launcher.spelling).await?;
}
writable.push(path.clone());
committing.push(worktree);
} else {
return Err(SubagentGrantError::CommitGrantUnsupported);
}
}
if launcher.committing.is_none() {
history.handed_out.extend(
paths
.iter()
.filter(|(_, commit)| !commit)
.map(|(path, _)| path.clone()),
);
for worktree in &committing {
if !history.committed.contains(worktree) {
history.committed.push(worktree.clone());
}
}
}
writable.extend(committing.iter().flat_map(CommittingWorktree::writable));
Ok(ResolvedGrant {
writable,
committing,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubagentCommit {
pub worktree: PathBuf,
pub commit: String,
pub subject: String,
}
#[derive(Debug, thiserror::Error)]
pub enum CommitLedgerError {
#[error("cannot run git on {}: {source}", .repository.display())]
Spawn {
repository: PathBuf,
source: io::Error,
},
#[error("git failed on {}: {stderr}", .repository.display())]
Git {
repository: PathBuf,
stderr: String,
},
#[error("unexpected git output on {}: {line:?}", .repository.display())]
Output {
repository: PathBuf,
line: String,
},
#[error("cannot read {}: {source}", .path.display())]
Read {
path: PathBuf,
source: io::Error,
},
#[error("the subagent repository {} reported {line:?}, which is not a ref of its namespace. {}", .repository.display(), unimported(.repository))]
Report {
repository: PathBuf,
line: String,
},
#[error("cannot export from the subagent repository {}: {source}. {}", .repository.display(), unimported(.repository))]
Export {
repository: PathBuf,
source: ExportError,
},
#[error("the pack from the subagent repository {} was refused: {stderr}. {}", .repository.display(), unimported(.repository))]
Rejected {
repository: PathBuf,
stderr: String,
},
#[error("the subagent repository {} reported commits that did not arrive whole: {detail}. {}", .repository.display(), unimported(.repository))]
Incomplete {
repository: PathBuf,
detail: String,
},
#[error("`{reference}` moved in the main repository while the commits of {} were imported", .repository.display())]
Moved {
repository: PathBuf,
reference: String,
},
#[error("cannot use {} to import a pack: {source}", .path.display())]
Quarantine {
path: PathBuf,
source: io::Error,
},
}
fn unimported(repository: &Path) -> String {
format!(
"Its commits that were not imported stay in {}; deleting that directory discards them, and granting the worktree again gives it a fresh repository",
repository.display()
)
}
#[derive(Debug, Clone)]
pub struct CommitMark {
tips: Vec<Vec<String>>,
setbacks: Arc<[CommitLedgerError]>,
}
impl CommitMark {
#[must_use]
pub fn setbacks(&self) -> &[CommitLedgerError] {
&self.setbacks
}
}
#[derive(Debug, Clone)]
pub struct CommitLedger {
worktrees: Vec<CommittingWorktree>,
git: SubagentGit,
limits: ImportLimits,
}
impl CommitLedger {
pub(crate) fn new(
worktrees: &[CommittingWorktree],
git: SubagentGit,
limits: ImportLimits,
) -> Option<Self> {
(!worktrees.is_empty()).then(|| Self {
worktrees: worktrees.to_vec(),
git,
limits,
})
}
pub async fn mark(&self) -> Result<CommitMark, CommitLedgerError> {
let prepared = join_all(self.worktrees.iter().map(|worktree| async move {
refresh(&self.git, worktree, &self.limits).await?;
worktree.import(&self.git, &self.limits).await
}))
.await;
let setbacks: Vec<CommitLedgerError> =
prepared.into_iter().filter_map(Result::err).collect();
for setback in &setbacks {
tracing::warn!(%setback, "a subagent repository could not be prepared for a run");
}
let tips = join_all(self.worktrees.iter().map(CommittingWorktree::tips))
.await
.into_iter()
.collect::<Result<_, _>>()?;
Ok(CommitMark {
tips,
setbacks: setbacks.into(),
})
}
pub async fn since(&self, mark: &CommitMark) -> Result<Vec<SubagentCommit>, CommitLedgerError> {
let listed = join_all(self.worktrees.iter().zip(&mark.tips).map(
|(worktree, before)| async move {
worktree.import(&self.git, &self.limits).await?;
let now = worktree.tips().await?;
worktree.commits_between(before, &now).await
},
))
.await;
let mut commits = Vec::new();
for listed in listed {
commits.extend(listed?);
}
Ok(commits)
}
}
async fn refresh(
git: &SubagentGit,
worktree: &CommittingWorktree,
limits: &ImportLimits,
) -> Result<(), CommitLedgerError> {
git.succeed(
&worktree.repository,
&[
"fetch",
"--quiet",
"--prune",
"--no-write-fetch-head",
"--no-recurse-submodules",
repository::MAIN_REMOTE,
],
limits.bounds(),
)
.await
.map(drop)
.map_err(|source| CommitLedgerError::Export {
repository: worktree.repository.clone(),
source,
})
}
#[cfg(windows)]
const NULL_DEVICE: &str = "NUL";
#[cfg(not(windows))]
const NULL_DEVICE: &str = "/dev/null";
#[cfg(test)]
pub mod tests;