1mod 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct SubagentGrant {
47 worktrees: Vec<WorktreeGrant>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52struct WorktreeGrant {
53 path: PathBuf,
54 commit: bool,
55}
56
57impl SubagentGrant {
58 #[must_use]
60 pub fn new() -> Self {
61 Self::default()
62 }
63
64 #[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 #[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#[derive(Debug, thiserror::Error)]
94pub enum SubagentGrantError {
95 #[error("{} is not writable by the agent launching the subagent", .0.display())]
97 OutsideAuthority(PathBuf),
98 #[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 #[error("cannot inspect {}: {source}", .path.display())]
107 Inspect {
108 path: PathBuf,
110 source: io::Error,
112 },
113 #[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 #[error("malformed git data of worktree {}: {reason}", .path.display())]
123 MalformedGitData {
124 path: PathBuf,
126 reason: &'static str,
128 },
129 #[error("{} is not a linked worktree, so there is nothing to commit in", .0.display())]
131 NotAWorktree(PathBuf),
132 #[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 worktree: PathBuf,
143 git_data: PathBuf,
145 writable: PathBuf,
147 },
148 #[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 worktree: PathBuf,
156 head: String,
158 },
159 #[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 worktree: PathBuf,
168 namespace: String,
170 other: String,
172 },
173 #[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 #[error(transparent)]
182 Ledger(#[from] CommitLedgerError),
183 #[error(
186 "the container runtime declares no workspace mount, so a subagent's paths cannot be confined in it"
187 )]
188 NoContainerMount,
189 #[error("{} has no path inside the container: {source}", .path.display())]
192 OutsideContainerMount {
193 path: PathBuf,
195 source: crate::MountRootError,
197 },
198 #[error("cannot create the subagent space {}: {source}", .path.display())]
200 Space {
201 path: PathBuf,
203 source: io::Error,
205 },
206 #[error(transparent)]
208 SpaceName(#[from] aither_core::IdsExhausted),
209 #[error("cannot prepare the subagent space {}: {source}", .space.display())]
212 Preparation {
213 space: PathBuf,
215 source: SpacePreparationError,
217 },
218 #[error(
221 "the path {} prepared for a subagent is outside its space {}",
222 .path.display(),
223 .space.display()
224 )]
225 PreparedOutsideSpace {
226 path: PathBuf,
228 space: PathBuf,
230 },
231 #[error("cannot create the subagent repository at {}: {source}", .path.display())]
233 Repository {
234 path: PathBuf,
236 source: io::Error,
238 },
239 #[error("{} cannot be written into a subagent repository", .0.display())]
242 UnrepresentablePath(PathBuf),
243 #[error(
247 "{} contains worktree {}, which is granted commit, and is writable by a subagent",
248 .writable.display(),
249 .worktree.display()
250 )]
251 WorktreeExposed {
252 worktree: PathBuf,
254 writable: PathBuf,
256 },
257 #[error("a commit grant needs git 2.29 or later; the host has `{found}`")]
259 GitTooOld {
260 found: String,
262 },
263 #[error("a commit grant needs a POSIX shell for its git shim; this platform has none")]
266 CommitGrantUnsupported,
267}
268
269#[derive(Clone, Copy)]
271pub struct Launcher<'a> {
272 pub writable: &'a [PathBuf],
275 pub committing: Option<&'a [CommittingWorktree]>,
279 pub spaces_root: &'a Path,
281 pub(crate) spelling: Spelling<'a>,
283}
284
285#[derive(Debug, Default)]
292pub struct LaunchHistory {
293 handed_out: Vec<PathBuf>,
295 committed: Vec<CommittingWorktree>,
297}
298
299#[derive(Debug)]
301pub struct ResolvedGrant {
302 pub writable: Vec<PathBuf>,
303 pub committing: Vec<CommittingWorktree>,
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct CommittingWorktree {
311 worktree: PathBuf,
313 git_dir: PathBuf,
316 common_dir: PathBuf,
318 repository: PathBuf,
321 namespace: String,
323}
324
325#[derive(Debug, Clone)]
334pub struct ImportBudget(Arc<AtomicU64>);
335
336impl ImportBudget {
337 #[must_use]
339 pub fn new(bytes: u64) -> Self {
340 Self(Arc::new(AtomicU64::new(bytes)))
341 }
342
343 pub fn set(&self, bytes: u64) {
345 self.0.store(bytes, Ordering::Relaxed);
346 }
347
348 #[must_use]
350 pub fn get(&self) -> u64 {
351 self.0.load(Ordering::Relaxed)
352 }
353
354 fn limit(&self) -> Option<u64> {
356 Some(self.get()).filter(|bytes| *bytes != 0)
357 }
358}
359
360#[derive(Debug, Clone)]
362pub struct ImportLimits {
363 pub bytes: ImportBudget,
366 pub time: Duration,
369}
370
371impl ImportLimits {
372 fn bounds(&self) -> Bounds {
374 Bounds {
375 bytes: self.bytes.limit(),
376 time: self.time,
377 }
378 }
379}
380
381fn 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 pub(crate) fn worktree(&self) -> &Path {
393 &self.worktree
394 }
395
396 pub(crate) fn git_dir(&self) -> &Path {
399 &self.git_dir
400 }
401
402 fn ref_prefix(&self) -> String {
404 format!("refs/heads/subagent/{}/", self.namespace)
405 }
406
407 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 async fn prepare(&self, spelling: Spelling<'_>) -> Result<(), SubagentGrantError> {
426 repository::ensure(self.layout(), spelling).await
427 }
428
429 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 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 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 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 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 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 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 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
637fn 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
643struct WorktreeGit {
645 git_dir: PathBuf,
647 common_dir: PathBuf,
649 converted: bool,
653}
654
655pub 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
676const DOT_GIT_LIMIT: u64 = 16 * 1024;
679
680enum DotGit {
682 Missing,
683 Directory,
684 File(String),
686}
687
688async 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
733async 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
750async 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
779pub 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
802async 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 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 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 #[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 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
1066pub struct SubagentCommit {
1067 pub worktree: PathBuf,
1069 pub commit: String,
1071 pub subject: String,
1073}
1074
1075#[derive(Debug, thiserror::Error)]
1077pub enum CommitLedgerError {
1078 #[error("cannot run git on {}: {source}", .repository.display())]
1080 Spawn {
1081 repository: PathBuf,
1083 source: io::Error,
1085 },
1086 #[error("git failed on {}: {stderr}", .repository.display())]
1088 Git {
1089 repository: PathBuf,
1091 stderr: String,
1093 },
1094 #[error("unexpected git output on {}: {line:?}", .repository.display())]
1096 Output {
1097 repository: PathBuf,
1099 line: String,
1101 },
1102 #[error("cannot read {}: {source}", .path.display())]
1104 Read {
1105 path: PathBuf,
1107 source: io::Error,
1109 },
1110 #[error("the subagent repository {} reported {line:?}, which is not a ref of its namespace. {}", .repository.display(), unimported(.repository))]
1113 Report {
1114 repository: PathBuf,
1116 line: String,
1118 },
1119 #[error("cannot export from the subagent repository {}: {source}. {}", .repository.display(), unimported(.repository))]
1122 Export {
1123 repository: PathBuf,
1125 source: ExportError,
1127 },
1128 #[error("the pack from the subagent repository {} was refused: {stderr}. {}", .repository.display(), unimported(.repository))]
1132 Rejected {
1133 repository: PathBuf,
1135 stderr: String,
1137 },
1138 #[error("the subagent repository {} reported commits that did not arrive whole: {detail}. {}", .repository.display(), unimported(.repository))]
1141 Incomplete {
1142 repository: PathBuf,
1144 detail: String,
1146 },
1147 #[error("`{reference}` moved in the main repository while the commits of {} were imported", .repository.display())]
1149 Moved {
1150 repository: PathBuf,
1152 reference: String,
1154 },
1155 #[error("cannot use {} to import a pack: {source}", .path.display())]
1158 Quarantine {
1159 path: PathBuf,
1161 source: io::Error,
1163 },
1164}
1165
1166fn 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#[derive(Debug, Clone)]
1177pub struct CommitMark {
1178 tips: Vec<Vec<String>>,
1179 setbacks: Arc<[CommitLedgerError]>,
1180}
1181
1182impl CommitMark {
1183 #[must_use]
1190 pub fn setbacks(&self) -> &[CommitLedgerError] {
1191 &self.setbacks
1192 }
1193}
1194
1195#[derive(Debug, Clone)]
1202pub struct CommitLedger {
1203 worktrees: Vec<CommittingWorktree>,
1204 git: SubagentGit,
1205 limits: ImportLimits,
1206}
1207
1208impl CommitLedger {
1209 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 pub async fn mark(&self) -> Result<CommitMark, CommitLedgerError> {
1239 let prepared = join_all(self.worktrees.iter().map(|worktree| async move {
1242 refresh(&self.git, worktree, &self.limits).await?;
1243 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 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
1290async 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#[cfg(windows)]
1320const NULL_DEVICE: &str = "NUL";
1321#[cfg(not(windows))]
1322const NULL_DEVICE: &str = "/dev/null";
1323
1324#[cfg(test)]
1325pub mod tests;