Skip to main content

change_capsule/manager/
mod.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fs::{self, File, OpenOptions};
3use std::io::Read;
4use std::path::{Component, Path, PathBuf};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use sha2::{Digest, Sha256};
8use ulid::Ulid;
9
10use crate::artifact::{ArtifactReader, ArtifactSink, PublishedArtifact};
11use crate::capabilities::{
12    IDEMPOTENCY_RECORD_SCHEMA_VERSION, LABEL_BYTES_LIMIT, LINK_KEY_BYTES_LIMIT,
13    LINK_VALUE_BYTES_LIMIT, LINKS_LIMIT,
14};
15use crate::error::{Error, Result, io};
16use crate::git::{CommitPatch, Git, Repository};
17use crate::idempotency::{
18    IdempotencyLookup, IdempotencyRecord, IdempotencyStatus, canonical_request_sha256, key_sha256,
19};
20use crate::model::{
21    ArtifactBundle, ArtifactDescriptor, ArtifactKind, BUNDLE_SCHEMA_VERSION, Capsule,
22    CapsuleHealth, CapsuleListing, CapsuleResult, CapsuleState, CapsuleStatus, CapsuleSummary,
23    Checkpoint, CheckpointJournal, Cleanup, Evidence, ExportReport, Integration, RecoveryAction,
24    ResultKind, ResultRef, SCHEMA_VERSION,
25};
26use crate::state::{StateStore, default_state_root, project_key};
27
28const LABEL_CAP: usize = LABEL_BYTES_LIMIT;
29const LINK_KEY_CAP: usize = LINK_KEY_BYTES_LIMIT;
30const LINK_VALUE_CAP: usize = LINK_VALUE_BYTES_LIMIT;
31const MESSAGE_CAP: usize = 16 * 1024;
32const EVIDENCE_COMMAND_CAP: usize = 16 * 1024;
33const EVIDENCE_SUMMARY_CAP: usize = 64 * 1024;
34const EVIDENCE_COUNT_CAP: usize = 64;
35const EVIDENCE_TOTAL_BYTES_CAP: usize = 256 * 1024;
36const CHECKPOINT_COUNT_CAP: usize = 128;
37const DEFAULT_AUTHOR_NAME: &str = "Capsule";
38const DEFAULT_AUTHOR_EMAIL: &str = "capsule@localhost";
39
40/// Commit identity used for checkpoints and integration commits.
41///
42/// Always explicit: this crate never reads the ambient Git configuration to
43/// decide who authored a change it creates.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub struct Author {
47    /// Name recorded as both author and committer.
48    pub name: String,
49    /// Email recorded as both author and committer. Must contain `@`.
50    pub email: String,
51}
52
53impl Author {
54    /// Identity to record as both author and committer.
55    ///
56    /// The email must contain `@`; it is validated at the operation boundary.
57    pub fn new(name: impl Into<String>, email: impl Into<String>) -> Self {
58        Self {
59            name: name.into(),
60            email: email.into(),
61        }
62    }
63}
64
65impl Default for Author {
66    fn default() -> Self {
67        Self {
68            name: DEFAULT_AUTHOR_NAME.to_owned(),
69            email: DEFAULT_AUTHOR_EMAIL.to_owned(),
70        }
71    }
72}
73
74/// Inputs for creating a capsule.
75#[derive(Debug, Clone)]
76#[non_exhaustive]
77pub struct CreateOptions {
78    /// Any path inside the source Git repository.
79    pub repository: PathBuf,
80    /// Revision to pin, resolved to an immutable commit before work starts.
81    pub base: String,
82    /// Optional human-facing description of the attempt.
83    pub label: Option<String>,
84    /// Opaque caller metadata, at most 32 entries. No key is privileged.
85    pub links: BTreeMap<String, String>,
86}
87
88impl CreateOptions {
89    /// Options for a capsule based on the repository's current `HEAD`.
90    pub fn new(repository: impl Into<PathBuf>) -> Self {
91        Self {
92            repository: repository.into(),
93            base: "HEAD".to_owned(),
94            label: None,
95            links: BTreeMap::new(),
96        }
97    }
98
99    /// Pin a different revision as the base.
100    #[must_use]
101    pub fn with_base(mut self, base: impl Into<String>) -> Self {
102        self.base = base.into();
103        self
104    }
105
106    /// Set the human-facing attempt label.
107    #[must_use]
108    pub fn with_label(mut self, label: impl Into<String>) -> Self {
109        self.label = Some(label.into());
110        self
111    }
112
113    /// Replace the opaque caller links.
114    #[must_use]
115    pub fn with_links(mut self, links: BTreeMap<String, String>) -> Self {
116        self.links = links;
117        self
118    }
119}
120
121/// Inputs for committing the workspace's current state as a checkpoint.
122#[derive(Debug, Clone)]
123#[non_exhaustive]
124pub struct CheckpointOptions {
125    /// Message for the checkpoint commit.
126    pub message: String,
127    /// Identity to record on the commit.
128    pub author: Author,
129}
130
131impl CheckpointOptions {
132    /// Options for a checkpoint commit with an explicit identity.
133    pub fn new(message: impl Into<String>, author: Author) -> Self {
134        Self {
135            message: message.into(),
136            author,
137        }
138    }
139}
140
141/// How a verification record is produced.
142///
143/// The two variants are deliberately separate types rather than a flag, because
144/// everything a verifier can conclude from the resulting [`Evidence`] depends on
145/// which one was used.
146#[derive(Debug, Clone)]
147#[non_exhaustive]
148pub enum EvidenceInput {
149    /// Run this argument vector in the capsule workspace and record what happened.
150    ///
151    /// Capsule spawns the program directly, with no shell, and observes the exit
152    /// status and output itself. The resulting record has `executed: true`.
153    Run {
154        /// Program and arguments. The first element is the program.
155        argv: Vec<String>,
156        /// Optional summary. Defaults to the tail of the captured output.
157        summary: Option<String>,
158        /// Kill the command and fail if it runs longer than this.
159        timeout: Option<std::time::Duration>,
160    },
161    /// Record a caller-supplied claim. Capsule executes nothing and vouches for nothing.
162    Claim {
163        /// Exact command line the caller reports having run.
164        command: String,
165        /// Exit status the caller reports having observed.
166        exit_code: i32,
167        /// Optional bounded summary of what happened.
168        summary: Option<String>,
169    },
170}
171
172impl EvidenceInput {
173    /// Have Capsule execute `argv` in the capsule workspace.
174    ///
175    /// This produces the only evidence a verifier can treat as fact.
176    pub fn run<I, S>(argv: I) -> Self
177    where
178        I: IntoIterator<Item = S>,
179        S: Into<String>,
180    {
181        Self::Run {
182            argv: argv.into_iter().map(Into::into).collect(),
183            summary: None,
184            timeout: None,
185        }
186    }
187
188    /// Record that `command` was run elsewhere and exited with `exit_code`.
189    ///
190    /// Capsule records the claim and never executes it.
191    pub fn claim(command: impl Into<String>, exit_code: i32) -> Self {
192        Self::Claim {
193            command: command.into(),
194            exit_code,
195            summary: None,
196        }
197    }
198
199    /// Attach a bounded summary.
200    #[must_use]
201    pub fn with_summary(mut self, text: impl Into<String>) -> Self {
202        match &mut self {
203            Self::Run { summary, .. } | Self::Claim { summary, .. } => {
204                *summary = Some(text.into());
205            }
206        }
207        self
208    }
209
210    /// Kill an executed command that runs longer than this. Ignored for a claim.
211    #[must_use]
212    pub fn with_timeout(mut self, limit: std::time::Duration) -> Self {
213        if let Self::Run { timeout, .. } = &mut self {
214            *timeout = Some(limit);
215        }
216        self
217    }
218
219    /// The command line this record will carry.
220    ///
221    /// For an executed run this renders `argv` with POSIX quoting, so an
222    /// argument containing spaces stays one argument to anyone reading the
223    /// receipt. It is a faithful rendering of what ran, not a string that was
224    /// ever handed to a shell: Capsule spawns the program directly.
225    pub fn command_line(&self) -> String {
226        match self {
227            Self::Run { argv, .. } => argv
228                .iter()
229                .map(|argument| render_argument(argument))
230                .collect::<Vec<_>>()
231                .join(" "),
232            Self::Claim { command, .. } => command.clone(),
233        }
234    }
235}
236
237/// Render one argument so a reader can tell where it starts and ends.
238fn render_argument(argument: &str) -> String {
239    let plain = !argument.is_empty()
240        && argument.bytes().all(|byte| {
241            byte.is_ascii_alphanumeric()
242                || matches!(
243                    byte,
244                    b'-' | b'_' | b'.' | b'/' | b'=' | b':' | b'+' | b'@' | b','
245                )
246        });
247    if plain {
248        argument.to_owned()
249    } else {
250        format!("'{}'", argument.replace('\'', r"'\''"))
251    }
252}
253
254/// Requirements a capsule must satisfy before its result is sealed.
255///
256/// These are independent, not a ladder. In particular
257/// [`Self::require_successful_evidence`] asks something the other two do not:
258/// that **no** record anywhere on the capsule failed. That deliberately forbids
259/// the ordinary agent loop of running tests, fixing what broke, and running them
260/// again, so combine it with the others only when you really mean it.
261#[derive(Debug, Clone, Copy, Default)]
262#[non_exhaustive]
263pub struct CloseOptions {
264    /// Refuse to seal unless evidence exists and *every* record's exit code is zero.
265    ///
266    /// A single earlier failure blocks sealing, even if the capsule has since
267    /// been fixed and re-verified.
268    pub require_successful_evidence: bool,
269    /// Refuse to seal unless some successful record is bound to the patch being sealed.
270    pub require_current_successful_evidence: bool,
271    /// Refuse to seal unless Capsule itself ran a command that passed on this patch.
272    ///
273    /// This is the strongest useful requirement, and it subsumes the one above:
274    /// the record it looks for is executed, passing, and bound to this patch.
275    pub require_executed_evidence: bool,
276}
277
278impl CloseOptions {
279    /// Seal with an explicit combination of requirements.
280    #[must_use]
281    pub fn requiring(
282        require_successful_evidence: bool,
283        require_current_successful_evidence: bool,
284        require_executed_evidence: bool,
285    ) -> Self {
286        Self {
287            require_successful_evidence,
288            require_current_successful_evidence,
289            require_executed_evidence,
290        }
291    }
292
293    /// Seal only when Capsule ran a passing command against the exact sealed patch.
294    ///
295    /// This is the level a merge gate should use. It does not also demand a
296    /// spotless history: an attempt whose tests failed and were then fixed
297    /// still seals, because what matters is the state of the patch being sealed.
298    #[must_use]
299    pub fn executed() -> Self {
300        Self {
301            require_successful_evidence: false,
302            require_current_successful_evidence: false,
303            require_executed_evidence: true,
304        }
305    }
306}
307
308/// Inputs for applying a sealed result to a target worktree.
309#[derive(Debug, Clone)]
310#[non_exhaustive]
311pub struct IntegrateOptions {
312    /// Any path inside the destination worktree.
313    ///
314    /// It must belong to the same repository, be clean, and still be at the
315    /// capsule's pinned base.
316    pub target: PathBuf,
317    /// Commit subject. Defaults to the capsule label, then a generated subject.
318    pub message: Option<String>,
319    /// Identity to record on the integration commit.
320    pub author: Author,
321}
322
323impl IntegrateOptions {
324    /// Options for applying a sealed result to `target`.
325    ///
326    /// Set [`Self::message`] to override the generated commit subject.
327    pub fn new(target: impl Into<PathBuf>, author: Author) -> Self {
328        Self {
329            target: target.into(),
330            message: None,
331            author,
332        }
333    }
334
335    /// Override the generated commit subject.
336    #[must_use]
337    pub fn with_message(mut self, message: impl Into<String>) -> Self {
338        self.message = Some(message.into());
339        self
340    }
341}
342
343/// Entry point for every capsule operation.
344///
345/// A manager owns one state directory and resolves the Git executable once when
346/// opened. Instances are cheap; operations serialize across processes through
347/// file locks, so several managers may safely share a state root.
348///
349/// # Example
350///
351/// ```no_run
352/// use change_capsule::{CapsuleManager, CreateOptions};
353///
354/// let manager = CapsuleManager::open_default()?;
355/// let capsule = manager.create(CreateOptions::new("."))?;
356/// println!("work in {}", capsule.workspace_path.display());
357/// # Ok::<(), change_capsule::Error>(())
358/// ```
359#[derive(Debug)]
360#[non_exhaustive]
361pub struct CapsuleManager {
362    store: StateStore,
363    git: Git,
364}
365
366mod artifacts;
367mod create;
368mod lifecycle;
369mod query;
370mod recover;
371
372impl CapsuleManager {
373    /// Open a manager on the default state directory.
374    ///
375    /// Honours `CAPSULE_HOME`, then the platform state directory.
376    pub fn open_default() -> Result<Self> {
377        Self::open(default_state_root()?)
378    }
379
380    /// Open a manager on an explicit state directory, creating it if needed.
381    pub fn open(state_root: impl Into<PathBuf>) -> Result<Self> {
382        let state_root = state_root.into();
383        Ok(Self {
384            store: StateStore::open(&state_root)?,
385            git: Git::discover()?,
386        })
387    }
388
389    /// Directory holding this manager's durable state.
390    pub fn state_root(&self) -> &Path {
391        self.store.root()
392    }
393}
394
395fn artifact_descriptor(
396    kind: ArtifactKind,
397    name: &str,
398    media_type: &str,
399    path: &Path,
400    digest: &str,
401    bytes: u64,
402) -> Result<ArtifactDescriptor> {
403    Ok(ArtifactDescriptor {
404        kind,
405        name: name.to_owned(),
406        media_type: media_type.to_owned(),
407        uri: file_uri(path)?,
408        content_address: format!("sha256:{digest}"),
409        sha256: digest.to_owned(),
410        bytes,
411    })
412}
413
414fn file_uri(path: &Path) -> Result<String> {
415    let absolute = if path.is_absolute() {
416        path.to_path_buf()
417    } else {
418        std::env::current_dir()
419            .map_err(|error| io(".", error))?
420            .join(path)
421    };
422    let text = absolute
423        .to_str()
424        .ok_or_else(|| Error::NonUtf8Path(absolute.clone()))?;
425    #[cfg(windows)]
426    let (prefix, normalized) = {
427        let normalized = text.replace('\\', "/");
428        if normalized.starts_with("//") {
429            ("file:", normalized)
430        } else {
431            ("file:///", normalized)
432        }
433    };
434    #[cfg(not(windows))]
435    let (prefix, normalized) = ("file://", text.to_owned());
436    let mut encoded = String::with_capacity(normalized.len() + prefix.len());
437    encoded.push_str(prefix);
438    for byte in normalized.bytes() {
439        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'.' | b'_' | b'~') {
440            encoded.push(char::from(byte));
441        } else {
442            use std::fmt::Write as _;
443            write!(encoded, "%{byte:02X}")
444                .map_err(|_| Error::UnsafeState("failed to encode artifact URI".to_owned()))?;
445        }
446    }
447    Ok(encoded)
448}
449
450fn safe_ignored_relative(ignored: &crate::model::GitPath) -> Result<PathBuf> {
451    let relative = ignored.to_path_buf().ok_or_else(|| {
452        Error::InvalidInput(format!(
453            "ignored path cannot be represented here: {ignored}"
454        ))
455    })?;
456    if relative.components().any(|component| {
457        matches!(
458            component,
459            Component::ParentDir | Component::RootDir | Component::Prefix(_)
460        )
461    }) {
462        return Err(Error::UnsafeState(format!(
463            "Git returned an unsafe ignored path: {ignored}"
464        )));
465    }
466    Ok(relative)
467}
468
469#[derive(Debug)]
470struct CloseSnapshotTransaction {
471    clean: bool,
472    snapshot: crate::git::Snapshot,
473    head: String,
474    ignored: IgnoredContentInventory,
475}
476
477#[derive(Debug, PartialEq, Eq)]
478struct IgnoredContentInventory {
479    paths: Vec<crate::model::GitPath>,
480    bytes: u64,
481    content_sha256: String,
482}
483
484fn ignored_content_inventory(
485    workspace: &Path,
486    ignored_paths: Vec<crate::model::GitPath>,
487) -> Result<IgnoredContentInventory> {
488    let mut digest = Sha256::new();
489    digest.update(b"change-capsule ignored-content inventory v2\0");
490    let mut total = 0_u64;
491    let mut seen = BTreeSet::new();
492    for ignored in &ignored_paths {
493        let relative = safe_ignored_relative(ignored)?;
494        inventory_path(workspace, &relative, &mut seen, &mut total, &mut digest)?;
495    }
496    Ok(IgnoredContentInventory {
497        paths: ignored_paths,
498        bytes: total,
499        content_sha256: hex::encode(digest.finalize()),
500    })
501}
502
503fn inventory_path(
504    workspace: &Path,
505    relative: &Path,
506    seen: &mut BTreeSet<PathBuf>,
507    total: &mut u64,
508    digest: &mut Sha256,
509) -> Result<()> {
510    if !seen.insert(relative.to_path_buf()) {
511        return Ok(());
512    }
513    let path = workspace.join(relative);
514    let metadata = fs::symlink_metadata(&path).map_err(|error| io(&path, error))?;
515    update_native_path(digest, b"relative", relative)?;
516    if metadata.file_type().is_symlink() {
517        digest.update(b"link");
518        let target = fs::read_link(&path).map_err(|error| io(&path, error))?;
519        update_native_path(digest, b"target", &target)?;
520        *total = total
521            .checked_add(metadata.len())
522            .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
523        return Ok(());
524    }
525    if metadata.is_file() {
526        let mut file = open_ignored_inventory_file(&path)?;
527        let opened = file.metadata().map_err(|error| io(&path, error))?;
528        if !opened_regular_file(&opened) || opened.len() != metadata.len() {
529            return Err(Error::UnsafeState(format!(
530                "ignored file changed while it was inspected: {}",
531                path.display()
532            )));
533        }
534        let expected = opened.len();
535        digest.update(b"file");
536        digest.update(expected.to_be_bytes());
537        let mut observed = 0_u64;
538        let mut buffer = vec![0_u8; 64 * 1024];
539        loop {
540            let read = file.read(&mut buffer).map_err(|error| io(&path, error))?;
541            if read == 0 {
542                break;
543            }
544            observed = observed
545                .checked_add(read as u64)
546                .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
547            if observed > expected {
548                return Err(Error::UnsafeState(format!(
549                    "ignored file changed while it was inspected: {}",
550                    path.display()
551                )));
552            }
553            digest.update(&buffer[..read]);
554        }
555        if observed != expected
556            || file.metadata().map_err(|error| io(&path, error))?.len() != expected
557        {
558            return Err(Error::UnsafeState(format!(
559                "ignored file changed while it was inspected: {}",
560                path.display()
561            )));
562        }
563        *total = total
564            .checked_add(observed)
565            .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
566        return Ok(());
567    }
568    if metadata.is_dir() {
569        digest.update(b"dir");
570        let mut entries = fs::read_dir(&path)
571            .map_err(|error| io(&path, error))?
572            .collect::<std::result::Result<Vec<_>, _>>()
573            .map_err(|error| io(&path, error))?;
574        entries.sort_by_key(std::fs::DirEntry::file_name);
575        for entry in entries {
576            inventory_path(
577                workspace,
578                &relative.join(entry.file_name()),
579                seen,
580                total,
581                digest,
582            )?;
583        }
584        return Ok(());
585    }
586    Err(Error::UnsafeState(format!(
587        "ignored path has an unsupported special-file type: {}",
588        path.display()
589    )))
590}
591
592fn opened_regular_file(metadata: &fs::Metadata) -> bool {
593    #[cfg(windows)]
594    {
595        use std::os::windows::fs::MetadataExt;
596        metadata.is_file()
597            && metadata.file_attributes()
598                & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT
599                == 0
600    }
601    #[cfg(not(windows))]
602    {
603        metadata.is_file()
604    }
605}
606
607fn open_ignored_inventory_file(path: &Path) -> Result<File> {
608    let mut options = OpenOptions::new();
609    options.read(true);
610    #[cfg(unix)]
611    {
612        use std::os::unix::fs::OpenOptionsExt;
613        let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK;
614        options.custom_flags(
615            i32::try_from(flags.bits())
616                .expect("O_NOFOLLOW | O_NONBLOCK fits platform custom_flags"),
617        );
618    }
619    #[cfg(windows)]
620    {
621        use std::os::windows::fs::OpenOptionsExt;
622        options.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);
623    }
624    options.open(path).map_err(|error| io(path, error))
625}
626
627#[cfg_attr(any(unix, windows), allow(clippy::unnecessary_wraps))]
628fn update_native_path(digest: &mut Sha256, field: &[u8], path: &Path) -> Result<()> {
629    digest.update((field.len() as u64).to_be_bytes());
630    digest.update(field);
631    #[cfg(unix)]
632    {
633        use std::os::unix::ffi::OsStrExt;
634        let bytes = path.as_os_str().as_bytes();
635        digest.update(b"unix-bytes");
636        digest.update((bytes.len() as u64).to_be_bytes());
637        digest.update(bytes);
638        Ok(())
639    }
640    #[cfg(windows)]
641    {
642        use std::os::windows::ffi::OsStrExt;
643        let units: Vec<u16> = path.as_os_str().encode_wide().collect();
644        digest.update(b"windows-utf16le");
645        digest.update((units.len() as u64).to_be_bytes());
646        for unit in units {
647            digest.update(unit.to_le_bytes());
648        }
649        Ok(())
650    }
651    #[cfg(not(any(unix, windows)))]
652    {
653        let value = path
654            .to_str()
655            .ok_or_else(|| Error::NonUtf8Path(path.to_path_buf()))?;
656        digest.update(b"portable-utf8");
657        digest.update((value.len() as u64).to_be_bytes());
658        digest.update(value.as_bytes());
659        Ok(())
660    }
661}
662
663fn artifact_error(id: &str, error: Error) -> Error {
664    match error {
665        Error::Io { ref source, .. } if source.kind() == std::io::ErrorKind::NotFound => {
666            Error::ResultDrift(id.to_owned())
667        }
668        Error::Json { .. } | Error::UnsafeState(_) | Error::SchemaVersion { .. } => {
669            Error::ResultDrift(id.to_owned())
670        }
671        other => other,
672    }
673}
674
675fn recorded_capsule_head(capsule: &Capsule, head: &str) -> bool {
676    head == capsule.base_commit
677        || capsule
678            .checkpoints
679            .iter()
680            .any(|checkpoint| checkpoint.commit == head)
681        || capsule
682            .result
683            .as_ref()
684            .is_some_and(|result| result.head_commit == head)
685        || capsule.checkpoint.as_ref().is_some_and(|checkpoint| {
686            checkpoint.head_before == head || checkpoint.head_after == head
687        })
688}
689
690fn checkpoint_ref(capsule: &Capsule) -> String {
691    format!("refs/change-capsule/{}/checkpoint", capsule.id)
692}
693
694fn integration_ref(capsule: &Capsule) -> String {
695    format!("refs/change-capsule/{}/integration", capsule.id)
696}
697
698#[cfg(test)]
699#[derive(Clone, Copy, PartialEq, Eq)]
700enum IdempotentCreateTestStage {
701    AfterReservation,
702    AfterManifest,
703}
704
705#[cfg(test)]
706static IDEMPOTENT_CREATE_TEST_HOOK: std::sync::Mutex<Option<IdempotentCreateTestStage>> =
707    std::sync::Mutex::new(None);
708
709#[cfg(test)]
710fn run_idempotent_create_test_hook(stage: IdempotentCreateTestStage) -> Result<()> {
711    let mut hook = IDEMPOTENT_CREATE_TEST_HOOK
712        .lock()
713        .expect("idempotent-create test hook lock");
714    if hook.as_ref() == Some(&stage) {
715        *hook = None;
716        return Err(Error::UnsafeState(
717            "injected idempotent creation interruption".to_owned(),
718        ));
719    }
720    Ok(())
721}
722
723fn is_unchecked_worktree_shape(path: &Path) -> Result<bool> {
724    let metadata = fs::symlink_metadata(path).map_err(|error| io(path, error))?;
725    if metadata.file_type().is_symlink() || !metadata.is_dir() {
726        return Ok(false);
727    }
728    let mut entries = fs::read_dir(path).map_err(|error| io(path, error))?;
729    let Some(entry) = entries
730        .next()
731        .transpose()
732        .map_err(|error| io(path, error))?
733    else {
734        return Ok(false);
735    };
736    if entry.file_name() != std::ffi::OsStr::new(".git")
737        || entries
738            .next()
739            .transpose()
740            .map_err(|error| io(path, error))?
741            .is_some()
742    {
743        return Ok(false);
744    }
745    let git_metadata =
746        fs::symlink_metadata(entry.path()).map_err(|error| io(entry.path(), error))?;
747    Ok(!git_metadata.file_type().is_symlink() && git_metadata.is_file())
748}
749
750fn new_capsule_id() -> String {
751    format!("cap-{}", Ulid::generate().to_string().to_ascii_lowercase())
752}
753
754fn path_entry_exists_no_follow(path: &Path) -> Result<bool> {
755    match fs::symlink_metadata(path) {
756        Ok(_) => Ok(true),
757        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
758        Err(error) => Err(io(path, error)),
759    }
760}
761
762fn validate_reservation_capsule(record: &IdempotencyRecord, capsule: &Capsule) -> Result<()> {
763    if capsule.id != record.capsule_id
764        || capsule.source_worktree != record.source_worktree
765        || capsule.repository_common_dir != record.repository_common_dir
766        || capsule.project_key != record.project_key
767        || capsule.base_commit != record.base_commit
768        || capsule.label != record.label
769        || capsule.links != record.links
770        || capsule.created_at_unix != record.reserved_at_unix
771    {
772        return Err(Error::UnsafeState(format!(
773            "idempotency reservation does not agree with capsule {}",
774            record.capsule_id
775        )));
776    }
777    Ok(())
778}
779
780fn validate_create_options(options: &CreateOptions) -> Result<()> {
781    if let Some(label) = &options.label {
782        validate_bounded_text(label, LABEL_CAP, "label", false)?;
783    }
784    if options.links.len() > LINKS_LIMIT {
785        return Err(Error::InvalidInput(format!(
786            "at most {LINKS_LIMIT} links are allowed"
787        )));
788    }
789    for (key, value) in &options.links {
790        let valid_key = !key.is_empty()
791            && key.len() <= LINK_KEY_CAP
792            && key
793                .bytes()
794                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
795        if !valid_key {
796            return Err(Error::InvalidInput(format!("invalid link key: {key:?}")));
797        }
798        validate_bounded_text(value, LINK_VALUE_CAP, "link value", false)?;
799    }
800    Ok(())
801}
802
803fn validate_author(author: &Author) -> Result<()> {
804    validate_bounded_text(&author.name, 256, "author name", false)?;
805    validate_bounded_text(&author.email, 512, "author email", false)?;
806    if !author.email.contains('@') {
807        return Err(Error::InvalidInput(
808            "author email must contain '@'".to_owned(),
809        ));
810    }
811    Ok(())
812}
813
814fn validate_message(message: &str, label: &str) -> Result<()> {
815    validate_bounded_text(message, MESSAGE_CAP, label, true)
816}
817
818fn validate_bounded_text(value: &str, cap: usize, label: &str, multiline: bool) -> Result<()> {
819    if value.trim().is_empty() || value.len() > cap || value.contains('\0') {
820        return Err(Error::InvalidInput(format!(
821            "{label} must contain 1-{cap} bytes without NUL"
822        )));
823    }
824    if value
825        .chars()
826        .any(|character| character.is_control() && !(multiline && matches!(character, '\n' | '\t')))
827    {
828        return Err(Error::InvalidInput(format!(
829            "{label} contains unsupported control characters"
830        )));
831    }
832    Ok(())
833}
834
835fn require_state(capsule: &Capsule, expected: CapsuleState, label: &str) -> Result<()> {
836    if capsule.state == expected {
837        Ok(())
838    } else {
839        Err(invalid_state(capsule, label))
840    }
841}
842
843fn invalid_state(capsule: &Capsule, expected: &str) -> Error {
844    Error::InvalidState {
845        id: capsule.id.clone(),
846        state: format!("{:?}", capsule.state).to_ascii_lowercase(),
847        expected: expected.to_owned(),
848    }
849}
850
851fn not_found(id: &str, error: Error) -> Error {
852    match error {
853        Error::Io { ref source, .. } if source.kind() == std::io::ErrorKind::NotFound => {
854            Error::NotFound(id.to_owned())
855        }
856        other => other,
857    }
858}
859
860fn now() -> Result<u64> {
861    SystemTime::now()
862        .duration_since(UNIX_EPOCH)
863        .map(|duration| duration.as_secs())
864        .map_err(|_| Error::InvalidInput("system clock is before the Unix epoch".to_owned()))
865}
866
867fn require_stable_ignored_content(
868    initial: &IgnoredContentInventory,
869    final_inventory: &IgnoredContentInventory,
870) -> Result<()> {
871    if initial != final_inventory {
872        return Err(Error::UnsafeState(
873            "capsule ignored paths or content changed while close was finalizing; no artifacts were written"
874                .to_owned(),
875        ));
876    }
877    Ok(())
878}
879
880#[cfg(test)]
881#[derive(Clone)]
882struct CloseIgnoredInventoryTestHook {
883    capsule_id: String,
884    initial_inventory_captured: std::sync::Arc<std::sync::Barrier>,
885    mutation_finished: std::sync::Arc<std::sync::Barrier>,
886}
887
888#[cfg(test)]
889static CLOSE_IGNORED_INVENTORY_TEST_HOOK: std::sync::Mutex<Option<CloseIgnoredInventoryTestHook>> =
890    std::sync::Mutex::new(None);
891
892#[cfg(test)]
893fn run_close_ignored_inventory_test_hook(capsule_id: &str) {
894    let hook = CLOSE_IGNORED_INVENTORY_TEST_HOOK
895        .lock()
896        .expect("close ignored-inventory test hook lock")
897        .clone();
898    if let Some(hook) = hook.filter(|hook| hook.capsule_id == capsule_id) {
899        hook.initial_inventory_captured.wait();
900        hook.mutation_finished.wait();
901    }
902}
903
904fn require_stable_close_snapshot(
905    initial: &crate::git::Snapshot,
906    initial_head: &str,
907    initial_clean: bool,
908    final_snapshot: &crate::git::Snapshot,
909    final_head: &str,
910    final_clean: bool,
911) -> Result<()> {
912    if initial.patch != final_snapshot.patch
913        || initial.changed_paths != final_snapshot.changed_paths
914        || initial_head != final_head
915        || initial_clean != final_clean
916    {
917        return Err(Error::UnsafeState(
918            "capsule tracked content, HEAD, or clean state changed while close was finalizing; no artifacts were written"
919                .to_owned(),
920        ));
921    }
922    Ok(())
923}
924
925fn result_sha256(result: &CapsuleResult) -> Result<String> {
926    let bytes = serde_json::to_vec(result).map_err(|source| Error::Json {
927        path: PathBuf::from("result digest"),
928        source,
929    })?;
930    Ok(sha256_hex(&bytes))
931}
932
933fn sha256_hex(bytes: &[u8]) -> String {
934    hex::encode(Sha256::digest(bytes))
935}
936
937fn canonical_existing(path: &Path) -> Result<PathBuf> {
938    crate::path::canonicalize(path).map_err(|error| io(path, error))
939}
940
941fn same_path_existing_or_clean(left: &Path, right: &Path) -> bool {
942    match (
943        crate::path::canonicalize(left),
944        crate::path::canonicalize(right),
945    ) {
946        (Ok(left), Ok(right)) => left == right,
947        _ => clean_absolute(left) == clean_absolute(right),
948    }
949}
950
951fn clean_absolute(path: &Path) -> Option<PathBuf> {
952    if path.is_absolute() {
953        Some(path.to_path_buf())
954    } else {
955        std::env::current_dir().ok().map(|cwd| cwd.join(path))
956    }
957}
958
959#[cfg(test)]
960mod tests;