A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
add workspace snapshot foundation for cloud sessions (#3157)
kt172bd84f5976
diff --git a/Cargo.lock b/Cargo.lockindex bd8d65875b..2940a0a989 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1310,6 +1310,7 @@ dependencies = ["serde","serde_json","serde_yaml",+ "sha1","sha2","tar","tempfile",diff --git a/crates/pa-core/Cargo.toml b/crates/pa-core/Cargo.tomlindex afac7752af..f6db562680 100644--- a/crates/pa-core/Cargo.toml+++ b/crates/pa-core/Cargo.toml@@ -28,6 +28,7 @@ libc = "0.2"nix = { version = "0.29", features = ["signal", "process", "user", "fs", "dir"] }tokio-util = "0.7"uuid = { version = "1", features = ["v4", "v7"] }+sha1 = "0.10"sha2 = "0.10"getrandom = "0.3"url = "2"diff --git a/crates/pa-core/README.md b/crates/pa-core/README.mdindex 08f6402a22..71b9d10b11 100644--- a/crates/pa-core/README.md+++ b/crates/pa-core/README.md@@ -50,12 +50,31 @@ HTML at the export step), and the two entry pointscommand, `export_from_file` for the CLI). Terminal theme rendering stayspa-tui's; tool renderers live with the session's tool surface;the share-viewer flow (gist creation) is the caller's.+Cloud workspace snapshots (`workspace_snapshot`): the portable, verifiable+capture of a git worktree's working state - tracked modifications, staged+paths, deletions, and nonignored untracked files - staged into an+owner-private directory as content-addressed blobs plus a deterministic+manifest that hashes them, with credential-shaped, symlink-ancestor,+escaping-symlink, nested-repo, and submodule exclusions recorded in the+manifest, hard entry/size bounds, race-free openat(O_NOFOLLOW) leaf reads+(Unix), and offline verification of a staged snapshot before upload. Capture+refuses on non-Unix targets: owner-only 0700 staging and 0600 files cannot be+enforced there. The baseline is an explicit caller choice (`BaselineMode`):+HEAD's tree content staged through the same filters as the delta (each entry+verified against HEAD's recorded object id and mode, no git history ships),+or an explicit external reference the consumer must reach itself. The secret+skip is a filename-shaped denylist only; ordinary-named files containing+secrets stage verbatim. Snapshot directories are secret-bearing: every+consumer must treat them as credentials. Capture does synchronous file I/O+inside its async entry point; callers must offload the entire operation with+`tokio::task::spawn_blocking` and `Handle::block_on`. Foundation plumbing+only: nothing wires it to a user-facing cloud toggle yet.## Non-goals-No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only.+No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only. No workspace snapshot upload, transport, or remote materialization (staging and verification live here; the cloud attach surface owns the transport when it ships).## Public API-`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill used` adoption event reports from the admission). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).+`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill used` adoption event reports from the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).## Depends onpa-types, pa-ai, pa-agent (one-way).diff --git a/crates/pa-core/src/lib.rs b/crates/pa-core/src/lib.rsindex 273fd4ad6f..dda352b185 100644--- a/crates/pa-core/src/lib.rs+++ b/crates/pa-core/src/lib.rs@@ -87,4 +87,5 @@ pub mod settings;pub mod skills;pub mod slash_command_args;pub mod update;+pub mod workspace_snapshot;pub use kernel::ReplKernelManager;diff --git a/crates/pa-core/src/workspace_snapshot/git.rs b/crates/pa-core/src/workspace_snapshot/git.rsnew file mode 100644index 0000000000..57f8455a8f--- /dev/null+++ b/crates/pa-core/src/workspace_snapshot/git.rs@@ -0,0 +1,391 @@+//! Git enumeration for workspace snapshots: one bounded `git status` run+//! yields the worktree delta (tracked modifications and deletions, plus+//! nonignored untracked paths) and the HEAD commit.++use std::collections::HashSet;+use std::path::{Path, PathBuf};++use super::SnapshotError;++/// Hard cap on `git status` output kept in memory. Past it the snapshot+/// aborts rather than silently truncating the capture set; the entry limit+/// normally trips first.+const MAX_STATUS_OUTPUT_BYTES: usize = 32 * 1024 * 1024;++/// Cap on captured git stderr (diagnostic text only).+const MAX_STDERR_BYTES: usize = 64 * 1024;++/// The submodule gitlink mode: a reference to a nested commit rather than+/// a file whose content can be captured.+const GITLINK_MODE: &str = "160000";++/// One `git status --porcelain=v2` record a snapshot cares about.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum StatusEntry {+ /// A tracked path with changes staged, unstaged, or both (`1`+ /// records), or an unmerged conflict path (`u` records). `gitlink`+ /// marks a submodule reference (mode `160000` in the index or the+ /// worktree), whose content is never captured.+ Tracked {+ path: String,+ xy: String,+ gitlink: bool,+ },+ /// A nonignored untracked path (`?` records). Paths ending in `/` are+ /// directories git declined to recurse into (nested repositories).+ Untracked { path: String },+}++impl StatusEntry {+ pub(crate) fn path(&self) -> &str {+ match self {+ StatusEntry::Tracked { path, .. } | StatusEntry::Untracked { path } => path,+ }+ }+}++/// The parsed status: the HEAD commit (absent on an unborn branch) and the+/// delta entries, sorted by path.+#[derive(Clone, Debug)]+pub(crate) struct GitStatus {+ pub(crate) head_commit: Option<String>,+ pub(crate) entries: Vec<StatusEntry>,+}++/// Resolve `dir` to the root of the git worktree it sits in; porcelain+/// paths are relative to that root, so it is the base for every read.+pub(crate) async fn resolve_worktree_root(+ dir: &Path,+ timeout_ms: u64,+) -> Result<PathBuf, SnapshotError> {+ let output = run_git(&["rev-parse", "--show-toplevel"], dir, timeout_ms).await?;+ let top = String::from_utf8(output)+ .map_err(|error| SnapshotError::Git {+ detail: format!("git rev-parse output is not UTF-8: {error}"),+ })?+ .trim_end()+ .to_string();+ if top.is_empty() {+ return Err(SnapshotError::Git {+ detail: "git rev-parse returned no worktree root".to_string(),+ });+ }+ Ok(PathBuf::from(top))+}++/// Read the worktree delta with one `git status --porcelain=v2` run+/// (NUL-separated, no rename detection, all untracked files enumerated).+pub(crate) async fn read_worktree_status(+ root: &Path,+ timeout_ms: u64,+) -> Result<GitStatus, SnapshotError> {+ let output = run_git(+ &[+ "--no-optional-locks",+ "status",+ "--porcelain=v2",+ "-z",+ "--branch",+ "--no-renames",+ "--untracked-files=all",+ ],+ root,+ timeout_ms,+ )+ .await?;+ parse_status(&output)+}++/// Run one git command, capturing stdout (bounded) and failing with a+/// classified [`SnapshotError`] on a non-zero exit or a timeout.+///+/// The pipes are drained concurrently with the wait: a child that writes+/// more than the OS pipe capacity would otherwise block forever on write+/// (the status output of a large untracked tree easily exceeds it), so+/// the drain futures, the wait, and one shared deadline race together.+/// The git child commands' environment: git-discovery variables inherited+/// from the caller would redirect every command to a different repository+/// or index than `cwd` (`GIT_DIR`/`GIT_WORK_TREE` select the tree the manifest+/// claims to describe), so they are scrubbed and the snapshot's git view+/// is always `cwd`'s own.+pub(super) fn git_command(args: &[&str], cwd: &Path) -> tokio::process::Command {+ const GIT_SELECTION_VARS: [&str; 7] = [+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_INDEX_FILE",+ "GIT_OBJECT_DIRECTORY",+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",+ "GIT_COMMON_DIR",+ "GIT_NAMESPACE",+ ];+ let mut command = tokio::process::Command::new("git");+ command.args(args).current_dir(cwd);+ for variable in GIT_SELECTION_VARS {+ command.env_remove(variable);+ }+ command+}++async fn run_git(args: &[&str], cwd: &Path, timeout_ms: u64) -> Result<Vec<u8>, SnapshotError> {+ let mut command = git_command(args, cwd);+ let mut child = command+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true)+ .spawn()+ .map_err(|error| SnapshotError::Git {+ detail: format!("failed to spawn git: {error}"),+ })?;+ let stdout_pipe = child.stdout.take();+ let stderr_pipe = child.stderr.take();+ let drain_and_wait = async {+ let wait = async {+ child.wait().await.map_err(|error| SnapshotError::Git {+ detail: format!("failed to reap git: {error}"),+ })+ };+ let stdout = read_pipe_capped(stdout_pipe, MAX_STATUS_OUTPUT_BYTES);+ let stderr = read_pipe_capped(stderr_pipe, MAX_STDERR_BYTES);+ let (status, (stdout, stdout_truncated), (stderr, stderr_truncated)) =+ tokio::join!(wait, stdout, stderr);+ let status = status?;+ if !status.success() {+ let mut detail = String::from_utf8_lossy(&stderr).trim().to_string();+ if detail.is_empty() {+ detail = format!("git exited with status {status}");+ }+ if detail.contains("not a git repository")+ || detail.contains("must be run in a work tree")+ {+ return Err(SnapshotError::NotAWorktree {+ path: cwd.to_path_buf(),+ detail,+ });+ }+ return Err(SnapshotError::Git { detail });+ }+ if stdout_truncated || stderr_truncated {+ return Err(SnapshotError::Git {+ detail: format!("git {} output exceeded its cap", args.join(" ")),+ });+ }+ Ok(stdout)+ };+ tokio::time::timeout(+ tokio::time::Duration::from_millis(timeout_ms.max(1)),+ drain_and_wait,+ )+ .await+ .map_err(|_| SnapshotError::Git {+ detail: format!("git {} timed out after {timeout_ms}ms", args.join(" ")),+ })?+}++/// Read one output pipe to EOF, keeping at most `cap` bytes; the remainder+/// is drained so a full pipe never blocks the child. Truncation is+/// reported so callers can fail instead of acting on partial output.+async fn read_pipe_capped<R: tokio::io::AsyncRead + Unpin>(+ mut pipe: Option<R>,+ cap: usize,+) -> (Vec<u8>, bool) {+ use tokio::io::AsyncReadExt;+ let mut kept: Vec<u8> = Vec::new();+ let mut truncated = false;+ if let Some(pipe) = pipe.as_mut() {+ let mut chunk = vec![0u8; 16 * 1024];+ loop {+ match pipe.read(&mut chunk).await {+ Ok(0) => break,+ Ok(read) => {+ let room = cap.saturating_sub(kept.len());+ kept.extend_from_slice(&chunk[..read.min(room)]);+ if read > room {+ truncated = true;+ }+ }+ Err(_) => {+ truncated = true;+ break;+ }+ }+ }+ }+ (kept, truncated)+}++/// One entry of HEAD's tree, from `git ls-tree -r`: a path with its mode.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct HeadTreeEntry {+ pub(crate) path: String,+ /// The git mode string (`100644`, `100755`, `120000`, `160000`).+ pub(crate) mode: String,+ /// A submodule gitlink rather than a file.+ pub(crate) gitlink: bool,+ /// The index marks the path skip-worktree (a sparse checkout, or+ /// `update-index --skip-worktree`): `git status` never reports its+ /// worktree state, so an absent leaf is by design, not a mutation.+ pub(crate) skip_worktree: bool,+ /// The object id HEAD records for the path (a blob id, or the+ /// gitlink commit id); the baseline verifies captured bytes against+ /// it, `git hash-object` equivalent.+ pub(crate) oid: String,+}++/// Read every path in `commit`'s tree, where `commit` is the object id+/// the preceding `git status` reported for HEAD. Enumerating that id+/// (instead of re-resolving `HEAD`) pins the baseline to the commit the+/// manifest will state: a concurrent commit between the two commands+/// can no longer pair the old head commit with a newer HEAD's tree, and+/// a vanished or rewritten object fails `ls-tree` loudly here. The+/// baseline stages these contents from the (unmodified) worktree, so+/// this is enumeration only - no history, no object payloads. The+/// index's skip-worktree bits ride along so the baseline can tell an+/// absent sparse path from a vanished one.+pub(crate) async fn read_head_tree(+ root: &Path,+ commit: &str,+ timeout_ms: u64,+) -> Result<Vec<HeadTreeEntry>, SnapshotError> {+ let output = run_git(&["ls-tree", "-r", "-z", commit], root, timeout_ms).await?;+ let index = run_git(&["ls-files", "-t", "-z"], root, timeout_ms).await?;+ let text = String::from_utf8(index).map_err(|_| SnapshotError::MalformedStatus {+ detail: "ls-files output is not UTF-8".to_string(),+ })?;+ let skip_worktree: HashSet<&str> = text+ .split('\0')+ .filter_map(|record| record.strip_prefix("S "))+ .collect();+ parse_head_tree(&output, &skip_worktree)+}++/// Parse NUL-separated `git ls-tree -r -z` records:+/// `<mode> <type> <object>\t<path>`.+fn parse_head_tree(+ output: &[u8],+ skip_worktree: &HashSet<&str>,+) -> Result<Vec<HeadTreeEntry>, SnapshotError> {+ let text = std::str::from_utf8(output).map_err(|_| SnapshotError::MalformedStatus {+ detail: "ls-tree output is not UTF-8".to_string(),+ })?;+ let mut entries = Vec::new();+ for record in text.split('\0') {+ if record.is_empty() {+ continue;+ }+ let Some((meta, path)) = record.split_once('\t') else {+ return Err(SnapshotError::MalformedStatus {+ detail: format!("unrecognized ls-tree record {record:?}"),+ });+ };+ let mut fields = meta.split(' ');+ let (Some(mode), Some(kind), Some(oid)) = (fields.next(), fields.next(), fields.next())+ else {+ return Err(SnapshotError::MalformedStatus {+ detail: format!("malformed ls-tree metadata {meta:?}"),+ });+ };+ if path.is_empty() {+ return Err(SnapshotError::MalformedStatus {+ detail: format!("empty ls-tree path for {meta:?}"),+ });+ }+ entries.push(HeadTreeEntry {+ path: path.to_string(),+ mode: mode.to_string(),+ gitlink: kind == "commit",+ skip_worktree: skip_worktree.contains(path),+ oid: oid.to_string(),+ });+ }+ entries.sort_by(|a, b| a.path.cmp(&b.path));+ Ok(entries)+}++/// Parse NUL-separated `git status --porcelain=v2 --branch` output into a+/// [`GitStatus`]. Records are sorted by path for deterministic capture.+pub(crate) fn parse_status(output: &[u8]) -> Result<GitStatus, SnapshotError> {+ let text = std::str::from_utf8(output).map_err(|_| SnapshotError::MalformedStatus {+ detail: "status output is not UTF-8".to_string(),+ })?;+ let mut head_commit = None;+ let mut entries = Vec::new();+ for record in text.split('\0') {+ if record.is_empty() {+ continue;+ }+ if let Some(oid) = record.strip_prefix("# branch.oid ") {+ // An unborn branch reports "(initial)"; no commit exists yet.+ if oid != "(initial)" {+ head_commit = Some(oid.to_string());+ }+ continue;+ }+ if record.starts_with('#') {+ continue; // branch.head / branch.upstream / branch.ab headers.+ }+ if let Some(path) = record.strip_prefix("? ") {+ entries.push(StatusEntry::Untracked {+ path: path.to_string(),+ });+ continue;+ }+ if record.starts_with("! ") {+ continue; // ignored paths are never captured.+ }+ if record.starts_with("1 ") || record.starts_with("u ") {+ entries.push(parse_tracked_record(record)?);+ continue;+ }+ return Err(SnapshotError::MalformedStatus {+ detail: format!("unrecognized status record {record:?}"),+ });+ }+ entries.sort_by(|a, b| a.path().cmp(b.path()));+ Ok(GitStatus {+ head_commit,+ entries,+ })+}++/// Parse one `1` (changed tracked) or `u` (unmerged conflict) record. The+/// path is the last field in both, but the field counts differ:+/// `1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>` (nine fields) —+/// gitlink when the index (`mI`) or worktree (`mW`) mode is `160000`;+/// `u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>` (eleven+/// fields) — gitlink when the stage-3 (`m3`) or worktree (`mW`) mode is+/// `160000`.+fn parse_tracked_record(record: &str) -> Result<StatusEntry, SnapshotError> {+ let malformed = |detail: String| SnapshotError::MalformedStatus {+ detail: format!("malformed status record {record:?}: {detail}"),+ };+ let conflict = record.starts_with("u ");+ let field_count = if conflict { 11 } else { 9 };+ let fields: Vec<&str> = record.splitn(field_count, ' ').collect();+ if fields.len() != field_count {+ return Err(malformed(format!(+ "expected {field_count} fields, found {}",+ fields.len()+ )));+ }+ let xy = fields[1];+ let path = fields[field_count - 1];+ if xy.len() != 2 || !xy.is_ascii() {+ return Err(malformed(format!("bad XY field {xy:?}")));+ }+ if path.is_empty() {+ return Err(malformed("empty path".to_string()));+ }+ // Field 2 is the submodule state; the mode fields follow, ending at+ // the worktree mode right before the hash fields.+ let gitlink = if conflict {+ fields[5] == GITLINK_MODE || fields[6] == GITLINK_MODE+ } else {+ fields[4] == GITLINK_MODE || fields[5] == GITLINK_MODE+ };+ Ok(StatusEntry::Tracked {+ path: path.to_string(),+ xy: xy.to_string(),+ gitlink,+ })+}diff --git a/crates/pa-core/src/workspace_snapshot/manifest.rs b/crates/pa-core/src/workspace_snapshot/manifest.rsnew file mode 100644index 0000000000..4f30171e51--- /dev/null+++ b/crates/pa-core/src/workspace_snapshot/manifest.rs@@ -0,0 +1,183 @@+//! The workspace snapshot manifest: the portable, verifiable description+//! of a captured worktree delta.+//!+//! A staged snapshot directory is+//!+//! ```text+//! <staging>/manifest.json this module's types, written last+//! <staging>/blobs/<sha256> content-addressed file blobs+//! ```+//!+//! Every manifest path is a repo-relative POSIX path in git's own form, so+//! a snapshot stages the same content on any filesystem. The manifest is+//! written after all blobs, so a reader that sees it holds a complete+//! set; determinism (path-sorted entries, no timestamps) makes two+//! snapshots of the same worktree byte-identical.++use std::path::{Component, Path};++use serde::{Deserialize, Serialize};++/// The manifest format version this build reads and writes.+pub const MANIFEST_VERSION: u32 = 2;++/// The manifest file name inside a staging directory.+pub const MANIFEST_FILE: &str = "manifest.json";++/// The blob directory name inside a staging directory.+pub const BLOBS_DIR: &str = "blobs";++/// A captured worktree path: file content staged as a blob, an in-root+/// symlink, or a deletion recorded for the materializer.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum CapturedEntry {+ /// A regular file staged as a content-addressed blob; `sha256` and+ /// `bytes` describe the blob and `executable` its mode bit.+ File {+ path: String,+ status: String,+ sha256: String,+ bytes: u64,+ executable: bool,+ },+ /// A symlink whose target resolves inside the worktree; the link is+ /// recreated from `target` verbatim (no blob).+ Symlink {+ path: String,+ status: String,+ target: String,+ },+ /// A tracked path absent from the worktree; the materializer removes+ /// it after checking out HEAD.+ Deleted { path: String, status: String },+}++impl CapturedEntry {+ /// The entry's repo-relative path.+ #[must_use]+ pub fn path(&self) -> &str {+ match self {+ CapturedEntry::File { path, .. }+ | CapturedEntry::Symlink { path, .. }+ | CapturedEntry::Deleted { path, .. } => path,+ }+ }+}++/// Why a path was deliberately left uncaptured.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ExcludeReason {+ /// A credential-shaped file name (`.env*`, `*.pem`, `id_rsa`, ...).+ Secret,+ /// A symlink whose target escapes the worktree root.+ EscapingSymlink,+ /// An untracked directory that is itself a git repository.+ NestedRepository,+ /// A submodule gitlink reference.+ Submodule,+ /// A path that is neither a regular file nor a symlink (a directory,+ /// fifo, socket, or device).+ NotRegularFile,+ /// A path whose ancestor directory is a symlink; the leaf resolves+ /// outside the worktree and is never read.+ SymlinkedAncestor,+ /// A HEAD path the index marks skip-worktree that is absent from the+ /// worktree (outside a sparse checkout): absent by design, so the+ /// baseline records it instead of failing.+ SkipWorktree,+}++/// A path excluded from capture, with the reason it was left out.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct ExcludedEntry {+ pub path: String,+ pub reason: ExcludeReason,+}++/// The baseline of a staged snapshot, stated explicitly so a materializer+/// never guesses. Present exactly when `head_commit` is.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum Baseline {+ /// HEAD's tree content staged as content-addressed blobs, minus+ /// secret-named paths (the same denylist the delta applies) and+ /// minus every path the delta already covers (the delta carries the+ /// newer state). No git history ships - no commits, no reverted+ /// content from any prior revision - and nothing here is a+ /// secret-safety guarantee: a credential under an innocuous name+ /// still stages, in the baseline or the delta. Entries are files and+ /// symlinks only - a deletion is not baseline content - and+ /// verification rejects any path claimed by more than one list, so+ /// the materializer never receives contradictory instructions for+ /// the same path (full HEAD-tree coverage itself stays a creator+ /// invariant: it cannot be proven offline from a commit id alone).+ HeadTree {+ entries: Vec<CapturedEntry>,+ excluded: Vec<ExcludedEntry>,+ },+ /// No baseline staged; the consumer must obtain `head_commit` itself+ /// (e.g. via the origin remote) and refuse to materialize when it+ /// cannot. Nothing here makes that reachable.+ External,+}++/// The manifest of one staged snapshot; `captured` and `excluded` are+/// sorted by path and written deterministically.+///+/// Invariant: `baseline` is present if and only if `head_commit` is. A+/// committed repository always declares which baseline it ships - a+/// staged bundle or an explicit external reference - and an unborn one+/// (no commits, every path untracked) needs none because its delta is+/// the whole worktree. Verification rejects any other combination, so a+/// missing or ambiguous baseline is never silent.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct SnapshotManifest {+ pub version: u32,+ pub head_commit: Option<String>,+ pub baseline: Option<Baseline>,+ pub captured: Vec<CapturedEntry>,+ pub excluded: Vec<ExcludedEntry>,+}++/// True for a repo-relative POSIX path that is safe to join onto a root:+/// non-empty, backslash-free (a backslash is a Windows separator, so a+/// portable manifest never records it inside a path either), with no+/// absolute, parent, or current-directory components.+pub(crate) fn is_safe_relative_path(path: &str) -> bool {+ !path.is_empty()+ && !path.contains('\\')+ && Path::new(path)+ .components()+ .all(|component| matches!(component, Component::Normal(_)))+}++/// True when the symlink `target` of the entry at `entry_path` resolves+/// inside the worktree: relative, colon-free and backslash-free (portable+/// across platforms: `\` is a Windows separator, so a UNC, drive-root, or+/// `..\` climb has no faithful portable meaning here), and never climbing+/// above the root via `..`.+pub(crate) fn symlink_target_stays_inside(entry_path: &str, target: &str) -> bool {+ if target.is_empty() || target.starts_with('/') || target.contains(':') || target.contains('\\')+ {+ return false;+ }+ let base_dir = entry_path.rsplit_once('/').map_or("", |(parent, _)| parent);+ let mut depth: i64 = 0;+ base_dir+ .split('/')+ .chain(target.split('/'))+ .filter(|segment| !segment.is_empty())+ .all(|segment| match segment {+ ".." => {+ depth -= 1;+ depth >= 0+ }+ "." => true,+ _ => {+ depth += 1;+ true+ }+ })+}diff --git a/crates/pa-core/src/workspace_snapshot/mod.rs b/crates/pa-core/src/workspace_snapshot/mod.rsnew file mode 100644index 0000000000..720c1c0320--- /dev/null+++ b/crates/pa-core/src/workspace_snapshot/mod.rs@@ -0,0 +1,962 @@+//! Cloud workspace snapshots.+//!+//! [`create_workspace_snapshot`] captures a git worktree's working state —+//! the delta from HEAD (modified, staged, and deleted tracked paths) plus+//! every nonignored untracked file — into an isolated staging directory+//! as a portable, self-verifying artifact: content-addressed blobs plus a+//! manifest that hashes them. [`verify_workspace_snapshot`] re-checks a+//! staged snapshot offline before it is uploaded anywhere.+//!+//! The baseline is the caller's explicit choice ([`BaselineMode`]):+//! HEAD's tree content staged through the same filters as the delta (no+//! git history ships, and the secret file-name denylist applies to both+//! layers), or none at all. That is not a secret-safety guarantee - a+//! credential under an innocuous name still stages, in either layer.+//! The capture is bounded (entry count, baseline count, per-file size,+//! total size) and deliberately incomplete in a recorded way:+//! credential-shaped file names, symlinks whose targets escape the+//! worktree (and paths whose ancestors became symlinks), nested+//! repositories, submodule gitlinks, and absent sparse-checkout+//! (skip-worktree) paths are excluded and listed in the manifest, so a+//! materializer knows exactly what was and was not captured. This is+//! foundation plumbing for cloud sessions; nothing wires it to a+//! user-facing toggle yet, and there is no transport here - staging and+//! verification only.++mod git;+mod manifest;+#[cfg(test)]+mod tests;+mod verify;++pub use manifest::{Baseline, CapturedEntry, ExcludeReason, ExcludedEntry, SnapshotManifest};+pub use verify::verify_workspace_snapshot;++use std::collections::HashSet;+use std::path::{Path, PathBuf};++use sha1::{Digest as Sha1Digest, Sha1};+use sha2::Sha256;++use git::{GitStatus, HeadTreeEntry, StatusEntry};+use manifest::{+ is_safe_relative_path, symlink_target_stays_inside, BLOBS_DIR, MANIFEST_FILE, MANIFEST_VERSION,+};++/// The hex length of a SHA-256 git object id (the alternate object+/// format's length; SHA-1's 40 is the historical default).+const SHA256_OID_HEX_LEN: usize = 64;++/// Bounds that keep a snapshot small and predictable: a worktree past+/// these fails loudly instead of staging an unbounded payload.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct SnapshotLimits {+ /// Maximum number of `git status` entries (captured, deleted, and+ /// excluded paths together).+ pub max_entries: usize,+ /// Maximum total size of captured file content.+ pub max_total_bytes: u64,+ /// Maximum size of one captured file.+ pub max_file_bytes: u64,+ /// Maximum number of HEAD-tree paths staged as the baseline.+ pub max_baseline_entries: usize,+ /// Timeout for each git child process.+ pub git_timeout_ms: u64,+}++impl Default for SnapshotLimits {+ /// 20,000 delta entries, 100,000 baseline paths, 512 MiB total+ /// captured content, 64 MiB per file, 10s per git call.+ fn default() -> Self {+ Self {+ max_entries: 20_000,+ max_total_bytes: 512 * 1024 * 1024,+ max_file_bytes: 64 * 1024 * 1024,+ max_baseline_entries: 100_000,+ git_timeout_ms: 10_000,+ }+ }+}++/// Whether [`create_workspace_snapshot`] ships the baseline alongside the+/// delta. Explicit and required at every call site. The `HeadTree`+/// baseline stages HEAD's tree content only - no commits, no reverted+/// content from prior revisions - and the credential-shaped file-name+/// filter applies to it exactly as to the delta. None of that is a+/// secret-safety guarantee: a credential under an innocuous file name+/// still stages, in either layer.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BaselineMode {+ /// Stage HEAD's tree content into the snapshot, so a guest+ /// materializes the base revision offline (unpushed worktrees+ /// included) without inheriting any git history.+ HeadTree,+ /// Ship the delta only; the manifest records an `external` baseline+ /// and the consumer must obtain the head commit itself, refusing to+ /// materialize when it cannot.+ External,+}++/// The outcome of a successful snapshot: where it staged and what it holds.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct WorkspaceSnapshot {+ /// The staging directory the snapshot was written into.+ pub staging_dir: PathBuf,+ /// The manifest's path (`<staging_dir>/manifest.json`).+ pub manifest_path: PathBuf,+ /// The staged manifest.+ pub manifest: SnapshotManifest,+}++/// Failures of [`create_workspace_snapshot`] and+/// [`verify_workspace_snapshot`].+#[derive(Debug, thiserror::Error)]+pub enum SnapshotError {+ /// The directory is not inside a git worktree.+ #[error("{} is not a git worktree: {detail}", path.display())]+ NotAWorktree { path: PathBuf, detail: String },+ /// A git child process failed or timed out.+ #[error("git failed: {detail}")]+ Git { detail: String },+ /// `git status` emitted a record this parser does not accept.+ #[error("malformed git status output: {detail}")]+ MalformedStatus { detail: String },+ /// The staging directory exists with prior content.+ #[error("staging directory {} exists and is not empty", path.display())]+ StagingDirNotEmpty { path: PathBuf },+ /// The staging directory lies inside the snapshotted worktree, which+ /// would capture the snapshot into itself.+ #[error("staging directory {} lies inside the snapshotted worktree", path.display())]+ StagingDirInsideWorktree { path: PathBuf },+ /// A [`SnapshotLimits`] bound was exceeded; `detail` names the+ /// offending path or size.+ #[error("snapshot limit exceeded ({limit}): {detail}")]+ Limit { limit: String, detail: String },+ /// The worktree changed under the capture: a baseline path's staged+ /// bytes (or its presence, or its mode) no longer reproduce what HEAD+ /// records, so the snapshot fails loudly instead of shipping a+ /// baseline that is not the stated commit.+ #[error("worktree changed during capture: {detail}")]+ ConcurrentMutation { detail: String },+ /// Capture cannot enforce owner-only staging permissions on this platform.+ #[error("workspace snapshot capture requires Unix owner-only file permissions")]+ UnsupportedPlatform,+ /// A filesystem error at `path`.+ #[error("io error at {}: {source}", path.display())]+ Io {+ path: PathBuf,+ source: std::io::Error,+ },+ /// The staged manifest is missing, unreadable, invalid JSON, or an+ /// unsupported version.+ #[error("manifest at {} is invalid: {detail}", path.display())]+ Manifest { path: PathBuf, detail: String },+ /// The staged snapshot failed an integrity check.+ #[error("snapshot at {} failed verification: {detail}", staging_dir.display())]+ Verification {+ staging_dir: PathBuf,+ detail: String,+ },+}++/// Capture the working state of the git worktree containing `root` into+/// `staging_dir`, under `limits`, shipping the baseline according to+/// `baseline_mode` (see [`BaselineMode`] for what a baseline does and+/// does not protect).+///+/// The staging directory is created if missing, tightened to owner-only+/// (0700), must otherwise be empty, and must lie outside the worktree.+/// The snapshot layout is `manifest.json` plus `blobs/<sha256>`+/// content-addressed blobs (staged owner-only, 0600) covering both the+/// delta and - in [`BaselineMode::HeadTree`] - the HEAD-tree baseline;+/// the manifest is written last, after everything it describes.+///+/// This capture is supported only on Unix. On other platforms the+/// permission wall cannot enforce owner-only modes, so capture refuses+/// before creating the staging directory. The secret skip is a filename-+/// shaped denylist only: ordinary-named files containing secrets stage+/// verbatim. The snapshot directory is secret-bearing; every consumer+/// must treat it as credentials.+///+/// Capture reads, hashes, and writes files synchronously inside this+/// async function (up to the configured entry and byte caps). Callers+/// must run the entire capture via `tokio::task::spawn_blocking` with+/// `tokio::runtime::Handle::block_on` rather than block a Tokio worker.+///+/// # Errors+/// Returns [`SnapshotError::UnsupportedPlatform`] on non-Unix targets,+/// [`SnapshotError::NotAWorktree`] when `root` is not inside a git worktree,+/// staging-guard errors for an unusable staging directory,+/// [`SnapshotError::Limit`] when a bound is exceeded, and git/io errors+/// for the enumeration, baseline, and capture steps.+#[tracing::instrument(+ level = "debug",+ name = "workspace_snapshot_create",+ skip_all,+ fields(root = %root.display())+)]+pub async fn create_workspace_snapshot(+ root: &Path,+ staging_dir: &Path,+ baseline_mode: BaselineMode,+ limits: &SnapshotLimits,+) -> Result<WorkspaceSnapshot, SnapshotError> {+ if !cfg!(unix) {+ return Err(SnapshotError::UnsupportedPlatform);+ }+ let worktree_root = git::resolve_worktree_root(root, limits.git_timeout_ms).await?;+ prepare_staging_dir(staging_dir, &worktree_root)?;+ let status = git::read_worktree_status(&worktree_root, limits.git_timeout_ms).await?;+ // Baseline, in the mode the caller chose. An unborn repository has+ // no commits and no tracked paths to restore - its delta already is+ // the whole worktree - so it stages no baseline and the manifest+ // says so explicitly (head commit and baseline are both null).+ let head_tree = match (&status.head_commit, baseline_mode) {+ (None, _) | (Some(_), BaselineMode::External) => Vec::new(),+ // Enumerate the tree of the commit status just reported, never+ // `HEAD` again: another process committing in between would+ // otherwise pair the old `head_commit` with a newer HEAD's tree.+ // With the enumeration pinned, the manifest's delta, baseline,+ // and head commit all describe one revision, and any later+ // worktree drift fails loudly per path instead.+ (Some(commit), BaselineMode::HeadTree) => {+ git::read_head_tree(&worktree_root, commit, limits.git_timeout_ms).await?+ }+ };+ let manifest = build_manifest(+ &worktree_root,+ staging_dir,+ &status,+ baseline_mode,+ &head_tree,+ limits,+ )?;+ let manifest_path = write_manifest(staging_dir, &manifest)?;+ Ok(WorkspaceSnapshot {+ staging_dir: staging_dir.to_path_buf(),+ manifest_path,+ manifest,+ })+}++/// Create the staging directory if needed, then reject prior content and+/// a location inside the worktree (which would capture the snapshot into+/// itself).+fn prepare_staging_dir(staging_dir: &Path, worktree_root: &Path) -> Result<(), SnapshotError> {+ crate::platform::perms::create_dir_all_private(staging_dir)+ .map_err(|error| io_error(staging_dir, error))?;+ let is_empty = std::fs::read_dir(staging_dir)+ .map_err(|error| io_error(staging_dir, error))?+ .next()+ .is_none();+ if !is_empty {+ return Err(SnapshotError::StagingDirNotEmpty {+ path: staging_dir.to_path_buf(),+ });+ }+ tighten_private(staging_dir)?;+ let staging_canonical = staging_dir+ .canonicalize()+ .map_err(|error| io_error(staging_dir, error))?;+ let root_canonical = worktree_root+ .canonicalize()+ .map_err(|error| io_error(worktree_root, error))?;+ if staging_canonical != root_canonical && staging_canonical.starts_with(&root_canonical) {+ return Err(SnapshotError::StagingDirInsideWorktree {+ path: staging_dir.to_path_buf(),+ });+ }+ Ok(())+}++/// Classify the delta (every `git status` entry) and the HEAD-tree+/// baseline the caller chose, staging content-addressed blobs and+/// recording in-root symlinks, tracked deletions, and every deliberate+/// exclusion with its reason.+fn build_manifest(+ worktree_root: &Path,+ staging_dir: &Path,+ status: &GitStatus,+ baseline_mode: BaselineMode,+ head_tree: &[HeadTreeEntry],+ limits: &SnapshotLimits,+) -> Result<SnapshotManifest, SnapshotError> {+ if status.entries.len() > limits.max_entries {+ return Err(limit_error(+ "max_entries",+ format!(+ "{} paths changed, cap is {}",+ status.entries.len(),+ limits.max_entries+ ),+ ));+ }+ if head_tree.len() > limits.max_baseline_entries {+ return Err(limit_error(+ "max_baseline_entries",+ format!(+ "{} paths in HEAD's tree, cap is {}",+ head_tree.len(),+ limits.max_baseline_entries+ ),+ ));+ }+ let blobs_dir = staging_dir.join(BLOBS_DIR);+ crate::platform::perms::create_dir_all_private(&blobs_dir)+ .map_err(|error| io_error(&blobs_dir, error))?;+ tighten_private(&blobs_dir)?;+ let mut captured: Vec<CapturedEntry> = Vec::new();+ let mut excluded: Vec<ExcludedEntry> = Vec::new();+ let mut total_bytes: u64 = 0;+ // One path, one row: `git rm --cached` leaves a tracked deletion and+ // the same path back as untracked in one `git status` run. The later+ // (untracked) row describes the worktree leaf that actually ships, so+ // it replaces the tracked row; both classify the same leaf, and a+ // duplicated path would trip verify's strictly-sorted check.+ let mut delta_rows: Vec<&StatusEntry> = Vec::with_capacity(status.entries.len());+ let mut seen: HashSet<&str> = HashSet::with_capacity(status.entries.len());+ for entry in status.entries.iter().rev() {+ if seen.insert(entry.path()) {+ delta_rows.push(entry);+ }+ }+ delta_rows.reverse();+ for entry in delta_rows {+ let path = entry.path();+ if !is_safe_relative_path(path) {+ return Err(SnapshotError::MalformedStatus {+ detail: format!("unsafe path {path:?}"),+ });+ }+ if is_secret_path(path) {+ excluded.push(ExcludedEntry {+ path: path.to_string(),+ reason: ExcludeReason::Secret,+ });+ continue;+ }+ let gitlink = matches!(entry, StatusEntry::Tracked { gitlink: true, .. });+ if gitlink {+ // A submodule reference's content is never captured; only its+ // absence from the worktree is recorded (as a deletion). The+ // probe refuses symlinked ancestors like every other read and+ // classifies the leaf kind WITHOUT reading content: the+ // bytes a replaced gitlink's stand-in file would cost are+ // discarded anyway, so they never touch the read budget.+ match open_leaf(worktree_root, path, 0, true) {+ Ok(OpenLeaf::Missing) => captured.push(CapturedEntry::Deleted {+ path: path.to_string(),+ status: entry_status(entry),+ }),+ Ok(OpenLeaf::AncestorSymlink) => excluded.push(ExcludedEntry {+ path: path.to_string(),+ reason: ExcludeReason::SymlinkedAncestor,+ }),+ Ok(OpenLeaf::File { .. } | OpenLeaf::Symlink { .. } | OpenLeaf::NotRegularFile) => {+ excluded.push(ExcludedEntry {+ path: path.to_string(),+ reason: ExcludeReason::Submodule,+ });+ }+ Err(error) => return Err(io_error(&worktree_root.join(path), error)),+ }+ continue;+ }+ let is_untracked = matches!(entry, StatusEntry::Untracked { .. });+ if is_untracked && path.ends_with('/') {+ // A directory git declined to recurse into: a nested+ // repository, shipped whole by other means or not at all.+ excluded.push(ExcludedEntry {+ path: path.to_string(),+ reason: ExcludeReason::NestedRepository,+ });+ continue;+ }+ match capture_leaf(+ worktree_root,+ &blobs_dir,+ path,+ &entry_status(entry),+ None,+ limits,+ &mut total_bytes,+ )? {+ LeafOutcome::Entry(entry) => captured.push(entry),+ LeafOutcome::Excluded(reason) => excluded.push(ExcludedEntry {+ path: path.to_string(),+ reason,+ }),+ // A tracked path missing from the worktree is a deletion; an+ // untracked path that vanished mid-capture never existed.+ LeafOutcome::Missing if !is_untracked => captured.push(CapturedEntry::Deleted {+ path: path.to_string(),+ status: entry_status(entry),+ }),+ LeafOutcome::Missing => {}+ }+ }+ let baseline = match (&status.head_commit, baseline_mode) {+ (None, _) => None,+ (Some(_), BaselineMode::External) => Some(Baseline::External),+ (Some(_), BaselineMode::HeadTree) => {+ // HEAD's tree content, staged from the worktree (a path git+ // status does not list matches HEAD), minus every path the+ // delta already carries - the delta holds the newer state.+ // No history ships and the same secret denylist applies; a+ // credential under an innocuous name still stages, in either+ // layer.+ let covered: HashSet<&str> = status.entries.iter().map(StatusEntry::path).collect();+ let mut entries: Vec<CapturedEntry> = Vec::new();+ let mut baseline_excluded: Vec<ExcludedEntry> = Vec::new();+ for tree_entry in head_tree {+ if covered.contains(tree_entry.path.as_str()) {+ continue;+ }+ if tree_entry.gitlink {+ baseline_excluded.push(ExcludedEntry {+ path: tree_entry.path.clone(),+ reason: ExcludeReason::Submodule,+ });+ continue;+ }+ match capture_leaf(+ worktree_root,+ &blobs_dir,+ &tree_entry.path,+ &tree_entry.mode,+ Some(tree_entry),+ limits,+ &mut total_bytes,+ )? {+ LeafOutcome::Entry(entry) => entries.push(entry),+ LeafOutcome::Excluded(reason) => baseline_excluded.push(ExcludedEntry {+ path: tree_entry.path.clone(),+ reason,+ }),+ LeafOutcome::Missing if tree_entry.skip_worktree => {+ baseline_excluded.push(ExcludedEntry {+ path: tree_entry.path.clone(),+ reason: ExcludeReason::SkipWorktree,+ });+ }+ // The path HEAD records is absent from the worktree+ // (or turned into something unreadable): the baseline+ // can no longer be the stated commit, so the snapshot+ // fails loudly rather than omitting silently.+ LeafOutcome::Missing => {+ return Err(SnapshotError::ConcurrentMutation {+ detail: format!(+ "{:?} vanished from the worktree during capture",+ tree_entry.path+ ),+ })+ }+ }+ }+ Some(Baseline::HeadTree {+ entries,+ excluded: baseline_excluded,+ })+ }+ };+ Ok(SnapshotManifest {+ version: MANIFEST_VERSION,+ head_commit: status.head_commit.clone(),+ baseline,+ captured,+ excluded,+ })+}++/// The git blob object id of `content` (`git hash-object` equivalent):+/// the object-format hash of `blob <len>\0` followed by the bytes. The+/// HEAD-tree baseline verifies every staged entry against the object id+/// `ls-tree` recorded, so the manifest's baseline provably is the stated+/// commit's content; the format follows the repository (SHA-1 or SHA-256).+pub(crate) fn git_blob_oid(content: &[u8], sha256: bool) -> String {+ let header = format!("blob {}\0", content.len());+ let digest = if sha256 {+ let mut hasher = Sha256::new();+ hasher.update(header.as_bytes());+ hasher.update(content);+ format!("{:x}", hasher.finalize())+ } else {+ let mut hasher = Sha1::new();+ hasher.update(header.as_bytes());+ hasher.update(content);+ format!("{:x}", hasher.finalize())+ };+ digest+}++/// What a single path's worktree leaf turned out to be.+#[derive(Debug)]+enum LeafOutcome {+ Entry(CapturedEntry),+ Excluded(ExcludeReason),+ Missing,+}++/// What a path's leaf opened as, with every component walked via+/// `openat` with `O_NOFOLLOW` on unix: no step follows a symlink.+#[cfg(unix)]+enum OpenLeaf {+ File {+ content: Vec<u8>,+ executable: bool,+ },+ Symlink {+ target: String,+ },+ /// An ancestor directory is a symlink: the leaf - if any - lives+ /// outside the worktree and is never read.+ AncestorSymlink,+ Missing,+ NotRegularFile,+}++/// Open one raw fd with `O_NOFOLLOW`, closing it on drop; the guard keeps+/// the walk's error paths leak-free without unsafe constructors.+#[cfg(unix)]+struct FdGuard(nix::libc::c_int);++#[cfg(unix)]+impl Drop for FdGuard {+ fn drop(&mut self) {+ let _ = nix::unistd::close(self.0);+ }+}++/// Open `path` beneath `root`, refusing to follow any symlink at any+/// step (unix): ancestors via `openat(O_DIRECTORY | O_NOFOLLOW)`, the+/// leaf via `openat(O_NOFOLLOW)` or `readlinkat`. A symlink swapped in+/// after the walk started still cannot redirect the read, because every+/// component is pinned by its opened fd, not its path.+#[cfg(unix)]+fn open_leaf(+ root: &Path,+ path: &str,+ max_bytes: usize,+ classify_only: bool,+) -> std::io::Result<OpenLeaf> {+ use nix::fcntl::{openat, AtFlags, OFlag};+ use nix::sys::stat::{fstat, fstatat, Mode, SFlag};+ let dir_flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;+ let root = openat(None, root, dir_flags, Mode::empty()).map_err(io_from_errno)?;+ let mut dir = FdGuard(root);+ let components: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();+ for component in &components[..components.len().saturating_sub(1)] {+ let component = *component;+ let fd = match openat(Some(dir.0), component, dir_flags, Mode::empty()) {+ Ok(fd) => FdGuard(fd),+ // The O_DIRECTORY|O_NOFOLLOW open of a symlink fails ELOOP+ // on older linux and ENOTDIR on current linux and darwin;+ // ENOTDIR also means a non-directory stands there, under+ // which the path does not exist.+ Err(nix::errno::Errno::ELOOP) => return Ok(OpenLeaf::AncestorSymlink),+ Err(nix::errno::Errno::ENOTDIR) => {+ let stat = fstatat(Some(dir.0), component, AtFlags::AT_SYMLINK_NOFOLLOW)+ .map_err(io_from_errno)?;+ return Ok(+ if stat.st_mode & SFlag::S_IFMT.bits() == SFlag::S_IFLNK.bits() {+ OpenLeaf::AncestorSymlink+ } else {+ OpenLeaf::Missing+ },+ );+ }+ Err(nix::errno::Errno::ENOENT) => return Ok(OpenLeaf::Missing),+ Err(errno) => return Err(io_from_errno(errno)),+ };+ dir = fd;+ }+ if let Some(leaf) = components.last() {+ let leaf = *leaf;+ // O_NONBLOCK: opening a FIFO (or a device) read-only blocks+ // until a writer or driver appears - an untracked named pipe in+ // the worktree would otherwise hang the whole capture. Regular+ // files ignore the flag, and the fstat below classifies before+ // any read happens.+ match openat(+ Some(dir.0),+ leaf,+ OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC,+ Mode::empty(),+ ) {+ Ok(fd) => {+ let fd = FdGuard(fd);+ let metadata = fstat(fd.0).map_err(io_from_errno)?;+ let mode = nix::sys::stat::SFlag::from_bits_truncate(metadata.st_mode);+ if mode.contains(nix::sys::stat::SFlag::S_IFREG) {+ if classify_only {+ // A kind-only probe (the replaced-gitlink path):+ // the leaf is classified from the fstat alone, so+ // discarded bytes never reach the read budget.+ return Ok(OpenLeaf::File {+ content: Vec::new(),+ executable: metadata.st_mode & 0o111 != 0,+ });+ }+ let mut content = Vec::new();+ let mut buffer = vec![0u8; 128 * 1024];+ loop {+ let read = nix::unistd::read(fd.0, &mut buffer).map_err(io_from_errno)?;+ if read == 0 {+ return Ok(OpenLeaf::File {+ content,+ executable: metadata.st_mode & 0o111 != 0,+ });+ }+ content.extend_from_slice(&buffer[..read]);+ // Past the caller's cap, stop reading: the size+ // check errors on the oversized capture instead+ // of buffering an unbounded raced-grown file.+ if content.len() > max_bytes {+ return Ok(OpenLeaf::File {+ content,+ executable: metadata.st_mode & 0o111 != 0,+ });+ }+ }+ }+ // A directory, fifo, socket, or device: not portable+ // content.+ Ok(OpenLeaf::NotRegularFile)+ }+ // O_NOFOLLOW on a symlink leaf: read the link through the+ // pinned parent fd instead.+ Err(nix::errno::Errno::ELOOP) => {+ let target = nix::fcntl::readlinkat(Some(dir.0), leaf).map_err(io_from_errno)?;+ let target = target.into_string().map_err(|_| {+ std::io::Error::new(std::io::ErrorKind::InvalidData, "non-UTF-8 link target")+ })?;+ Ok(OpenLeaf::Symlink { target })+ }+ Err(nix::errno::Errno::ENOENT) => Ok(OpenLeaf::Missing),+ // A unix socket path: present, but nothing regular to read.+ // linux reports ENXIO, darwin EOPNOTSUPP.+ Err(nix::errno::Errno::ENXIO | nix::errno::Errno::EOPNOTSUPP) => {+ Ok(OpenLeaf::NotRegularFile)+ }+ Err(errno) => Err(io_from_errno(errno)),+ }+ } else {+ Ok(OpenLeaf::Missing)+ }+}++#[cfg(unix)]+fn io_from_errno(errno: nix::errno::Errno) -> std::io::Error {+ std::io::Error::from_raw_os_error(errno as i32)+}++/// Non-unix fallback: component validation before the read. Without+/// `openat`, an untrusted concurrent actor can still swap an ancestor+/// for a symlink between the check and the read, so the residual race is+/// documented rather than closed: staging on non-unix targets must not+/// run with untrusted concurrent filesystem actors.+#[cfg(not(unix))]+enum OpenLeaf {+ File { content: Vec<u8>, executable: bool },+ Symlink { target: String },+ AncestorSymlink,+ Missing,+ NotRegularFile,+}++#[cfg(not(unix))]+fn open_leaf(+ root: &Path,+ path: &str,+ max_bytes: usize,+ classify_only: bool,+) -> std::io::Result<OpenLeaf> {+ let components: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();+ let mut prefix = PathBuf::new();+ for component in &components[..components.len().saturating_sub(1)] {+ prefix.push(component);+ if let Ok(metadata) = std::fs::symlink_metadata(root.join(&prefix)) {+ if metadata.is_symlink() {+ return Ok(OpenLeaf::AncestorSymlink);+ }+ }+ }+ let absolute = root.join(path);+ let metadata = match std::fs::symlink_metadata(&absolute) {+ Ok(metadata) => metadata,+ // A tracked deletion or a leaf that vanished between the status+ // run and this open is a missing leaf, not a capture error+ // (the unix arm's ENOENT path, in the std error kind).+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(OpenLeaf::Missing),+ Err(error) => return Err(error),+ };+ if metadata.file_type().is_symlink() {+ return Ok(OpenLeaf::Symlink {+ target: std::fs::read_link(&absolute)?+ .to_string_lossy()+ .into_owned(),+ });+ }+ if metadata.is_file() {+ if classify_only {+ // A kind-only probe (the replaced-gitlink path): the leaf+ // is classified from the metadata alone, so discarded bytes+ // never reach the read budget.+ return Ok(OpenLeaf::File {+ content: Vec::new(),+ executable: false,+ });+ }+ let mut file = std::fs::File::open(&absolute)?;+ let mut content = Vec::new();+ let mut buffer = vec![0u8; 128 * 1024];+ loop {+ let read = std::io::Read::read(&mut file, &mut buffer)?;+ if read == 0 {+ break;+ }+ content.extend_from_slice(&buffer[..read]);+ // Past the caller's cap, stop reading: the caller's size+ // check errors on the oversized capture instead of+ // buffering an unbounded raced-grown file whole.+ if content.len() > max_bytes {+ break;+ }+ }+ return Ok(OpenLeaf::File {+ content,+ executable: false,+ });+ }+ Ok(OpenLeaf::NotRegularFile)+}++/// Classify and stage one path's worktree leaf: a regular file becomes a+/// content-addressed blob (owner-only mode), an in-root symlink a link+/// entry, and anything deliberately uncaptured an exclusion reason.+/// `expected`, when present, is HEAD's `ls-tree` record for the path: the+/// captured bytes and mode are verified against it, so a worktree that+/// mutates under the capture fails loudly instead of shipping a baseline+/// that is not the stated commit.+fn capture_leaf(+ worktree_root: &Path,+ blobs_dir: &Path,+ path: &str,+ status: &str,+ expected: Option<&HeadTreeEntry>,+ limits: &SnapshotLimits,+ total_bytes: &mut u64,+) -> Result<LeafOutcome, SnapshotError> {+ if is_secret_path(path) {+ return Ok(LeafOutcome::Excluded(ExcludeReason::Secret));+ }+ let cap = usize::try_from(limits.max_file_bytes).unwrap_or(usize::MAX);+ let absolute = worktree_root.join(path);+ match open_leaf(worktree_root, path, cap, false) {+ Ok(OpenLeaf::AncestorSymlink) => {+ Ok(LeafOutcome::Excluded(ExcludeReason::SymlinkedAncestor))+ }+ Ok(OpenLeaf::Missing) => Ok(LeafOutcome::Missing),+ Ok(OpenLeaf::NotRegularFile) => Ok(LeafOutcome::Excluded(ExcludeReason::NotRegularFile)),+ Ok(OpenLeaf::Symlink { target }) => {+ if symlink_target_stays_inside(path, &target) {+ if let Some(expected) = expected {+ verify_against_head(+ path,+ "120000",+ &git_blob_oid(target.as_bytes(), expected.oid.len() == SHA256_OID_HEX_LEN),+ expected,+ )?;+ }+ Ok(LeafOutcome::Entry(CapturedEntry::Symlink {+ path: path.to_string(),+ status: status.to_string(),+ target,+ }))+ } else {+ Ok(LeafOutcome::Excluded(ExcludeReason::EscapingSymlink))+ }+ }+ Ok(OpenLeaf::File {+ content,+ executable,+ }) => {+ if content.len() as u64 > limits.max_file_bytes {+ return Err(limit_error(+ "max_file_bytes",+ format!(+ "{path} is {} bytes, cap is {}",+ content.len(),+ limits.max_file_bytes+ ),+ ));+ }+ *total_bytes += content.len() as u64;+ if *total_bytes > limits.max_total_bytes {+ return Err(limit_error(+ "max_total_bytes",+ format!(+ "{total_bytes} bytes of captured content, cap is {}",+ limits.max_total_bytes+ ),+ ));+ }+ let mut executable = executable;+ if let Some(expected) = expected {+ let oid = git_blob_oid(&content, expected.oid.len() == SHA256_OID_HEX_LEN);+ if expected.oid == oid {+ // A clean leaf restates HEAD's own mode: the object+ // id is the mutation check, and the filesystem bit+ // is not git's truth under core.filemode=false+ // (WSL drvfs, FAT/exFAT).+ executable = expected.mode == "100755";+ }+ verify_against_head(+ path,+ if executable { "100755" } else { "100644" },+ &oid,+ expected,+ )?;+ }+ let sha256 = format!("{:x}", Sha256::digest(&content));+ let blob = blobs_dir.join(&sha256);+ if std::fs::symlink_metadata(&blob).is_err() {+ std::fs::write(&blob, &content).map_err(|error| io_error(&blob, error))?;+ tighten_private_file(&blob)?;+ }+ Ok(LeafOutcome::Entry(CapturedEntry::File {+ path: path.to_string(),+ status: status.to_string(),+ sha256,+ bytes: content.len() as u64,+ executable,+ }))+ }+ Err(error) => Err(io_error(&absolute, error)),+ }+}++/// Verify one captured baseline leaf against HEAD's `ls-tree` record:+/// the mode must match and the staged bytes must hash to the recorded+/// object id. Any mismatch is a concurrent worktree mutation, a loud+/// error rather than a silently wrong baseline.+fn verify_against_head(+ path: &str,+ mode: &str,+ oid: &str,+ expected: &HeadTreeEntry,+) -> Result<(), SnapshotError> {+ // The object id is the primary mutation detector; the mode is+ // secondary (a host without an observable executable bit reports+ // its derived mode as 100644, so a mutated file must fail on the+ // content first, never on a mode it cannot observe).+ if expected.oid != oid {+ return Err(SnapshotError::ConcurrentMutation {+ detail: format!(+ "{path} hashes to object {oid} but HEAD records {}",+ expected.oid+ ),+ });+ }+ if expected.mode != mode {+ return Err(SnapshotError::ConcurrentMutation {+ detail: format!("{path} is mode {mode} but HEAD records {}", expected.mode),+ });+ }+ Ok(())+}++/// Staged content files (blobs, the manifest) are tightened to+/// owner-only (0600) regardless of umask, so a file later moved out of+/// the private staging directory keeps no group/other access. Both+/// modes route through the platform permission wall.+fn tighten_private(dir: &Path) -> Result<(), SnapshotError> {+ crate::platform::perms::restrict_dir(dir).map_err(|error| io_error(dir, error))+}++fn tighten_private_file(path: &Path) -> Result<(), SnapshotError> {+ crate::platform::perms::restrict_file(path).map_err(|error| io_error(path, error))+}++fn limit_error(limit: &str, detail: String) -> SnapshotError {+ SnapshotError::Limit {+ limit: limit.to_string(),+ detail,+ }+}++fn io_error(path: &Path, error: std::io::Error) -> SnapshotError {+ SnapshotError::Io {+ path: path.to_path_buf(),+ source: error,+ }+}++/// Write the manifest deterministically (path-sorted entries, no+/// timestamps) via a temp file and rename, so a reader that sees it holds+/// a complete blob set.+fn write_manifest(+ staging_dir: &Path,+ manifest: &SnapshotManifest,+) -> Result<PathBuf, SnapshotError> {+ let manifest_path = staging_dir.join(MANIFEST_FILE);+ let bytes = serde_json::to_vec(manifest).map_err(|error| SnapshotError::Manifest {+ path: manifest_path.clone(),+ detail: format!("serialization failed: {error}"),+ })?;+ // The verifier's manifest cap is a property of the format, so a+ // manifest past it fails the capture loudly instead of producing an+ // artifact verify would always reject (symlink targets do not count+ // toward the content budget, so the entry caps alone do not bound+ // the serialized size).+ if bytes.len() as u64 > verify::MAX_MANIFEST_BYTES {+ return Err(limit_error(+ "max_manifest_bytes",+ format!(+ "manifest is {} bytes, cap is {}",+ bytes.len(),+ verify::MAX_MANIFEST_BYTES+ ),+ ));+ }+ let temp_path = staging_dir.join(format!("{MANIFEST_FILE}.tmp"));+ std::fs::write(&temp_path, &bytes).map_err(|error| io_error(&temp_path, error))?;+ crate::platform::rename_onto(&temp_path, &manifest_path)+ .map_err(|error| io_error(&manifest_path, error))?;+ tighten_private_file(&manifest_path)?;+ Ok(manifest_path)+}++/// The `git status` XY pair for an entry, or `"??"` for untracked paths;+/// recorded in the manifest for diagnostics.+fn entry_status(entry: &StatusEntry) -> String {+ match entry {+ StatusEntry::Tracked { xy, .. } => xy.clone(),+ StatusEntry::Untracked { .. } => "??".to_string(),+ }+}++/// File names never captured, tracked or not: credential-shaped locals+/// that must not ride along to a remote staging area. Deliberately small+/// and exact - broadening the list is a policy decision, not a drive-by.+pub(crate) fn is_secret_path(path: &str) -> bool {+ const EXACT_NAMES: &[&str] = &[+ ".env",+ ".envrc",+ ".npmrc",+ ".netrc",+ ".git-credentials",+ "id_rsa",+ "id_dsa",+ "id_ecdsa",+ "id_ed25519",+ ];+ const SECRET_SUFFIXES: &[&str] = &[".pem", ".key", ".p12", ".pfx"];+ let name = match path.rsplit_once('/') {+ Some((_, name)) => name,+ None => path,+ };+ EXACT_NAMES.contains(&name)+ || name.starts_with(".env.")+ || SECRET_SUFFIXES.iter().any(|suffix| name.ends_with(suffix))+}diff --git a/crates/pa-core/src/workspace_snapshot/tests.rs b/crates/pa-core/src/workspace_snapshot/tests.rsnew file mode 100644index 0000000000..1951b6d216--- /dev/null+++ b/crates/pa-core/src/workspace_snapshot/tests.rs@@ -0,0 +1,1855 @@+//! Fixture-repo tests for workspace snapshots: real `git` in tempdirs (the+//! crate's established pattern for worktree-touching tests) plus pure+//! parser, manifest, and verification cases.++use std::path::Path;++use sha2::{Digest, Sha256};++use super::git::{git_command, parse_status, GitStatus, HeadTreeEntry, StatusEntry};+#[cfg(unix)]+use super::git::{read_head_tree, read_worktree_status};+use super::manifest::{is_safe_relative_path, symlink_target_stays_inside};+use super::{+ build_manifest, capture_leaf, create_workspace_snapshot, git_blob_oid, is_secret_path,+ verify_workspace_snapshot, Baseline, BaselineMode, CapturedEntry, ExcludeReason, ExcludedEntry,+ LeafOutcome, SnapshotError, SnapshotLimits, SnapshotManifest,+};+#[cfg(unix)]+use super::{open_leaf, OpenLeaf};++#[cfg(unix)]+fn git(dir: &Path, args: &[&str]) {+ let output = git_command(args, dir).into_std().output().unwrap();+ assert!(+ output.status.success(),+ "git {args:?} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}++#[cfg(unix)]+fn init_repo(dir: &Path) {+ git(dir, &["init", "-q"]);+ git(dir, &["config", "user.email", "[email protected]"]);+ git(dir, &["config", "user.name", "t"]);+}++#[cfg(unix)]+fn write(dir: &Path, rel: &str, content: &str) {+ let path = dir.join(rel);+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).unwrap();+ }+ std::fs::write(path, content).unwrap();+}++#[cfg(unix)]+fn git_show(dir: &Path, revision: &str) -> String {+ let output = git_command(&["show", revision], dir)+ .into_std()+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "git show {revision} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8(output.stdout).unwrap()+}++#[cfg(unix)]+fn head_commit(dir: &Path) -> String {+ let output = git_command(&["rev-parse", "HEAD"], dir)+ .into_std()+ .output()+ .unwrap();+ assert!(output.status.success());+ String::from_utf8(output.stdout).unwrap().trim().to_string()+}++fn digest(content: &[u8]) -> String {+ format!("{:x}", Sha256::digest(content))+}++fn file_entry(path: &str, status: &str, content: &str) -> CapturedEntry {+ CapturedEntry::File {+ path: path.to_string(),+ status: status.to_string(),+ sha256: digest(content.as_bytes()),+ bytes: content.len() as u64,+ executable: false,+ }+}++fn limits() -> SnapshotLimits {+ SnapshotLimits::default()+}++fn secret(path: &str) -> ExcludedEntry {+ ExcludedEntry {+ path: path.to_string(),+ reason: ExcludeReason::Secret,+ }+}++fn head_tree(entries: Vec<CapturedEntry>) -> Baseline {+ Baseline::HeadTree {+ entries,+ excluded: vec![],+ }+}++/// A manifest for hand-built staging: no commits, no baseline, version 2.+fn bare_manifest(captured: Vec<CapturedEntry>, excluded: Vec<ExcludedEntry>) -> SnapshotManifest {+ SnapshotManifest {+ version: 2,+ head_commit: None,+ baseline: None,+ captured,+ excluded,+ }+}++/// The manifest a committed repository produces with a HEAD-tree+/// baseline.+#[cfg(unix)]+fn repo_manifest(+ root: &Path,+ baseline: Baseline,+ captured: Vec<CapturedEntry>,+ excluded: Vec<ExcludedEntry>,+) -> SnapshotManifest {+ SnapshotManifest {+ version: 2,+ head_commit: Some(head_commit(root)),+ baseline: Some(baseline),+ captured,+ excluded,+ }+}++fn stage(manifest: &SnapshotManifest, blobs: &[(&str, &[u8])]) -> tempfile::TempDir {+ let staging = tempfile::tempdir().unwrap();+ let blobs_dir = staging.path().join("blobs");+ std::fs::create_dir(&blobs_dir).unwrap();+ for (name, content) in blobs {+ std::fs::write(blobs_dir.join(name), content).unwrap();+ }+ std::fs::write(+ staging.path().join("manifest.json"),+ serde_json::to_vec(manifest).unwrap(),+ )+ .unwrap();+ staging+}++#[cfg(unix)]+fn read_blob(staging: &Path, sha256: &str) -> Vec<u8> {+ std::fs::read(staging.join("blobs").join(sha256)).unwrap()+}++/// Capture refuses before querying git or creating private-looking files+/// when owner-only modes cannot be guaranteed by the platform wall.+#[cfg(not(unix))]+#[tokio::test]+async fn capture_refuses_unsupported_platform_without_staging() {+ let dir = tempfile::tempdir().unwrap();+ let staging = dir.path().join("staging");+ let error = create_workspace_snapshot(dir.path(), &staging, BaselineMode::External, &limits())+ .await+ .unwrap_err();+ assert!(matches!(error, SnapshotError::UnsupportedPlatform));+ assert!(!staging.exists());+}++/// A SHA-256 repository snapshots and verifies the same as a SHA-1 one:+/// the object ids follow the repository's own format, and the manifest's+/// head commit is the repository's 64-character branch id.+#[cfg(unix)]+#[tokio::test]+async fn a_sha256_repository_snapshots_and_verifies() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ git(root, &["init", "-q", "--object-format=sha256", "."]);+ git(root, &["config", "user.email", "[email protected]"]);+ git(root, &["config", "user.name", "t"]);+ write(root, "a.txt", "sha256\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ let manifest = verify_workspace_snapshot(staging.path()).unwrap();+ assert_eq!(snapshot.manifest, manifest);+ assert_eq!(+ manifest.head_commit.as_deref().map(str::len),+ Some(64),+ "a SHA-256 repository publishes a 64-character head commit"+ );+ // The whole worktree is clean, so the HEAD-tree baseline carries it+ // and the delta is empty: the baseline entry landing at all is the+ // SHA-256 proof — the object-id cross-check passed, and a SHA-1 hash+ // of the same content could never match the repository's+ // 64-character tree ids.+ assert!(manifest.captured.is_empty());+ let Baseline::HeadTree { entries, .. } = manifest.baseline.as_ref().unwrap() else {+ panic!("the HEAD-tree baseline");+ };+ let CapturedEntry::File {+ path,+ sha256,+ bytes,+ ..+ } = &entries[0]+ else {+ panic!("the baseline file entry");+ };+ assert_eq!(path, "a.txt");+ assert_eq!(*sha256, digest(b"sha256\n"));+ assert_eq!(*bytes, 7);+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_collapses_a_path_git_lists_twice() {+ // `git rm --cached` leaves a staged deletion and an untracked row+ // for the same path in one `git status` run; the manifest carries+ // the path once, and its own verify accepts the result.+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ git(root, &["rm", "-q", "--cached", "tracked.txt"]);+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ let expected = repo_manifest(+ root,+ // The delta row covers the path, so the HEAD-tree baseline does not+ // restate it.+ head_tree(vec![]),+ vec![file_entry("tracked.txt", "??", "base\n")],+ vec![],+ );+ assert_eq!(snapshot.manifest, expected);+ assert_eq!(verify_workspace_snapshot(staging.path()).unwrap(), expected);+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_captures_worktree_delta() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ write(root, "gone.txt", "gone\n");+ write(root, ".gitignore", "ignored.log\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ // The working-state delta: unstaged modification, staged addition,+ // staged deletion, two untracked paths, and one ignored path.+ write(root, "tracked.txt", "modified\n");+ write(root, "staged.txt", "staged\n");+ git(root, &["add", "staged.txt"]);+ git(root, &["rm", "-q", "gone.txt"]);+ write(root, "untracked.txt", "fresh\n");+ write(root, "sub/deep.txt", "deep\n");+ write(root, "ignored.log", "never\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ // Only .gitignore is unmodified, so it alone forms the HEAD-tree+ // baseline; every changed path is carried by the delta instead.+ let expected = repo_manifest(+ root,+ head_tree(vec![file_entry(".gitignore", "100644", "ignored.log\n")]),+ vec![+ CapturedEntry::Deleted {+ path: "gone.txt".to_string(),+ status: "D.".to_string(),+ },+ file_entry("staged.txt", "A.", "staged\n"),+ file_entry("sub/deep.txt", "??", "deep\n"),+ file_entry("tracked.txt", ".M", "modified\n"),+ file_entry("untracked.txt", "??", "fresh\n"),+ ],+ vec![],+ );+ assert_eq!(snapshot.manifest, expected);+ assert_eq!(snapshot.staging_dir, staging.path());+ assert_eq!(snapshot.manifest_path, staging.path().join("manifest.json"));+ assert_eq!(+ read_blob(staging.path(), &digest(b"modified\n")),+ b"modified\n"+ );+ assert_eq!(read_blob(staging.path(), &digest(b"staged\n")), b"staged\n");+ // Verification agrees with what was staged, manifest included.+ assert_eq!(verify_workspace_snapshot(staging.path()).unwrap(), expected);+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_is_deterministic() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "a.txt", "one\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "b.txt", "two\n");+ let first = tempfile::tempdir().unwrap();+ let second = tempfile::tempdir().unwrap();+ let snapshot_a =+ create_workspace_snapshot(root, first.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ let snapshot_b =+ create_workspace_snapshot(root, second.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ // No timestamps and no git pack bytes: identical manifests, byte for+ // byte, and each one verifies in full.+ assert_eq!(snapshot_a.manifest, snapshot_b.manifest);+ let bytes_a = std::fs::read(&snapshot_a.manifest_path).unwrap();+ let bytes_b = std::fs::read(&snapshot_b.manifest_path).unwrap();+ assert_eq!(bytes_a, bytes_b);+ assert!(verify_workspace_snapshot(first.path()).is_ok());+ assert!(verify_workspace_snapshot(second.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_excludes_secret_named_files_in_delta_and_baseline() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ // A committed secret left unmodified and a modified tracked one: the+ // denylist must reach the baseline exactly like the delta.+ write(root, "old.pem", "committed-secret\n");+ write(root, ".env", "old-secret\n");+ write(root, "keep.txt", "kept\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, ".env", "new-secret\n");+ write(root, ".env.local", "local\n");+ write(root, "cert.pem", "cert\n");+ write(root, "id_rsa", "key\n");+ write(root, "keys/private.key", "key\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ Baseline::HeadTree {+ entries: vec![file_entry("keep.txt", "100644", "kept\n")],+ excluded: vec![secret("old.pem")],+ },+ vec![],+ vec![+ secret(".env"),+ secret(".env.local"),+ secret("cert.pem"),+ secret("id_rsa"),+ secret("keys/private.key"),+ ]+ )+ );+ // Exactly one blob is staged - the unmodified keep.txt baseline -+ // and no secret content from either layer.+ let staged_blobs: Vec<String> = std::fs::read_dir(staging.path().join("blobs"))+ .unwrap()+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ assert_eq!(staged_blobs, vec![digest(b"kept\n")]);+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_captures_in_root_symlinks_and_excludes_escaping_ones() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ std::os::unix::fs::symlink("tracked.txt", root.join("ok-link")).unwrap();+ std::os::unix::fs::symlink("../escape", root.join("escape-link")).unwrap();+ std::os::unix::fs::symlink("/absolute", root.join("abs-link")).unwrap();+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![file_entry("tracked.txt", "100644", "base\n")]),+ vec![CapturedEntry::Symlink {+ path: "ok-link".to_string(),+ status: "??".to_string(),+ target: "tracked.txt".to_string(),+ }],+ vec![+ ExcludedEntry {+ path: "abs-link".to_string(),+ reason: ExcludeReason::EscapingSymlink,+ },+ ExcludedEntry {+ path: "escape-link".to_string(),+ reason: ExcludeReason::EscapingSymlink,+ },+ ]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_never_reads_behind_symlinked_ancestors() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "sub/file.txt", "tracked\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ // Replace the tracked directory with a symlink to a directory outside+ // the worktree that carries a file with the same name: a naive+ // `root.join(path)` read would stage the victim's content.+ let victim = tempfile::tempdir().unwrap();+ std::fs::write(victim.path().join("file.txt"), "VICTIM-SECRET\n").unwrap();+ std::fs::remove_dir_all(root.join("sub")).unwrap();+ std::os::unix::fs::symlink(victim.path(), root.join("sub")).unwrap();+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ // The tracked path behind the symlink is excluded unread; the+ // symlink itself is excluded for its escaping target. The HEAD tree+ // only holds sub/file.txt, which the delta already covers.+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![]),+ vec![],+ vec![+ ExcludedEntry {+ path: "sub".to_string(),+ reason: ExcludeReason::EscapingSymlink,+ },+ ExcludedEntry {+ path: "sub/file.txt".to_string(),+ reason: ExcludeReason::SymlinkedAncestor,+ },+ ]+ )+ );+ // No file content was staged at all, victim's or otherwise.+ assert!(std::fs::read_dir(staging.path().join("blobs"))+ .unwrap()+ .next()+ .is_none());+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn a_directory_replaced_by_a_file_deletes_its_tracked_paths() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "dir/x", "x\n");+ write(root, "keep.txt", "k\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ std::fs::remove_dir_all(root.join("dir")).unwrap();+ write(root, "dir", "file now\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![file_entry("keep.txt", "100644", "k\n")]),+ vec![+ file_entry("dir", "??", "file now\n"),+ CapturedEntry::Deleted {+ path: "dir/x".to_string(),+ status: ".D".to_string(),+ },+ ],+ vec![]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+ // The replaced directory read as a baseline path after the status+ // run: HEAD still records dir/x, but the standing file is not a+ // path to it, so the baseline can no longer be the stated commit.+ let staging = tempfile::tempdir().unwrap();+ let error = build_manifest(+ root,+ staging.path(),+ &GitStatus {+ head_commit: Some(head_commit(root)),+ entries: vec![],+ },+ BaselineMode::HeadTree,+ &[HeadTreeEntry {+ path: "dir/x".to_string(),+ mode: "100644".to_string(),+ gitlink: false,+ skip_worktree: false,+ oid: git_blob_oid(b"x\n", false),+ }],+ &limits(),+ )+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::ConcurrentMutation { .. }),+ "{error}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_excludes_nested_repositories() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ let nested = root.join("nested");+ std::fs::create_dir(&nested).unwrap();+ init_repo(&nested);+ write(&nested, "inner.txt", "inner\n");+ git(&nested, &["add", "."]);+ git(&nested, &["commit", "-q", "-m", "inner"]);+ write(root, "untracked.txt", "fresh\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![file_entry("tracked.txt", "100644", "base\n")]),+ vec![file_entry("untracked.txt", "??", "fresh\n")],+ vec![ExcludedEntry {+ path: "nested/".to_string(),+ reason: ExcludeReason::NestedRepository,+ }]+ )+ );+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_records_gitlink_absence_and_excludes_present_submodules() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ // A gitlink registered without its directory: only the absence is+ // meaningful, so it is recorded as a deletion.+ git(+ root,+ &[+ "update-index",+ "--add",+ "--cacheinfo",+ "160000,5b1c2d3e4f6071829b34a5678901234567890abc,submod",+ ],+ );+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest.captured,+ vec![CapturedEntry::Deleted {+ path: "submod".to_string(),+ status: "AD".to_string(),+ }]+ );+ // Once the submodule directory exists its content is never captured.+ std::fs::create_dir(root.join("submod")).unwrap();+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![file_entry("tracked.txt", "100644", "base\n")]),+ vec![],+ vec![ExcludedEntry {+ path: "submod".to_string(),+ reason: ExcludeReason::Submodule,+ }]+ )+ );+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_captures_unmerged_conflict_worktree_content() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "f.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ git(root, &["checkout", "-q", "-b", "side"]);+ write(root, "f.txt", "side\n");+ git(root, &["commit", "-q", "-am", "side"]);+ git(root, &["checkout", "-q", "-"]);+ write(root, "f.txt", "main\n");+ git(root, &["commit", "-q", "-am", "main"]);+ let merge = git_command(&["merge", "side"], root)+ .into_std()+ .output()+ .unwrap();+ assert!(!merge.status.success(), "expected a conflict");+ let conflict = std::fs::read_to_string(root.join("f.txt")).unwrap();+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ // f.txt differs from HEAD, so the delta covers it and the HEAD-tree+ // baseline stays empty.+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![]),+ vec![file_entry("f.txt", "UU", &conflict)],+ vec![]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn head_tree_baseline_ships_head_content_and_full_coverage() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "a.txt", "one\n");+ write(root, "b.txt", "bee\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "one"]);+ write(root, "a.txt", "two\n");+ git(root, &["commit", "-q", "-am", "two"]);+ // A dirty delta on top of history that exists nowhere but here: the+ // unpushed-worktree case the baseline exists for. a.txt changes, so+ // the delta carries it; unmodified b.txt is what the HEAD-tree+ // baseline stages.+ write(root, "a.txt", "working\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ let head = head_commit(root);+ assert_eq!(+ snapshot.manifest.head_commit.as_deref(),+ Some(head.as_str())+ );+ // The baseline holds HEAD's content for the unmodified path - the+ // changed path is carried by the delta instead.+ assert_eq!(+ snapshot.manifest.baseline,+ Some(head_tree(vec![file_entry("b.txt", "100644", "bee\n")]))+ );+ assert_eq!(+ snapshot.manifest.captured,+ vec![file_entry("a.txt", ".M", "working\n")]+ );+ // Proven with git itself: the staged baseline blob is exactly what+ // `git show HEAD:b.txt` reports, and the object-id verification+ // matches `git hash-object` byte for byte.+ assert_eq!(git_show(root, "HEAD:b.txt"), "bee\n");+ assert_eq!(read_blob(staging.path(), &digest(b"bee\n")), b"bee\n");+ let hash_object = git_command(&["hash-object", "--", "b.txt"], root)+ .into_std()+ .output()+ .unwrap();+ assert!(hash_object.status.success());+ let head_content = std::fs::read(root.join("b.txt")).unwrap();+ assert_eq!(+ git_blob_oid(&head_content, false),+ String::from_utf8(hash_object.stdout).unwrap().trim()+ );+ // Materializing = baseline plus delta blobs: the worktree's content,+ // reproduced from the staging directory alone.+ assert_eq!(+ read_blob(staging.path(), &digest(b"working\n")),+ b"working\n"+ );+ // Full coverage: every path in HEAD's tree is carried by the delta,+ // the baseline, or an exclusion with a reason.+ let ls_tree = git_command(&["ls-tree", "-r", "--name-only", "HEAD"], root)+ .into_std()+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&ls_tree.stdout);+ let head_paths: Vec<&str> = stdout.lines().filter(|line| !line.is_empty()).collect();+ let carried = |path: &str| -> bool {+ snapshot.manifest.baseline.as_ref().is_some_and(|baseline| {+ matches!(+ baseline,+ Baseline::HeadTree { entries, excluded }+ if entries.iter().any(|entry| entry.path() == path)+ || excluded.iter().any(|entry| entry.path == path)+ )+ }) || snapshot+ .manifest+ .captured+ .iter()+ .any(|entry| entry.path() == path)+ || snapshot+ .manifest+ .excluded+ .iter()+ .any(|entry| entry.path == path)+ };+ assert!(!head_paths.is_empty());+ for path in head_paths {+ assert!(carried(path), "HEAD path {path} is not covered");+ }+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn head_tree_pins_to_the_status_reported_commit() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "a.txt", "A\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "one"]);+ let pinned = read_worktree_status(root, limits().git_timeout_ms)+ .await+ .unwrap()+ .head_commit+ .unwrap();+ // Another process commits between the status run and the tree+ // enumeration: the enumeration must describe the status-reported+ // commit, not the moved HEAD, or the manifest would publish the+ // old head commit with the new HEAD's tree.+ write(root, "a.txt", "B\n");+ write(root, "b.txt", "new\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "two"]);+ let tree = read_head_tree(root, &pinned, limits().git_timeout_ms)+ .await+ .unwrap();+ assert_eq!(+ tree,+ vec![HeadTreeEntry {+ path: "a.txt".to_string(),+ mode: "100644".to_string(),+ gitlink: false,+ skip_worktree: false,+ oid: git_blob_oid(b"A\n", false),+ }]+ );+}++#[cfg(unix)]+#[tokio::test]+async fn head_tree_baseline_excludes_only_absent_skip_worktree_paths() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "keep.txt", "k\n");+ write(root, "sparse/x.txt", "x\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ // A cone-mode sparse checkout keeps only root-level files: git+ // status reports nothing for the absent path, but the index still+ // marks it skip-worktree.+ git(root, &["sparse-checkout", "set", "--cone"]);+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ Baseline::HeadTree {+ entries: vec![file_entry("keep.txt", "100644", "k\n")],+ excluded: vec![ExcludedEntry {+ path: "sparse/x.txt".to_string(),+ reason: ExcludeReason::SkipWorktree,+ }],+ },+ vec![],+ vec![]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+ // Without a sparse checkout, git keeps the bit on a present file+ // (`update-index --skip-worktree`): the leaf is on disk and must+ // stage.+ git(root, &["sparse-checkout", "disable"]);+ git(root, &["update-index", "--skip-worktree", "keep.txt"]);+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![+ file_entry("keep.txt", "100644", "k\n"),+ file_entry("sparse/x.txt", "100644", "x\n"),+ ]),+ vec![],+ vec![]+ )+ );+}++#[test]+fn baseline_rejects_concurrent_mutation_loudly() {+ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("a.txt"), "right\n").unwrap();+ let staging = tempfile::tempdir().unwrap();+ let blobs = staging.path().join("blobs");+ std::fs::create_dir(&blobs).unwrap();+ let limits = SnapshotLimits::default();+ let mut total_bytes = 0u64;+ let head_entry = |oid: &str, mode: &str| HeadTreeEntry {+ path: "a.txt".to_string(),+ mode: mode.to_string(),+ gitlink: false,+ skip_worktree: false,+ oid: oid.to_string(),+ };+ // Matching content, mode, and object id stages the leaf.+ let expected = head_entry(&git_blob_oid(b"right\n", false), "100644");+ let outcome = capture_leaf(+ root.path(),+ &blobs,+ "a.txt",+ "100644",+ Some(&expected),+ &limits,+ &mut total_bytes,+ )+ .unwrap();+ assert!(matches!(outcome, LeafOutcome::Entry(_)));+ // Content that no longer reproduces HEAD's object id fails loudly.+ let mutated = head_entry(&git_blob_oid(b"other\n", false), "100644");+ let error = capture_leaf(+ root.path(),+ &blobs,+ "a.txt",+ "100644",+ Some(&mutated),+ &limits,+ &mut total_bytes,+ )+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::ConcurrentMutation { .. }),+ "{error}"+ );+ assert!(error.to_string().contains("hashes to object"), "{error}");+ // A path HEAD records that vanished from the worktree is an error,+ // never a silent omission: drive it through build_manifest itself.+ let bare = tempfile::tempdir().unwrap();+ let status = GitStatus {+ head_commit: Some("ee3a902349fa5446bf3edd1e1e8d8f7f48013081".to_string()),+ entries: vec![],+ };+ let staging = tempfile::tempdir().unwrap();+ let error = build_manifest(+ bare.path(),+ staging.path(),+ &status,+ BaselineMode::HeadTree,+ &[expected],+ &limits,+ )+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::ConcurrentMutation { .. }),+ "{error}"+ );+ assert!(+ error.to_string().contains("vanished from the worktree"),+ "{error}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn external_baseline_mode_records_the_choice() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "untracked.txt", "fresh\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::External, &limits())+ .await+ .unwrap();+ // The delta ships and the manifest states explicitly that the+ // consumer must obtain the head commit itself.+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ Baseline::External,+ vec![file_entry("untracked.txt", "??", "fresh\n")],+ vec![]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn unborn_repository_snapshot_is_self_contained() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "fresh.txt", "fresh\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ // No commits: no baseline to stage, and the manifest says so+ // explicitly - the delta already is the whole worktree.+ assert_eq!(+ snapshot.manifest,+ bare_manifest(vec![file_entry("fresh.txt", "??", "fresh\n")], vec![])+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_drains_status_output_beyond_pipe_capacity() {+ // Regression guard for the child-process drain: `git status` writing+ // more than the OS pipe capacity must not deadlock the capture (the+ // drain races with the wait, not after it).+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ for i in 0..3000 {+ let path = root.join(format!("u/file_{i:04}.txt"));+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).unwrap();+ }+ std::fs::write(&path, format!("{i}\n")).unwrap();+ }+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(snapshot.manifest.captured.len(), 3000);+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+async fn capture_error(root: &Path, limits: &SnapshotLimits) -> String {+ let staging = tempfile::tempdir().unwrap();+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, limits)+ .await+ .unwrap_err()+ .to_string()+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_enforces_limits() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "one.txt", "one\n");+ write(root, "two.txt", "two\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "big.txt", "0123456789");+ write(root, "small.txt", "01234");++ let error = capture_error(+ root,+ &SnapshotLimits {+ max_entries: 1,+ ..limits()+ },+ )+ .await;+ assert!(error.contains("max_entries"), "{error}");+ let error = capture_error(+ root,+ &SnapshotLimits {+ max_file_bytes: 4,+ ..limits()+ },+ )+ .await;+ assert!(error.contains("big.txt"), "{error}");+ let error = capture_error(+ root,+ &SnapshotLimits {+ max_total_bytes: 12,+ ..limits()+ },+ )+ .await;+ assert!(error.contains("max_total_bytes"), "{error}");+ // An oversized HEAD tree fails its own bound.+ let error = capture_error(+ root,+ &SnapshotLimits {+ max_baseline_entries: 1,+ ..limits()+ },+ )+ .await;+ assert!(error.contains("max_baseline_entries"), "{error}");+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_rejects_unusable_staging_directories() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "untracked.txt", "fresh\n");+ // A staging directory holding prior content is refused.+ let occupied = tempfile::tempdir().unwrap();+ std::fs::write(occupied.path().join("prior.txt"), "prior\n").unwrap();+ let error = create_workspace_snapshot(root, occupied.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::StagingDirNotEmpty { .. }),+ "{error}"+ );+ // A staging directory inside the worktree would capture itself.+ let inside = root.join(".staging");+ let error = create_workspace_snapshot(root, &inside, BaselineMode::HeadTree, &limits())+ .await+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::StagingDirInsideWorktree { .. }),+ "{error}"+ );+ // A missing nested staging directory is created.+ let outside = tempfile::tempdir().unwrap();+ let staging = outside.path().join("nested/stage");+ create_workspace_snapshot(root, &staging, BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert!(staging.join("manifest.json").is_file());+}++#[cfg(unix)]+#[tokio::test]+async fn untracked_special_paths_never_block_the_leaf_open() {+ // Regression guard: a plain read-only open of a FIFO (or a unix+ // socket) blocks until a writer or client appears, which would hang+ // the whole capture. git does not enumerate special files as+ // untracked (probed), so this is defense in depth for the open+ // itself: with O_NONBLOCK it must classify immediately instead.+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ nix::unistd::mkfifo(&root.join("pipe"), nix::sys::stat::Mode::S_IRWXU).unwrap();+ let listener = std::os::unix::net::UnixListener::bind(root.join("sock")).unwrap();+ assert!(matches!(+ open_leaf(root, "pipe", 1024, false),+ Ok(OpenLeaf::NotRegularFile)+ ));+ assert!(matches!(+ open_leaf(root, "sock", 1024, false),+ Ok(OpenLeaf::NotRegularFile)+ ));+ drop(listener);+ // The fix's end-to-end behavior: a repo holding such files snapshots+ // and verifies fine, mentioning them nowhere (git does not list them).+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "tracked.txt"]);+ git(root, &["commit", "-q", "-m", "base"]);+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![file_entry("tracked.txt", "100644", "base\n")]),+ vec![],+ vec![]+ )+ );+ assert!(verify_workspace_snapshot(staging.path()).is_ok());+}++#[cfg(unix)]+#[tokio::test]+async fn staging_and_staged_files_are_owner_private() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "untracked.txt", "fresh\n");+ let mode_of = |path: &Path| {+ use std::os::unix::fs::PermissionsExt;+ std::fs::metadata(path).unwrap().permissions().mode() & 0o777+ };+ // A pre-existing empty staging directory is tightened, not trusted.+ let staging = tempfile::tempdir().unwrap();+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(mode_of(staging.path()), 0o700);+ assert_eq!(mode_of(&staging.path().join("blobs")), 0o700);+ // Staged files stay owner-only even if later moved out of staging.+ for entry in std::fs::read_dir(staging.path().join("blobs")).unwrap() {+ assert_eq!(mode_of(&entry.unwrap().path()), 0o600);+ }+ assert_eq!(mode_of(&staging.path().join("manifest.json")), 0o600);+ // A freshly created nested staging directory is private from birth.+ let parent = tempfile::tempdir().unwrap();+ let staging = parent.path().join("nested/stage");+ create_workspace_snapshot(root, &staging, BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(mode_of(&staging), 0o700);+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_requires_a_git_worktree() {+ let plain = tempfile::tempdir().unwrap();+ let staging = tempfile::tempdir().unwrap();+ let error = create_workspace_snapshot(+ plain.path(),+ staging.path(),+ BaselineMode::HeadTree,+ &limits(),+ )+ .await+ .unwrap_err();+ assert!(+ matches!(error, SnapshotError::NotAWorktree { .. }),+ "{error}"+ );+ assert!(staging.path().join("manifest.json").read_dir().is_err());+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_from_a_subdirectory_captures_the_whole_repository() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "tracked.txt", "modified\n");+ write(root, "sub/deep.txt", "deep\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot = create_workspace_snapshot(+ &root.join("sub"),+ staging.path(),+ BaselineMode::HeadTree,+ &limits(),+ )+ .await+ .unwrap();+ // Porcelain paths are repository-root-relative from any cwd.+ assert_eq!(+ snapshot.manifest.captured,+ vec![+ file_entry("sub/deep.txt", "??", "deep\n"),+ file_entry("tracked.txt", ".M", "modified\n"),+ ]+ );+}++#[cfg(unix)]+#[tokio::test]+async fn snapshot_records_executable_bits() {+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "tracked.txt", "base\n");+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ write(root, "script.sh", "#!/bin/sh\n");+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(+ root.join("script.sh"),+ std::fs::Permissions::from_mode(0o755),+ )+ .unwrap();+ }+ write(root, "plain.txt", "plain\n");+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ let executable = |path: &str| {+ snapshot+ .manifest+ .captured+ .iter()+ .find_map(|entry| match entry {+ CapturedEntry::File {+ path: entry_path,+ executable,+ ..+ } if entry_path == path => Some(*executable),+ _ => None,+ })+ .unwrap()+ };+ assert!(executable("script.sh"));+ assert!(!executable("plain.txt"));+}++#[cfg(unix)]+#[tokio::test]+async fn head_tree_baseline_restates_head_mode_under_core_filemode_false() {+ use std::os::unix::fs::PermissionsExt;+ let repo = tempfile::tempdir().unwrap();+ let root = repo.path();+ init_repo(root);+ write(root, "run.sh", "#!/bin/sh\n");+ std::fs::set_permissions(root.join("run.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();+ git(root, &["add", "."]);+ git(root, &["commit", "-q", "-m", "base"]);+ // What a FAT or WSL drvfs mount reports for the bit: the mode is+ // gone from the filesystem and git is told to ignore mode drift, so+ // a clean worktree stays a clean worktree.+ git(root, &["config", "core.filemode", "false"]);+ std::fs::set_permissions(root.join("run.sh"), std::fs::Permissions::from_mode(0o644)).unwrap();+ let staging = tempfile::tempdir().unwrap();+ let snapshot =+ create_workspace_snapshot(root, staging.path(), BaselineMode::HeadTree, &limits())+ .await+ .unwrap();+ assert_eq!(+ snapshot.manifest,+ repo_manifest(+ root,+ head_tree(vec![CapturedEntry::File {+ path: "run.sh".to_string(),+ status: "100755".to_string(),+ sha256: digest(b"#!/bin/sh\n"),+ bytes: 10,+ executable: true,+ }]),+ vec![],+ vec![]+ )+ );+}++#[test]+fn git_selection_env_is_scrubbed_from_child_commands() {+ // GIT_DIR/GIT_WORK_TREE inherited from the caller would point every+ // git command at another repository; the child command drops the+ // git-discovery variables so the capture always describes the root+ // it was given.+ let command = git_command(&["status"], Path::new("/tmp"));+ let removed: Vec<String> = command+ .as_std()+ .get_envs()+ .filter(|(_, value)| value.is_none())+ .map(|(key, _)| key.to_string_lossy().into_owned())+ .collect();+ for variable in [+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_INDEX_FILE",+ "GIT_OBJECT_DIRECTORY",+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",+ "GIT_COMMON_DIR",+ "GIT_NAMESPACE",+ ] {+ assert!(+ removed.iter().any(|entry| entry == variable),+ "{variable} must be scrubbed from the git child env"+ );+ }+}++#[test]+fn status_parser_reads_porcelain_v2_records() {+ let output = b"# branch.oid ee3a902349fa5446bf3edd1e1e8d8f7f48013081\0\+# branch.head main\0\+? untracked.txt\0\+! ignored.txt\0\+1 .M N... 100644 100644 100644 h1 h2 tracked.txt\0\+1 A. S... 000000 160000 000000 h1 h2 submod\0\+u UU N... 100644 100644 100644 100644 h1 h2 h3 f.txt\0";+ let status = parse_status(output).unwrap();+ assert_eq!(+ status.head_commit.as_deref(),+ Some("ee3a902349fa5446bf3edd1e1e8d8f7f48013081")+ );+ assert_eq!(+ status.entries,+ vec![+ StatusEntry::Tracked {+ path: "f.txt".to_string(),+ xy: "UU".to_string(),+ gitlink: false,+ },+ StatusEntry::Tracked {+ path: "submod".to_string(),+ xy: "A.".to_string(),+ gitlink: true,+ },+ StatusEntry::Tracked {+ path: "tracked.txt".to_string(),+ xy: ".M".to_string(),+ gitlink: false,+ },+ StatusEntry::Untracked {+ path: "untracked.txt".to_string(),+ },+ ]+ );+ // An unborn branch has no commit to pin.+ let unborn = b"# branch.oid (initial)\0# branch.head main\0";+ assert_eq!(parse_status(unborn).unwrap().head_commit, None);+}++#[test]+fn status_parser_rejects_unknown_records() {+ // Rename records cannot appear under --no-renames; treat them, and+ // anything else unrecognized, as a failure rather than guessing.+ let renamed = b"2 R. N... 100644 100644 100644 h1 h2\0old.txt\0new.txt\0";+ assert!(matches!(+ parse_status(renamed),+ Err(SnapshotError::MalformedStatus { .. })+ ));+ let truncated = b"1 .M N...\0";+ assert!(matches!(+ parse_status(truncated),+ Err(SnapshotError::MalformedStatus { .. })+ ));+}++#[test]+fn path_and_target_safety_rules() {+ assert!(is_safe_relative_path("a/b.txt"));+ assert!(is_safe_relative_path("nested/"));+ for unsafe_path in ["", "/abs", "../up", "./cur", "a/../../b", "a\\b.txt"] {+ assert!(!is_safe_relative_path(unsafe_path));+ }+ assert!(symlink_target_stays_inside("link", "a.txt"));+ assert!(symlink_target_stays_inside("a/b/link", "../c.txt"));+ assert!(!symlink_target_stays_inside("a/link", "../../x"));+ assert!(!symlink_target_stays_inside("link", "/absolute"));+ assert!(!symlink_target_stays_inside("link", "C:/x"));+ assert!(!symlink_target_stays_inside("link", ""));+ // Backslash forms climb or address a root on Windows (UNC,+ // drive-root-relative), so a portable manifest never blesses them.+ assert!(!symlink_target_stays_inside("link", "..\\..\\evil"));+ assert!(!symlink_target_stays_inside("link", "\\\\server\\share\\x"));+ assert!(!symlink_target_stays_inside("link", "\\root"));+}++#[test]+fn secret_name_rules() {+ for path in [+ ".env",+ ".env.production",+ ".envrc",+ ".npmrc",+ "cert.pem",+ "id_rsa",+ "ssh/id_ed25519",+ "keys/private.key",+ "bundle.p12",+ "bundle.pfx",+ ] {+ assert!(is_secret_path(path), "{path} should be excluded");+ }+ for path in [+ "environment.rs",+ ".envoys",+ ".gitignore",+ "key.json",+ "id_rsa.pub",+ "README.md",+ ] {+ assert!(!is_secret_path(path), "{path} should be captured");+ }+}++#[test]+fn verification_hashes_a_shared_blob_once_and_accepts_it() {+ // Two paths sharing one digest: every entry's size claim is checked,+ // the content hash runs once, and the snapshot verifies.+ let shared = digest(b"same\n");+ let manifest = bare_manifest(+ vec![+ CapturedEntry::File {+ path: "one.txt".to_string(),+ status: "??".to_string(),+ sha256: shared.clone(),+ bytes: 5,+ executable: false,+ },+ CapturedEntry::File {+ path: "two.txt".to_string(),+ status: "??".to_string(),+ sha256: shared,+ bytes: 5,+ executable: false,+ },+ ],+ vec![],+ );+ let staging = stage(&manifest, &[(&digest(b"same\n"), b"same\n")]);+ assert_eq!(verify_workspace_snapshot(staging.path()).unwrap(), manifest);+}++#[test]+fn verification_rejects_a_non_regular_file_manifest() {+ // A FIFO named manifest.json reports length zero but blocks the+ // open until a writer appears; it is a malformed staging area.+ #[cfg(unix)]+ {+ let staging = tempfile::tempdir().unwrap();+ let fifo = staging.path().join("manifest.json");+ let mkfifo = std::process::Command::new("mkfifo")+ .arg(&fifo)+ .output()+ .unwrap();+ assert!(mkfifo.status.success(), "mkfifo works on unix");+ let error = verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string();+ assert!(error.contains("not a regular file"), "{error}");+ }+}++#[test]+fn verification_accepts_a_hand_built_snapshot() {+ let manifest = bare_manifest(+ vec![+ CapturedEntry::Deleted {+ path: "gone.txt".to_string(),+ status: "D.".to_string(),+ },+ CapturedEntry::File {+ path: "hello.txt".to_string(),+ status: "??".to_string(),+ sha256: digest(b"hello\n"),+ bytes: 6,+ executable: false,+ },+ CapturedEntry::Symlink {+ path: "link".to_string(),+ status: "??".to_string(),+ target: "hello.txt".to_string(),+ },+ ],+ vec![secret(".env")],+ );+ let staging = stage(&manifest, &[(&digest(b"hello\n"), b"hello\n")]);+ assert_eq!(verify_workspace_snapshot(staging.path()).unwrap(), manifest);+}++#[test]+fn verification_rejects_tampered_blobs() {+ let manifest = bare_manifest(+ vec![CapturedEntry::File {+ path: "hello.txt".to_string(),+ status: "??".to_string(),+ sha256: digest(b"hello\n"),+ bytes: 6,+ executable: false,+ }],+ vec![],+ );+ let error = |staging: &tempfile::TempDir| {+ verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string()+ };+ // A flipped byte fails the recorded hash.+ let staging = stage(&manifest, &[(&digest(b"hello\n"), b"jello\n")]);+ assert!(error(&staging).contains("hashes to"), "{}", error(&staging));+ // A missing blob fails its file entry.+ let staging = stage(&manifest, &[]);+ assert!(+ error(&staging).contains("missing blob"),+ "{}",+ error(&staging)+ );+ // An unreferenced blob fails the set check.+ let staging = stage(+ &manifest,+ &[+ (&digest(b"hello\n"), b"hello\n"),+ (&digest(b"extra\n"), b"extra\n"),+ ],+ );+ assert!(+ error(&staging).contains("unreferenced blob"),+ "{}",+ error(&staging)+ );+ // A size lie fails before any hashing.+ let lying = bare_manifest(+ vec![CapturedEntry::File {+ path: "hello.txt".to_string(),+ status: "??".to_string(),+ sha256: digest(b"hello\n"),+ bytes: 99,+ executable: false,+ }],+ vec![],+ );+ let staging = stage(&lying, &[(&digest(b"hello\n"), b"hello\n")]);+ assert!(+ error(&staging).contains("manifest says"),+ "{}",+ error(&staging)+ );+}++#[test]+fn verification_rejects_baseline_tampering() {+ let head = "ee3a902349fa5446bf3edd1e1e8d8f7f48013081";+ let manifest = SnapshotManifest {+ version: 2,+ head_commit: Some(head.to_string()),+ baseline: Some(head_tree(vec![CapturedEntry::File {+ path: "a.txt".to_string(),+ status: "100644".to_string(),+ sha256: digest(b"a\n"),+ bytes: 2,+ executable: false,+ }])),+ captured: vec![],+ excluded: vec![],+ };+ let error = |staging: &tempfile::TempDir| {+ verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string()+ };+ // A manifest head without a baseline is rejected.+ let headless = SnapshotManifest {+ baseline: None,+ ..manifest.clone()+ };+ let staging = stage(&headless, &[]);+ assert!(+ error(&staging).contains("no baseline in the manifest"),+ "{}",+ error(&staging)+ );+ // A baseline without a head commit is rejected.+ let headless = SnapshotManifest {+ head_commit: None,+ ..manifest.clone()+ };+ let staging = stage(&headless, &[]);+ assert!(+ error(&staging).contains("without a head commit"),+ "{}",+ error(&staging)+ );+ // A baseline entry's missing blob is rejected.+ let staging = stage(&manifest, &[]);+ assert!(+ error(&staging).contains("missing blob"),+ "{}",+ error(&staging)+ );+ // A tampered baseline blob fails the recorded hash.+ let staging = stage(&manifest, &[(&digest(b"a\n"), b"b\n")]);+ assert!(error(&staging).contains("hashes to"), "{}", error(&staging));+ // The untampered pair verifies.+ let staging = stage(&manifest, &[(&digest(b"a\n"), b"a\n")]);+ assert_eq!(verify_workspace_snapshot(staging.path()).unwrap(), manifest);+}++#[test]+fn verification_rejects_paths_claimed_by_two_lists() {+ let head = "ee3a902349fa5446bf3edd1e1e8d8f7f48013081";+ let error = |staging: &tempfile::TempDir| {+ verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string()+ };+ // A delta path cannot be captured and excluded at once.+ let overlap = bare_manifest(+ vec![CapturedEntry::Deleted {+ path: "a.txt".to_string(),+ status: "D.".to_string(),+ }],+ vec![ExcludedEntry {+ path: "a.txt".to_string(),+ reason: ExcludeReason::NotRegularFile,+ }],+ );+ let staging = stage(&overlap, &[]);+ assert!(+ error(&staging).contains("claimed by both the captured and excluded lists"),+ "{}",+ error(&staging)+ );+ // Nor can a baseline path be staged and excluded at once.+ let overlap = SnapshotManifest {+ version: 2,+ head_commit: Some(head.to_string()),+ baseline: Some(Baseline::HeadTree {+ entries: vec![file_entry("a.txt", "100644", "a\n")],+ excluded: vec![ExcludedEntry {+ path: "a.txt".to_string(),+ reason: ExcludeReason::Secret,+ }],+ }),+ captured: vec![],+ excluded: vec![],+ };+ let staging = stage(&overlap, &[(&digest(b"a\n"), b"a\n")]);+ assert!(+ error(&staging).contains("claimed by both the baseline and baseline excluded lists"),+ "{}",+ error(&staging)+ );+ // Nor can the delta and the baseline carry the same path - the+ // delta holds the newer state, so the baseline must omit it.+ let overlap = SnapshotManifest {+ version: 2,+ head_commit: Some(head.to_string()),+ baseline: Some(head_tree(vec![file_entry("a.txt", "100644", "a\n")])),+ captured: vec![file_entry("a.txt", ".M", "b\n")],+ excluded: vec![],+ };+ let staging = stage(+ &overlap,+ &[(&digest(b"a\n"), b"a\n"), (&digest(b"b\n"), b"b\n")],+ );+ assert!(+ error(&staging).contains("claimed by both the captured and baseline lists"),+ "{}",+ error(&staging)+ );+}++#[test]+fn verification_rejects_deletions_in_a_head_tree_baseline() {+ // A deletion restates nothing HEAD's tree holds; it would tell the+ // materializer to remove a path the baseline exists to provide.+ let manifest = SnapshotManifest {+ version: 2,+ head_commit: Some("ee3a902349fa5446bf3edd1e1e8d8f7f48013081".to_string()),+ baseline: Some(head_tree(vec![CapturedEntry::Deleted {+ path: "a.txt".to_string(),+ status: "100644".to_string(),+ }])),+ captured: vec![],+ excluded: vec![],+ };+ let staging = stage(&manifest, &[]);+ let error = verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string();+ assert!(error.contains("deletion in baseline"), "{error}");+}++#[test]+fn verification_rejects_bad_manifests() {+ let good = bare_manifest(+ vec![CapturedEntry::Deleted {+ path: "gone.txt".to_string(),+ status: "D.".to_string(),+ }],+ vec![],+ );+ let error = |staging: &tempfile::TempDir| {+ verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string()+ };+ // Missing, unreadable, or unparseable manifests.+ let empty = tempfile::tempdir().unwrap();+ assert!(error(&empty).contains("unreadable"), "{}", error(&empty));+ let staging = tempfile::tempdir().unwrap();+ std::fs::write(staging.path().join("manifest.json"), "not json").unwrap();+ let unreadable = verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string();+ assert!(unreadable.contains("invalid JSON"), "{unreadable}");+ // A manifest past the read cap is rejected before it is loaded: entry+ // counts are bounded at capture, so a larger file is tampering.+ let staging = tempfile::tempdir().unwrap();+ std::fs::write(+ staging.path().join("manifest.json"),+ vec![b'x'; super::verify::MAX_MANIFEST_BYTES as usize + 1],+ )+ .unwrap();+ let oversized = verify_workspace_snapshot(staging.path())+ .err()+ .unwrap()+ .to_string();+ assert!(oversized.contains("cap is"), "{oversized}");+ // Unsupported version.+ let future = SnapshotManifest {+ version: 3,+ ..good.clone()+ };+ let staging = stage(&future, &[]);+ assert!(+ error(&staging).contains("unsupported version"),+ "{}",+ error(&staging)+ );+ // Unsafe, duplicated, and unsorted paths.+ let escaping = bare_manifest(+ vec![CapturedEntry::Deleted {+ path: "../evil".to_string(),+ status: "D.".to_string(),+ }],+ vec![],+ );+ let staging = stage(&escaping, &[]);+ assert!(error(&staging).contains("unsafe"), "{}", error(&staging));+ // An unsafe path inside a HEAD-tree baseline is rejected too.+ let bad_baseline = SnapshotManifest {+ head_commit: Some("ee3a902349fa5446bf3edd1e1e8d8f7f48013081".to_string()),+ baseline: Some(head_tree(vec![CapturedEntry::Deleted {+ path: "../evil".to_string(),+ status: "100644".to_string(),+ }])),+ ..good.clone()+ };+ let staging = stage(&bad_baseline, &[]);+ assert!(error(&staging).contains("unsafe"), "{}", error(&staging));+ let duplicated = bare_manifest(+ vec![+ CapturedEntry::Deleted {+ path: "a.txt".to_string(),+ status: "D.".to_string(),+ },+ CapturedEntry::Deleted {+ path: "a.txt".to_string(),+ status: "D.".to_string(),+ },+ ],+ vec![],+ );+ let staging = stage(&duplicated, &[]);+ assert!(+ error(&staging).contains("duplicated"),+ "{}",+ error(&staging)+ );+ // Escaping symlink target.+ let escaping_link = bare_manifest(+ vec![CapturedEntry::Symlink {+ path: "link".to_string(),+ status: "??".to_string(),+ target: "../../outside".to_string(),+ }],+ vec![],+ );+ let staging = stage(&escaping_link, &[]);+ assert!(+ error(&staging).contains("escapes the worktree"),+ "{}",+ error(&staging)+ );+ // Malformed digests and commit ids.+ let bad_digest = bare_manifest(+ vec![CapturedEntry::File {+ path: "hello.txt".to_string(),+ status: "??".to_string(),+ sha256: "nothex".to_string(),+ bytes: 6,+ executable: false,+ }],+ vec![],+ );+ let staging = stage(&bad_digest, &[("nothex", b"hello\n")]);+ assert!(+ error(&staging).contains("malformed blob digest"),+ "{}",+ error(&staging)+ );+ let bad_head = SnapshotManifest {+ head_commit: Some("nothex".to_string()),+ ..good+ };+ let staging = stage(&bad_head, &[]);+ assert!(+ error(&staging).contains("malformed head commit"),+ "{}",+ error(&staging)+ );+}diff --git a/crates/pa-core/src/workspace_snapshot/verify.rs b/crates/pa-core/src/workspace_snapshot/verify.rsnew file mode 100644index 0000000000..886cd5b77b--- /dev/null+++ b/crates/pa-core/src/workspace_snapshot/verify.rs@@ -0,0 +1,368 @@+//! Offline verification of a staged snapshot: every manifest claim is+//! checked against the staged blobs and the blob set against the+//! manifest, so an incomplete or tampered staging area fails loudly+//! before it is uploaded anywhere.++use std::collections::{HashMap, HashSet};+use std::io::Read as _;+use std::path::Path;++use sha2::{Digest, Sha256};++use super::manifest::{+ is_safe_relative_path, symlink_target_stays_inside, Baseline, CapturedEntry, ExcludedEntry,+ SnapshotManifest, BLOBS_DIR, MANIFEST_FILE, MANIFEST_VERSION,+};+use super::SnapshotError;++/// The length of a git commit id.+const COMMIT_HEX_LEN: usize = 40;+/// The alternate object format's commit id length (SHA-256 repositories).+const SHA256_COMMIT_HEX_LEN: usize = 64;++/// The length of a SHA-256 digest.+const DIGEST_HEX_LEN: usize = 64;++/// Hard cap on a manifest read into memory: entry counts are bounded at+/// capture (`max_entries` + `max_baseline_entries`), so a manifest past+/// this size is tampering, not payload.+pub(crate) const MAX_MANIFEST_BYTES: u64 = 64 * 1024 * 1024;++/// Whether a captured-entry list may record deletions: the worktree+/// delta does (a tracked path may have been removed from the worktree),+/// but a HEAD-tree baseline restates content the tree holds, so a+/// deletion there is a contradictory instruction for the materializer.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Deletions {+ Allowed,+ Forbidden,+}++/// Verify a staged snapshot: parse the manifest, re-hash every blob+/// (delta and baseline alike), and reject unreferenced or missing blobs.+/// Returns the verified manifest.+///+/// # Errors+/// Returns [`SnapshotError::Manifest`] when the manifest is missing,+/// unreadable, invalid JSON, or an unsupported version, and+/// [`SnapshotError::Verification`] when any structural or content+/// integrity claim fails.+pub fn verify_workspace_snapshot(staging_dir: &Path) -> Result<SnapshotManifest, SnapshotError> {+ let manifest_path = staging_dir.join(MANIFEST_FILE);+ let manifest = read_manifest(&manifest_path)?;+ verify_structure(staging_dir, &manifest)?;+ verify_baseline_invariant(staging_dir, &manifest)?;+ verify_blobs(staging_dir, &manifest)?;+ Ok(manifest)+}++fn read_manifest(path: &Path) -> Result<SnapshotManifest, SnapshotError> {+ let reject = |detail: String| SnapshotError::Manifest {+ path: path.to_path_buf(),+ detail,+ };+ let metadata =+ std::fs::symlink_metadata(path).map_err(|error| reject(format!("unreadable: {error}")))?;+ // A named pipe (or a device) named as the manifest would otherwise+ // pass the length check — a FIFO reports length zero — and block+ // the open until a writer appears; anything but a regular file is+ // a malformed staging area.+ if !metadata.is_file() {+ return Err(reject("manifest is not a regular file".to_string()));+ }+ if metadata.len() > MAX_MANIFEST_BYTES {+ return Err(reject(format!(+ "manifest is {} bytes, cap is {MAX_MANIFEST_BYTES}",+ metadata.len()+ )));+ }+ let file = std::fs::File::open(path).map_err(|error| reject(format!("unreadable: {error}")))?;+ let mut bytes = Vec::new();+ std::io::Read::take(file, MAX_MANIFEST_BYTES)+ .read_to_end(&mut bytes)+ .map_err(|error| reject(format!("unreadable: {error}")))?;+ let manifest: SnapshotManifest =+ serde_json::from_slice(&bytes).map_err(|error| reject(format!("invalid JSON: {error}")))?;+ if manifest.version != MANIFEST_VERSION {+ return Err(reject(format!(+ "unsupported version {} (expected {MANIFEST_VERSION})",+ manifest.version+ )));+ }+ Ok(manifest)+}++/// Structural checks: safe and strictly path-sorted (hence+/// duplicate-free) entry lists, well-formed digests, in-root symlink+/// targets, file-or-symlink baseline items, and globally disjoint path+/// claims - for the delta lists and for a HEAD-tree baseline alike.+/// Whether the baseline covers the head commit's whole tree cannot be+/// proven offline from a commit string alone; that guarantee remains a+/// creator invariant, not a verified manifest property.+fn verify_structure(staging_dir: &Path, manifest: &SnapshotManifest) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ if let Some(head) = &manifest.head_commit {+ // Either object format's id is a well-formed commit: SHA-1 (40)+ // or SHA-256 (64) repositories both publish a branch.oid here.+ if !is_lower_hex(head, COMMIT_HEX_LEN) && !is_lower_hex(head, SHA256_COMMIT_HEX_LEN) {+ return Err(reject(format!("malformed head commit {head:?}")));+ }+ }+ verify_captured_list(+ staging_dir,+ &manifest.captured,+ "captured",+ Deletions::Allowed,+ )?;+ verify_excluded_list(staging_dir, &manifest.excluded, "excluded")?;+ if let Some(Baseline::HeadTree { entries, excluded }) = &manifest.baseline {+ verify_captured_list(staging_dir, entries, "baseline", Deletions::Forbidden)?;+ verify_excluded_list(staging_dir, excluded, "baseline excluded")?;+ }+ verify_disjoint_paths(staging_dir, manifest)?;+ Ok(())+}++/// Cross-list path disjointness: every path is stated by at most one of+/// the four lists (delta captured, delta excluded, baseline entries,+/// baseline excluded). The creator sends each status or tree path to+/// exactly one list, so a path claimed twice gives the materializer+/// contradictory instructions - a staged blob alongside an exclusion for+/// the same path, or the delta and the baseline disagreeing about who+/// holds the newer state. Within-list duplicates are already rejected+/// by the sorted-order checks.+fn verify_disjoint_paths(+ staging_dir: &Path,+ manifest: &SnapshotManifest,+) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ // Gather every (path, list) claim, then reject the first path a+ // second list also claims.+ let mut claims: Vec<(&str, &str)> = manifest+ .captured+ .iter()+ .map(|entry| (entry.path(), "captured"))+ .chain(+ manifest+ .excluded+ .iter()+ .map(|entry| (entry.path.as_str(), "excluded")),+ )+ .collect();+ if let Some(Baseline::HeadTree { entries, excluded }) = &manifest.baseline {+ claims.extend(entries.iter().map(|entry| (entry.path(), "baseline")));+ claims.extend(+ excluded+ .iter()+ .map(|entry| (entry.path.as_str(), "baseline excluded")),+ );+ }+ let mut claimed: HashMap<&str, &str> = HashMap::new();+ for (path, list) in claims {+ if let Some(prior) = claimed.insert(path, list) {+ return Err(reject(format!(+ "path {path:?} is claimed by both the {prior} and {list} lists"+ )));+ }+ }+ Ok(())+}++fn verify_captured_list(+ staging_dir: &Path,+ entries: &[CapturedEntry],+ list: &str,+ deletions: Deletions,+) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ let mut previous: Option<&str> = None;+ for entry in entries {+ let path = entry.path();+ if !is_safe_relative_path(path) {+ return Err(reject(format!("unsafe {list} path {path:?}")));+ }+ if previous.is_some_and(|prior| prior >= path) {+ return Err(reject(format!(+ "{list} entries out of order or duplicated at {path:?}"+ )));+ }+ previous = Some(path);+ match entry {+ CapturedEntry::File { sha256, .. } => {+ if !is_lower_hex(sha256, DIGEST_HEX_LEN) {+ return Err(reject(format!("malformed blob digest {sha256:?}")));+ }+ }+ CapturedEntry::Symlink { target, .. } => {+ if !symlink_target_stays_inside(path, target) {+ return Err(reject(format!(+ "symlink at {path:?} in {list} escapes the worktree"+ )));+ }+ }+ CapturedEntry::Deleted { .. } => {+ if deletions == Deletions::Forbidden {+ return Err(reject(format!(+ "deletion in {list} at {path:?}: baseline entries must be files or symlinks"+ )));+ }+ }+ }+ }+ Ok(())+}++fn verify_excluded_list(+ staging_dir: &Path,+ entries: &[ExcludedEntry],+ list: &str,+) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ let mut previous: Option<&str> = None;+ for entry in entries {+ if !is_safe_relative_path(&entry.path) {+ return Err(reject(format!("unsafe {list} path {:?}", entry.path)));+ }+ if previous.is_some_and(|prior| prior >= entry.path.as_str()) {+ return Err(reject(format!(+ "{list} entries out of order or duplicated at {:?}",+ entry.path+ )));+ }+ previous = Some(entry.path.as_str());+ }+ Ok(())+}++/// Baseline invariant: a manifest with a head commit must state which+/// baseline it ships - HEAD-tree content or an explicit external+/// reference - and a manifest without one must not carry a baseline. A+/// missing or ambiguous baseline is never silent.+fn verify_baseline_invariant(+ staging_dir: &Path,+ manifest: &SnapshotManifest,+) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ match (&manifest.head_commit, &manifest.baseline) {+ // No commits need no baseline; a committed repository states+ // which baseline it ships either way.+ (None, None) | (Some(_), Some(Baseline::External | Baseline::HeadTree { .. })) => Ok(()),+ (None, Some(_)) => Err(reject("baseline present without a head commit".to_string())),+ (Some(head), None) => Err(reject(format!(+ "head commit {head} has no baseline in the manifest"+ ))),+ }+}++/// Content checks: every file entry's blob (delta or baseline) exists+/// with the recorded size and hash, and the blob directory holds nothing+/// unreferenced.+fn verify_blobs(staging_dir: &Path, manifest: &SnapshotManifest) -> Result<(), SnapshotError> {+ let reject = |detail: String| SnapshotError::Verification {+ staging_dir: staging_dir.to_path_buf(),+ detail,+ };+ let blobs_dir = staging_dir.join(BLOBS_DIR);+ let mut referenced: HashSet<&str> = HashSet::new();+ let mut file_entries: Vec<(&str, &CapturedEntry)> = Vec::new();+ for entry in &manifest.captured {+ file_entries.push(("captured", entry));+ }+ if let Some(Baseline::HeadTree { entries, .. }) = &manifest.baseline {+ for entry in entries {+ file_entries.push(("baseline", entry));+ }+ }+ for (list, entry) in file_entries {+ let CapturedEntry::File {+ path,+ sha256,+ bytes,+ ..+ } = entry+ else {+ continue;+ };+ let first_reference = referenced.insert(sha256.as_str());+ let blob = blobs_dir.join(sha256);+ let metadata = std::fs::symlink_metadata(&blob).map_err(|error| {+ reject(format!(+ "missing blob {sha256} for {list} {path:?}: {error}"+ ))+ })?;+ if !metadata.is_file() {+ return Err(reject(format!("blob {sha256} is not a regular file")));+ }+ // Every entry's size claim is checked against the blob; the+ // expensive content hash runs once per digest — a manifest that+ // shares one blob across many paths cannot amplify it into a+ // re-hash per path.+ if metadata.len() != *bytes {+ return Err(reject(format!(+ "blob {sha256} for {list} {path:?} is {} bytes, manifest says {bytes}",+ metadata.len()+ )));+ }+ if !first_reference {+ continue;+ }+ let mut blob = std::fs::File::open(&blob)+ .map_err(|error| reject(format!("unreadable blob {sha256}: {error}")))?;+ let mut hasher = Sha256::new();+ let mut buffer = vec![0u8; 128 * 1024];+ loop {+ let read = std::io::Read::read(&mut blob, &mut buffer)+ .map_err(|error| reject(format!("unreadable blob {sha256}: {error}")))?;+ if read == 0 {+ break;+ }+ hasher.update(&buffer[..read]);+ }+ let digest = format!("{:x}", hasher.finalize());+ if digest != *sha256 {+ return Err(reject(format!(+ "blob {sha256} for {list} {path:?} hashes to {digest}"+ )));+ }+ }+ let staged: HashSet<String> = std::fs::read_dir(&blobs_dir)+ .map_err(|error| reject(format!("unreadable blobs directory: {error}")))?+ .map(|entry| entry.map(|entry| entry.file_name().to_string_lossy().into_owned()))+ .collect::<Result<HashSet<_>, _>>()+ .map_err(|error| reject(format!("unreadable blobs directory: {error}")))?;+ let referenced: HashSet<String> = referenced+ .iter()+ .map(|sha256| (*sha256).to_string())+ .collect();+ if let Some(unreferenced) = staged.difference(&referenced).next() {+ return Err(reject(format!("unreferenced blob {unreferenced}")));+ }+ if let Some(missing) = referenced.difference(&staged).next() {+ return Err(reject(format!("missing blob {missing}")));+ }+ Ok(())+}++/// True for a `len`-character lowercase hex string (a git commit id or a+/// SHA-256 digest as the manifest writes them).+fn is_lower_hex(value: &str, len: usize) -> bool {+ value.len() == len+ && value+ .chars()+ .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())+}