diff --git a/codex-rs/git-utils/src/apply.rs b/codex-rs/git-utils/src/apply.rs index 373aa6ad64..2b6fc15cdb 100644 --- a/codex-rs/git-utils/src/apply.rs +++ b/codex-rs/git-utils/src/apply.rs @@ -1089,6 +1089,61 @@ mod tests { assert_ne!(r.exit_code, 0, "non-zero exit on missing index"); } + #[cfg(unix)] + #[test] + fn missing_index_three_way_classification_does_not_run_post_index_change_hook() { + use std::os::unix::fs::PermissionsExt; + + let _g = env_lock().lock().unwrap(); + let repo = init_repo(); + let root = repo.path(); + let hooks = root.join(".githooks"); + std::fs::create_dir(&hooks).expect("create hooks directory"); + let hook = hooks.join("post-index-change"); + std::fs::write(&hook, "#!/bin/sh\nprintf ran > \"$PWD/hook-ran\"\n") + .expect("write post-index-change hook"); + let mut permissions = std::fs::metadata(&hook) + .expect("hook metadata") + .permissions(); + permissions.set_mode(0o755); + std::fs::set_permissions(&hook, permissions).expect("make hook executable"); + assert_eq!( + run(root, &["git", "config", "core.hooksPath", ".githooks"]).0, + 0 + ); + std::fs::write(root.join("new.txt"), b"local\n").expect("write untracked path"); + assert!( + !root.join(".git/index").exists(), + "fixture has a real index" + ); + + let result = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff: "diff --git a/new.txt b/new.txt\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..893adcd31e963b01dfbbcfe3ec58a008f0d81201\n--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1 @@\n+patched\n".to_string(), + revert: false, + preflight: false, + }) + .expect("classify missing-index three-way fallback"); + + assert_ne!( + result.exit_code, 0, + "untracked destination must not be replaced" + ); + assert!(result.cmd_for_log.contains("--3way"), "{result:?}"); + assert!( + !root.join("hook-ran").exists(), + "post-index-change hook ran" + ); + assert!( + !root.join(".git/index").exists(), + "scratch initialization created the real index" + ); + assert_eq!( + std::fs::read(root.join("new.txt")).expect("read untracked path"), + b"local\n" + ); + } + #[test] fn apply_then_revert_success() { let _g = env_lock().lock().unwrap(); diff --git a/codex-rs/git-utils/src/git_command.rs b/codex-rs/git-utils/src/git_command.rs index bd6adbf216..adc9e0967e 100644 --- a/codex-rs/git-utils/src/git_command.rs +++ b/codex-rs/git-utils/src/git_command.rs @@ -28,6 +28,7 @@ use crate::git_executable::windows_path_requires_fail_closed; use crate::repository_authority::RepositoryAuthority; #[cfg(test)] use crate::repository_authority::parse_marker_path as parse_git_marker_path; +use crate::safe_git::DISABLED_HOOKS_PATH; use crate::safe_git::isolate_git_command_environment; pub(crate) const MAX_INTERNAL_GIT_OUTPUT_BYTES: usize = 16 * 1024 * 1024; @@ -102,7 +103,7 @@ pub(crate) struct IsolatedGitReadContext { } impl IsolatedGitStorage { - fn index_path(&self) -> PathBuf { + pub(crate) fn index_path(&self) -> PathBuf { self.root.path().join("index") } @@ -570,7 +571,42 @@ impl GitRunner { "owned isolated Git scratch storage", )?; std::fs::create_dir(root.path().join("objects"))?; - copy_regular_file_without_follow(&source_index, &root.path().join("index"))?; + let isolated_index = root.path().join("index"); + match copy_regular_file_without_follow(&source_index, &isolated_index) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // An unborn repository may not have materialized an index + // yet. Create the equivalent empty index through trusted Git + // in operation-owned storage; an empty file is not a valid + // index, and hand-encoding one would couple this path to the + // repository hash algorithm and index checksum format. + let worktree = self.authority.active_worktree_root().ok_or_else(|| { + io::Error::new( + io::ErrorKind::PermissionDenied, + "active Git worktree is unavailable for empty scratch index creation", + ) + })?; + let mut command = self.command_for_cwd(worktree)?; + let disabled_hooks = format!("core.hooksPath={DISABLED_HOOKS_PATH}"); + command.args([ + "-c", + &disabled_hooks, + "-c", + "core.fsmonitor=false", + "read-tree", + "--empty", + ]); + let output = self.output_with_new_isolated_index(command, &isolated_index)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "failed to initialize an empty isolated Git index (status {}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + } + Err(error) => return Err(error), + } // A copied split index resolves its content-addressed base beside the // active per-worktree index, not in a distinct common directory. Copy // only well-formed names from that authoritative Git directory; Git @@ -615,6 +651,27 @@ impl GitRunner { Ok(context) } + fn output_with_new_isolated_index( + &self, + mut command: GitCommand, + index_path: &Path, + ) -> io::Result { + self.revalidate_active_repository_metadata()?; + self.authority + .ensure_config_source_is_not_worktree_controlled( + index_path, + "owned isolated Git scratch index", + )?; + isolate_git_command_environment(&mut command.inner); + command.inner.env("GIT_INDEX_FILE", index_path); + command.inner.env("GIT_OPTIONAL_LOCKS", "0"); + command.inner.envs(crate::local_only_git_env()); + harden_git_launch_environment(&mut command.inner, &self.safe_path); + let output = command.inner.output()?; + self.revalidate_active_repository_metadata()?; + Ok(output) + } + pub(crate) fn output(&self, mut command: GitCommand) -> io::Result { self.prepare_command_for_launch(&mut command.inner)?; command.inner.output() @@ -625,7 +682,7 @@ impl GitRunner { command: GitCommand, isolated: &IsolatedGitCommonDir, ) -> io::Result { - self.output_in_isolated_common_dir_with_storage(command, isolated, None) + self.output_in_isolated_common_dir_with_storage(command, isolated, /*storage*/ None) } pub(crate) fn output_in_isolated_scratch( @@ -637,6 +694,32 @@ impl GitRunner { self.output_in_isolated_common_dir_with_storage(command, isolated, Some(storage)) } + /// Run against an operation-owned copy of the active index while retaining + /// the repository's normal config and attribute sources. This is used only + /// for nonmutating classification and `update-index --info-only` setup; + /// callers cannot redirect the object database or common directory. + pub(crate) fn output_with_isolated_index( + &self, + mut command: GitCommand, + storage: &IsolatedGitStorage, + ) -> io::Result { + self.revalidate_active_repository_metadata()?; + storage.validate()?; + self.authority + .ensure_config_source_is_not_worktree_controlled( + storage.root.path(), + "owned isolated Git scratch storage", + )?; + isolate_git_command_environment(&mut command.inner); + command.inner.env("GIT_INDEX_FILE", storage.index_path()); + command.inner.envs(crate::local_only_git_env()); + harden_git_launch_environment(&mut command.inner, &self.safe_path); + let output = command.inner.output()?; + self.revalidate_active_repository_metadata()?; + storage.validate()?; + Ok(output) + } + fn output_in_isolated_common_dir_with_storage( &self, mut command: GitCommand, diff --git a/codex-rs/git-utils/src/guarded_config.rs b/codex-rs/git-utils/src/guarded_config.rs index 6a9ad21c9a..be61d4013a 100644 --- a/codex-rs/git-utils/src/guarded_config.rs +++ b/codex-rs/git-utils/src/guarded_config.rs @@ -1730,15 +1730,16 @@ impl<'git> GuardedGitConfig<'git> { value: &str, ) -> io::Result<()> { debug_assert!(matches!(name, "clean" | "smudge" | "process" | "required")); - let mut command = self - .sources - .git - .command_for_cwd(&self.sources.canonical_root)?; - command - .args(&self.sources.base_config_args) - .args(["config", "--file"]) - .arg(config_path) - .args(["--add", &format!("filter.{driver}.{name}"), value]); + // The destination is operation-owned and absolute. Avoid repository + // setup while serializing the already inventoried driver names: a + // malformed repository setting must not preempt the typed policy + // error that the guarded operation reports later. + let mut command = self.sources.git.command(); + command.args(["config", "--file"]).arg(config_path).args([ + "--add", + &format!("filter.{driver}.{name}"), + value, + ]); let output = self.sources.git.output(command)?; if !output.status.success() { return Err(io::Error::other(format!( diff --git a/codex-rs/git-utils/src/guarded_config/merge_overlay.rs b/codex-rs/git-utils/src/guarded_config/merge_overlay.rs index 4532facb47..705463d55c 100644 --- a/codex-rs/git-utils/src/guarded_config/merge_overlay.rs +++ b/codex-rs/git-utils/src/guarded_config/merge_overlay.rs @@ -20,6 +20,23 @@ const REPOSITORY_FORMAT_CONFIG_PATTERN: &str = const SANITIZED_CONFIG_PATTERN: &str = r"^(core\.(filemode|symlinks|ignorecase|precomposeunicode|protecthfs|protectntfs|trustctime|checkstat|longpaths|fscache|splitindex|sparsecheckout|sparsecheckoutcone|autocrlf|eol|safecrlf|checkroundtripencoding|bigfilethreshold)|index\.(sparse|version)|merge\.conflictstyle)$"; // Git ignores an attribute line whose content length is at least this value. const GIT_ATTRIBUTE_LINE_LENGTH_LIMIT: usize = 2048; +const THREE_WAY_ATTRIBUTE_NAMES: [&str; 9] = [ + "merge", + "whitespace", + "conflict-marker-size", + "text", + "crlf", + "eol", + "ident", + "filter", + "working-tree-encoding", +]; +// `ls-files` has no pathspec-from-file mode on the oldest supported Git. Keep +// each discriminator command comfortably below the Windows command-line +// limit after accounting for the fixed Git and config arguments. +const SENTINEL_PATHSPEC_BYTES_LIMIT: usize = 16 * 1024; +const SENTINEL_PROBE_OUTPUT_BYTES_LIMIT: usize = 4 * 1024 * 1024; +const SENTINEL_PROBE_PATHS_LIMIT: usize = 4_096; /// A complete, fresh merge-config read bound to one authorized operation. /// @@ -75,12 +92,8 @@ impl BuiltinMergeDriver { } } -/// Per-path apply semantics frozen at the strict `check-attr` probe. -/// -/// Git's public `check-attr` format conflates special states with the literal -/// values `set`, `unset`, and `unspecified`. This snapshot intentionally uses -/// Git's conventional rendering for those uncommon literal spellings. Every -/// other safely representable value is retained byte-for-byte. +/// Per-path apply semantics frozen at the strict `check-attr` probe and its +/// attribute-pathspec discriminator. struct MergeAttributeSnapshot { owner: Arc, paths: BTreeMap, @@ -95,6 +108,7 @@ struct FrozenPathApplyAttributes { #[derive(Clone, Debug, Eq, PartialEq)] struct ParsedPathApplyAttributes { merge: String, + merge_sentinel: Option, safe: SafeApplyAttributes, } @@ -106,23 +120,62 @@ enum ProjectedAttribute { Unset, Unspecified, Value(Vec), + Ambiguous(AttributeSentinel), +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +enum AttributeSentinel { + Set, + Unset, + Unspecified, +} + +impl AttributeSentinel { + fn from_check_attr(value: &[u8]) -> Option { + match value { + b"set" => Some(Self::Set), + b"unset" => Some(Self::Unset), + b"unspecified" => Some(Self::Unspecified), + _ => None, + } + } + + fn spelling(self) -> &'static str { + match self { + Self::Set => "set", + Self::Unset => "unset", + Self::Unspecified => "unspecified", + } + } + + fn special_requirement(self, name: &str) -> String { + match self { + Self::Set => name.to_string(), + Self::Unset => format!("-{name}"), + Self::Unspecified => format!("!{name}"), + } + } + + fn projected(self) -> ProjectedAttribute { + match self { + Self::Set => ProjectedAttribute::Set, + Self::Unset => ProjectedAttribute::Unset, + Self::Unspecified => ProjectedAttribute::Unspecified, + } + } } impl ProjectedAttribute { fn from_check_attr(value: &[u8]) -> io::Result { // `git check-attr` deliberately renders both special states and the // literal values `=set`, `=unset`, and `=unspecified` with the same - // sentinel text. Match Git's documented convention for this bounded - // PR while retaining all other raw values. - match value { - b"set" => Ok(Self::Set), - b"unset" => Ok(Self::Unset), - b"unspecified" => Ok(Self::Unspecified), - value => { - validate_projected_attribute_value(value)?; - Ok(Self::Value(value.to_vec())) - } + // bytes. Keep them unresolved until an attribute-aware pathspec has + // proved which meaning Git selected. + if let Some(sentinel) = AttributeSentinel::from_check_attr(value) { + return Ok(Self::Ambiguous(sentinel)); } + validate_projected_attribute_value(value)?; + Ok(Self::Value(value.to_vec())) } fn projected_token(&self, name: &str) -> Vec { @@ -137,6 +190,7 @@ impl ProjectedAttribute { token.extend_from_slice(value); token } + Self::Ambiguous(_) => Vec::new(), } } } @@ -156,6 +210,77 @@ struct SafeApplyAttributes { _filter: ProjectedAttribute, } +impl ParsedPathApplyAttributes { + fn ambiguous_sentinel(&self, name: &str) -> io::Result> { + if name == "merge" { + return Ok(self.merge_sentinel); + } + let attribute = self.safe.attribute(name)?; + Ok(match attribute { + ProjectedAttribute::Ambiguous(sentinel) => Some(*sentinel), + _ => None, + }) + } + + fn resolve_special_sentinel( + &mut self, + name: &str, + sentinel: AttributeSentinel, + ) -> io::Result<()> { + if name == "merge" { + if self.merge_sentinel != Some(sentinel) || self.merge != sentinel.spelling() { + return Err(invalid_attribute_output( + "Git merge sentinel changed during disambiguation", + )); + } + self.merge_sentinel = None; + return Ok(()); + } + let attribute = self.safe.attribute_mut(name)?; + if *attribute != ProjectedAttribute::Ambiguous(sentinel) { + return Err(invalid_attribute_output( + "Git apply sentinel changed during disambiguation", + )); + } + *attribute = sentinel.projected(); + Ok(()) + } +} + +impl SafeApplyAttributes { + fn attribute(&self, name: &str) -> io::Result<&ProjectedAttribute> { + match name { + "whitespace" => Ok(&self.whitespace), + "conflict-marker-size" => Ok(&self.conflict_marker_size), + "text" => Ok(&self.text), + "crlf" => Ok(&self.crlf), + "eol" => Ok(&self.eol), + "ident" => Ok(&self.ident), + "filter" => Ok(&self._filter), + "working-tree-encoding" => Ok(&self.working_tree_encoding), + _ => Err(invalid_attribute_output( + "unexpected Git attribute discriminator name", + )), + } + } + + fn attribute_mut(&mut self, name: &str) -> io::Result<&mut ProjectedAttribute> { + match name { + "whitespace" => Ok(&mut self.whitespace), + "conflict-marker-size" => Ok(&mut self.conflict_marker_size), + "text" => Ok(&mut self.text), + "crlf" => Ok(&mut self.crlf), + "eol" => Ok(&mut self.eol), + "ident" => Ok(&mut self.ident), + "filter" => Ok(&mut self._filter), + "working-tree-encoding" => Ok(&mut self.working_tree_encoding), + _ => Err(invalid_attribute_output( + "unexpected Git attribute discriminator name", + )), + } + } +} + impl MergeAttributeSnapshot { fn from_effective( owner: &Arc, @@ -358,6 +483,10 @@ impl<'git> GuardedGitConfig<'git> { ) -> io::Result<()> { let paths = self.apply_filter_paths()?; let snapshot = self.read_merge_config_snapshot()?; + let repository_format = self + .sources + .read_direct_common_config(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")?; + let object_format = index_object_format(&repository_format)?; let input = merge_attribute_input(&paths)?; let output = self.query_merge_attributes(&snapshot, input)?; if !output.status.success() { @@ -368,6 +497,13 @@ impl<'git> GuardedGitConfig<'git> { ))); } let parsed_attributes = parse_three_way_attributes(&output.stdout, &paths)?; + let parsed_attributes = self.disambiguate_attribute_sentinels( + &snapshot, + &paths, + parsed_attributes, + &output, + object_format, + )?; let merge_attributes = parsed_attributes .iter() .map(|(path, attributes)| (path.clone(), attributes.merge.clone())) @@ -400,6 +536,7 @@ impl<'git> GuardedGitConfig<'git> { paths, selected_custom, custom_destinations, + repository_format, )?; self.attach_merge_override(isolated) } @@ -459,6 +596,215 @@ impl<'git> GuardedGitConfig<'git> { self.sources.git.output(command) } + fn disambiguate_attribute_sentinels( + &self, + snapshot: &MergeConfigSnapshot, + paths: &[String], + mut attributes: BTreeMap, + initial: &std::process::Output, + object_format: IndexObjectFormat, + ) -> io::Result> { + snapshot.ensure_owner(&self.identity)?; + if paths.len() > SENTINEL_PROBE_PATHS_LIMIT { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "too many paths for bounded Git attribute sentinel classification", + )); + } + + let mut unresolved = BTreeMap::<&'static str, Vec<(String, AttributeSentinel)>>::new(); + for name in THREE_WAY_ATTRIBUTE_NAMES { + let mut entries = Vec::new(); + for path in paths { + let parsed = attributes + .get(path) + .ok_or_else(|| invalid_attribute_output("missing parsed Git attribute path"))?; + if let Some(sentinel) = parsed.ambiguous_sentinel(name)? { + entries.push((path.clone(), sentinel)); + } + } + if !entries.is_empty() { + unresolved.insert(name, entries); + } + } + if unresolved.is_empty() { + return Ok(attributes); + } + + let storage = self.sources.git.create_isolated_git_storage()?; + self.populate_attribute_probe_phantoms(&storage, paths, object_format)?; + for (name, entries) in unresolved { + let literal = self.run_attribute_sentinel_probe( + &storage, + name, + &entries, + SentinelProbeKind::Literal, + )?; + let special = self.run_attribute_sentinel_probe( + &storage, + name, + &entries, + SentinelProbeKind::Special, + )?; + for (path, sentinel) in entries { + match (literal.contains(&path), special.contains(&path)) { + (true, false) => { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + format!( + "refusing a three-way apply because {name}={:?} is a literal Git attribute value for {path:?}", + sentinel.spelling() + ), + )); + } + (false, true) => attributes + .get_mut(&path) + .ok_or_else(|| { + invalid_attribute_output("missing parsed Git attribute path") + })? + .resolve_special_sentinel(name, sentinel)?, + (false, false) | (true, true) => { + return Err(invalid_attribute_output( + "inconclusive Git attribute sentinel classification", + )); + } + } + } + } + + // A second exact nine-attribute snapshot brackets all attribute-aware + // pathspec reads. If any effective source changed to a different + // public state, the operation fails before scratch or real mutation. + let recheck = self.query_merge_attributes(snapshot, merge_attribute_input(paths)?)?; + if recheck.status != initial.status + || recheck.stdout != initial.stdout + || recheck.stderr != initial.stderr + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Git attributes changed during sentinel classification", + )); + } + Ok(attributes) + } + + fn populate_attribute_probe_phantoms( + &self, + storage: &IsolatedGitStorage, + paths: &[String], + object_format: IndexObjectFormat, + ) -> io::Result<()> { + let mut command = self.command_with_attached_overlays()?; + command.env("GIT_OPTIONAL_LOCKS", "0"); + command.args([ + "--literal-pathspecs", + "ls-files", + "--cached", + "--full-name", + "-z", + "--", + ]); + command.args(paths); + let output = self + .sources + .git + .output_with_isolated_index(command, storage)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "failed to inspect copied Git index for attribute probes (status {}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + let expected = paths.iter().cloned().collect::>(); + let present = parse_sentinel_probe_paths(&output.stdout, &expected)?; + let missing = paths + .iter() + .filter(|path| !present.contains(*path)) + .collect::>(); + if missing.is_empty() { + return Ok(()); + } + + use std::io::Seek; + let mut input = tempfile::tempfile()?; + let object_id = match object_format { + IndexObjectFormat::Sha1 => "1".repeat(40), + IndexObjectFormat::Sha256 => "1".repeat(64), + }; + for path in missing { + input.write_all(b"100644 ")?; + input.write_all(object_id.as_bytes())?; + input.write_all(b"\t")?; + input.write_all(path.as_bytes())?; + input.write_all(&[0])?; + } + input.rewind()?; + let mut command = self.command_with_attached_overlays()?; + command + .env("GIT_OPTIONAL_LOCKS", "0") + .args(["update-index", "--add", "--info-only", "-z", "--index-info"]) + .stdin(Stdio::from(input)); + let output = self + .sources + .git + .output_with_isolated_index(command, storage)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "failed to populate copied Git index for attribute probes (status {}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + Ok(()) + } + + fn run_attribute_sentinel_probe( + &self, + storage: &IsolatedGitStorage, + name: &str, + entries: &[(String, AttributeSentinel)], + kind: SentinelProbeKind, + ) -> io::Result> { + let mut pathspecs = Vec::with_capacity(entries.len()); + let mut pathspec_bytes = 0_usize; + let mut expected = BTreeSet::new(); + for (path, sentinel) in entries { + let requirement = match kind { + SentinelProbeKind::Literal => format!("{name}={}", sentinel.spelling()), + SentinelProbeKind::Special => sentinel.special_requirement(name), + }; + let pathspec = format!(":(top,literal,attr:{requirement}){path}"); + pathspec_bytes = pathspec_bytes + .checked_add(pathspec.len() + 1) + .ok_or_else(|| invalid_attribute_output("Git attribute pathspec size overflow"))?; + if pathspec_bytes > SENTINEL_PATHSPEC_BYTES_LIMIT { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "Git attribute sentinel pathspec budget exceeded", + )); + } + expected.insert(path.clone()); + pathspecs.push(pathspec); + } + let mut command = self.command_with_attached_overlays()?; + command.env("GIT_OPTIONAL_LOCKS", "0"); + command.args(["ls-files", "--cached", "--full-name", "-z", "--"]); + command.args(pathspecs); + let output = self + .sources + .git + .output_with_isolated_index(command, storage)?; + if !output.status.success() { + return Err(io::Error::other(format!( + "Git attribute sentinel probe failed with status {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + parse_sentinel_probe_paths(&output.stdout, &expected) + } + fn build_merge_override( &self, snapshot: &MergeConfigSnapshot, @@ -466,6 +812,7 @@ impl<'git> GuardedGitConfig<'git> { effective_paths: Vec, selected_custom: BTreeMap, custom_destinations: BTreeSet, + repository_format: BTreeMap, ) -> io::Result { snapshot.ensure_owner(&self.identity)?; attributes.ensure_owner(&self.identity)?; @@ -485,9 +832,6 @@ impl<'git> GuardedGitConfig<'git> { .as_ref() .map(normalize_shared_repository) .transpose()?; - let repository_format = self - .sources - .read_direct_common_config(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")?; let object_format = index_object_format(&repository_format)?; let common_dir = self.sources.git.create_isolated_common_dir()?; let config_path = common_dir.config_path(); @@ -759,7 +1103,8 @@ impl<'git> GuardedGitConfig<'git> { "merge-policy scratch proof does not match the final apply", )); } - let current_index = self.capture_merge_index_stage_snapshot(&effective_paths, None)?; + let current_index = + self.capture_merge_index_stage_snapshot(&effective_paths, /*storage*/ None)?; if current_index != proof.prospective_index { return Err(io::Error::new( io::ErrorKind::PermissionDenied, @@ -1237,6 +1582,7 @@ fn append_projected_attribute_lines( #[derive(Default)] struct PendingPathApplyAttributes { merge: Option, + merge_sentinel: Option, whitespace: Option, conflict_marker_size: Option, text: Option, @@ -1250,6 +1596,7 @@ struct PendingPathApplyAttributes { impl PendingPathApplyAttributes { fn insert(&mut self, attribute: &[u8], value: &[u8]) -> io::Result<()> { if attribute == b"merge" { + let sentinel = AttributeSentinel::from_check_attr(value); let value = std::str::from_utf8(value) .map_err(|_| invalid_attribute_output("non-UTF-8 Git merge attribute value"))?; if self.merge.replace(value.to_string()).is_some() { @@ -1257,6 +1604,7 @@ impl PendingPathApplyAttributes { "duplicate Git merge attribute record", )); } + self.merge_sentinel = sentinel; return Ok(()); } @@ -1287,6 +1635,7 @@ impl PendingPathApplyAttributes { fn finish(self) -> io::Result { Ok(ParsedPathApplyAttributes { merge: required_attribute(self.merge, "merge")?, + merge_sentinel: self.merge_sentinel, safe: SafeApplyAttributes { whitespace: required_attribute(self.whitespace, "whitespace")?, conflict_marker_size: required_attribute( @@ -1311,6 +1660,50 @@ fn required_attribute(value: Option, name: &str) -> io::Result { value.ok_or_else(|| invalid_attribute_output(&format!("missing Git {name} attribute record"))) } +#[derive(Clone, Copy)] +enum SentinelProbeKind { + Literal, + Special, +} + +fn parse_sentinel_probe_paths( + output: &[u8], + expected: &BTreeSet, +) -> io::Result> { + if output.len() > SENTINEL_PROBE_OUTPUT_BYTES_LIMIT { + return Err(invalid_attribute_output( + "Git attribute sentinel probe output exceeded its byte budget", + )); + } + if output.is_empty() { + return Ok(BTreeSet::new()); + } + let body = output.strip_suffix(&[0]).ok_or_else(|| { + invalid_attribute_output("unterminated Git attribute sentinel probe output") + })?; + if body.is_empty() { + return Err(invalid_attribute_output( + "empty Git attribute sentinel probe record", + )); + } + let mut found = BTreeSet::new(); + for path in body.split(|byte| *byte == 0) { + let path = std::str::from_utf8(path) + .map_err(|_| invalid_attribute_output("non-UTF-8 Git attribute sentinel probe path"))?; + if !expected.contains(path) { + return Err(invalid_attribute_output( + "unexpected Git attribute sentinel probe path", + )); + } + // Do not rely on `ls-files --deduplicate`: older supported Git + // versions lack it, and an unmerged index legitimately emits one + // record per stage. Every repeated record is still exact, expected, + // NUL framed, and covered by the aggregate byte bound. + found.insert(path.to_string()); + } + Ok(found) +} + /// Parse the strict NUL-framed output of the one fixed nine-attribute query. /// Every authorized path must have exactly one record for every consumed name; /// extra, duplicate, malformed, or unrepresentable data fails closed. diff --git a/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs b/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs index e902e18177..84f060103f 100644 --- a/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs +++ b/codex-rs/git-utils/src/guarded_config/merge_overlay_tests.rs @@ -181,10 +181,17 @@ fn exit_one_completion_witness_requires_new_noncustom_unmerged_state() { } let custom = BTreeSet::from(["custom.txt".to_string()]); - let clean_before = BTreeMap::from([("peer.txt".to_string(), BTreeMap::from([(0, entry(1))]))]); + let clean_before = BTreeMap::from([( + "peer.txt".to_string(), + BTreeMap::from([(0, entry(/*byte*/ 1))]), + )]); let newly_conflicted = BTreeMap::from([( "peer.txt".to_string(), - BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + BTreeMap::from([ + (1, entry(/*byte*/ 1)), + (2, entry(/*byte*/ 2)), + (3, entry(/*byte*/ 3)), + ]), )]); assert!(newly_unmerged_noncustom_path( &clean_before, @@ -194,11 +201,19 @@ fn exit_one_completion_witness_requires_new_noncustom_unmerged_state() { let already_unmerged = BTreeMap::from([( "peer.txt".to_string(), - BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + BTreeMap::from([ + (1, entry(/*byte*/ 1)), + (2, entry(/*byte*/ 2)), + (3, entry(/*byte*/ 3)), + ]), )]); let changed_unmerged = BTreeMap::from([( "peer.txt".to_string(), - BTreeMap::from([(1, entry(4)), (2, entry(5)), (3, entry(6))]), + BTreeMap::from([ + (1, entry(/*byte*/ 4)), + (2, entry(/*byte*/ 5)), + (3, entry(/*byte*/ 6)), + ]), )]); assert!(!newly_unmerged_noncustom_path( &already_unmerged, @@ -208,7 +223,11 @@ fn exit_one_completion_witness_requires_new_noncustom_unmerged_state() { let custom_conflict = BTreeMap::from([( "custom.txt".to_string(), - BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]), + BTreeMap::from([ + (1, entry(/*byte*/ 1)), + (2, entry(/*byte*/ 2)), + (3, entry(/*byte*/ 3)), + ]), )]); assert!(!newly_unmerged_noncustom_path( &IndexStageSnapshot::new(), @@ -243,6 +262,7 @@ fn sealed_merge_override_rejects_another_operation_identity() { "file.txt".to_string(), ParsedPathApplyAttributes { merge: "unspecified".to_string(), + merge_sentinel: None, safe: unspecified_safe_attributes(), }, )]), @@ -256,6 +276,7 @@ fn sealed_merge_override_rejects_another_operation_identity() { vec!["file.txt".to_string()], BTreeMap::new(), BTreeSet::new(), + BTreeMap::new(), ) .expect("build isolated merge config"); let error = second @@ -496,13 +517,16 @@ fn projected_whitespace_states_mask_lower_sources() { .values() .map(|attributes| attributes.safe.whitespace.clone()) .collect::>(), - whitespace - ); - assert!( - actual - .values() - .all(|attributes| attributes.safe._filter == ProjectedAttribute::Unspecified) + vec![ + ProjectedAttribute::Ambiguous(AttributeSentinel::Set), + ProjectedAttribute::Ambiguous(AttributeSentinel::Unset), + ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified), + whitespace[3].clone(), + ] ); + assert!(actual.values().all(|attributes| { + attributes.safe._filter == ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified) + })); } #[test] @@ -638,7 +662,7 @@ fn projected_attribute_lines_split_below_git_limit_or_fail_closed() { } #[test] -fn native_check_attr_conflates_sentinels_for_every_projected_name() { +fn native_check_attr_marks_conflated_sentinels_unresolved_for_every_projected_name() { let repo = tempfile::tempdir().expect("repo"); let root = repo.path(); run_git(root, &["init", "-q"]); @@ -734,16 +758,21 @@ fn native_check_attr_conflates_sentinels_for_every_projected_name() { let expected_paths = paths.map(str::to_string).to_vec(); let parsed = parse_three_way_attributes(&output.stdout, &expected_paths) .expect("parse conventional sentinel rendering"); - // The bounded implementation accepts this documented residual: literal - // sentinel values are projected as their same-spelled special states. - assert_eq!(parsed["literal-set"].safe.text, ProjectedAttribute::Set); + assert_eq!( + parsed["literal-set"].safe.text, + ProjectedAttribute::Ambiguous(AttributeSentinel::Set) + ); assert_eq!( parsed["literal-unset"].safe.ident, - ProjectedAttribute::Unset + ProjectedAttribute::Ambiguous(AttributeSentinel::Unset) ); assert_eq!( parsed["literal-unspecified"].safe._filter, - ProjectedAttribute::Unspecified + ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified) + ); + assert_eq!( + parsed["literal-set"].merge_sentinel, + Some(AttributeSentinel::Set) ); } diff --git a/codex-rs/git-utils/src/guarded_config_tests.rs b/codex-rs/git-utils/src/guarded_config_tests.rs index 8dd766180b..dcb2c3da65 100644 --- a/codex-rs/git-utils/src/guarded_config_tests.rs +++ b/codex-rs/git-utils/src/guarded_config_tests.rs @@ -71,7 +71,7 @@ fn frozen_apply_policy_overrides_later_repository_config_changes() { .expect("authorize filter path"); let patch = patch.to_str().expect("UTF-8 patch path"); let (rendered, gate) = config - .run_apply_policy_gate(false, patch) + .run_apply_policy_gate(/*revert*/ false, patch) .expect("run policy gate"); assert!(rendered.contains("apply.whitespace=warn"), "{rendered}"); assert!( @@ -93,7 +93,7 @@ fn frozen_apply_policy_overrides_later_repository_config_changes() { run_git(root, &["config", "core.whitespace", "trailing-space"]); let final_apply = config - .run_direct_apply(false, patch) + .run_direct_apply(/*revert*/ false, patch) .expect("run final apply"); assert!( final_apply.status.success(), @@ -170,11 +170,17 @@ fn apply_whitespace_modes_are_typed_and_case_sensitive_at_the_gate() { .expect("authorize filter path"); assert!( config - .final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path")) + .final_apply_whitespace_mode( + /*revert*/ false, + patch.to_str().expect("UTF-8 patch path"), + ) .is_err() ); let (_, gate) = config - .run_apply_policy_gate(false, patch.to_str().expect("UTF-8 patch path")) + .run_apply_policy_gate( + /*revert*/ false, + patch.to_str().expect("UTF-8 patch path"), + ) .expect("run invalid policy gate"); assert!(!gate.status.success()); assert!( @@ -184,7 +190,10 @@ fn apply_whitespace_modes_are_typed_and_case_sensitive_at_the_gate() { ); assert!( config - .final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path")) + .final_apply_whitespace_mode( + /*revert*/ false, + patch.to_str().expect("UTF-8 patch path"), + ) .is_err() ); } @@ -217,22 +226,30 @@ fn successful_apply_policy_gate_is_one_shot_and_bound_to_patch_orientation() { .authorize_filter_paths(&["file.txt".to_string()]) .expect("authorize filter path"); let (_, gate) = config - .run_apply_policy_gate(false, patch) + .run_apply_policy_gate(/*revert*/ false, patch) .expect("run successful policy gate"); assert!(gate.status.success()); assert_eq!( config - .final_apply_whitespace_mode(false, patch) + .final_apply_whitespace_mode(/*revert*/ false, patch) .expect("matching proof"), ApplyWhitespaceMode::Error ); - assert!(config.final_apply_whitespace_mode(true, patch).is_err()); assert!( config - .final_apply_whitespace_mode(false, "different.patch") + .final_apply_whitespace_mode(/*revert*/ true, patch) + .is_err() + ); + assert!( + config + .final_apply_whitespace_mode(/*revert*/ false, "different.patch") + .is_err() + ); + assert!( + config + .run_apply_policy_gate(/*revert*/ false, patch) .is_err() ); - assert!(config.run_apply_policy_gate(false, patch).is_err()); } #[test] diff --git a/codex-rs/git-utils/src/merge_driver_race_tests.rs b/codex-rs/git-utils/src/merge_driver_race_tests.rs index b77f251a24..bd849427f6 100644 --- a/codex-rs/git-utils/src/merge_driver_race_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_race_tests.rs @@ -187,6 +187,23 @@ fn assert_mutation_happened_between_probe_and_three_way(trace: &Path) { assert!(mutation < three_way, "final Git started before mutation"); } +fn assert_mutation_happened_after_probe_before_refusal(trace: &Path) { + let contents = std::fs::read_to_string(trace).expect("read completed trace"); + let probe_start = contents.find("check-attr").expect("merge attribute probe"); + let probe_exit = probe_start + + contents[probe_start..] + .find("\"event\":\"exit\"") + .expect("merge attribute probe exit"); + let mutation = contents + .find(TRACE_MUTATION_MARKER) + .expect("mutation trace marker"); + assert!(probe_exit < mutation, "mutation preceded probe exit"); + assert!( + !contents[mutation..].contains("--3way"), + "a three-way apply started after an incoherent attribute snapshot" + ); +} + fn append_driver_config(root: &Path, driver: &str, command: &str) { let mut config = OpenOptions::new() .append(true) @@ -329,10 +346,10 @@ fn selected_empty_and_equals_named_drivers_reject_without_marker_or_index_mutati } #[test] -fn post_probe_attribute_change_cannot_run_empty_named_driver() { +fn post_probe_attribute_change_refuses_before_empty_named_driver() { if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { run_isolated_test( - "merge_driver::race_tests::post_probe_attribute_change_cannot_run_empty_named_driver", + "merge_driver::race_tests::post_probe_attribute_change_refuses_before_empty_named_driver", ); return; } @@ -355,20 +372,20 @@ fn post_probe_attribute_change_cannot_run_empty_named_driver() { observed }); - let result = apply_git_patch(&request(root, patch, /*revert*/ false)) - .expect("neutralized three-way apply"); + let error = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect_err("attribute mutation during sentinel classification must fail closed"); assert!(watcher.join().expect("attribute watcher")); - assert_mutation_happened_between_probe_and_three_way(&trace); - assert_ne!(result.exit_code, 0); + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}"); + assert_mutation_happened_after_probe_before_refusal(&trace); assert!(!configured_marker_exists(root, "codex.oldmergeran")); } #[test] -fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() { +fn post_probe_attribute_and_driver_change_refuses_before_helper_dispatch() { if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { run_isolated_test( - "merge_driver::race_tests::post_probe_attribute_and_same_driver_command_change_stays_neutralized", + "merge_driver::race_tests::post_probe_attribute_and_driver_change_refuses_before_helper_dispatch", ); return; } @@ -395,21 +412,21 @@ fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() { observed }); - let result = apply_git_patch(&request(root, patch, /*revert*/ false)) - .expect("neutralized three-way apply"); + let error = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect_err("attribute mutation during sentinel classification must fail closed"); assert!(watcher.join().expect("config watcher")); - assert_mutation_happened_between_probe_and_three_way(&trace); - assert_ne!(result.exit_code, 0); + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}"); + assert_mutation_happened_after_probe_before_refusal(&trace); assert!(!configured_marker_exists(root, "codex.oldmergeran")); assert!(!configured_marker_exists(root, "codex.newmergeran")); } #[test] -fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() { +fn post_probe_worktree_attribute_change_refuses_snapshot_drift() { if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { run_isolated_test( - "merge_driver::race_tests::post_probe_worktree_attribute_change_preserves_probed_union_semantics", + "merge_driver::race_tests::post_probe_worktree_attribute_change_refuses_snapshot_drift", ); return; } @@ -431,16 +448,12 @@ fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() { observed }); - let result = apply_git_patch(&request(root, patch, /*revert*/ false)) - .expect("run frozen union three-way apply"); + let error = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect_err("attribute mutation during sentinel classification must fail closed"); assert!(watcher.join().expect("attribute watcher")); - assert_mutation_happened_between_probe_and_three_way(&trace); - assert_eq!(result.exit_code, 0, "{}", result.stderr); - let contents = read_file_normalized(&root.join("target.txt")); - assert!(contents.contains("ours\n"), "{contents}"); - assert!(contents.contains("theirs\n"), "{contents}"); - assert!(!contents.contains("<<<<<<<"), "{contents}"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}"); + assert_mutation_happened_after_probe_before_refusal(&trace); } #[test] @@ -507,13 +520,19 @@ fn isolated_three_way_config_blocks_driver_namespace_introduction_races() { let outcome = apply_git_patch(&request(root, patch, /*revert*/ false)); assert!(watcher.join().expect("namespace watcher"), "{race:?}"); - assert_mutation_happened_between_probe_and_three_way(&trace); - if matches!(race, DriverNamespaceRace::KnownEmpty) { + if matches!(race, DriverNamespaceRace::BrandNewAttribute) { + let error = outcome + .expect_err("attribute mutation during sentinel classification must fail closed"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}"); + assert_mutation_happened_after_probe_before_refusal(&trace); + } else if matches!(race, DriverNamespaceRace::KnownEmpty) { + assert_mutation_happened_between_probe_and_three_way(&trace); let error = outcome.expect_err( "an explicit empty driver is a selected namespace and must refuse when reachable", ); assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{error}"); } else { + assert_mutation_happened_between_probe_and_three_way(&trace); let result = outcome.expect("run isolated three-way apply"); assert_ne!(result.exit_code, 0, "{race:?}"); assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=")); @@ -524,10 +543,10 @@ fn isolated_three_way_config_blocks_driver_namespace_introduction_races() { } #[test] -fn isolated_three_way_config_scrubs_command_config_channels() { +fn post_probe_command_config_selection_refuses_snapshot_drift() { if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() { run_isolated_test_with_env( - "merge_driver::race_tests::isolated_three_way_config_scrubs_command_config_channels", + "merge_driver::race_tests::post_probe_command_config_selection_refuses_snapshot_drift", &[ ("GIT_CONFIG_COUNT", OsStr::new("1")), ("GIT_CONFIG_KEY_0", OsStr::new("merge.env-selected.driver")), @@ -564,12 +583,16 @@ fn isolated_three_way_config_scrubs_command_config_channels() { observed }); - let result = apply_git_patch(&request(root, patch, /*revert*/ false)) - .expect("run isolated three-way apply"); + let error = apply_git_patch(&request(root, patch, /*revert*/ false)) + .expect_err("attribute mutation during sentinel classification must fail closed"); assert!(watcher.join().expect("config-channel watcher"), "{driver}"); - assert_mutation_happened_between_probe_and_three_way(&trace); - assert_ne!(result.exit_code, 0, "{driver}"); + assert_eq!( + error.kind(), + io::ErrorKind::InvalidData, + "{driver}: {error}" + ); + assert_mutation_happened_after_probe_before_refusal(&trace); assert!(!configured_marker_exists(root, "codex.envmergeran")); assert!(!configured_marker_exists(root, "codex.basemergeran")); } diff --git a/codex-rs/git-utils/src/merge_driver_tests.rs b/codex-rs/git-utils/src/merge_driver_tests.rs index d849c643a7..1d8de5183a 100644 --- a/codex-rs/git-utils/src/merge_driver_tests.rs +++ b/codex-rs/git-utils/src/merge_driver_tests.rs @@ -15,6 +15,114 @@ use pretty_assertions::assert_eq; use std::ffi::OsStr; use std::path::Path; +#[test] +fn three_way_refuses_literal_text_set_before_mutating_index_or_worktree() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "f.txt text=set\n") + .expect("write literal attribute"); + std::fs::write(root.join("f.txt"), b"x\n").expect("write base"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0); + + std::fs::write(root.join("f.txt"), b"y\n").expect("write patch side"); + let (diff_code, diff, diff_err) = run(root, &["git", "diff", "--full-index", "--", "f.txt"]); + assert_eq!(diff_code, 0, "create patch: {diff_err}"); + assert_eq!(run(root, &["git", "checkout", "--", "f.txt"]).0, 0); + std::fs::write(root.join("f.txt"), b"x\r\n").expect("write CRLF worktree state"); + + let before_index = run(root, &["git", "rev-parse", ":f.txt"]).1; + let before_worktree = std::fs::read(root.join("f.txt")).expect("read before worktree"); + let error = apply_git_patch(&ApplyGitRequest { + cwd: root.to_path_buf(), + diff, + revert: false, + preflight: false, + }) + .expect_err("literal text=set must fail closed"); + + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert!(error.to_string().contains("text=\"set\""), "{error}"); + assert_eq!(run(root, &["git", "rev-parse", ":f.txt"]).1, before_index); + assert_eq!( + std::fs::read(root.join("f.txt")).expect("read after worktree"), + before_worktree + ); +} + +#[test] +fn sentinel_probe_populates_an_absent_path_in_its_copied_index() { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), "new.txt text\n").expect("write attributes"); + assert_eq!(run(root, &["git", "add", ".gitattributes"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "attributes"]).0, 0); + assert_eq!(run(root, &["git", "update-index", "--split-index"]).0, 0); + + install_merge_policy(root, &["new.txt".to_string()]) + .expect("classify special attributes for an absent patch destination"); + assert_eq!(run(root, &["git", "ls-files", "--", "new.txt"]).1, ""); +} + +#[test] +fn three_way_sentinel_classifier_distinguishes_special_and_literal_states() { + for (attribute, spelling, special_token) in [ + ("merge", "set", "merge"), + ("text", "unset", "-text"), + ("whitespace", "unspecified", "!whitespace"), + ] { + for (label, token, literal) in [ + ("special", special_token.to_string(), false), + ("literal", format!("{attribute}={spelling}"), true), + ] { + let repo = init_repo(); + let root = repo.path(); + std::fs::write(root.join(".gitattributes"), format!("f.txt {token}\n")) + .expect("write sentinel attributes"); + std::fs::write(root.join("f.txt"), "content\n").expect("write tracked path"); + assert_eq!(run(root, &["git", "add", "."]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "fixture"]).0, 0); + + let result = install_merge_policy(root, &["f.txt".to_string()]); + if literal { + let error = result.expect_err("literal sentinel must fail closed"); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + assert!( + error + .to_string() + .contains(&format!("{attribute}=\"{spelling}\"")), + "{attribute} {label}: {error}" + ); + } else { + result.unwrap_or_else(|error| { + panic!("{attribute} {label} sentinel must be preserved: {error}") + }); + } + } + } +} + +#[test] +fn sentinel_probe_populates_an_absent_path_in_a_sha256_copied_index() { + let repo = tempfile::tempdir().expect("repo tempdir"); + let root = repo.path(); + let init = run(root, &["git", "init", "--object-format=sha256"]); + assert_eq!(init.0, 0, "initialize SHA-256 repository: {}", init.2); + assert_eq!( + run(root, &["git", "config", "user.email", "codex@example.com"]).0, + 0 + ); + assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0); + assert_eq!(run(root, &["git", "config", "core.autocrlf", "false"]).0, 0); + std::fs::write(root.join(".gitattributes"), "new.txt text\n").expect("write attributes"); + assert_eq!(run(root, &["git", "add", ".gitattributes"]).0, 0); + assert_eq!(run(root, &["git", "commit", "-m", "attributes"]).0, 0); + + install_merge_policy(root, &["new.txt".to_string()]) + .expect("classify special attributes with a SHA-256 phantom entry"); + assert_eq!(run(root, &["git", "ls-files", "--", "new.txt"]).1, ""); +} + #[test] fn apply_allows_unused_global_merge_driver() { if std::env::var_os("CODEX_GIT_UTILS_MERGE_ENV_CHILD").is_none() { @@ -134,7 +242,7 @@ fn apply_rejects_global_merge_driver_before_three_way() { .expect_err("reject global merge driver"); assert_eq!(config_source_authorization_count(), 1); assert_eq!(merge_config_read_count(), 1); - assert_eq!(merge_attribute_read_count(), 1); + assert_eq!(merge_attribute_read_count(), 2); assert_eq!(merge_overlay_count(), 1); assert_eq!(error.kind(), io::ErrorKind::Unsupported); let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]); @@ -572,7 +680,7 @@ fn custom_merge_driver_proof_is_consumed_before_final_spawn() { .authorize_filter_paths(&["file.txt".to_string()]) .expect("apply filter policy"); let (_, gate) = config - .run_apply_policy_gate(false, patch) + .run_apply_policy_gate(/*revert*/ false, patch) .expect("policy gate"); assert!(gate.status.success()); config @@ -580,15 +688,15 @@ fn custom_merge_driver_proof_is_consumed_before_final_spawn() { .expect("merge policy"); let scratch = config.create_three_way_scratch_storage().expect("scratch"); config - .prove_three_way_merge_policy_safety(&scratch, false, patch) + .prove_three_way_merge_policy_safety(&scratch, /*revert*/ false, patch) .expect("proof"); let first = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect("first final apply"); assert!(first.status.success()); let second = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect_err("proof must not be reusable"); assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); } @@ -621,7 +729,7 @@ fn custom_merge_driver_proof_is_consumed_before_failed_index_revalidation() { .authorize_filter_paths(&["file.txt".to_string()]) .expect("apply filter policy"); let (_, gate) = config - .run_apply_policy_gate(false, patch) + .run_apply_policy_gate(/*revert*/ false, patch) .expect("policy gate"); assert!(gate.status.success()); config @@ -629,20 +737,20 @@ fn custom_merge_driver_proof_is_consumed_before_failed_index_revalidation() { .expect("merge policy"); let scratch = config.create_three_way_scratch_storage().expect("scratch"); config - .prove_three_way_merge_policy_safety(&scratch, false, patch) + .prove_three_way_merge_policy_safety(&scratch, /*revert*/ false, patch) .expect("proof"); std::fs::write(root.join("file.txt"), "index-raced\n").expect("write raced index entry"); assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); let first = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect_err("changed live index must invalidate proof"); assert_eq!(first.kind(), io::ErrorKind::PermissionDenied); assert!(first.to_string().contains("index changed"), "{first}"); let second = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect_err("failed revalidation must still consume proof"); assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); assert!( @@ -674,7 +782,7 @@ fn conditional_merge_config_proof_is_consumed_before_failed_index_revalidation() .authorize_filter_paths(&["file.txt".to_string()]) .expect("apply filter policy"); let (_, gate) = config - .run_apply_policy_gate(false, patch) + .run_apply_policy_gate(/*revert*/ false, patch) .expect("policy gate"); assert!(gate.status.success()); config @@ -688,19 +796,19 @@ fn conditional_merge_config_proof_is_consumed_before_failed_index_revalidation() ); let scratch = config.create_three_way_scratch_storage().expect("scratch"); config - .prove_three_way_merge_policy_safety(&scratch, false, patch) + .prove_three_way_merge_policy_safety(&scratch, /*revert*/ false, patch) .expect("conditional merge-config proof"); std::fs::write(root.join("file.txt"), "index-raced\n").expect("write raced index entry"); assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0); let first = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect_err("changed live index must invalidate proof"); assert_eq!(first.kind(), io::ErrorKind::PermissionDenied); assert!(first.to_string().contains("index changed"), "{first}"); let second = config - .run_three_way_apply(false, patch) + .run_three_way_apply(/*revert*/ false, patch) .expect_err("failed revalidation must still consume proof"); assert_eq!(second.kind(), io::ErrorKind::PermissionDenied); assert!( @@ -818,7 +926,7 @@ fn three_way_apply_allows_unrelated_local_merge_driver() { .expect("allow unrelated local merge driver during three-way fallback"); assert_eq!(config_source_authorization_count(), 1); assert_eq!(merge_config_read_count(), 1); - assert_eq!(merge_attribute_read_count(), 1); + assert_eq!(merge_attribute_read_count(), 2); assert_eq!(merge_overlay_count(), 1); assert_eq!(result.exit_code, 0, "three-way apply: {}", result.stderr); assert!(result.cmd_for_log.contains("--3way")); @@ -1242,6 +1350,12 @@ fn malformed_shared_repository_refuses_before_reverse_index_staging() { let diff = build_three_way_fixture(root); let index_path = root.join(".git/index"); let before_index = std::fs::read(&index_path).expect("read index before refusal"); + let unused_filter = run(root, &["git", "config", "filter.lfs.clean", "cat"]); + assert_eq!( + unused_filter.0, 0, + "configure unused filter: {}", + unused_filter.2 + ); let configured = run( root, &["git", "config", "core.sharedRepository", "not-a-permission"], @@ -2297,5 +2411,6 @@ fn init_repo() -> tempfile::TempDir { let _ = run(root, &["git", "init"]); let _ = run(root, &["git", "config", "user.email", "codex@example.com"]); let _ = run(root, &["git", "config", "user.name", "Codex"]); + let _ = run(root, &["git", "config", "core.autocrlf", "false"]); repo } diff --git a/codex-rs/git-utils/src/reverse_apply_tests.rs b/codex-rs/git-utils/src/reverse_apply_tests.rs index 21852c3ed3..2a7922f689 100644 --- a/codex-rs/git-utils/src/reverse_apply_tests.rs +++ b/codex-rs/git-utils/src/reverse_apply_tests.rs @@ -804,6 +804,6 @@ fn reverse_three_way_with_staging_candidate_uses_one_authorization() { assert_eq!(config_source_authorization_count(), 1); assert_eq!(filter_policy_read_count(), 2); assert_eq!(merge_config_read_count(), 1); - assert_eq!(merge_attribute_read_count(), 1); + assert_eq!(merge_attribute_read_count(), 2); assert_eq!(read_file_normalized(&root.join("file.txt")), expected); } diff --git a/codex-rs/git-utils/src/reverse_staging.rs b/codex-rs/git-utils/src/reverse_staging.rs index 0d0418ff56..6eb13384b2 100644 --- a/codex-rs/git-utils/src/reverse_staging.rs +++ b/codex-rs/git-utils/src/reverse_staging.rs @@ -213,7 +213,8 @@ pub(crate) fn execute_reverse_staging_plan( plan: SealedReverseStagingPlan, ) -> io::Result<()> { config.ensure_operation_identity(&plan.owner)?; - let result = execute_prepared_reverse_index_update(config, &plan.update, None)?; + let result = + execute_prepared_reverse_index_update(config, &plan.update, /*scratch*/ None)?; reverse_staging_result(result) }