From 7c91950443378dafed03785844cb8f2ccc33f593 Mon Sep 17 00:00:00 2001 From: Tomasz Kalinowski Date: Fri, 4 Dec 2026 08:12:34 -0500 Subject: [PATCH 01/64] Require an explicit path for in-place formatting --- README.md | 2 +- RELEASE_NOTES.md | 2 ++ src/cli.rs | 15 ++++++++++++- src/workspace.rs | 17 ++++++++++++++- src/workspace/paths.rs | 11 +++------- tests/cases/format_default_check_path.case | 15 +++++++++++++ tests/cases/format_default_diff_path.case | 13 ++++++++++++ tests/cases/format_missing_path.case | 17 +++++++++++++++ .../format_missing_path_with_config.case | 21 +++++++++++++++++++ tests/config_discovery.rs | 17 +++++++++++++++ tests/website.rs | 5 +++-- website/assets/social-card.svg | 2 +- website/cli-help.html.md | 9 +++++--- website/cli-help.qmd | 7 +++++-- website/directives.html.md | 2 +- website/directives.qmd | 2 +- website/index.html.md | 2 +- website/index.qmd | 2 +- website/usage.html.md | 2 +- website/usage.qmd | 2 +- 20 files changed, 140 insertions(+), 25 deletions(-) create mode 100644 tests/cases/format_default_check_path.case create mode 100644 tests/cases/format_default_diff_path.case create mode 100644 tests/cases/format_missing_path.case create mode 100644 tests/cases/format_missing_path_with_config.case diff --git a/README.md b/README.md index e643e2df..a40c1683 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ yamark format config.yaml docs/ Format the current directory: ```sh -yamark format +yamark format . ``` Check whether files are already formatted without writing changes: diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index beca0803..7d4a1782 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,5 +1,7 @@ +To format the current directory in place, use `yamark format .`. Bare `yamark format` now exits with a usage error, even when the directory contains a `yamark.toml`. Both `yamark format --check` and `yamark format --diff` still default to the current directory. + Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yamark formatting. Its gitignore-style patterns are relative to the config directory. Unlike `.gitignore` and `.ignore`, which affect only directory traversal, `exclude` also applies to explicit paths, `--stdin-file-path`, and Git clean and smudge filters. Excluded file paths are counted as skipped, and stdin for an excluded path passes through unchanged. This also applies to editor Format Document and format-on-save; a configured next formatter still runs. `[paths]` overrides now match a `--stdin-file-path` that does not exist on disk on Windows, or when the path passes through a symlinked directory. Previously these paths could fail to match the config directory. diff --git a/src/cli.rs b/src/cli.rs index 7a3e0d73..6121d988 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -79,7 +79,10 @@ enum Command { compact: bool, #[arg(long)] skip_embedded_formatters: bool, - #[arg(value_name = "PATHS")] + #[arg( + value_name = "PATHS", + help = "Files or directories to format in place (required for writes). Use '.' for the current directory" + )] paths: Vec, }, #[command(about = "Convert JSON-family input from stdin to formatted YAML")] @@ -369,6 +372,16 @@ fn run_format( } else { FormatMode::Write }; + let paths = match mode.resolve_paths(paths) { + Ok(paths) => paths, + Err(message) => { + eprintln!("error: {message}\n"); + eprintln!( + "Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin." + ); + return ExitCode::from(2); + } + }; match format_paths_with_trace_and_overrides(paths, options, mode, config, execution) { Ok(run) => { if mode == FormatMode::Diff { diff --git a/src/workspace.rs b/src/workspace.rs index f5e14c1a..be989da6 100644 --- a/src/workspace.rs +++ b/src/workspace.rs @@ -35,6 +35,21 @@ pub enum FormatMode { Diff, } +impl FormatMode { + pub(crate) fn resolve_paths( + self, + paths: Vec, + ) -> std::result::Result, &'static str> { + if !paths.is_empty() { + return Ok(paths); + } + match self { + Self::Write => Err("in-place formatting requires a file or directory path"), + Self::Check | Self::Diff => Ok(vec![PathBuf::from(".")]), + } + } +} + #[derive(Debug, Clone, Copy, Default)] pub(crate) struct FormatExecutionOptions { pub(crate) collect_trace: bool, @@ -272,7 +287,7 @@ pub fn format_paths_with_trace( collect_trace: bool, ) -> Result { format_paths_with_trace_and_overrides( - paths, + mode.resolve_paths(paths).map_err(YamarkError::new)?, options, mode, config_path, diff --git a/src/workspace/paths.rs b/src/workspace/paths.rs index 48d438dd..166aa938 100644 --- a/src/workspace/paths.rs +++ b/src/workspace/paths.rs @@ -49,10 +49,10 @@ fn format_worker_count() -> usize { fn format_worker_count_for_roots(paths: &[PathBuf]) -> usize { let max_workers = format_worker_count(); - if paths.is_empty() || !paths.iter().all(|path| path_is_file_like(path)) { + if !paths.iter().all(|path| path_is_file_like(path)) { return max_workers; } - max_workers.min(paths.len()).max(1) + max_workers.min(paths.len()) } fn path_is_file_like(path: &Path) -> bool { @@ -197,12 +197,7 @@ impl CandidateProducer { } fn stream(&mut self, paths: Vec) -> Result<()> { - let roots = if paths.is_empty() { - vec![PathBuf::from(".")] - } else { - paths - }; - for root in roots { + for root in paths { self.stream_root(root)?; } Ok(()) diff --git a/tests/cases/format_default_check_path.case b/tests/cases/format_default_check_path.case new file mode 100644 index 00000000..eeb24bab --- /dev/null +++ b/tests/cases/format_default_check_path.case @@ -0,0 +1,15 @@ +-- git-fixture +{ + "config": {"core.autocrlf": "false"}, + "files": {"docs/input.md": "# Title\n"} +} +-- args +format --check +-- stdin +-- stdout +-- stderr +1 files scanned, 1 formatted, 0 unchanged, 0 skipped, 0 failed +-- git-worktree +{"docs/input.md": "# Title\n"} +-- status +1 diff --git a/tests/cases/format_default_diff_path.case b/tests/cases/format_default_diff_path.case new file mode 100644 index 00000000..5faa5b5c --- /dev/null +++ b/tests/cases/format_default_diff_path.case @@ -0,0 +1,13 @@ +-- git-fixture +{ + "config": {"core.autocrlf": "false"}, + "files": {"docs/input.md": "# Title\n"} +} +-- args +format --diff +-- stdin +-- stdout +-- stderr +1 files scanned, 0 formatted, 1 unchanged, 0 skipped, 0 failed +-- status +0 diff --git a/tests/cases/format_missing_path.case b/tests/cases/format_missing_path.case new file mode 100644 index 00000000..1af8f46f --- /dev/null +++ b/tests/cases/format_missing_path.case @@ -0,0 +1,17 @@ +-- git-fixture +{ + "config": {"core.autocrlf": "false"}, + "files": {"docs/input.md": "# Title\n"} +} +-- args +format +-- stdin +-- stdout +-- stderr +error: in-place formatting requires a file or directory path + +Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin. +-- git-worktree +{"docs/input.md": "# Title\n"} +-- status +2 diff --git a/tests/cases/format_missing_path_with_config.case b/tests/cases/format_missing_path_with_config.case new file mode 100644 index 00000000..63a39c69 --- /dev/null +++ b/tests/cases/format_missing_path_with_config.case @@ -0,0 +1,21 @@ +-- git-fixture +{ + "config": {"core.autocrlf": "false"}, + "files": { + "yamark.toml": "[format]\nwrap = \"none\"\n", + "docs/input.md": "# Title\n" + } +} +-- args +format --wrap 40 +-- stdin +# Piped +-- stdout +-- stderr +error: in-place formatting requires a file or directory path + +Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin. +-- git-worktree +{"docs/input.md": "# Title\n"} +-- status +2 diff --git a/tests/config_discovery.rs b/tests/config_discovery.rs index 6556d29f..1cd25c30 100644 --- a/tests/config_discovery.rs +++ b/tests/config_discovery.rs @@ -2,6 +2,23 @@ use std::fs; use assert_cmd::Command; use tempfile::tempdir; +use yamark::workspace::{FormatMode, format_paths}; + +#[test] +fn empty_write_paths_are_rejected_before_loading_config() { + let dir = tempdir().unwrap(); + let error = format_paths( + vec![], + Default::default(), + FormatMode::Write, + Some(dir.path().join("missing.toml")), + ) + .unwrap_err(); + assert_eq!( + error.diagnostic.message, + "in-place formatting requires a file or directory path" + ); +} #[test] fn relative_file_and_directory_paths_discover_ancestor_config() { diff --git a/tests/website.rs b/tests/website.rs index 29f7a42d..ca870a15 100644 --- a/tests/website.rs +++ b/tests/website.rs @@ -667,7 +667,7 @@ fn website_homepage_leads_with_purpose_and_scope() { for text in [ "A fast formatter for YAML and Markdown.", - "uvx yamark format", + "uvx yamark format .", ] { assert!(rendered.contains(text), "homepage should include {text:?}"); } @@ -1379,7 +1379,8 @@ fn website_documents_command_line_reference() { "`yamark format --diff PATHS`", "`yamark format --stdin-file-path PATH`", "`yamark to-yaml --stdin-file-path PATH`", - "When `PATHS` is omitted from `yamark format`, Yamark uses the current directory (`.`)", + "Use `yamark format .` to format the current directory and its subdirectories.", + "With `--check` or `--diff`, omitting the path selects the current directory.", "An unsupported `--stdin-file-path` is an error", "Unified diffs", "Formatted YAML only", diff --git a/website/assets/social-card.svg b/website/assets/social-card.svg index d0974707..b2e544b0 100644 --- a/website/assets/social-card.svg +++ b/website/assets/social-card.svg @@ -18,6 +18,6 @@ - $ uvx yamark format + $ uvx yamark format . diff --git a/website/cli-help.html.md b/website/cli-help.html.md index ea557463..d9a7d1e8 100644 --- a/website/cli-help.html.md +++ b/website/cli-help.html.md @@ -29,8 +29,11 @@ generated from the current Yamark binary. exits `1` when formatting fails and `0` on success otherwise. Invalid command syntax exits `2`. -When `PATHS` is omitted from `yamark format`, Yamark uses the current directory -(`.`). Format path mode counts unsupported extensions as skipped without +In-place formatting requires a path, even in a directory with a `yamark.toml`. +Use `yamark format .` to format the current directory and its subdirectories. +With `--check` or `--diff`, omitting the path selects the current directory. + +Format path mode counts unsupported extensions as skipped without failing. An unsupported `--stdin-file-path` is an error because stdin mode requires a supported file type. @@ -69,7 +72,7 @@ Run `yamark <COMMAND> --help` for command-level help.
Usage: yamark format [OPTIONS] [PATHS]...
 
 Arguments:
-  [PATHS]...
+  [PATHS]...  Files or directories to format in place (required for writes). Use '.' for the current directory
 
 Options:
       --check
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index 679658c2..47d2300d 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -62,8 +62,11 @@ generated from the current Yamark binary.
 exits `1` when formatting fails and `0` on success otherwise. Invalid command
 syntax exits `2`.
 
-When `PATHS` is omitted from `yamark format`, Yamark uses the current directory
-(`.`). Format path mode counts unsupported extensions as skipped without
+In-place formatting requires a path, even in a directory with a `yamark.toml`.
+Use `yamark format .` to format the current directory and its subdirectories.
+With `--check` or `--diff`, omitting the path selects the current directory.
+
+Format path mode counts unsupported extensions as skipped without
 failing. An unsupported `--stdin-file-path` is an error because stdin mode
 requires a supported file type.
 
diff --git a/website/directives.html.md b/website/directives.html.md
index 426f724a..8fcce1a3 100644
--- a/website/directives.html.md
+++ b/website/directives.html.md
@@ -248,7 +248,7 @@ workflow:
 - In an editor, enable format on save. The [Editors](editors.qmd) page shows
   the VS Code and Positron settings. This is the most direct way to see a
   directive take effect while editing.
-- In a pre-commit hook, run `yamark format`. In CI, use
+- In a pre-commit hook, run `yamark format .`. In CI, use
   `yamark format --check` to verify files without changing them.
 
 The experimental [Git Filter](git-filter.qmd) serves a narrower workflow: it
diff --git a/website/directives.qmd b/website/directives.qmd
index 426f724a..8fcce1a3 100644
--- a/website/directives.qmd
+++ b/website/directives.qmd
@@ -248,7 +248,7 @@ workflow:
 - In an editor, enable format on save. The [Editors](editors.qmd) page shows
   the VS Code and Positron settings. This is the most direct way to see a
   directive take effect while editing.
-- In a pre-commit hook, run `yamark format`. In CI, use
+- In a pre-commit hook, run `yamark format .`. In CI, use
   `yamark format --check` to verify files without changing them.
 
 The experimental [Git Filter](git-filter.qmd) serves a narrower workflow: it
diff --git a/website/index.html.md b/website/index.html.md
index 6bcd2334..fe59bd7b 100644
--- a/website/index.html.md
+++ b/website/index.html.md
@@ -24,7 +24,7 @@ from code, keeping source readable and changes easy to review.
 
 ::: {.hero-command}
 Run directly from PyPI
-`uvx yamark format`
+`uvx yamark format .`
 :::
 :::
 :::
diff --git a/website/index.qmd b/website/index.qmd
index 338c86f3..6b6b1c9b 100644
--- a/website/index.qmd
+++ b/website/index.qmd
@@ -54,7 +54,7 @@ from code, keeping source readable and changes easy to review.
 
 ::: {.hero-command}
 Run directly from PyPI
-`uvx yamark format`
+`uvx yamark format .`
 :::
 :::
 :::
diff --git a/website/usage.html.md b/website/usage.html.md
index 8d8b4d05..b7d82955 100644
--- a/website/usage.html.md
+++ b/website/usage.html.md
@@ -41,7 +41,7 @@ yamark format config.yaml docs/
 Format the current directory:
 
 ```sh
-yamark format
+yamark format .
 ```
 
 By default, Markdown prose wraps at column 72 without forcing sentence
diff --git a/website/usage.qmd b/website/usage.qmd
index 8d8b4d05..b7d82955 100644
--- a/website/usage.qmd
+++ b/website/usage.qmd
@@ -41,7 +41,7 @@ yamark format config.yaml docs/
 Format the current directory:
 
 ```sh
-yamark format
+yamark format .
 ```
 
 By default, Markdown prose wraps at column 72 without forcing sentence

From 0826d47360aae1df3027331b8f4bd3d5c766289d Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:43:01 -0500
Subject: [PATCH 02/64] Record template overrides for a virtual stdin path

---
 .../config_virtual_stdin_path_override.case   | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)
 create mode 100644 tests/cases/config_virtual_stdin_path_override.case

diff --git a/tests/cases/config_virtual_stdin_path_override.case b/tests/cases/config_virtual_stdin_path_override.case
new file mode 100644
index 00000000..9b4b187b
--- /dev/null
+++ b/tests/cases/config_virtual_stdin_path_override.case
@@ -0,0 +1,20 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[paths.\"docs\".template]\nadd_delimiters = [{ open = \"<<\", close = \">>\" }]\n"
+  }
+}
+-- args
+format --stdin-file-path docs/new.md
+-- stdin
+#   Draft
+
+Keep << these   spaces >> here.
+-- stdout
+# Draft
+
+Keep << these   spaces >> here.
+-- stderr
+-- status
+0

From c72ec30aec273b8e1c5d35495d61cf86f94cb31a Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:43:01 -0500
Subject: [PATCH 03/64] Document excluded stdin paths with unsupported
 extensions

---
 tests/cases/config_exclude_unsupported_stdin.case | 14 ++++++++++++++
 tests/website.rs                                  |  6 ++++--
 website/cli-help.html.md                          |  9 +++++----
 website/cli-help.qmd                              |  9 +++++----
 website/reference-files.html.md                   |  6 ++++--
 website/reference-files.qmd                       |  6 ++++--
 6 files changed, 36 insertions(+), 14 deletions(-)
 create mode 100644 tests/cases/config_exclude_unsupported_stdin.case

diff --git a/tests/cases/config_exclude_unsupported_stdin.case b/tests/cases/config_exclude_unsupported_stdin.case
new file mode 100644
index 00000000..5974e01a
--- /dev/null
+++ b/tests/cases/config_exclude_unsupported_stdin.case
@@ -0,0 +1,14 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {"yamark.toml": "[format]\nexclude = [\"*.txt\"]\n"}
+}
+-- args
+format --stdin-file-path notes.txt
+-- stdin
+#   Notes
+-- stdout
+#   Notes
+-- stderr
+-- status
+0
diff --git a/tests/website.rs b/tests/website.rs
index ca870a15..9411e1e5 100644
--- a/tests/website.rs
+++ b/tests/website.rs
@@ -1281,7 +1281,8 @@ fn website_documents_user_facing_references() {
         "A multi-file write run is not transactional",
         "Extension matching is ASCII case-insensitive",
         "unsupported extensions are counted as skipped and do not make the run fail",
-        "unsupported `--stdin-file-path` is an error",
+        "Yamark exits `1` for an unsupported extension unless the path is excluded",
+        "copies stdin to stdout byte for byte and exits `0`",
         "writes are direct rather than atomic",
         "does not promise rollback",
     ] {
@@ -1381,7 +1382,8 @@ fn website_documents_command_line_reference() {
             "`yamark to-yaml --stdin-file-path PATH`",
             "Use `yamark format .` to format the current directory and its subdirectories.",
             "With `--check` or `--diff`, omitting the path selects the current directory.",
-            "An unsupported `--stdin-file-path` is an error",
+            "Yamark exits `1` for an unsupported extension unless the path is excluded",
+            "copies stdin to stdout byte for byte and exits `0`",
             "Unified diffs",
             "Formatted YAML only",
             "exits `1`",
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index d9a7d1e8..9e59eb5c 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -22,7 +22,7 @@ generated from the current Yamark binary.
 | `yamark format PATHS` | Writes changed files. | Summary. | Failures and requested diagnostics. |
 | `yamark format --check PATHS` | Does not write. | - | Summary, failures, and requested diagnostics. |
 | `yamark format --diff PATHS` | Does not write. | Unified diffs. | Summary, failures, and requested diagnostics. |
-| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content only. | Failures and requested diagnostics. |
+| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content or the original bytes for an excluded path. | Failures and requested diagnostics. |
 | `yamark to-yaml --stdin-file-path PATH` | Does not read or write `PATH`; uses its JSON-family suffix to parse stdin. | Formatted YAML only. | Failures. |
 
 `--check` and `--diff` exit `1` when any selected file would change. Every mode
@@ -33,9 +33,10 @@ In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 With `--check` or `--diff`, omitting the path selects the current directory.
 
-Format path mode counts unsupported extensions as skipped without
-failing. An unsupported `--stdin-file-path` is an error because stdin mode
-requires a supported file type.
+Format path mode counts unsupported extensions as skipped without failing.
+With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
+the path is excluded. For an excluded path, it copies stdin to stdout byte for
+byte and exits `0`.
 
 Format stdin mode rejects additional paths and cannot be combined with
 `--check` or `--diff`. `yamark to-yaml` always reads stdin, requires a `.json`,
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index 47d2300d..2b17598e 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -55,7 +55,7 @@ generated from the current Yamark binary.
 | `yamark format PATHS` | Writes changed files. | Summary. | Failures and requested diagnostics. |
 | `yamark format --check PATHS` | Does not write. | - | Summary, failures, and requested diagnostics. |
 | `yamark format --diff PATHS` | Does not write. | Unified diffs. | Summary, failures, and requested diagnostics. |
-| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content only. | Failures and requested diagnostics. |
+| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content or the original bytes for an excluded path. | Failures and requested diagnostics. |
 | `yamark to-yaml --stdin-file-path PATH` | Does not read or write `PATH`; uses its JSON-family suffix to parse stdin. | Formatted YAML only. | Failures. |
 
 `--check` and `--diff` exit `1` when any selected file would change. Every mode
@@ -66,9 +66,10 @@ In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 With `--check` or `--diff`, omitting the path selects the current directory.
 
-Format path mode counts unsupported extensions as skipped without
-failing. An unsupported `--stdin-file-path` is an error because stdin mode
-requires a supported file type.
+Format path mode counts unsupported extensions as skipped without failing.
+With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
+the path is excluded. For an excluded path, it copies stdin to stdout byte for
+byte and exits `0`.
 
 Format stdin mode rejects additional paths and cannot be combined with
 `--check` or `--diff`. `yamark to-yaml` always reads stdin, requires a `.json`,
diff --git a/website/reference-files.html.md b/website/reference-files.html.md
index eb41f913..0b3088ba 100644
--- a/website/reference-files.html.md
+++ b/website/reference-files.html.md
@@ -22,8 +22,10 @@ the output.
 | YAML literal scalars following `# fmt: ` or `# fmt: embedded ` | The scalar value through a built-in or configured embedded formatter. | Explicit directive. |
 
 Extension matching is ASCII case-insensitive. In path mode, unsupported
-extensions are counted as skipped and do not make the run fail. An unsupported
-`--stdin-file-path` is an error because stdin mode requires file-aware behavior.
+extensions are counted as skipped and do not make the run fail.
+With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
+the path is excluded. For an excluded path, it copies stdin to stdout byte for
+byte and exits `0`.
 
 Directory traversal skips hidden paths and respects `.gitignore`, `.ignore`,
 and global Git ignore files. Passing a hidden path explicitly selects it. To
diff --git a/website/reference-files.qmd b/website/reference-files.qmd
index eb41f913..0b3088ba 100644
--- a/website/reference-files.qmd
+++ b/website/reference-files.qmd
@@ -22,8 +22,10 @@ the output.
 | YAML literal scalars following `# fmt: ` or `# fmt: embedded ` | The scalar value through a built-in or configured embedded formatter. | Explicit directive. |
 
 Extension matching is ASCII case-insensitive. In path mode, unsupported
-extensions are counted as skipped and do not make the run fail. An unsupported
-`--stdin-file-path` is an error because stdin mode requires file-aware behavior.
+extensions are counted as skipped and do not make the run fail.
+With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
+the path is excluded. For an excluded path, it copies stdin to stdout byte for
+byte and exits `0`.
 
 Directory traversal skips hidden paths and respects `.gitignore`, `.ignore`,
 and global Git ignore files. Passing a hidden path explicitly selects it. To

From ab67db19cd4594d4d93e6550913ba475d7635f13 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:43:04 -0500
Subject: [PATCH 04/64] Preserve default-based FormatConfig construction

---
 src/config.rs | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/src/config.rs b/src/config.rs
index 012bb7cb..9b1401b5 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -22,6 +22,16 @@ pub struct Config {
     pub config_dir: Option,
 }
 
+/// Formatting settings from the `[format]` table.
+///
+/// ```
+/// use yamark::config::FormatConfig;
+///
+/// let format = FormatConfig {
+///     compact: Some(true),
+///     ..Default::default()
+/// };
+/// ```
 #[derive(Debug, Clone, Default)]
 pub struct FormatConfig {
     pub compact: Option,
@@ -29,11 +39,14 @@ pub struct FormatConfig {
     pub markdown_table_widths: Option,
     pub markdown_horizontal_rule: Option<&'static str>,
     pub abbreviations: AbbreviationOverrides,
-    /// Compiled `exclude` patterns, matched against paths relative to the
-    /// config directory.
-    pub(crate) exclude: Option>,
+    pub exclude: Option,
 }
 
+/// Exclusion patterns parsed from `[format] exclude` and matched relative to
+/// the config directory.
+#[derive(Debug, Clone)]
+pub struct ExcludePatterns(Arc);
+
 #[derive(Debug, Clone)]
 pub struct PathConfig {
     pub path: PathBuf,
@@ -152,7 +165,7 @@ impl Config {
     /// Whether `[format] exclude` matches `path`. Patterns are relative to the
     /// config directory, so they never match a path outside it.
     pub fn excludes(&self, path: &Path) -> bool {
-        let Some(exclude) = &self.format.exclude else {
+        let Some(ExcludePatterns(exclude)) = &self.format.exclude else {
             return false;
         };
         let Some(relative) = self.written_path_below_config_dir(path) else {
@@ -386,7 +399,7 @@ fn apply_format_layer(value: &toml::Value, format: &mut FormatConfig) -> Result<
         format.abbreviations = parse_abbreviations(value)?;
     }
     if let Some(value) = table.get("exclude") {
-        format.exclude = Some(Arc::new(parse_exclude(value)?));
+        format.exclude = Some(ExcludePatterns(Arc::new(parse_exclude(value)?)));
     }
     Ok(())
 }

From a60b92a88a9f9e17a9b3a26388cee1d76c0b8e58 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:44:04 -0500
Subject: [PATCH 05/64] Match braces literally in exclusion patterns

---
 src/config.rs                                 | 34 ++++++++++++++++++-
 .../cases/config_exclude_invalid_pattern.case |  4 +--
 .../cases/config_exclude_literal_braces.case  | 34 +++++++++++++++++++
 3 files changed, 69 insertions(+), 3 deletions(-)
 create mode 100644 tests/cases/config_exclude_literal_braces.case

diff --git a/src/config.rs b/src/config.rs
index 9b1401b5..c2778796 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -419,7 +419,7 @@ fn parse_exclude(value: &toml::Value) -> Result {
     let mut builder = GitignoreBuilder::new("");
     for pattern in patterns {
         builder
-            .add_line(None, pattern)
+            .add_line(None, &escape_gitignore_braces(pattern))
             .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))?;
     }
     builder
@@ -427,6 +427,38 @@ fn parse_exclude(value: &toml::Value) -> Result {
         .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))
 }
 
+/// Git wildmatch treats braces literally. The glob matcher used by
+/// `GitignoreBuilder` also recognizes brace alternatives.
+fn escape_gitignore_braces(pattern: &str) -> String {
+    let mut out = String::with_capacity(pattern.len());
+    let mut chars = pattern.chars();
+    let mut may_have_class = true;
+    while let Some(c) = chars.next() {
+        if matches!(c, '{' | '}') {
+            out.push('\\');
+        }
+        out.push(c);
+        match c {
+            '\\' => out.extend(chars.next()),
+            '[' if may_have_class => {
+                // Braces inside a character class already match literally.
+                // A leading ']' (after optional negation) is a class member.
+                let rest = chars.as_str();
+                let members = rest.strip_prefix(['!', '^']).unwrap_or(rest);
+                let members = members.strip_prefix(']').unwrap_or(members);
+                if let Some((_, after)) = members.split_once(']') {
+                    out.push_str(&rest[..rest.len() - after.len()]);
+                    chars = after.chars();
+                } else {
+                    may_have_class = false;
+                }
+            }
+            _ => {}
+        }
+    }
+    out
+}
+
 fn parse_abbreviations(value: &toml::Value) -> Result {
     let table = value
         .as_table()
diff --git a/tests/cases/config_exclude_invalid_pattern.case b/tests/cases/config_exclude_invalid_pattern.case
index 204a48e4..c50dc2a0 100644
--- a/tests/cases/config_exclude_invalid_pattern.case
+++ b/tests/cases/config_exclude_invalid_pattern.case
@@ -2,7 +2,7 @@
 {
   "config": {"core.autocrlf": "false"},
   "files": {
-    "yamark.toml": "[format]\nexclude = [\"{deck.qmd\"]\n"
+    "yamark.toml": "[format]\nexclude = [\"[z-a].md\"]\n"
   }
 }
 -- args
@@ -11,6 +11,6 @@ format --config yamark.toml --stdin-file-path input.md
 #   Title
 -- stdout
 -- stderr
-yamark.toml:1:1: error: format.exclude: error parsing glob '{deck.qmd': unclosed alternate group; missing '}' (maybe escape '{' with '[{]'?)
+yamark.toml:1:1: error: format.exclude: error parsing glob '[z-a].md': invalid range; 'z' > 'a'
 -- status
 1
diff --git a/tests/cases/config_exclude_literal_braces.case b/tests/cases/config_exclude_literal_braces.case
new file mode 100644
index 00000000..3713f221
--- /dev/null
+++ b/tests/cases/config_exclude_literal_braces.case
@@ -0,0 +1,34 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "yamark.toml": "[format]\nexclude = ['{id}.md', '{a,b}.md', 'open{.md', 'escaped\\{x\\}.md', '[a-{]-range.md']\n",
+    "{id}.md": "#   Title\n",
+    "id.md": "#   Title\n",
+    "{a,b}.md": "#   Title\n",
+    "a.md": "#   Title\n",
+    "open{.md": "#   Title\n",
+    "escaped{x}.md": "#   Title\n",
+    "z-range.md": "#   Title\n"
+  }
+}
+-- args
+format {id}.md id.md {a,b}.md a.md open{.md escaped{x}.md z-range.md
+-- stdin
+-- stdout
+7 files scanned, 2 formatted, 0 unchanged, 5 skipped, 0 failed
+-- stderr
+-- git-worktree
+{
+  "{id}.md": "#   Title\n",
+  "id.md": "# Title\n",
+  "{a,b}.md": "#   Title\n",
+  "a.md": "# Title\n",
+  "open{.md": "#   Title\n",
+  "escaped{x}.md": "#   Title\n",
+  "z-range.md": "#   Title\n"
+}
+-- status
+0

From 304f40e8f6bb00e56571807ba6ae596c58aea61d Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:43:45 -0500
Subject: [PATCH 06/64] Exercise directory-link exclusions on Windows

---
 tests/cases/README.md       |  4 ++--
 tests/cli_cases.rs          | 25 ++++++++++++++++++++++---
 tests/spec_cli/workspace.rs | 32 +++++++++-----------------------
 tests/support/symlink.rs    | 21 +++++++++++++++++++++
 4 files changed, 54 insertions(+), 28 deletions(-)
 create mode 100644 tests/support/symlink.rs

diff --git a/tests/cases/README.md b/tests/cases/README.md
index 97fa0edd..b8fd718a 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -52,7 +52,7 @@ The `markdown_list_wide_marker_raw_boundary`, `markdown_list_child_headings`, an
 
 `markdown_sentence_no_answer` and `markdown_column_no_answer` cover both readings of `No.`: an answer ends a sentence and permits a line break, while `No.` before a number stays on the same line as the number. `tests/sentence_wrap.rs` checks both readings in sentence, column, and combined wrapping with LF, CRLF, and CR line endings, including second passes. `markdown_sentence_number_abbreviations` and `markdown_column_number_abbreviations` cover the other words that are abbreviations only before a number, such as `n.`, `p.`, and `sec.`, including a sentence-starting `c.` whose period is escaped because it would otherwise start a list. `markdown_sentence_technical_abbreviations` and `markdown_column_technical_abbreviations` cover the abbreviations Yamark adds to Pandoc's list, such as `Fig.` and `w.r.t.`, the case-sensitive boundary (`Etc.`), and both readings of `etc.` and `i.i.d.`, which are abbreviations only before a lowercase letter. `markdown_sentence_et_al` and `markdown_column_et_al` cover `al.`, which is an abbreviation unless the next whitespace-separated source token starts with an uppercase letter: `et al. We` ends a sentence, while `et al. (2020)`, `et al. showed`, an escaped `et al\.`, and `abbreviations.add "al."` do not. `markdown_sentence_abbreviation_closers` and `markdown_sentence_column_abbreviation_closers` cover abbreviations followed by closing quotation marks or brackets, such as `(e.g.)`: they do not end a sentence, and column wrapping may still break after them. The `markdown_*_period_reference` transcripts cover `.` as an explicit sentence end in sentence and combined wrapping, including after abbreviations and before closing brackets. They also record that an escaped `\.` and the hexadecimal form are ordinary text and that column wrapping alone keeps the reference without forcing a break. The `*_directive_abbreviations` transcripts cover `fmt: abbreviations.add` and `fmt: abbreviations.remove` in Markdown, YAML, Python, and R: each scope, a later directive overriding an earlier one, a correction that replaces a rule depending on the next token, and column wrapping. `markdown_directive_abbreviations_late_file_scope` applies file-scoped corrections to text before the directive. The `markdown_directive_abbreviations_unquoted`, `_no_words`, and `_no_period` transcripts record the errors for a missing or invalid word. `config_abbreviations` covers `[format.abbreviations]` in `yamark.toml` and a directive that overrides it. The `config_abbreviations_both_lists`, `_invalid_word`, `_not_strings`, and `_unknown_key` transcripts record the configuration errors.
 
-The `config_exclude_*` transcripts cover `exclude` in the `[format]` table of `yamark.toml`. `config_exclude_stdin` returns excluded stdin unchanged, and `config_exclude_stdin_unmatched` formats another file under the same config. `config_exclude_explicit_path` counts an excluded explicit path as skipped. `config_exclude_directory_walk` counts files below an excluded directory as skipped and checks that their contents are unchanged. `config_exclude_patterns` covers directory, glob, anchored, and negated patterns. `config_exclude_parent_directory` keeps a file below an excluded directory excluded whether its `!` pattern comes before or after the directory pattern. `config_exclude_relative_ancestor` and `config_exclude_explicit_config` cover patterns relative to a config discovered in an ancestor or passed with `--config`; the latter also formats a file outside the config directory. `git_filter_clean_excluded` passes an excluded file through the clean filter unchanged. The `config_exclude_not_strings` and `_invalid_pattern` transcripts record the configuration errors. Transcripts cannot create symbolic links or carry non-UTF-8 stdin, so `tests/spec_cli/workspace.rs` covers symlink names, `tests/spec_cli/commands.rs` covers byte pass-through for excluded stdin, and `tests/git_filter_paths.rs` covers adopting and checking a repository with an excluded UTF-16 file.
+The `config_exclude_*` transcripts cover `exclude` in the `[format]` table of `yamark.toml`. `config_exclude_stdin` returns excluded stdin unchanged, and `config_exclude_stdin_unmatched` formats another file under the same config. `config_exclude_explicit_path` counts an excluded explicit path as skipped. `config_exclude_directory_walk` counts files below an excluded directory as skipped and checks that their contents are unchanged. `config_exclude_patterns` covers directory, glob, anchored, and negated patterns. `config_exclude_parent_directory` keeps a file below an excluded directory excluded whether its `!` pattern comes before or after the directory pattern. `config_exclude_relative_ancestor` and `config_exclude_explicit_config` cover patterns relative to a config discovered in an ancestor or passed with `--config`; the latter also formats a file outside the config directory. `git_filter_clean_excluded` passes an excluded file through the clean filter unchanged. The `config_exclude_not_strings` and `_invalid_pattern` transcripts record the configuration errors. For non-UTF-8 input, `tests/spec_cli/commands.rs` covers byte pass-through for excluded stdin, and `tests/git_filter_paths.rs` covers adopting and checking a repository with an excluded UTF-16 file.
 
 The `markdown_bom_*` transcripts read a first line holding only a byte order mark and spaces as blank before thematic breaks, paragraphs, and directives. `markdown_feff_content_setext` keeps U+FEFF later in the file and at the start of blockquote and footnote content as setext heading text.
 
@@ -64,7 +64,7 @@ The `external_formatter_*.case` transcripts cover formatters that remove only th
 
 `external_formatter_early_stdin_close.case` covers a successful formatter that closes stdin before reading it. The public CLI specifications repeat this with input larger than a pipe buffer and check that nonzero status, stderr, invalid UTF-8, and unsafe fence output still fail.
 
-Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
+Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. An optional `symlinks` mapping adds working-tree links after the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
 
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 307682f3..76293305 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -4,6 +4,9 @@ use std::path::{Path, PathBuf};
 
 use assert_cmd::Command;
 
+#[path = "support/symlink.rs"]
+mod symlink;
+
 #[derive(Default)]
 struct Case {
     args: String,
@@ -45,7 +48,14 @@ fn cli_cases() {
         {
             continue;
         }
-        let repo = case.git_fixture.as_ref().map(create_git_fixture);
+        let repo = if let Some(fixture) = &case.git_fixture {
+            let Some(repo) = create_git_fixture(fixture) else {
+                continue;
+            };
+            Some(repo)
+        } else {
+            None
+        };
         let mut command = Command::cargo_bin("yamark").unwrap();
         if let Some(repo) = &repo {
             let cwd = case.git_fixture.as_ref().unwrap()["cwd"]
@@ -173,7 +183,7 @@ fn case_selection_rejects_unmatched_filters() {
     }
 }
 
-fn create_git_fixture(fixture: &serde_json::Value) -> tempfile::TempDir {
+fn create_git_fixture(fixture: &serde_json::Value) -> Option {
     let repo = tempfile::tempdir().unwrap();
     let git = |args: &[&str]| {
         Command::new("git")
@@ -229,7 +239,16 @@ fn create_git_fixture(fixture: &serde_json::Value) -> tempfile::TempDir {
     }
     git(&["add", "."]);
     git(&["commit", "-q", "-m", "fixture"]);
-    repo
+    if let Some(links) = fixture.get("symlinks") {
+        for (name, target) in links.as_object().unwrap() {
+            let link = repo.path().join(name);
+            let target = repo.path().join(target.as_str().unwrap());
+            if !symlink::make_symlink(&target, &link) {
+                return None;
+            }
+        }
+    }
+    Some(repo)
 }
 
 fn redact_repo(bytes: &[u8], repo: Option<&tempfile::TempDir>) -> String {
diff --git a/tests/spec_cli/workspace.rs b/tests/spec_cli/workspace.rs
index ad0b2a1a..11ab01b9 100644
--- a/tests/spec_cli/workspace.rs
+++ b/tests/spec_cli/workspace.rs
@@ -1,6 +1,8 @@
 use super::support::{run_stdin, yamark};
+#[path = "../support/symlink.rs"]
+mod symlink;
 use std::fs;
-use std::path::Path;
+use symlink::make_symlink;
 use tempfile::tempdir;
 
 #[test]
@@ -630,13 +632,14 @@ fn exclude_matches_an_absolute_virtual_stdin_path() {
     assert_eq!((status, stdout.as_str(), stderr.as_str()), (0, input, ""));
 }
 
-#[cfg(unix)]
 #[test]
 fn exclude_matches_a_virtual_stdin_path_below_a_symlinked_directory() {
     let dir = tempdir().unwrap();
     let real = dir.path().join("real");
     fs::create_dir(&real).unwrap();
-    std::os::unix::fs::symlink(&real, dir.path().join("link")).unwrap();
+    if !make_symlink(&real, &dir.path().join("link")) {
+        return;
+    }
     fs::write(real.join("yamark.toml"), "[format]\nexclude = [\"new/\"]\n").unwrap();
     let path = dir.path().join("link").join("new").join("deck.qmd");
     let input = "#   Title\n";
@@ -679,7 +682,6 @@ fn exclude_matches_a_symlinked_file_by_its_own_name() {
     );
 }
 
-#[cfg(unix)]
 #[test]
 fn exclude_matches_a_symlinked_directory_by_its_own_name() {
     let dir = tempdir().unwrap();
@@ -691,7 +693,9 @@ fn exclude_matches_a_symlinked_directory_by_its_own_name() {
     .unwrap();
     let input = "#   Title\n";
     fs::write(outside.path().join("deck.md"), input).unwrap();
-    std::os::unix::fs::symlink(outside.path(), dir.path().join("slides")).unwrap();
+    if !make_symlink(outside.path(), &dir.path().join("slides")) {
+        return;
+    }
 
     let output = yamark()
         .current_dir(dir.path())
@@ -839,24 +843,6 @@ fn non_spec_hard_break_space_config_is_rejected() {
     );
 }
 
-#[cfg(unix)]
-fn make_symlink(path: &Path, link: &Path) -> bool {
-    std::os::unix::fs::symlink(path, link).unwrap();
-    true
-}
-
-#[cfg(windows)]
-fn make_symlink(path: &Path, link: &Path) -> bool {
-    match std::os::windows::fs::symlink_file(path, link) {
-        Ok(()) => true,
-        Err(err) if err.raw_os_error() == Some(1314) => {
-            eprintln!("symlink test requires Windows Developer Mode or symlink privileges: {err}");
-            false
-        }
-        Err(err) => panic!("failed to create symlink: {err}"),
-    }
-}
-
 #[test]
 fn template_delimiter_entries_reject_unknown_fields() {
     let dir = tempdir().unwrap();
diff --git a/tests/support/symlink.rs b/tests/support/symlink.rs
new file mode 100644
index 00000000..bc1210a8
--- /dev/null
+++ b/tests/support/symlink.rs
@@ -0,0 +1,21 @@
+use std::path::Path;
+
+pub fn make_symlink(target: &Path, link: &Path) -> bool {
+    #[cfg(unix)]
+    let result = std::os::unix::fs::symlink(target, link);
+    #[cfg(windows)]
+    let result = if target.is_dir() {
+        std::os::windows::fs::symlink_dir(target, link)
+    } else {
+        std::os::windows::fs::symlink_file(target, link)
+    };
+    match result {
+        Ok(()) => true,
+        #[cfg(windows)]
+        Err(err) if err.raw_os_error() == Some(1314) => {
+            eprintln!("symlink test requires Windows Developer Mode or symlink privileges: {err}");
+            false
+        }
+        Err(err) => panic!("failed to create symlink {}: {err}", link.display()),
+    }
+}

From 2fa28d0531de9ad2937c1ffdc6ea4fb736a5c0f1 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:43:55 -0500
Subject: [PATCH 07/64] Resolve exclusions beside a symlinked config file

---
 src/config.rs                                 |  3 +--
 ...fig_exclude_explicit_symlinked_config.case | 20 +++++++++++++++++++
 .../config_exclude_symlinked_config.case      | 19 ++++++++++++++++++
 3 files changed, 40 insertions(+), 2 deletions(-)
 create mode 100644 tests/cases/config_exclude_explicit_symlinked_config.case
 create mode 100644 tests/cases/config_exclude_symlinked_config.case

diff --git a/src/config.rs b/src/config.rs
index c2778796..2d9fd482 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -79,8 +79,7 @@ impl Config {
             )
         })?;
         let mut config = Self::from_toml_str(&input).map_err(|err| err.with_path(path))?;
-        let absolute = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
-        config.config_dir = absolute.parent().map(Path::to_path_buf);
+        config.config_dir = path.parent().map(absolute_normalized_path);
         Ok(config)
     }
 
diff --git a/tests/cases/config_exclude_explicit_symlinked_config.case b/tests/cases/config_exclude_explicit_symlinked_config.case
new file mode 100644
index 00000000..81906780
--- /dev/null
+++ b/tests/cases/config_exclude_explicit_symlinked_config.case
@@ -0,0 +1,20 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "shared/settings.toml": "[format]\nexclude = [\"keep.md\"]\n",
+    "project/keep.md": "#   Project\n",
+    "shared/keep.md": "#   Shared\n"
+  },
+  "symlinks": {"project/config.toml": "shared/settings.toml"}
+}
+-- args
+format --config project/config.toml project/keep.md shared/keep.md
+-- stdin
+-- stdout
+2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
+-- stderr
+-- git-worktree
+{"project/keep.md": "#   Project\n", "shared/keep.md": "# Shared\n"}
+-- status
+0
diff --git a/tests/cases/config_exclude_symlinked_config.case b/tests/cases/config_exclude_symlinked_config.case
new file mode 100644
index 00000000..2cf9594e
--- /dev/null
+++ b/tests/cases/config_exclude_symlinked_config.case
@@ -0,0 +1,19 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "shared/settings.toml": "[format]\nexclude = [\"keep.md\"]\n",
+    "project/keep.md": "#   Keep\n"
+  },
+  "symlinks": {"project/yamark.toml": "shared/settings.toml"}
+}
+-- args
+format project/keep.md
+-- stdin
+-- stdout
+1 files scanned, 0 formatted, 0 unchanged, 1 skipped, 0 failed
+-- stderr
+-- git-worktree
+{"project/keep.md": "#   Keep\n"}
+-- status
+0

From b6dd2f0c02915431ef264d6603b95b251fda4d28 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:45:40 -0500
Subject: [PATCH 08/64] Keep surviving symlink names when resolving parent
 paths

---
 src/config.rs                                 | 40 +++++++++++--------
 ...nfig_exclude_symlink_parent_component.case | 27 +++++++++++++
 2 files changed, 50 insertions(+), 17 deletions(-)
 create mode 100644 tests/cases/config_exclude_symlink_parent_component.case

diff --git a/src/config.rs b/src/config.rs
index 2d9fd482..b025ed51 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -220,24 +220,30 @@ impl Config {
     }
 }
 
-/// Resolves an absolute `path` through its last `..` component using the
-/// filesystem when possible, keeping later names as written.
-///
-/// The filesystem resolves `..` after following symlinks, so collapsing it
-/// lexically could name a different file.
+/// Preserve written symlink names while resolving each `..` to its filesystem
+/// parent. A missing directory in a virtual stdin path has only a lexical parent.
 fn resolve_parent_components(path: &Path) -> PathBuf {
-    let components = path.components().collect::>();
-    let Some(last_parent) = components
-        .iter()
-        .rposition(|component| *component == Component::ParentDir)
-    else {
-        return push_normalized(PathBuf::new(), path);
-    };
-    let (resolved, written) = components.split_at(last_parent + 1);
-    push_normalized(
-        absolute_normalized_path(&resolved.iter().collect::()),
-        &written.iter().collect::(),
-    )
+    let mut written = PathBuf::new();
+    for component in path.components() {
+        if component != Component::ParentDir {
+            written.push(component.as_os_str());
+            continue;
+        }
+        let parent = fs::canonicalize(written.join(".."));
+        written.pop();
+        if let Ok(parent) = parent {
+            // A symlink followed by `..` can land elsewhere. Keep the deepest
+            // written prefix that still leads to this parent.
+            written = written
+                .ancestors()
+                .find_map(|prefix| {
+                    let resolved = fs::canonicalize(prefix).ok()?;
+                    Some(prefix.join(parent.strip_prefix(resolved).ok()?))
+                })
+                .unwrap_or(parent);
+        }
+    }
+    written
 }
 
 fn absolute_normalized_path(path: &Path) -> PathBuf {
diff --git a/tests/cases/config_exclude_symlink_parent_component.case b/tests/cases/config_exclude_symlink_parent_component.case
new file mode 100644
index 00000000..f08f7d5a
--- /dev/null
+++ b/tests/cases/config_exclude_symlink_parent_component.case
@@ -0,0 +1,27 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "project/yamark.toml": "[format]\nexclude = [\"/slides/\"]\n",
+    "assets/sub/.keep": "",
+    "assets/deck.md": "#   Slides\n",
+    "assets/handout.md": "#   Handout\n",
+    "assets/talk/handout.md": "#   Handout\n",
+    "assets/talk/notes/.keep": ""
+  },
+  "symlinks": {"project/slides": "assets", "assets/notes": "assets/talk/notes"}
+}
+-- args
+format project/slides/sub/../deck.md project/slides/notes/../handout.md
+-- stdin
+-- stdout
+2 files scanned, 0 formatted, 0 unchanged, 2 skipped, 0 failed
+-- stderr
+-- git-worktree
+{
+  "assets/deck.md": "#   Slides\n",
+  "assets/handout.md": "#   Handout\n",
+  "assets/talk/handout.md": "#   Handout\n"
+}
+-- status
+0

From e66dd5968d1513b803845c21109cdadb0ff2879f Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:49:08 -0500
Subject: [PATCH 09/64] Illustrate exclusion roots and literal brace patterns

---
 website/reference-config.html.md | 11 +++++++----
 website/reference-config.qmd     | 11 +++++++----
 2 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/website/reference-config.html.md b/website/reference-config.html.md
index e502354b..7e0349ac 100644
--- a/website/reference-config.html.md
+++ b/website/reference-config.html.md
@@ -41,10 +41,13 @@ exclude = ["slides/", "*.generated.md", "/NEWS.md"]
 `exclude` lists files that `yamark format` leaves unchanged. Patterns use
 [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) and are
 relative to the directory containing `yamark.toml` or the file passed with
-`--config`. Names below that directory are matched as written, so a symbolic
-link matches by its own name, not its target's. A pattern without a slash
-matches at any depth. A leading slash anchors the pattern to the config
-directory, and a trailing slash matches a directory and everything below it. A
+`--config`. For example, if `project/yamark.toml` is a symbolic link to shared
+settings, `/NEWS.md` selects `project/NEWS.md`. Names below the config
+directory match as written, including symbolic link names.
+
+A pattern without a slash matches at any depth. Braces match literally, so
+`{id}.md` selects files named `{id}.md`. A leading slash anchors the pattern to
+the config directory, and a trailing slash matches a directory and everything below it. A
 later `!` pattern re-includes a file matched by a file-level pattern. As in
 Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
diff --git a/website/reference-config.qmd b/website/reference-config.qmd
index e502354b..7e0349ac 100644
--- a/website/reference-config.qmd
+++ b/website/reference-config.qmd
@@ -41,10 +41,13 @@ exclude = ["slides/", "*.generated.md", "/NEWS.md"]
 `exclude` lists files that `yamark format` leaves unchanged. Patterns use
 [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) and are
 relative to the directory containing `yamark.toml` or the file passed with
-`--config`. Names below that directory are matched as written, so a symbolic
-link matches by its own name, not its target's. A pattern without a slash
-matches at any depth. A leading slash anchors the pattern to the config
-directory, and a trailing slash matches a directory and everything below it. A
+`--config`. For example, if `project/yamark.toml` is a symbolic link to shared
+settings, `/NEWS.md` selects `project/NEWS.md`. Names below the config
+directory match as written, including symbolic link names.
+
+A pattern without a slash matches at any depth. Braces match literally, so
+`{id}.md` selects files named `{id}.md`. A leading slash anchors the pattern to
+the config directory, and a trailing slash matches a directory and everything below it. A
 later `!` pattern re-includes a file matched by a file-level pattern. As in
 Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config

From cae990fc0db5c88587c6997497ddcd8a458c278e Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:55:58 -0500
Subject: [PATCH 10/64] Accept Git filter filenames beginning with a dash

---
 src/cli/git_filter.rs                          | 4 ++--
 tests/cases/git_filter_clean_leading_dash.case | 9 +++++++++
 2 files changed, 11 insertions(+), 2 deletions(-)
 create mode 100644 tests/cases/git_filter_clean_leading_dash.case

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 0dc0231f..2b33759a 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -30,11 +30,11 @@ use process::{
 #[derive(Debug, Subcommand)]
 pub(super) enum GitFilterCommand {
     Clean {
-        #[arg(long)]
+        #[arg(long, allow_hyphen_values = true)]
         stdin_filename: PathBuf,
     },
     Smudge {
-        #[arg(long)]
+        #[arg(long, allow_hyphen_values = true)]
         stdin_filename: PathBuf,
         #[arg(long, default_value_t = 72, value_parser = parse_positive_usize)]
         markdown_wrap_at_column: usize,
diff --git a/tests/cases/git_filter_clean_leading_dash.case b/tests/cases/git_filter_clean_leading_dash.case
new file mode 100644
index 00000000..93630907
--- /dev/null
+++ b/tests/cases/git_filter_clean_leading_dash.case
@@ -0,0 +1,9 @@
+-- args
+git-filter clean --stdin-filename -leading.md
+-- stdin
+#   Title
+-- stdout
+# Title
+-- stderr
+-- status
+0

From cdaf3686b8bcd6777e7fdebfa2e37607ccd3c085 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:58:02 -0500
Subject: [PATCH 11/64] Use the incoming Git configuration when smudging a
 checkout

---
 docs/ARCHITECTURE.md                          |   2 +
 external-tests/cli/test_git_filter.py         |   4 +-
 src/cli.rs                                    |  12 +-
 src/cli/git_filter.rs                         |  67 +++--
 src/cli/git_filter/checkout.rs                | 262 ++++++++++++++++++
 src/cli/git_filter/driver.rs                  | 200 +++++++++++++
 src/config.rs                                 |   5 +-
 .../cases/git_filter_smudge_source_tree.case  |  20 ++
 tests/git_filter_paths.rs                     | 160 ++++++++++-
 tests/website.rs                              |   2 +
 website/git-filter.qmd                        |  14 +
 11 files changed, 722 insertions(+), 26 deletions(-)
 create mode 100644 src/cli/git_filter/checkout.rs
 create mode 100644 src/cli/git_filter/driver.rs
 create mode 100644 tests/cases/git_filter_smudge_source_tree.case

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 8702420d..7a3be8ba 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,6 +98,8 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
+The Git process filter delegates each request to the configured clean or smudge command, including per-invocation Git overrides. Smudge finds the nearest tracked `yamark.toml` in the tree supplied by Git or in the index when Git omits the tree. Reading this configuration before decoding the blob keeps exclusions independent of checkout order. Clean and direct smudge invocations without `--source-tree` discover configuration in the working tree.
+
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 
 The editor extension passes text to the CLI and applies returned edits. It does not maintain an independent Markdown or YAML formatter.
diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index b35ac99e..4b2be3aa 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -63,6 +63,7 @@ def test_git_filter_help_explains_git_config_and_attributes() -> None:
                 '"yamark git-filter smudge --stdin-filename %f '
                 '--markdown-wrap-at-column 72"'
             ),
+            'git config filter.yamark-md.process "yamark git-filter process"',
             "Git only runs the filter for paths matched by attributes",
             "*.md filter=yamark-md",
             "*.qmd filter=yamark-md",
@@ -431,7 +432,7 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         result = run_yamark(repo, "git-filter", "teardown")
 
         assert "Removed yamark Git filter setup" in result.stdout
-        assert "Unset 4 local Git config value(s)" in result.stdout
+        assert "Unset 5 local Git config value(s)" in result.stdout
         assert "Removed 1 yamark attribute pattern(s)" in result.stdout
         assert attributes_path.read_text(encoding="utf-8") == (
             "NEWS.md -filter\n"
@@ -445,6 +446,7 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         for key in [
             "filter.yamark-md.clean",
             "filter.yamark-md.smudge",
+            "filter.yamark-md.process",
             "filter.yamark-md.required",
             "merge.renormalize",
         ]:
diff --git a/src/cli.rs b/src/cli.rs
index 6121d988..0e5f652c 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -116,6 +116,7 @@ Configure the filter driver with:
   yamark git-filter teardown
   git config filter.yamark-md.clean \"yamark git-filter clean --stdin-filename %f\"
   git config filter.yamark-md.smudge \"yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72\"
+  git config filter.yamark-md.process \"yamark git-filter process\"
 
 Git only runs the filter for paths matched by attributes. Put these patterns in
 .git/info/attributes for personal use or .gitattributes for a shared repo:
@@ -362,7 +363,12 @@ fn run_format(
     };
 
     if let Some(path) = stdin_file_path {
-        return run_stdin(path, config, options, execution);
+        return run_stdin(
+            path,
+            |path| load_config_for_formatted_path(path, config.as_deref()),
+            options,
+            execution,
+        );
     }
 
     let mode = if diff {
@@ -417,7 +423,7 @@ fn run_format(
 
 fn run_stdin(
     path: PathBuf,
-    config: Option,
+    load_config: impl FnOnce(&Path) -> crate::diagnostic::Result,
     options: FormatOptions,
     execution: FormatExecutionOptions,
 ) -> ExitCode {
@@ -428,7 +434,7 @@ fn run_stdin(
             return ExitCode::from(1);
         }
     };
-    let config = match load_config_for_formatted_path(&path, config.as_deref()) {
+    let config = match load_config(&path) {
         Ok(config) => config,
         Err(err) => {
             eprintln!("{}", err.diagnostic.render());
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 2b33759a..9db50499 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -1,6 +1,8 @@
 //! Git clean/smudge commands and repository adoption lifecycle.
 
 mod attributes;
+mod checkout;
+mod driver;
 mod process;
 
 use std::env;
@@ -13,9 +15,10 @@ use std::process::{Command as ProcessCommand, ExitCode};
 use clap::Subcommand;
 
 use super::{parse_positive_usize, run_stdin};
+use crate::config::Config;
 use crate::core::document::{FormatOptions, MarkdownWrap};
 use crate::workspace::{
-    FormatExecutionOptions, format_source_for_path_with_overrides, load_config_for_formatted_path,
+    FormatExecutionOptions, format_source_with_config, load_config_for_formatted_path,
 };
 use attributes::{
     append_missing_attribute_lines, count_yamark_filter_attribute_lines,
@@ -36,9 +39,13 @@ pub(super) enum GitFilterCommand {
     Smudge {
         #[arg(long, allow_hyphen_values = true)]
         stdin_filename: PathBuf,
+        #[arg(long, help = "Read configuration from this Git tree during checkout")]
+        source_tree: Option,
         #[arg(long, default_value_t = 72, value_parser = parse_positive_usize)]
         markdown_wrap_at_column: usize,
     },
+    #[command(about = "Serve Git's process filter protocol for checkout-aware smudging")]
+    Process,
     #[command(about = "Adopt the yamark Git filter for a shared repository")]
     Adopt {
         #[arg(
@@ -145,15 +152,18 @@ pub(super) enum GitFilterCommand {
 pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     match command {
         GitFilterCommand::Clean { stdin_filename } => {
-            run_git_filter(stdin_filename, MarkdownWrap::Sentence)
+            run_git_filter(stdin_filename, MarkdownWrap::Sentence, None)
         }
         GitFilterCommand::Smudge {
             stdin_filename,
             markdown_wrap_at_column,
+            source_tree,
         } => run_git_filter(
             stdin_filename,
             MarkdownWrap::Column(markdown_wrap_at_column),
+            source_tree.or_else(|| env::var(driver::SOURCE_TREE_ENV).ok()),
         ),
+        GitFilterCommand::Process => driver::run(),
         GitFilterCommand::Adopt {
             repo,
             yamark,
@@ -179,7 +189,7 @@ pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     }
 }
 
-fn run_git_filter(path: PathBuf, wrap: MarkdownWrap) -> ExitCode {
+fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source_tree: Option) -> ExitCode {
     if crate::core::document::FileKind::for_path(&path) != crate::core::document::FileKind::Markdown
     {
         eprintln!("{}:1:1: error: unsupported Git filter path", path.display());
@@ -193,7 +203,10 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap) -> ExitCode {
     };
     run_stdin(
         path,
-        None,
+        |path| match source_tree {
+            Some(tree) => checkout::config_for_path(Path::new("."), &tree, path),
+            None => load_config_for_formatted_path(path, None),
+        },
         options,
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
@@ -413,11 +426,16 @@ enum BlobSource {
 }
 
 impl BlobSource {
+    fn tree(self) -> &'static str {
+        match self {
+            Self::Head => "HEAD",
+            Self::Index => "",
+        }
+    }
+
     fn spec(self, path: &Path) -> OsString {
-        let mut spec = OsString::from(match self {
-            Self::Head => "HEAD:",
-            Self::Index => ":",
-        });
+        let mut spec = OsString::from(self.tree());
+        spec.push(":");
         spec.push(path);
         spec
     }
@@ -448,6 +466,11 @@ fn configure_git_filter(
         ),
     )?;
     run_git_config(repo_root, "filter.yamark-md.required", "true")?;
+    run_git_config(
+        repo_root,
+        "filter.yamark-md.process",
+        &format!("{yamark} git-filter process"),
+    )?;
     run_git_config(repo_root, "merge.renormalize", "true")
 }
 
@@ -480,6 +503,7 @@ fn ensure_no_local_yamark_filter_setup(
     for key in [
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
+        "filter.yamark-md.process",
         "filter.yamark-md.required",
         "merge.renormalize",
     ] {
@@ -598,20 +622,21 @@ fn verify_roundtrip(
 ) -> Result<(), String> {
     let mut failures = Vec::new();
     for path in paths {
-        // Discover configuration beside the target file even when --repo
-        // selects a repository outside the caller's working directory.
         let source_path = repo_root.join(path);
-        // Excluded files pass through the filters byte for byte.
-        let excluded = load_config_for_formatted_path(&source_path, None)
-            .map_err(|err| err.diagnostic.render())?
-            .excludes(&source_path);
-        if excluded {
+        let config = checkout::config_for_path(repo_root, source.tree(), path)
+            .map_err(|err| err.diagnostic.render())?;
+        if config.excludes(&source_path) {
             continue;
         }
         let blob = git_blob(repo_root, source, path)?;
-        let smudged =
-            format_git_filter_text(&source_path, blob.clone(), MarkdownWrap::Column(width))?;
-        let cleaned = format_git_filter_text(&source_path, smudged, MarkdownWrap::Sentence)?;
+        let smudged = format_git_filter_text(
+            &source_path,
+            blob.clone(),
+            MarkdownWrap::Column(width),
+            &config,
+        )?;
+        let cleaned =
+            format_git_filter_text(&source_path, smudged, MarkdownWrap::Sentence, &config)?;
         if cleaned != blob {
             failures.push(format!(
                 "{}: roundtrip failure: clean(smudge(blob)) != blob",
@@ -664,6 +689,7 @@ fn format_git_filter_text(
     path: &Path,
     input: String,
     wrap: MarkdownWrap,
+    config: &Config,
 ) -> Result {
     let options = FormatOptions {
         markdown_wrap: wrap,
@@ -671,11 +697,11 @@ fn format_git_filter_text(
         respect_frontmatter_markdown_options: false,
         ..FormatOptions::default()
     };
-    format_source_for_path_with_overrides(
+    format_source_with_config(
         path,
         input,
         options,
-        None,
+        config,
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
             ..FormatExecutionOptions::default()
@@ -746,6 +772,7 @@ fn unset_git_filter_config(repo_root: &Path) -> Result {
     [
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
+        "filter.yamark-md.process",
         "filter.yamark-md.required",
         "merge.renormalize",
     ]
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
new file mode 100644
index 00000000..2cc51939
--- /dev/null
+++ b/src/cli/git_filter/checkout.rs
@@ -0,0 +1,262 @@
+//! Resolve checkout configuration from the incoming Git tree or stage-zero index.
+//! Git may invoke smudge before materializing the configuration in the worktree.
+
+use std::collections::VecDeque;
+use std::ffi::OsString;
+use std::path::{Component, Path, PathBuf};
+use std::process::{Command, Stdio};
+
+use super::driver::{native_path, run_with_input};
+use super::process::{git_stdout, git_stdout_bytes};
+use crate::config::Config;
+use crate::diagnostic::{Result, YamarkError};
+
+struct Entry {
+    oid: String,
+    symlink: bool,
+}
+
+pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result {
+    let path = path.strip_prefix(".").unwrap_or(path);
+    if path.as_os_str().is_empty()
+        || !path
+            .components()
+            .all(|part| matches!(part, Component::Normal(_)))
+    {
+        return Err(YamarkError::new(
+            "Git checkout requires a repository-relative filename",
+        ));
+    }
+    let candidates: Vec<_> = path
+        .ancestors()
+        .skip(1)
+        .map(|dir| dir.join("yamark.toml"))
+        .collect();
+    let Some((config_path, entry)) = nearest_entry(repo_root, tree, &candidates)? else {
+        return Ok(Config::default());
+    };
+    let bytes = if entry.symlink && !tree.is_empty() {
+        tree_symlink_contents(repo_root, tree, &config_path)
+    } else {
+        blob_contents(repo_root, &config_path, entry)
+    }
+    .map_err(|err| err.with_path(&config_path))?;
+    let input = std::str::from_utf8(&bytes).map_err(|err| {
+        YamarkError::new(format!("invalid config encoding: {err}")).with_path(&config_path)
+    })?;
+    let mut config = Config::from_toml_str(input).map_err(|err| err.with_path(&config_path))?;
+    // Git paths start at the worktree root. The nested directory itself may
+    // still be absent, or contain a symlink from the checkout being replaced.
+    let root = std::fs::canonicalize(repo_root).map_err(|err| YamarkError::new(err.to_string()))?;
+    let dir = config_path.parent().expect("a config has a parent");
+    config.config_dir = Some(root.join(dir));
+    Ok(config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor")))
+}
+
+/// Candidates are ordered nearest first. Use literal pathspecs and NUL-delimited
+/// Git records so filenames are never treated as globs or display-quoted text.
+fn nearest_entry(
+    repo: &Path,
+    tree: &str,
+    candidates: &[PathBuf],
+) -> Result> {
+    let mut args = Vec::new();
+    if tree.is_empty() {
+        args.extend(
+            ["--no-literal-pathspecs", "ls-files", "--stage", "-z", "--"].map(OsString::from),
+        );
+        for path in candidates {
+            let mut literal = OsString::from(":(top,literal)");
+            literal.push(git_path(path));
+            args.push(literal);
+            if !candidates
+                .iter()
+                .any(|other| other != path && other.starts_with(path))
+            {
+                // An exact directory argument to ls-files would list every
+                // tracked descendant. We need only a stage-zero file entry.
+                let mut descendants = OsString::from(":(top,exclude,literal)");
+                descendants.push(git_path(path));
+                descendants.push("/");
+                args.push(descendants);
+            }
+        }
+    } else {
+        args.extend(
+            [
+                "--literal-pathspecs",
+                "ls-tree",
+                "--full-tree",
+                "-z",
+                "--end-of-options",
+                tree,
+                "--",
+            ]
+            .map(OsString::from),
+        );
+        args.extend(candidates.iter().map(|path| git_path(path)));
+    }
+    let records = git_stdout_bytes(repo, args).map_err(YamarkError::new)?;
+    let mut nearest = None;
+    for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
+        let tab = record
+            .iter()
+            .position(|&byte| byte == b'\t')
+            .ok_or_else(|| YamarkError::new("invalid Git entry record"))?;
+        let path = Path::new(
+            native_path(&record[tab + 1..]).map_err(|err| YamarkError::new(err.to_string()))?,
+        );
+        let Some(rank) = candidates.iter().position(|candidate| candidate == path) else {
+            continue;
+        };
+        let fields = record[..tab]
+            .split(|&byte| byte == b' ')
+            .collect::>();
+        let [mode, second, third] = fields.as_slice() else {
+            return Err(YamarkError::new("invalid Git entry metadata"));
+        };
+        let oid = if tree.is_empty() {
+            if *third != b"0" {
+                continue;
+            }
+            second
+        } else {
+            third
+        };
+        if !matches!(*mode, b"100644" | b"100755" | b"120000") {
+            continue;
+        }
+        if nearest.as_ref().is_none_or(|(best, _)| rank < *best) {
+            let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
+            nearest = Some((
+                rank,
+                Entry {
+                    oid: oid.to_owned(),
+                    symlink: *mode == b"120000",
+                },
+            ));
+        }
+    }
+    Ok(nearest.map(|(rank, entry)| (candidates[rank].clone(), entry)))
+}
+
+fn tree_symlink_contents(repo: &Path, tree: &str, path: &Path) -> Result> {
+    // A tree expression can itself be a subtree, e.g. HEAD:docs. Use its OID
+    // before appending the Git path. NUL input also accepts literal newlines.
+    let tree = git_stdout(repo, ["rev-parse", "--verify", "--end-of-options", tree])
+        .map_err(YamarkError::new)?;
+    let mut query = tree.trim_end().as_bytes().to_vec();
+    query.push(b':');
+    query.extend_from_slice(git_path(path).as_encoded_bytes());
+    let mut command = Command::new("git");
+    command
+        .arg("-C")
+        .arg(repo)
+        .args(["cat-file", "--batch=%(objecttype)", "--follow-symlinks"]);
+    if query.contains(&b'\n') {
+        command.arg("-z");
+        query.push(0);
+    } else {
+        query.push(b'\n');
+    }
+    let output =
+        run_with_input(&mut command, &query).map_err(|err| YamarkError::new(err.to_string()))?;
+    if !output.status.success() {
+        return Err(YamarkError::new(format!(
+            "git cat-file failed with {}",
+            output.status
+        )));
+    }
+    if output.stdout.starts_with(b"symlink ") {
+        return Err(YamarkError::new(
+            "config symlink points outside the checkout",
+        ));
+    }
+    output
+        .stdout
+        .strip_prefix(b"blob\n")
+        .and_then(|data| data.strip_suffix(b"\n"))
+        .map(Vec::from)
+        .ok_or_else(|| YamarkError::new("config symlink has no file target in checkout"))
+}
+
+fn blob_contents(repo: &Path, path: &Path, mut entry: Entry) -> Result> {
+    // cat-file --follow-symlinks handles tree paths, but :path returns the
+    // link blob itself. Resolve staged links exclusively against the index.
+    let mut current = path.to_path_buf();
+    let mut pending = VecDeque::new();
+    let mut links = 0;
+    loop {
+        let bytes =
+            git_stdout_bytes(repo, ["cat-file", "blob", &entry.oid]).map_err(YamarkError::new)?;
+        if !entry.symlink {
+            return if pending.is_empty() {
+                Ok(bytes)
+            } else {
+                Err(YamarkError::new("config symlink traverses a regular file"))
+            };
+        }
+        links += 1;
+        if links > 40 {
+            return Err(YamarkError::new("too many config symlinks in checkout"));
+        }
+        current.pop();
+        let target =
+            Path::new(native_path(&bytes).map_err(|err| YamarkError::new(err.to_string()))?);
+        for part in target.components().rev() {
+            pending.push_front(part.as_os_str().to_owned());
+        }
+        loop {
+            let next = pending
+                .pop_front()
+                .ok_or_else(|| YamarkError::new("config symlink has no file target in checkout"))?;
+            match Path::new(&next).components().next() {
+                Some(Component::CurDir) => continue,
+                Some(Component::ParentDir) if !current.as_os_str().is_empty() => {
+                    // A directory removed by '..' must exist too. Ancestors of
+                    // the staged config already have a tracked descendant.
+                    if !path.starts_with(¤t) {
+                        let status = Command::new("git")
+                            .arg("-C")
+                            .arg(repo)
+                            .args(["--literal-pathspecs", "ls-files", "--error-unmatch", "--"])
+                            .arg(git_path(¤t))
+                            .stdout(Stdio::null())
+                            .stderr(Stdio::null())
+                            .status()
+                            .map_err(|err| YamarkError::new(err.to_string()))?;
+                        if !status.success() {
+                            return Err(YamarkError::new(
+                                "config symlink traverses a missing directory",
+                            ));
+                        }
+                    }
+                    current.pop();
+                    continue;
+                }
+                Some(Component::Normal(name)) => current.push(name),
+                _ => {
+                    return Err(YamarkError::new(
+                        "config symlink points outside the checkout",
+                    ));
+                }
+            }
+            if let Some((_, found)) = nearest_entry(repo, "", std::slice::from_ref(¤t))? {
+                entry = found;
+                break;
+            }
+        }
+    }
+}
+
+// Git object expressions and literal pathspecs use '/' on Windows as well.
+fn git_path(path: &Path) -> OsString {
+    let mut out = OsString::new();
+    for name in path.iter() {
+        if !out.is_empty() {
+            out.push("/");
+        }
+        out.push(name);
+    }
+    out
+}
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
new file mode 100644
index 00000000..dc14ddea
--- /dev/null
+++ b/src/cli/git_filter/driver.rs
@@ -0,0 +1,200 @@
+//! Git's v2 process filter supplies the tree being checked out for each smudge.
+//! Keep the configured single-file commands authoritative, including -c overrides.
+
+use std::ffi::OsStr;
+use std::io::{self, BufRead, Read, Write};
+use std::process::{Command, ExitCode, Stdio};
+
+pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
+
+pub(super) fn run() -> ExitCode {
+    match serve() {
+        Ok(()) => ExitCode::SUCCESS,
+        Err(err) => {
+            eprintln!("error: Git filter process: {err}");
+            ExitCode::FAILURE
+        }
+    }
+}
+
+fn serve() -> io::Result<()> {
+    let mut input = io::stdin().lock();
+    let mut output = io::stdout().lock();
+    let hello = read_section(&mut input)?;
+    if hello.first().map(Vec::as_slice) != Some(b"git-filter-client\n")
+        || !hello.iter().any(|line| line == b"version=2\n")
+    {
+        return Err(io::Error::other("expected git-filter-client version 2"));
+    }
+    write_section(&mut output, &[b"git-filter-server\n", b"version=2\n"])?;
+    let caps = read_section(&mut input)?;
+    let accepted: Vec<_> = caps
+        .iter()
+        .map(Vec::as_slice)
+        .filter(|&cap| cap == b"capability=clean\n" || cap == b"capability=smudge\n")
+        .collect();
+    write_section(&mut output, &accepted)?;
+
+    let clean = driver_command("filter.yamark-md.clean")?;
+    let smudge = driver_command("filter.yamark-md.smudge")?;
+    while !input.fill_buf()?.is_empty() {
+        let fields = read_section(&mut input)?;
+        let mut contents = Vec::new();
+        while read_packet(&mut input, &mut contents)? {}
+        match filter_file(&fields, &contents, &clean, &smudge) {
+            Ok(bytes) => {
+                write_section(&mut output, &[b"status=success\n"])?;
+                for chunk in bytes.chunks(65516) {
+                    write_packet(&mut output, chunk)?;
+                }
+                output.write_all(b"00000000")?;
+                output.flush()?;
+            }
+            Err(err) => {
+                eprintln!("error: Git filter process: {err}");
+                write_section(&mut output, &[b"status=error\n"])?;
+            }
+        }
+    }
+    Ok(())
+}
+
+fn filter_file(
+    fields: &[Vec],
+    contents: &[u8],
+    clean: &str,
+    smudge: &str,
+) -> io::Result> {
+    let field = |prefix: &[u8]| {
+        fields.iter().find_map(|line| {
+            line.strip_suffix(b"\n")
+                .unwrap_or(line)
+                .strip_prefix(prefix)
+        })
+    };
+    let path = field(b"pathname=").ok_or_else(|| io::Error::other("missing pathname"))?;
+    let (command, tree) = match field(b"command=") {
+        Some(b"clean") => (clean, None),
+        // Without a tree (e.g. checkout-index), Git smudges from the index.
+        Some(b"smudge") => (smudge, Some(field(b"treeish=").unwrap_or(b""))),
+        _ => return Err(io::Error::other("unknown filter command")),
+    };
+    let mut child = Command::new("git");
+    // Git supplies the shell on every platform. Keep native path bytes
+    // out of shell source and expand them as one quoted argument.
+    child
+        .arg("-c")
+        .arg(command)
+        .arg("yamark-single-file")
+        .env("YAMARK_GIT_FILTER_PATH", native_path(path)?)
+        .env_remove(SOURCE_TREE_ENV);
+    if let Some(tree) = tree {
+        child.env(
+            SOURCE_TREE_ENV,
+            std::str::from_utf8(tree).map_err(io::Error::other)?,
+        );
+    }
+    let result = run_with_input(&mut child, contents)?;
+    if !result.status.success() {
+        return Err(io::Error::other(format!(
+            "single-file filter exited with {}",
+            result.status
+        )));
+    }
+    Ok(result.stdout)
+}
+
+fn driver_command(key: &str) -> io::Result {
+    let text = super::git_stdout(std::path::Path::new("."), ["config", "--get", key])
+        .map_err(io::Error::other)?;
+    let mut chars = text.trim_end_matches('\n').chars().peekable();
+    let mut alias = String::from("alias.yamark-single-file=!");
+    while let Some(ch) = chars.next() {
+        if ch == '%' && chars.next_if_eq(&'f').is_some() {
+            alias.push_str("\"$YAMARK_GIT_FILTER_PATH\"");
+        } else if ch == '%' && chars.next_if_eq(&'%').is_some() {
+            alias.push('%');
+        } else {
+            alias.push(ch);
+        }
+    }
+    Ok(alias)
+}
+
+pub(super) fn native_path(bytes: &[u8]) -> io::Result<&OsStr> {
+    #[cfg(unix)]
+    {
+        use std::os::unix::ffi::OsStrExt;
+        Ok(OsStr::from_bytes(bytes))
+    }
+    #[cfg(not(unix))]
+    {
+        std::str::from_utf8(bytes)
+            .map(OsStr::new)
+            .map_err(io::Error::other)
+    }
+}
+
+pub(super) fn run_with_input(
+    command: &mut Command,
+    bytes: &[u8],
+) -> io::Result {
+    let mut child = command
+        .stdin(Stdio::piped())
+        .stdout(Stdio::piped())
+        .spawn()?;
+    let mut stdin = child.stdin.take().expect("piped stdin");
+    std::thread::scope(|scope| {
+        let writer = scope.spawn(move || stdin.write_all(bytes));
+        let output = child.wait_with_output()?;
+        let written = writer.join().expect("stdin writer panicked");
+        if let Err(err) = written
+            && err.kind() != io::ErrorKind::BrokenPipe
+        {
+            return Err(err);
+        }
+        Ok(output)
+    })
+}
+
+fn read_section(reader: &mut impl Read) -> io::Result>> {
+    let mut packets = Vec::new();
+    loop {
+        let mut bytes = Vec::new();
+        if !read_packet(reader, &mut bytes)? {
+            return Ok(packets);
+        }
+        packets.push(bytes);
+    }
+}
+
+/// Append one payload, or report the flush that terminates this section.
+fn read_packet(reader: &mut impl Read, bytes: &mut Vec) -> io::Result {
+    let mut header = [0; 4];
+    reader.read_exact(&mut header)?;
+    if &header == b"0000" {
+        return Ok(false);
+    }
+    let len = std::str::from_utf8(&header)
+        .ok()
+        .and_then(|s| usize::from_str_radix(s, 16).ok())
+        .filter(|len| (4..=65520).contains(len))
+        .ok_or_else(|| io::Error::other("invalid Git packet length"))?;
+    let start = bytes.len();
+    bytes.resize(start + (len - 4), 0);
+    reader.read_exact(&mut bytes[start..])?;
+    Ok(true)
+}
+
+fn write_packet(writer: &mut impl Write, bytes: &[u8]) -> io::Result<()> {
+    write!(writer, "{:04x}", bytes.len() + 4)?;
+    writer.write_all(bytes)
+}
+
+fn write_section(writer: &mut impl Write, lines: &[&[u8]]) -> io::Result<()> {
+    for line in lines {
+        write_packet(writer, line)?;
+    }
+    writer.write_all(b"0000")?;
+    writer.flush()
+}
diff --git a/src/config.rs b/src/config.rs
index b025ed51..d1f56612 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -136,8 +136,11 @@ impl Config {
         if self.path_configs.is_empty() {
             return self.clone();
         }
+        self.for_relative_path(&self.relative_formatted_path(path))
+    }
+
+    pub(crate) fn for_relative_path(&self, relative: &Path) -> Self {
         let mut config = self.clone();
-        let relative = self.relative_formatted_path(path);
         let mut matching = self
             .path_configs
             .iter()
diff --git a/tests/cases/git_filter_smudge_source_tree.case b/tests/cases/git_filter_smudge_source_tree.case
new file mode 100644
index 00000000..706e18eb
--- /dev/null
+++ b/tests/cases/git_filter_smudge_source_tree.case
@@ -0,0 +1,20 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "incoming/docs/yamark.toml": "[format]\nexclude = [\"NEWS.md\"]\n"
+  }
+}
+-- args
+git-filter smudge --source-tree HEAD:incoming --stdin-filename docs/NEWS.md
+-- stdin
+#   News
+
+First sentence. Second sentence.
+-- stdout
+#   News
+
+First sentence. Second sentence.
+-- stderr
+-- status
+0
diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index fc2349c4..e2ef5d6b 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -5,7 +5,7 @@ use tempfile::tempdir;
 
 #[test]
 fn git_filter_adopts_quoted_names() {
-    check_git_filter_paths(&["café.md", "with space.md"]);
+    check_git_filter_paths(&["café.md", "with space.md", "-it's $5!.md"]);
 }
 
 // Windows filenames cannot contain line feeds, tabs, quotes, or backslashes.
@@ -192,6 +192,44 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     );
     git(&["commit", "-q", "-m", "adopt"]);
 
+    let copy = tempdir().unwrap();
+    git(&[
+        "worktree",
+        "add",
+        "-q",
+        "--detach",
+        copy.path().to_str().unwrap(),
+        "HEAD",
+    ]);
+    assert_eq!(fs::read(copy.path().join("NEWS.md")).unwrap(), utf16);
+    assert_eq!(
+        fs::read(copy.path().join("post.md")).unwrap(),
+        b"First sentence. Second sentence?\n"
+    );
+    assert!(git(&["-C", copy.path().to_str().unwrap(), "status", "--porcelain"]).is_empty());
+
+    // checkout-index supplies a blob without a source tree. Select its staged
+    // config even while both files are absent from the working directory.
+    fs::remove_file(copy.path().join("NEWS.md")).unwrap();
+    fs::remove_file(copy.path().join("yamark.toml")).unwrap();
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(dir.path())
+        .args(["git-filter", "check", "--repo"])
+        .arg(copy.path())
+        .assert()
+        .success()
+        .stderr("");
+    git(&[
+        "-C",
+        copy.path().to_str().unwrap(),
+        "checkout-index",
+        "--",
+        "NEWS.md",
+        "yamark.toml",
+    ]);
+    assert_eq!(fs::read(copy.path().join("NEWS.md")).unwrap(), utf16);
+
     Command::cargo_bin("yamark")
         .unwrap()
         .current_dir(dir.path())
@@ -206,6 +244,126 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     fs::write(dir.path().join("NEWS.md"), revised).unwrap();
     git(&["add", "NEWS.md"]);
     assert_eq!(git(&["show", ":NEWS.md"]), revised);
+
+    // Switch both ways across a change to a nested config.
+    fs::create_dir(dir.path().join("docs")).unwrap();
+    let ordinary = b"First sentence. Second sentence?\n";
+    fs::write(dir.path().join("docs/notes.md"), ordinary).unwrap();
+    git(&["add", "docs"]);
+    git(&["commit", "-q", "-m", "selected notes"]);
+    let select = String::from_utf8(git(&["rev-parse", "HEAD"])).unwrap();
+    let copy_path = copy.path().to_str().unwrap();
+    git(&["-C", copy_path, "checkout", "-q", "--detach", select.trim()]);
+    assert_eq!(
+        fs::read(copy.path().join("docs/notes.md")).unwrap(),
+        ordinary
+    );
+    fs::write(
+        dir.path().join("docs/yamark.toml"),
+        "[format]\nexclude = [\"notes.md\"]\n",
+    )
+    .unwrap();
+    let excluded = b"#   New\n\nFirst sentence. Second sentence.\n";
+    fs::write(dir.path().join("docs/notes.md"), excluded).unwrap();
+    git(&["add", "docs"]);
+    git(&["commit", "-q", "-m", "excluded notes"]);
+    let skip = String::from_utf8(git(&["rev-parse", "HEAD"])).unwrap();
+    git(&["-C", copy_path, "checkout", "-q", "--detach", skip.trim()]);
+    assert_eq!(
+        fs::read(copy.path().join("docs/notes.md")).unwrap(),
+        excluded
+    );
+    assert!(git(&["-C", copy_path, "status", "--porcelain"]).is_empty());
+    git(&["-C", copy_path, "checkout", "-q", "--detach", select.trim()]);
+    assert_eq!(
+        fs::read(copy.path().join("docs/notes.md")).unwrap(),
+        ordinary
+    );
+    assert!(git(&["-C", copy_path, "status", "--porcelain"]).is_empty());
+
+    let unstaged = b"#   This spelling is intentional\n";
+    fs::write(copy.path().join("docs/notes.md"), unstaged).unwrap();
+    git(&[
+        "-C",
+        copy_path,
+        "-c",
+        "filter.yamark-md.clean=cat",
+        "add",
+        "docs/notes.md",
+    ]);
+    assert_eq!(git(&["-C", copy_path, "show", ":docs/notes.md"]), unstaged);
+}
+
+#[test]
+fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
+    let dir = tempdir().unwrap();
+    let repo = dir.path();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(repo)
+            .args(args)
+            .assert()
+            .success()
+            .get_output()
+            .stdout
+            .clone()
+    };
+    git(&["init", "-q"]);
+    fs::create_dir(repo.join("project")).unwrap();
+    fs::create_dir(repo.join("shared")).unwrap();
+    fs::write(repo.join("project/keep.md"), "#   Keep\n").unwrap();
+    fs::write(
+        repo.join("shared/settings.toml"),
+        "[format]\nexclude = [\"/keep.md\"]\n",
+    )
+    .unwrap();
+    git(&["add", "shared", "project"]);
+    // Stage a Git symlink without requiring the operating system to create one.
+    let link = Command::new("git")
+        .current_dir(repo)
+        .args(["hash-object", "-w", "--stdin"])
+        .write_stdin("../shared/settings.toml")
+        .assert()
+        .success()
+        .get_output()
+        .stdout
+        .clone();
+    let oid = std::str::from_utf8(&link).unwrap().trim();
+    git(&[
+        "update-index",
+        "--add",
+        "--cacheinfo",
+        "120000",
+        oid,
+        "project/yamark.toml",
+    ]);
+    let tree = git(&["write-tree"]);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(repo)
+        .args([
+            "git-filter",
+            "smudge",
+            "--source-tree",
+            std::str::from_utf8(&tree).unwrap().trim(),
+            "--stdin-filename",
+            "project/keep.md",
+        ])
+        .write_stdin("#   Keep\n")
+        .assert()
+        .success()
+        .stdout("#   Keep\n")
+        .stderr("");
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(repo)
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+    assert_eq!(
+        git(&["cat-file", "--filters", ":project/keep.md"]),
+        b"#   Keep\n"
+    );
 }
 
 fn check_git_filter_paths(paths: &[&str]) {
diff --git a/tests/website.rs b/tests/website.rs
index 9411e1e5..70966447 100644
--- a/tests/website.rs
+++ b/tests/website.rs
@@ -1579,6 +1579,8 @@ fn website_documents_editor_and_git_filter_integrations() {
         "yamark git-filter check",
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
+        "filter.yamark-md.process",
+        "--source-tree",
         ".gitattributes",
         "git add --renormalize .",
         "clean(smudge(blob)) == blob",
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index d7b7477f..ad9f6c50 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -29,6 +29,15 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
+During checkout, Git tells the process filter which tree it is reading. Yamark
+looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
+`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git runs the
+filter without specifying a tree, as with `git checkout-index`, smudge reads
+the staged configuration. Clean reads the working-tree config.
+
+Invoking `yamark git-filter smudge` directly uses the working-tree config.
+Pass `--source-tree ` to read configuration from a particular tree.
+
 Unsupported paths fail. The filter is for Markdown-like files, not YAML or
 source files.
 
@@ -132,11 +141,16 @@ Use `--repo path/to/repo` when running from outside the repository. Use
 Setup prints the local files and config keys it changed, plus the commands below
 for undoing or bypassing the filter.
 
+If you already have clean and smudge commands configured, add the
+`filter.yamark-md.process` setting below to use the checkout tree's config.
+`adopt`, `join`, and `setup` install this setting automatically.
+
 To configure the same pieces manually, set the filter driver:
 
 ```sh
 git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
+git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
 git config merge.renormalize true
 ```

From 7820e97a791d0fcbdd8b78cc2834d966331de434 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 09:59:39 -0500
Subject: [PATCH 12/64] Publish checkout filter usage and upgrade instructions

---
 RELEASE_NOTES.md           |  2 ++
 website/cli-help.html.md   |  2 ++
 website/git-filter.html.md | 15 +++++++++++++++
 website/git-filter.qmd     |  5 +++--
 4 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 7d4a1782..bdd10dff 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -4,4 +4,6 @@ To format the current directory in place, use `yamark format .`. Bare `yamark fo
 
 Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yamark formatting. Its gitignore-style patterns are relative to the config directory. Unlike `.gitignore` and `.ignore`, which affect only directory traversal, `exclude` also applies to explicit paths, `--stdin-file-path`, and Git clean and smudge filters. Excluded file paths are counted as skipped, and stdin for an excluded path passes through unchanged. This also applies to editor Format Document and format-on-save; a configured next formatter still runs.
 
+The experimental Git filter now reads the tracked `yamark.toml` from the tree being checked out, so excluded files keep their original bytes in a fresh worktree. New filter installations configure this automatically. To update an existing installation with `yamark` on your path, run `git config filter.yamark-md.process "yamark git-filter process"` in the repository.
+
 `[paths]` overrides now match a `--stdin-file-path` that does not exist on disk on Windows, or when the path passes through a symlinked directory. Previously these paths could fail to match the config directory.
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index 9e59eb5c..5e0c3a3e 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -128,6 +128,7 @@ Configure the filter driver with:
   yamark git-filter teardown
   git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
   git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
+  git config filter.yamark-md.process "yamark git-filter process"
 
 Git only runs the filter for paths matched by attributes. Put these patterns in
 .git/info/attributes for personal use or .gitattributes for a shared repo:
@@ -141,6 +142,7 @@ Git only runs the filter for paths matched by attributes. Put these patterns in
 Commands:
   clean
   smudge
+  process   Serve Git's process filter protocol for checkout-aware smudging
   adopt     Adopt the yamark Git filter for a shared repository
   join      Join a repository that has already adopted the yamark Git filter
   check     Check committed yamark Git filter blobs round-trip safely
diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index d7b7477f..f11fd4db 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -29,6 +29,16 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
+During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
+looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
+`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git runs the
+filter without specifying a tree, as with `git checkout-index`, smudge reads
+the staged configuration. If `yamark.toml` is a symbolic link, its target
+must also be present in that tree or index. Clean reads the working-tree config.
+
+Invoking `yamark git-filter smudge` directly uses the working-tree config.
+Pass `--source-tree ` to read configuration from a particular tree.
+
 Unsupported paths fail. The filter is for Markdown-like files, not YAML or
 source files.
 
@@ -132,11 +142,16 @@ Use `--repo path/to/repo` when running from outside the repository. Use
 Setup prints the local files and config keys it changed, plus the commands below
 for undoing or bypassing the filter.
 
+If you already have clean and smudge commands configured, add the
+`filter.yamark-md.process` setting below to use the checkout tree's config.
+`adopt`, `join`, and `setup` install this setting automatically.
+
 To configure the same pieces manually, set the filter driver:
 
 ```sh
 git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
+git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
 git config merge.renormalize true
 ```
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index ad9f6c50..f11fd4db 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -29,11 +29,12 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
-During checkout, Git tells the process filter which tree it is reading. Yamark
+During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
 looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
 `NEWS.md` applies even if Git checks out `NEWS.md` first. When Git runs the
 filter without specifying a tree, as with `git checkout-index`, smudge reads
-the staged configuration. Clean reads the working-tree config.
+the staged configuration. If `yamark.toml` is a symbolic link, its target
+must also be present in that tree or index. Clean reads the working-tree config.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.

From 0046223b317c40f7c1749732798df54b3ff5b652 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:11:47 -0500
Subject: [PATCH 13/64] Keep Git line-ending conversion out of the smudge
 fixture

---
 tests/git_filter_paths.rs | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index e2ef5d6b..fa236056 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -309,6 +309,8 @@ fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
             .clone()
     };
     git(&["init", "-q"]);
+    // Git's own line-ending conversion is independent of the smudge filter.
+    fs::write(repo.join(".gitattributes"), "project/keep.md -text\n").unwrap();
     fs::create_dir(repo.join("project")).unwrap();
     fs::create_dir(repo.join("shared")).unwrap();
     fs::write(repo.join("project/keep.md"), "#   Keep\n").unwrap();
@@ -317,7 +319,7 @@ fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
         "[format]\nexclude = [\"/keep.md\"]\n",
     )
     .unwrap();
-    git(&["add", "shared", "project"]);
+    git(&["add", ".gitattributes", "shared", "project"]);
     // Stage a Git symlink without requiring the operating system to create one.
     let link = Command::new("git")
         .current_dir(repo)

From 0ac69cf0ee6675993d1b6362474f5de0e6f86e77 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:48:23 -0500
Subject: [PATCH 14/64] Reject unsupported POSIX classes in exclusion patterns

---
 src/config.rs                               | 37 +++++++++++++++++----
 tests/cases/config_exclude_digit_range.case | 22 ++++++++++++
 tests/cases/config_exclude_posix_class.case | 22 ++++++++++++
 website/reference-config.html.md            |  3 ++
 website/reference-config.qmd                |  3 ++
 5 files changed, 81 insertions(+), 6 deletions(-)
 create mode 100644 tests/cases/config_exclude_digit_range.case
 create mode 100644 tests/cases/config_exclude_posix_class.case

diff --git a/src/config.rs b/src/config.rs
index d1f56612..46001058 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -427,7 +427,7 @@ fn parse_exclude(value: &toml::Value) -> Result {
     let mut builder = GitignoreBuilder::new("");
     for pattern in patterns {
         builder
-            .add_line(None, &escape_gitignore_braces(pattern))
+            .add_line(None, &gitignore_pattern(pattern)?)
             .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))?;
     }
     builder
@@ -435,9 +435,12 @@ fn parse_exclude(value: &toml::Value) -> Result {
         .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))
 }
 
-/// Git wildmatch treats braces literally. The glob matcher used by
-/// `GitignoreBuilder` also recognizes brace alternatives.
-fn escape_gitignore_braces(pattern: &str) -> String {
+/// Adapt Git's literal braces and diagnose named classes the glob matcher
+/// would silently interpret as ordinary bracket expressions.
+fn gitignore_pattern(pattern: &str) -> Result {
+    if pattern.starts_with('#') {
+        return Ok(pattern.to_owned());
+    }
     let mut out = String::with_capacity(pattern.len());
     let mut chars = pattern.chars();
     let mut may_have_class = true;
@@ -454,7 +457,29 @@ fn escape_gitignore_braces(pattern: &str) -> String {
                 let rest = chars.as_str();
                 let members = rest.strip_prefix(['!', '^']).unwrap_or(rest);
                 let members = members.strip_prefix(']').unwrap_or(members);
-                if let Some((_, after)) = members.split_once(']') {
+                let mut scan = members.chars();
+                let end = loop {
+                    match scan.next() {
+                        Some(']') => break Some(scan.as_str()),
+                        Some('\\') => {
+                            scan.next();
+                        }
+                        Some('[') => {
+                            if let Some(name) = scan.as_str().strip_prefix(':')
+                                && let Some((name, _)) = name.split_once(":]")
+                                && !name.is_empty()
+                                && name.bytes().all(|b| b.is_ascii_alphabetic())
+                            {
+                                return Err(YamarkError::new(format!(
+                                    "format.exclude: POSIX character class [:{name}:] is unsupported in '{pattern}'"
+                                )));
+                            }
+                        }
+                        Some(_) => {}
+                        None => break None,
+                    }
+                };
+                if let Some(after) = end {
                     out.push_str(&rest[..rest.len() - after.len()]);
                     chars = after.chars();
                 } else {
@@ -464,7 +489,7 @@ fn escape_gitignore_braces(pattern: &str) -> String {
             _ => {}
         }
     }
-    out
+    Ok(out)
 }
 
 fn parse_abbreviations(value: &toml::Value) -> Result {
diff --git a/tests/cases/config_exclude_digit_range.case b/tests/cases/config_exclude_digit_range.case
new file mode 100644
index 00000000..352c3a3b
--- /dev/null
+++ b/tests/cases/config_exclude_digit_range.case
@@ -0,0 +1,22 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nexclude = ['[0-9]*.md']\n",
+    "1-report.md": "#   Report\n",
+    "letter.md": "#   Letter\n"
+  }
+}
+-- args
+format --config yamark.toml 1-report.md letter.md
+-- stdin
+-- stdout
+2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
+-- stderr
+-- git-worktree
+{
+  "1-report.md": "#   Report\n",
+  "letter.md": "# Letter\n"
+}
+-- status
+0
diff --git a/tests/cases/config_exclude_posix_class.case b/tests/cases/config_exclude_posix_class.case
new file mode 100644
index 00000000..92036ff2
--- /dev/null
+++ b/tests/cases/config_exclude_posix_class.case
@@ -0,0 +1,22 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nexclude = ['[[:digit:]]*.md']\n",
+    "1-report.md": "#   Report\n",
+    "letter.md": "#   Letter\n"
+  }
+}
+-- args
+format --config yamark.toml 1-report.md letter.md
+-- stdin
+-- stdout
+-- stderr
+yamark.toml:1:1: error: format.exclude: POSIX character class [:digit:] is unsupported in '[[:digit:]]*.md'
+-- git-worktree
+{
+  "1-report.md": "#   Report\n",
+  "letter.md": "#   Letter\n"
+}
+-- status
+1
diff --git a/website/reference-config.html.md b/website/reference-config.html.md
index 7e0349ac..55342b6e 100644
--- a/website/reference-config.html.md
+++ b/website/reference-config.html.md
@@ -53,6 +53,9 @@ Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
+For ASCII digits, use a range such as `[0-9]*.md`. POSIX named character
+classes such as `[[:digit:]]` cause a configuration error before formatting.
+
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:
 
diff --git a/website/reference-config.qmd b/website/reference-config.qmd
index 7e0349ac..55342b6e 100644
--- a/website/reference-config.qmd
+++ b/website/reference-config.qmd
@@ -53,6 +53,9 @@ Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
+For ASCII digits, use a range such as `[0-9]*.md`. POSIX named character
+classes such as `[[:digit:]]` cause a configuration error before formatting.
+
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:
 

From 0cf0b09bd0f904972a208b28e6278ddf61f8a6e3 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:47:42 -0500
Subject: [PATCH 15/64] Select regular index entries before Git filter adoption

---
 src/cli/git_filter.rs                         | 26 +++++++++++-------
 tests/cases/README.md                         |  2 +-
 .../git_filter_adopt_regular_entries.case     | 27 +++++++++++++++++++
 tests/cli_cases.rs                            |  5 +++-
 website/git-filter.qmd                        |  3 +++
 5 files changed, 51 insertions(+), 12 deletions(-)
 create mode 100644 tests/cases/git_filter_adopt_regular_entries.case

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 9db50499..80b9a7ef 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -569,20 +569,26 @@ fn ensure_shared_yamark_attributes(repo_root: &Path) -> Result<(), String> {
 fn tracked_yamark_filter_paths(repo_root: &Path) -> Result, String> {
     // NUL records contain native filename bytes, not UTF-8 text or Git's
     // presentation quoting. Each check-attr response is path, name, then value.
-    let tracked = git_stdout_bytes(repo_root, ["ls-files", "-z"])?;
+    let tracked = git_stdout_bytes(repo_root, ["ls-files", "--stage", "-z"])?;
     let mut paths = Vec::new();
-    for path in tracked
+    for entry in tracked
         .split(|byte| *byte == 0)
-        .filter(|path| !path.is_empty())
+        .filter(|entry| !entry.is_empty())
     {
-        #[cfg(unix)]
-        let path = {
-            use std::os::unix::ffi::OsStrExt;
-            PathBuf::from(std::ffi::OsStr::from_bytes(path))
-        };
-        #[cfg(not(unix))]
+        let tab = entry
+            .iter()
+            .position(|byte| *byte == b'\t')
+            .ok_or("missing path in git ls-files --stage output")?;
+        let metadata = &entry[..tab];
+        // Only regular, stage-zero blobs belong in the worktree write set.
+        if !(metadata.starts_with(b"100644 ") || metadata.starts_with(b"100755 "))
+            || !metadata.ends_with(b" 0")
+        {
+            continue;
+        }
         let path = PathBuf::from(
-            std::str::from_utf8(path).map_err(|err| format!("git path was not UTF-8: {err}"))?,
+            driver::native_path(&entry[tab + 1..])
+                .map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
         if crate::core::document::FileKind::for_path(&path)
             != crate::core::document::FileKind::Markdown
diff --git a/tests/cases/README.md b/tests/cases/README.md
index b8fd718a..48a94b17 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -64,7 +64,7 @@ The `external_formatter_*.case` transcripts cover formatters that remove only th
 
 `external_formatter_early_stdin_close.case` covers a successful formatter that closes stdin before reading it. The public CLI specifications repeat this with input larger than a pipe buffer and check that nonzero status, stderr, invalid UTF-8, and unsafe fence output still fail.
 
-Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. An optional `symlinks` mapping adds working-tree links after the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
+Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
 
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
diff --git a/tests/cases/git_filter_adopt_regular_entries.case b/tests/cases/git_filter_adopt_regular_entries.case
new file mode 100644
index 00000000..da39bfa1
--- /dev/null
+++ b/tests/cases/git_filter_adopt_regular_entries.case
@@ -0,0 +1,27 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false", "core.symlinks": "true"},
+  "files": {
+    "post.md": "First sentence. Second sentence?\n",
+    "notes/keep.txt": "Keep this file.\n",
+    "yamark.toml": "[format]\nexclude = [\"link.md\"]\n"
+  },
+  "symlinks": {"link.md": "notes"},
+  "track-symlinks": true
+}
+-- args
+git-filter adopt
+-- stdin
+-- stdout
+Adopted yamark Git filter in {{repo}}
+Updated .gitattributes with 4 new attribute pattern(s)
+Staged .gitattributes and 1 normalized Markdown file(s).
+
+Review and commit with:
+  git diff --cached
+  git commit -m "Normalize Markdown with yamark Git filter"
+-- stderr
+-- git-worktree
+{"link.md/keep.txt": "Keep this file.\n", "post.md": "First sentence. Second sentence?\n"}
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 76293305..4313adb5 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -238,7 +238,6 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
         }
     }
     git(&["add", "."]);
-    git(&["commit", "-q", "-m", "fixture"]);
     if let Some(links) = fixture.get("symlinks") {
         for (name, target) in links.as_object().unwrap() {
             let link = repo.path().join(name);
@@ -246,8 +245,12 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
             if !symlink::make_symlink(&target, &link) {
                 return None;
             }
+            if fixture["track-symlinks"] == true {
+                git(&["add", "--", name]);
+            }
         }
     }
+    git(&["commit", "-q", "-m", "fixture"]);
     Some(repo)
 }
 
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index f11fd4db..774ffaf0 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -83,6 +83,9 @@ files, and checks the codec invariant:
 clean(smudge(blob)) == blob
 ```
 
+`adopt` and `join` process regular files in Git's index. Both skip symbolic links
+and submodules.
+
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:
 

From 69168f91b40506d1e3f0bbba16c0e3c381d8da02 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:46:24 -0500
Subject: [PATCH 16/64] Isolate internal Git lookups from caller pathspec flags

---
 src/cli/git_filter/checkout.rs                |  6 +--
 src/cli/git_filter/process.rs                 | 18 ++++++--
 tests/cases/README.md                         |  2 +
 .../git_filter_smudge_inherited_pathspec.case | 18 ++++++++
 tests/cli_cases.rs                            |  4 +-
 tests/git_filter_paths.rs                     | 45 +++++++++++++++++++
 6 files changed, 85 insertions(+), 8 deletions(-)
 create mode 100644 tests/cases/git_filter_smudge_inherited_pathspec.case

diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index 2cc51939..057b83d1 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -7,7 +7,7 @@ use std::path::{Component, Path, PathBuf};
 use std::process::{Command, Stdio};
 
 use super::driver::{native_path, run_with_input};
-use super::process::{git_stdout, git_stdout_bytes};
+use super::process::{git_query, git_stdout, git_stdout_bytes};
 use crate::config::Config;
 use crate::diagnostic::{Result, YamarkError};
 
@@ -216,9 +216,7 @@ fn blob_contents(repo: &Path, path: &Path, mut entry: Entry) -> Result>
                     // A directory removed by '..' must exist too. Ancestors of
                     // the staged config already have a tracked descendant.
                     if !path.starts_with(¤t) {
-                        let status = Command::new("git")
-                            .arg("-C")
-                            .arg(repo)
+                        let status = git_query(repo)
                             .args(["--literal-pathspecs", "ls-files", "--error-unmatch", "--"])
                             .arg(git_path(¤t))
                             .stdout(Stdio::null())
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index ed46fe8c..5f9b46db 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -31,13 +31,25 @@ pub(super) fn run_git_os(repo_root: &Path, args: &[OsString]) -> Result<(), Stri
     }
 }
 
+// Git exports its caller's pathspec flags to filters. Each internal query
+// defines its own path selection, independent of the outer Git command.
+pub(super) fn git_query(repo: &Path) -> ProcessCommand {
+    let mut command = ProcessCommand::new("git");
+    command
+        .arg("-C")
+        .arg(repo)
+        .env_remove("GIT_LITERAL_PATHSPECS")
+        .env_remove("GIT_GLOB_PATHSPECS")
+        .env_remove("GIT_NOGLOB_PATHSPECS")
+        .env_remove("GIT_ICASE_PATHSPECS");
+    command
+}
+
 pub(super) fn git_stdout_bytes(
     repo_root: &Path,
     args: impl IntoIterator>,
 ) -> Result, String> {
-    let output = ProcessCommand::new("git")
-        .arg("-C")
-        .arg(repo_root)
+    let output = git_query(repo_root)
         .args(args)
         .output()
         .map_err(|err| format!("failed to run git: {err}"))?;
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 48a94b17..33c39a3a 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -17,6 +17,8 @@ expected stderr
 
 The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
 
+An optional `-- env` section supplies a JSON object of environment variables for the recorded command. The fixture setup uses the caller's environment.
+
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
 ## Running selected cases
diff --git a/tests/cases/git_filter_smudge_inherited_pathspec.case b/tests/cases/git_filter_smudge_inherited_pathspec.case
new file mode 100644
index 00000000..85960ade
--- /dev/null
+++ b/tests/cases/git_filter_smudge_inherited_pathspec.case
@@ -0,0 +1,18 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "[docs]/yamark.toml": "[format]\nexclude = [\"NEWS.md\"]\n"
+  }
+}
+-- args
+git-filter smudge --source-tree HEAD --stdin-filename [docs]/NEWS.md
+-- env
+{"GIT_ICASE_PATHSPECS": "1"}
+-- stdin
+#   News
+-- stdout
+#   News
+-- stderr
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 4313adb5..ca92580a 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -10,6 +10,7 @@ mod symlink;
 #[derive(Default)]
 struct Case {
     args: String,
+    env: BTreeMap,
     stdin: String,
     stdout: String,
     stderr: String,
@@ -63,7 +64,7 @@ fn cli_cases() {
                 .unwrap_or(".");
             command.current_dir(repo.path().join(cwd));
         }
-        command.args(split_args(&case.args));
+        command.envs(&case.env).args(split_args(&case.args));
         command.write_stdin(case.stdin);
         let assert = command.assert().code(case.status);
         let output = assert.get_output();
@@ -289,6 +290,7 @@ fn flush(case: &mut Case, section: &str, body: &str) {
     let value = body.strip_suffix('\n').unwrap_or(body);
     match section {
         "args" => case.args = value.to_owned(),
+        "env" => case.env = serde_json::from_str(value).unwrap(),
         "stdin" => case.stdin = body.to_owned(),
         "stdout" => case.stdout = body.to_owned(),
         "stderr" => case.stderr = body.to_owned(),
diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index fa236056..16016b07 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -294,6 +294,51 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     assert_eq!(git(&["-C", copy_path, "show", ":docs/notes.md"]), unstaged);
 }
 
+#[test]
+fn restores_under_pathspec_flags_use_literal_filter_config_paths() {
+    let dir = tempdir().unwrap();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(dir.path())
+            .args(args)
+            .assert()
+            .success();
+    };
+    git(&["init", "-q"]);
+    git(&["config", "user.name", "Git Filter Test"]);
+    git(&["config", "user.email", "git-filter@example.test"]);
+    git(&["config", "commit.gpgSign", "false"]);
+    git(&["config", "core.autocrlf", "false"]);
+    fs::create_dir(dir.path().join("[docs]")).unwrap();
+    fs::write(
+        dir.path().join("[docs]/yamark.toml"),
+        "[format]\nexclude = ['*.md']\n",
+    )
+    .unwrap();
+    let path = dir.path().join("[docs]/doc.md");
+    let original = b"#    Keep this spacing\n";
+    fs::write(&path, original).unwrap();
+    git(&["add", "."]);
+    git(&["commit", "-q", "-m", "fixture"]);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(dir.path())
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+    for flag in [
+        "--icase-pathspecs",
+        "--glob-pathspecs",
+        "--noglob-pathspecs",
+        "--literal-pathspecs",
+    ] {
+        fs::remove_file(&path).unwrap();
+        // "." is a directory selector under every pathspec mode.
+        git(&[flag, "restore", "--source=HEAD", "--worktree", "--", "."]);
+        assert_eq!(fs::read(&path).unwrap(), original, "{flag}");
+    }
+}
+
 #[test]
 fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
     let dir = tempdir().unwrap();

From 62e6b8a3608cf061864332b4a81fe8a905eb7a87 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:47:46 -0500
Subject: [PATCH 17/64] Negotiate Git filter capabilities independently

---
 src/cli/git_filter/driver.rs                  | 35 +++++++++++++------
 tests/cases/README.md                         |  2 ++
 .../cases/git_filter_process_clean_only.case  | 23 ++++++++++++
 .../cases/git_filter_process_smudge_only.case | 23 ++++++++++++
 tests/cli_cases.rs                            | 14 ++++++++
 5 files changed, 87 insertions(+), 10 deletions(-)
 create mode 100644 tests/cases/git_filter_process_clean_only.case
 create mode 100644 tests/cases/git_filter_process_smudge_only.case

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index dc14ddea..8345a164 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -27,21 +27,24 @@ fn serve() -> io::Result<()> {
         return Err(io::Error::other("expected git-filter-client version 2"));
     }
     write_section(&mut output, &[b"git-filter-server\n", b"version=2\n"])?;
+    let clean = driver_command("filter.yamark-md.clean")?;
+    let smudge = driver_command("filter.yamark-md.smudge")?;
     let caps = read_section(&mut input)?;
     let accepted: Vec<_> = caps
         .iter()
         .map(Vec::as_slice)
-        .filter(|&cap| cap == b"capability=clean\n" || cap == b"capability=smudge\n")
+        .filter(|&cap| {
+            (cap == b"capability=clean\n" && clean.is_some())
+                || (cap == b"capability=smudge\n" && smudge.is_some())
+        })
         .collect();
     write_section(&mut output, &accepted)?;
 
-    let clean = driver_command("filter.yamark-md.clean")?;
-    let smudge = driver_command("filter.yamark-md.smudge")?;
     while !input.fill_buf()?.is_empty() {
         let fields = read_section(&mut input)?;
         let mut contents = Vec::new();
         while read_packet(&mut input, &mut contents)? {}
-        match filter_file(&fields, &contents, &clean, &smudge) {
+        match filter_file(&fields, &contents, clean.as_deref(), smudge.as_deref()) {
             Ok(bytes) => {
                 write_section(&mut output, &[b"status=success\n"])?;
                 for chunk in bytes.chunks(65516) {
@@ -62,8 +65,8 @@ fn serve() -> io::Result<()> {
 fn filter_file(
     fields: &[Vec],
     contents: &[u8],
-    clean: &str,
-    smudge: &str,
+    clean: Option<&str>,
+    smudge: Option<&str>,
 ) -> io::Result> {
     let field = |prefix: &[u8]| {
         fields.iter().find_map(|line| {
@@ -79,6 +82,7 @@ fn filter_file(
         Some(b"smudge") => (smudge, Some(field(b"treeish=").unwrap_or(b""))),
         _ => return Err(io::Error::other("unknown filter command")),
     };
+    let command = command.ok_or_else(|| io::Error::other("filter command is not configured"))?;
     let mut child = Command::new("git");
     // Git supplies the shell on every platform. Keep native path bytes
     // out of shell source and expand them as one quoted argument.
@@ -104,9 +108,20 @@ fn filter_file(
     Ok(result.stdout)
 }
 
-fn driver_command(key: &str) -> io::Result {
-    let text = super::git_stdout(std::path::Path::new("."), ["config", "--get", key])
-        .map_err(io::Error::other)?;
+fn driver_command(key: &str) -> io::Result> {
+    let result = Command::new("git")
+        .args(["config", "--get", key])
+        .output()?;
+    if result.status.code() == Some(1) {
+        return Ok(None);
+    }
+    if !result.status.success() {
+        return Err(io::Error::other(String::from_utf8_lossy(&result.stderr)));
+    }
+    let text = String::from_utf8(result.stdout).map_err(io::Error::other)?;
+    if text == "\n" {
+        return Ok(None);
+    }
     let mut chars = text.trim_end_matches('\n').chars().peekable();
     let mut alias = String::from("alias.yamark-single-file=!");
     while let Some(ch) = chars.next() {
@@ -118,7 +133,7 @@ fn driver_command(key: &str) -> io::Result {
             alias.push(ch);
         }
     }
-    Ok(alias)
+    Ok(Some(alias))
 }
 
 pub(super) fn native_path(bytes: &[u8]) -> io::Result<&OsStr> {
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 33c39a3a..27e09b14 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -21,6 +21,8 @@ An optional `-- env` section supplies a JSON object of environment variables for
 
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
+For the Git process filter, `-- stdin-packets` and `-- stdout-packets` record an exact stream of Git packet lines as a JSON array. Each string is one packet payload, including any trailing newline. A `null` is a flush packet.
+
 ## Running selected cases
 
 Run the complete transcript suite with `cargo test --test cli_cases`. To run one case or a related group, set `YAMARK_CASE` for that command:
diff --git a/tests/cases/git_filter_process_clean_only.case b/tests/cases/git_filter_process_clean_only.case
new file mode 100644
index 00000000..04e71399
--- /dev/null
+++ b/tests/cases/git_filter_process_clean_only.case
@@ -0,0 +1,23 @@
+-- git-fixture
+{
+  "config": {"filter.yamark-md.clean": "cat"},
+  "files": {"notes.md": "Notes\n"}
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=clean\n", "pathname=notes.md\n", null,
+  "Notes\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", null,
+  "status=success\n", null, "Notes\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_process_smudge_only.case b/tests/cases/git_filter_process_smudge_only.case
new file mode 100644
index 00000000..7e0e0700
--- /dev/null
+++ b/tests/cases/git_filter_process_smudge_only.case
@@ -0,0 +1,23 @@
+-- git-fixture
+{
+  "config": {"filter.yamark-md.smudge": "cat"},
+  "files": {"notes.md": "Notes\n"}
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=smudge\n", "pathname=notes.md\n", null,
+  "Notes\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "status=success\n", null, "Notes\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index ca92580a..58d7ed1d 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -292,7 +292,9 @@ fn flush(case: &mut Case, section: &str, body: &str) {
         "args" => case.args = value.to_owned(),
         "env" => case.env = serde_json::from_str(value).unwrap(),
         "stdin" => case.stdin = body.to_owned(),
+        "stdin-packets" => case.stdin = packet_stream(value),
         "stdout" => case.stdout = body.to_owned(),
+        "stdout-packets" => case.stdout = packet_stream(value),
         "stderr" => case.stderr = body.to_owned(),
         "status" => case.status = value.trim().parse().unwrap(),
         "git-fixture" => case.git_fixture = Some(serde_json::from_str(value).unwrap()),
@@ -307,3 +309,15 @@ fn flush(case: &mut Case, section: &str, body: &str) {
 fn split_args(input: &str) -> Vec {
     input.split_whitespace().map(ToOwned::to_owned).collect()
 }
+
+fn packet_stream(json: &str) -> String {
+    use std::fmt::Write;
+    let mut stream = String::new();
+    for packet in serde_json::from_str::>>(json).unwrap() {
+        match packet {
+            Some(payload) => write!(stream, "{:04x}{payload}", payload.len() + 4).unwrap(),
+            None => stream.push_str("0000"),
+        }
+    }
+    stream
+}

From fb68b745996a41402903e83f419c86426442917b Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:49:31 -0500
Subject: [PATCH 18/64] Record teardown output for current and legacy filter
 setups

---
 tests/cases/git_filter_teardown_legacy.case  | 31 +++++++++++++++++++
 tests/cases/git_filter_teardown_process.case | 32 ++++++++++++++++++++
 tests/cli_cases.rs                           | 12 ++++++--
 3 files changed, 73 insertions(+), 2 deletions(-)
 create mode 100644 tests/cases/git_filter_teardown_legacy.case
 create mode 100644 tests/cases/git_filter_teardown_process.case

diff --git a/tests/cases/git_filter_teardown_legacy.case b/tests/cases/git_filter_teardown_legacy.case
new file mode 100644
index 00000000..94a972f7
--- /dev/null
+++ b/tests/cases/git_filter_teardown_legacy.case
@@ -0,0 +1,31 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false",
+    "filter.yamark-md.clean": "cat",
+    "filter.yamark-md.smudge": "cat",
+    "filter.yamark-md.required": "true",
+    "merge.renormalize": "true"
+  },
+  "files": {
+    "file.txt": "fixture\n",
+    ".git/info/attributes": "*.md filter=yamark-md\n*.txt text\n"
+  }
+}
+-- args
+git-filter teardown
+-- stdin
+-- stdout
+Removed yamark Git filter setup from {{repo}}
+Unset 4 local Git config value(s)
+Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
+
+Tracked files keep their current index content until staged again. Run:
+  git add --renormalize .
+if you want to restage them without the filter.
+-- stderr
+-- git-status
+-- git-worktree
+{".git/info/attributes": "*.txt text\n"}
+-- status
+0
diff --git a/tests/cases/git_filter_teardown_process.case b/tests/cases/git_filter_teardown_process.case
new file mode 100644
index 00000000..5e00f77d
--- /dev/null
+++ b/tests/cases/git_filter_teardown_process.case
@@ -0,0 +1,32 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false",
+    "filter.yamark-md.clean": "cat",
+    "filter.yamark-md.smudge": "cat",
+    "filter.yamark-md.process": "yamark git-filter process",
+    "filter.yamark-md.required": "true",
+    "merge.renormalize": "true"
+  },
+  "files": {
+    "file.txt": "fixture\n",
+    ".git/info/attributes": "*.md filter=yamark-md\n*.txt text\n"
+  }
+}
+-- args
+git-filter teardown
+-- stdin
+-- stdout
+Removed yamark Git filter setup from {{repo}}
+Unset 5 local Git config value(s)
+Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
+
+Tracked files keep their current index content until staged again. Run:
+  git add --renormalize .
+if you want to restage them without the filter.
+-- stderr
+-- git-status
+-- git-worktree
+{".git/info/attributes": "*.txt text\n"}
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 58d7ed1d..37331252 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -260,8 +260,16 @@ fn redact_repo(bytes: &[u8], repo: Option<&tempfile::TempDir>) -> String {
     let Some(repo) = repo else { return text };
     let root = repo.path().canonicalize().unwrap();
     let root = root.to_str().unwrap().trim_start_matches(r"\\?\");
-    text.replace(root, "{{repo}}")
-        .replace(&root.replace('\\', "/"), "{{repo}}")
+    let text = text
+        .replace(root, "{{repo}}")
+        .replace(&root.replace('\\', "/"), "{{repo}}");
+    // On Windows Path::join inserts a backslash between Git's
+    // slash-separated root and the relative path to info/attributes.
+    if cfg!(windows) {
+        text.replace(r"{{repo}}\", "{{repo}}/")
+    } else {
+        text
+    }
 }
 
 fn parse_case(input: &str) -> Case {

From 6afeb310f8a7dce7febed82a14c9cc92cfbf4be6 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:50:16 -0500
Subject: [PATCH 19/64] Explain when checkout needs a manual filter refresh

---
 website/git-filter.qmd | 26 ++++++++++++++++++++++----
 1 file changed, 22 insertions(+), 4 deletions(-)

diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 774ffaf0..eabb7707 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -31,10 +31,12 @@ output to keep storage diffs small.
 
 During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
 looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
-`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git runs the
-filter without specifying a tree, as with `git checkout-index`, smudge reads
-the staged configuration. If `yamark.toml` is a symbolic link, its target
-must also be present in that tree or index. Clean reads the working-tree config.
+`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies
+no tree, smudge uses the staged configuration if Git identifies the file's
+staged blob. If the blob is missing or differs from the staged blob, as can
+happen during a merge or cherry-pick, smudge returns the incoming bytes
+unchanged. If `yamark.toml` is a symbolic link, its target must also be present
+in the selected tree or index. Clean reads the working-tree config.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.
@@ -222,6 +224,22 @@ pass through the filter but Yamark should preserve its contents. A file matched
 by [`exclude`](reference-config.qmd#excluded-files) in `yamark.toml` also passes
 through the filter byte for byte, so it need not be UTF-8.
 
+### Refresh a file after changing exclusions
+
+If two commits differ only in `yamark.toml`, Git can leave an unchanged
+Markdown blob on disk with its old wrapping. The next `git add` can then stage
+that wrapping as an edit to a newly excluded file.
+
+To see the working-tree version produced by the staged rules, run:
+
+```sh
+git checkout-index --temp -- NEWS.md
+```
+
+Git writes a temporary file and prints its name alongside `NEWS.md`. Compare
+the two files. If you have local edits, copy them into the temporary file
+before replacing `NEWS.md` with it. This refresh leaves the index intact.
+
 ## Diff shape
 
 Without the filter, editing one sentence inside a wrapped paragraph can modify

From 55339e41224e4d00f939f44a12b389295995404d Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:50:01 -0500
Subject: [PATCH 20/64] Keep embedded formatter commands out of Git conversions

---
 RELEASE_NOTES.md                              |  2 +
 src/cli/git_filter.rs                         | 28 ++++++-------
 tests/cases/git_filter_check_declarative.case | 19 +++++++++
 tests/cases/git_filter_clean_declarative.case | 26 ++++++++++++
 .../cases/git_filter_smudge_declarative.case  | 42 +++++++++++++++++++
 website/git-filter.qmd                        |  2 +
 6 files changed, 105 insertions(+), 14 deletions(-)
 create mode 100644 tests/cases/git_filter_check_declarative.case
 create mode 100644 tests/cases/git_filter_clean_declarative.case
 create mode 100644 tests/cases/git_filter_smudge_declarative.case

diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index bdd10dff..84380103 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -6,4 +6,6 @@ Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yama
 
 The experimental Git filter now reads the tracked `yamark.toml` from the tree being checked out, so excluded files keep their original bytes in a fresh worktree. New filter installations configure this automatically. To update an existing installation with `yamark` on your path, run `git config filter.yamark-md.process "yamark git-filter process"` in the repository.
 
+Git clean, smudge, and round-trip checks now skip external embedded formatters. Use `yamark format ` in a trusted checkout to format embedded code with your project's tools.
+
 `[paths]` overrides now match a `--stdin-file-path` that does not exist on disk on Windows, or when the path passes through a symlinked directory. Previously these paths could fail to match the config directory.
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 80b9a7ef..7ab59882 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -189,25 +189,31 @@ pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     }
 }
 
+fn filter_options(wrap: MarkdownWrap) -> FormatOptions {
+    FormatOptions {
+        markdown_wrap: wrap,
+        markdown_compact_tables: true,
+        respect_frontmatter_markdown_options: false,
+        // Git can supply configuration from a revision before checkout.
+        // Keep both directions and round-trip checks independent of executables.
+        skip_embedded_formatters: true,
+        ..FormatOptions::default()
+    }
+}
+
 fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source_tree: Option) -> ExitCode {
     if crate::core::document::FileKind::for_path(&path) != crate::core::document::FileKind::Markdown
     {
         eprintln!("{}:1:1: error: unsupported Git filter path", path.display());
         return ExitCode::from(1);
     }
-    let options = FormatOptions {
-        markdown_wrap: wrap,
-        markdown_compact_tables: true,
-        respect_frontmatter_markdown_options: false,
-        ..FormatOptions::default()
-    };
     run_stdin(
         path,
         |path| match source_tree {
             Some(tree) => checkout::config_for_path(Path::new("."), &tree, path),
             None => load_config_for_formatted_path(path, None),
         },
-        options,
+        filter_options(wrap),
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
             ..FormatExecutionOptions::default()
@@ -697,16 +703,10 @@ fn format_git_filter_text(
     wrap: MarkdownWrap,
     config: &Config,
 ) -> Result {
-    let options = FormatOptions {
-        markdown_wrap: wrap,
-        markdown_compact_tables: true,
-        respect_frontmatter_markdown_options: false,
-        ..FormatOptions::default()
-    };
     format_source_with_config(
         path,
         input,
-        options,
+        filter_options(wrap),
         config,
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
diff --git a/tests/cases/git_filter_check_declarative.case b/tests/cases/git_filter_check_declarative.case
new file mode 100644
index 00000000..e5ed412d
--- /dev/null
+++ b/tests/cases/git_filter_check_declarative.case
@@ -0,0 +1,19 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n",
+    "post.md": "***\n\n```example\nunformatted  input\n```\n"
+  }
+}
+-- args
+git-filter check
+-- stdin
+-- stdout
+yamark Git filter check passed for 1 Markdown file(s).
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_clean_declarative.case b/tests/cases/git_filter_clean_declarative.case
new file mode 100644
index 00000000..02da1143
--- /dev/null
+++ b/tests/cases/git_filter_clean_declarative.case
@@ -0,0 +1,26 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n"
+  }
+}
+-- args
+git-filter clean --stdin-filename post.md
+-- stdin
+- - -
+
+```example
+unformatted  input
+```
+-- stdout
+***
+
+```example
+unformatted  input
+```
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_smudge_declarative.case b/tests/cases/git_filter_smudge_declarative.case
new file mode 100644
index 00000000..eb53f634
--- /dev/null
+++ b/tests/cases/git_filter_smudge_declarative.case
@@ -0,0 +1,42 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "incoming/yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n"
+  }
+}
+-- args
+git-filter smudge --source-tree HEAD:incoming --stdin-filename post.md
+-- stdin
+---
+# fmt: example
+sample: |
+  unformatted  input
+---
+
+# Draft
+
+- - -
+
+```example
+unformatted  input
+```
+-- stdout
+---
+# fmt: example
+sample: |
+  unformatted  input
+---
+
+# Draft
+
+***
+
+```example
+unformatted  input
+```
+-- stderr
+-- status
+0
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index eabb7707..0d16731b 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -29,6 +29,8 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
+Yamark's clean and smudge commands and its round-trip checks skip external embedded formatters. Checkout applies the revision's formatting settings even before its tools are available. To format embedded code with those tools, run `yamark format ` in a trusted checkout. Git still runs custom clean or smudge commands you configure in your local Git settings.
+
 During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
 looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
 `NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies

From 294f9af292ebe901442acd25ff0aa620b4ca5585 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:49:25 -0500
Subject: [PATCH 21/64] Expand single-quoted custom filter filename arguments

---
 src/cli/git_filter/driver.rs                  | 17 ++++++++++----
 .../git_filter_process_quoted_filename.case   | 23 +++++++++++++++++++
 2 files changed, 36 insertions(+), 4 deletions(-)
 create mode 100644 tests/cases/git_filter_process_quoted_filename.case

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 8345a164..d615804b 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -122,15 +122,24 @@ fn driver_command(key: &str) -> io::Result> {
     if text == "\n" {
         return Ok(None);
     }
-    let mut chars = text.trim_end_matches('\n').chars().peekable();
+    let mut template = text.trim_end_matches('\n');
     let mut alias = String::from("alias.yamark-single-file=!");
-    while let Some(ch) = chars.next() {
-        if ch == '%' && chars.next_if_eq(&'f').is_some() {
+    // Keep path bytes in the environment. A filter may already surround its
+    // standalone %f with single quotes; replace the entire word in that case.
+    while !template.is_empty() {
+        if let Some(rest) = template
+            .strip_prefix("'%f'")
+            .or_else(|| template.strip_prefix("%f"))
+        {
             alias.push_str("\"$YAMARK_GIT_FILTER_PATH\"");
-        } else if ch == '%' && chars.next_if_eq(&'%').is_some() {
+            template = rest;
+        } else if let Some(rest) = template.strip_prefix("%%") {
             alias.push('%');
+            template = rest;
         } else {
+            let ch = template.chars().next().expect("nonempty template");
             alias.push(ch);
+            template = &template[ch.len_utf8()..];
         }
     }
     Ok(Some(alias))
diff --git a/tests/cases/git_filter_process_quoted_filename.case b/tests/cases/git_filter_process_quoted_filename.case
new file mode 100644
index 00000000..484eaea8
--- /dev/null
+++ b/tests/cases/git_filter_process_quoted_filename.case
@@ -0,0 +1,23 @@
+-- git-fixture
+{
+  "config": {"filter.yamark-md.clean": "printf '%%s\\n' '%f'"},
+  "files": {"notes.md": "Notes\n"}
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=clean\n", "pathname=notes.md\n", null,
+  "Notes\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", null,
+  "status=success\n", null, "notes.md\n", null, null
+]
+-- stderr
+-- status
+0

From bfca01d37d58aefd86de72e7e846fb2f19192281 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:51:13 -0500
Subject: [PATCH 22/64] Run the installed Git filters in the persistent process

---
 src/cli/git_filter.rs          |  14 ++--
 src/cli/git_filter/checkout.rs |  49 ++++++++++----
 src/cli/git_filter/driver.rs   | 116 +++++++++++++++++++++++++++++----
 tests/git_filter_process.rs    |  67 +++++++++++++++++++
 4 files changed, 214 insertions(+), 32 deletions(-)
 create mode 100644 tests/git_filter_process.rs

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 7ab59882..536e56c3 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -462,14 +462,12 @@ fn configure_git_filter(
     run_git_config(
         repo_root,
         "filter.yamark-md.clean",
-        &format!("{yamark} git-filter clean --stdin-filename %f"),
+        &default_clean_command(&yamark),
     )?;
     run_git_config(
         repo_root,
         "filter.yamark-md.smudge",
-        &format!(
-            "{yamark} git-filter smudge --stdin-filename %f --markdown-wrap-at-column {width}"
-        ),
+        &format!("{}{width}", default_smudge_prefix(&yamark)),
     )?;
     run_git_config(repo_root, "filter.yamark-md.required", "true")?;
     run_git_config(
@@ -480,6 +478,14 @@ fn configure_git_filter(
     run_git_config(repo_root, "merge.renormalize", "true")
 }
 
+fn default_clean_command(yamark: &str) -> String {
+    format!("{yamark} git-filter clean --stdin-filename %f")
+}
+
+fn default_smudge_prefix(yamark: &str) -> String {
+    format!("{yamark} git-filter smudge --stdin-filename %f --markdown-wrap-at-column ")
+}
+
 fn ensure_clean_worktree(repo_root: &Path) -> Result<(), String> {
     let status = git_stdout(repo_root, ["status", "--porcelain"])?;
     if status.is_empty() {
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index 057b83d1..fb0f5627 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -1,7 +1,7 @@
 //! Resolve checkout configuration from the incoming Git tree or stage-zero index.
 //! Git may invoke smudge before materializing the configuration in the worktree.
 
-use std::collections::VecDeque;
+use std::collections::{HashMap, VecDeque};
 use std::ffi::OsString;
 use std::path::{Component, Path, PathBuf};
 use std::process::{Command, Stdio};
@@ -17,23 +17,44 @@ struct Entry {
 }
 
 pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result {
-    let path = path.strip_prefix(".").unwrap_or(path);
-    if path.as_os_str().is_empty()
-        || !path
-            .components()
-            .all(|part| matches!(part, Component::Normal(_)))
-    {
-        return Err(YamarkError::new(
-            "Git checkout requires a repository-relative filename",
-        ));
+    CheckoutConfigs::default().for_path(repo_root, tree, path)
+}
+
+#[derive(Default)]
+pub(super) struct CheckoutConfigs {
+    directories: HashMap<(String, PathBuf), (PathBuf, Config)>,
+}
+
+impl CheckoutConfigs {
+    pub(super) fn for_path(&mut self, repo: &Path, tree: &str, path: &Path) -> Result {
+        let path = path.strip_prefix(".").unwrap_or(path);
+        if path.as_os_str().is_empty()
+            || !path
+                .components()
+                .all(|part| matches!(part, Component::Normal(_)))
+        {
+            return Err(YamarkError::new(
+                "Git checkout requires a repository-relative filename",
+            ));
+        }
+        let parent = path.parent().expect("nonempty relative path");
+        let key = (tree.to_owned(), parent.to_owned());
+        use std::collections::hash_map::Entry;
+        let (dir, config) = match self.directories.entry(key) {
+            Entry::Occupied(entry) => entry.into_mut(),
+            Entry::Vacant(entry) => entry.insert(config_for_directory(repo, tree, parent)?),
+        };
+        Ok(config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor")))
     }
-    let candidates: Vec<_> = path
+}
+
+fn config_for_directory(repo_root: &Path, tree: &str, parent: &Path) -> Result<(PathBuf, Config)> {
+    let candidates: Vec<_> = parent
         .ancestors()
-        .skip(1)
         .map(|dir| dir.join("yamark.toml"))
         .collect();
     let Some((config_path, entry)) = nearest_entry(repo_root, tree, &candidates)? else {
-        return Ok(Config::default());
+        return Ok((PathBuf::new(), Config::default()));
     };
     let bytes = if entry.symlink && !tree.is_empty() {
         tree_symlink_contents(repo_root, tree, &config_path)
@@ -50,7 +71,7 @@ pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Resu
     let root = std::fs::canonicalize(repo_root).map_err(|err| YamarkError::new(err.to_string()))?;
     let dir = config_path.parent().expect("a config has a parent");
     config.config_dir = Some(root.join(dir));
-    Ok(config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor")))
+    Ok((dir.to_owned(), config))
 }
 
 /// Candidates are ordered nearest first. Use literal pathspecs and NUL-delimited
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index d615804b..24a5e6c8 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -1,10 +1,17 @@
 //! Git's v2 process filter supplies the tree being checked out for each smudge.
 //! Keep the configured single-file commands authoritative, including -c overrides.
 
+use std::collections::HashMap;
+use std::collections::hash_map::Entry;
 use std::ffi::OsStr;
 use std::io::{self, BufRead, Read, Write};
+use std::path::{Path, PathBuf};
 use std::process::{Command, ExitCode, Stdio};
 
+use super::checkout::CheckoutConfigs;
+use crate::config::{Config, discover_config_path};
+use crate::core::document::{FileKind, MarkdownWrap};
+
 pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
 
 pub(super) fn run() -> ExitCode {
@@ -27,8 +34,25 @@ fn serve() -> io::Result<()> {
         return Err(io::Error::other("expected git-filter-client version 2"));
     }
     write_section(&mut output, &[b"git-filter-server\n", b"version=2\n"])?;
-    let clean = driver_command("filter.yamark-md.clean")?;
-    let smudge = driver_command("filter.yamark-md.smudge")?;
+    let exe = super::shell_quote_path(&std::env::current_exe()?).map_err(io::Error::other)?;
+    let clean = driver_command("filter.yamark-md.clean")?.map(|command| {
+        if command == super::default_clean_command(&exe) {
+            Driver::Yamark(MarkdownWrap::Sentence)
+        } else {
+            Driver::Custom(custom_alias(&command))
+        }
+    });
+    let smudge_prefix = super::default_smudge_prefix(&exe);
+    let smudge = driver_command("filter.yamark-md.smudge")?.map(|command| {
+        if let Some(width) = command.strip_prefix(&smudge_prefix)
+            && let Ok(width) = super::super::parse_positive_usize(width)
+        {
+            Driver::Yamark(MarkdownWrap::Column(width))
+        } else {
+            Driver::Custom(custom_alias(&command))
+        }
+    });
+    let mut configs = FilterConfigs::default();
     let caps = read_section(&mut input)?;
     let accepted: Vec<_> = caps
         .iter()
@@ -44,7 +68,13 @@ fn serve() -> io::Result<()> {
         let fields = read_section(&mut input)?;
         let mut contents = Vec::new();
         while read_packet(&mut input, &mut contents)? {}
-        match filter_file(&fields, &contents, clean.as_deref(), smudge.as_deref()) {
+        match filter_file(
+            &fields,
+            contents,
+            clean.as_ref(),
+            smudge.as_ref(),
+            &mut configs,
+        ) {
             Ok(bytes) => {
                 write_section(&mut output, &[b"status=success\n"])?;
                 for chunk in bytes.chunks(65516) {
@@ -62,11 +92,43 @@ fn serve() -> io::Result<()> {
     Ok(())
 }
 
+enum Driver {
+    Yamark(MarkdownWrap),
+    Custom(String),
+}
+
+#[derive(Default)]
+struct FilterConfigs {
+    worktree: HashMap,
+    checkout: CheckoutConfigs,
+}
+
+impl FilterConfigs {
+    fn for_path(&mut self, path: &Path, tree: Option<&str>) -> crate::diagnostic::Result {
+        if let Some(tree) = tree {
+            return self.checkout.for_path(Path::new("."), tree, path);
+        }
+        let parent = path.parent().unwrap_or_else(|| Path::new("."));
+        let base = match self.worktree.entry(parent.to_owned()) {
+            Entry::Occupied(entry) => entry.into_mut(),
+            Entry::Vacant(entry) => {
+                let config = discover_config_path(path)
+                    .map(|path| Config::from_path(&path))
+                    .transpose()?
+                    .unwrap_or_default();
+                entry.insert(config)
+            }
+        };
+        Ok(base.for_formatted_path(path))
+    }
+}
+
 fn filter_file(
     fields: &[Vec],
-    contents: &[u8],
-    clean: Option<&str>,
-    smudge: Option<&str>,
+    contents: Vec,
+    clean: Option<&Driver>,
+    smudge: Option<&Driver>,
+    configs: &mut FilterConfigs,
 ) -> io::Result> {
     let field = |prefix: &[u8]| {
         fields.iter().find_map(|line| {
@@ -83,6 +145,32 @@ fn filter_file(
         _ => return Err(io::Error::other("unknown filter command")),
     };
     let command = command.ok_or_else(|| io::Error::other("filter command is not configured"))?;
+    let path = Path::new(native_path(path)?);
+    let tree = tree
+        .map(std::str::from_utf8)
+        .transpose()
+        .map_err(io::Error::other)?;
+    let command = match command {
+        Driver::Yamark(wrap) => {
+            if FileKind::for_path(path) != FileKind::Markdown {
+                return Err(io::Error::other(format!(
+                    "{}: unsupported Git filter path",
+                    path.display()
+                )));
+            }
+            let config = configs.for_path(path, tree).map_err(io::Error::other)?;
+            if config.excludes(path) {
+                return Ok(contents);
+            }
+            let input = super::super::decode_utf8(contents).map_err(|message| {
+                io::Error::other(format!("{}:1:1: error: {message}", path.display()))
+            })?;
+            return super::format_git_filter_text(path, input, *wrap, &config)
+                .map(String::into_bytes)
+                .map_err(io::Error::other);
+        }
+        Driver::Custom(alias) => alias,
+    };
     let mut child = Command::new("git");
     // Git supplies the shell on every platform. Keep native path bytes
     // out of shell source and expand them as one quoted argument.
@@ -90,15 +178,12 @@ fn filter_file(
         .arg("-c")
         .arg(command)
         .arg("yamark-single-file")
-        .env("YAMARK_GIT_FILTER_PATH", native_path(path)?)
+        .env("YAMARK_GIT_FILTER_PATH", path)
         .env_remove(SOURCE_TREE_ENV);
     if let Some(tree) = tree {
-        child.env(
-            SOURCE_TREE_ENV,
-            std::str::from_utf8(tree).map_err(io::Error::other)?,
-        );
+        child.env(SOURCE_TREE_ENV, tree);
     }
-    let result = run_with_input(&mut child, contents)?;
+    let result = run_with_input(&mut child, &contents)?;
     if !result.status.success() {
         return Err(io::Error::other(format!(
             "single-file filter exited with {}",
@@ -122,7 +207,10 @@ fn driver_command(key: &str) -> io::Result> {
     if text == "\n" {
         return Ok(None);
     }
-    let mut template = text.trim_end_matches('\n');
+    Ok(Some(text.trim_end_matches('\n').to_owned()))
+}
+
+fn custom_alias(mut template: &str) -> String {
     let mut alias = String::from("alias.yamark-single-file=!");
     // Keep path bytes in the environment. A filter may already surround its
     // standalone %f with single quotes; replace the entire word in that case.
@@ -142,7 +230,7 @@ fn driver_command(key: &str) -> io::Result> {
             template = &template[ch.len_utf8()..];
         }
     }
-    Ok(Some(alias))
+    alias
 }
 
 pub(super) fn native_path(bytes: &[u8]) -> io::Result<&OsStr> {
diff --git a/tests/git_filter_process.rs b/tests/git_filter_process.rs
new file mode 100644
index 00000000..387a5bf5
--- /dev/null
+++ b/tests/git_filter_process.rs
@@ -0,0 +1,67 @@
+use std::fs;
+use std::path::Path;
+
+use assert_cmd::Command;
+use tempfile::tempdir;
+
+#[test]
+fn default_filters_reuse_configuration_for_files_in_one_directory() {
+    let repo = tempdir().unwrap();
+    let root = repo.path();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(root)
+            .args(args)
+            .assert()
+            .success();
+    };
+    git(&["init", "-q"]);
+    git(&["config", "core.autocrlf", "false"]);
+    let names = ["one.md", "two.md", "three.md"];
+    fs::write(root.join("yamark.toml"), "[format]\nexclude = ['two.md']\n").unwrap();
+    for name in names {
+        fs::write(root.join(name), b"First sentence.\nSecond sentence?\n").unwrap();
+    }
+    git(&["add", "."]);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(root)
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+
+    let trace_dir = tempdir().unwrap();
+    let checkout = |files: &[&str], trace: &Path| {
+        for name in files {
+            fs::remove_file(root.join(name)).unwrap();
+        }
+        Command::new("git")
+            .current_dir(root)
+            .env("GIT_TRACE2_EVENT", trace)
+            .args(["checkout-index", "--"])
+            .args(files)
+            .assert()
+            .success();
+        fs::read_to_string(trace)
+            .unwrap()
+            .lines()
+            .map(|event| serde_json::from_str::(event).unwrap())
+            .filter(|event| event["event"] == "start")
+            .count()
+    };
+    let single = checkout(&names[..1], &trace_dir.path().join("single.jsonl"));
+    let multiple = checkout(&names, &trace_dir.path().join("multiple.jsonl"));
+    assert!(single > 0);
+    assert_eq!(
+        multiple, single,
+        "extra Git processes for files sharing a config"
+    );
+    for name in names {
+        let expected = if name == "two.md" {
+            "First sentence.\nSecond sentence?\n"
+        } else {
+            "First sentence. Second sentence?\n"
+        };
+        assert_eq!(fs::read_to_string(root.join(name)).unwrap(), expected);
+    }
+}

From beb9a10c71d886a12836a8fc96c45583544a7f09 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:49:29 -0500
Subject: [PATCH 23/64] Check treeless smudges against staged blob identities

---
 src/cli/git_filter/checkout.rs                | 69 ++++++++++++++-----
 src/cli/git_filter/driver.rs                  | 27 +++++++-
 tests/cases/README.md                         |  2 +-
 .../git_filter_process_treeless_smudge.case   | 27 ++++++++
 tests/cli_cases.rs                            |  8 +++
 tests/git_filter_paths.rs                     | 61 ++++++++++++++++
 6 files changed, 175 insertions(+), 19 deletions(-)
 create mode 100644 tests/cases/git_filter_process_treeless_smudge.case

diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index fb0f5627..bcfb7655 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -9,6 +9,7 @@ use std::process::{Command, Stdio};
 use super::driver::{native_path, run_with_input};
 use super::process::{git_query, git_stdout, git_stdout_bytes};
 use crate::config::Config;
+use crate::core::document::FileKind;
 use crate::diagnostic::{Result, YamarkError};
 
 struct Entry {
@@ -16,6 +17,38 @@ struct Entry {
     symlink: bool,
 }
 
+/// Git may report a blob but no tree during checkout-index, merges, and
+/// cherry-picks. Only use staged settings for a file whose staged blob agrees.
+pub(super) struct IndexSnapshot {
+    markdown: HashMap>,
+}
+
+impl IndexSnapshot {
+    pub(super) fn load(repo: &Path) -> Result {
+        let records = git_stdout_bytes(repo, ["ls-files", "--stage", "--full-name", "-z"])
+            .map_err(YamarkError::new)?;
+        let mut markdown = HashMap::new();
+        for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
+            let (filename, [mode, oid, stage]) = entry_fields(record)?;
+            if stage != b"0" || !matches!(mode, b"100644" | b"100755") {
+                continue;
+            }
+            // The rest of the index may include paths this OS cannot represent.
+            if let Ok(filename) = native_path(filename) {
+                let path = Path::new(filename);
+                if FileKind::for_path(path) == FileKind::Markdown {
+                    markdown.insert(path.to_owned(), oid.to_vec());
+                }
+            }
+        }
+        Ok(Self { markdown })
+    }
+
+    pub(super) fn matches_blob(&self, path: &Path, blob: &[u8]) -> bool {
+        self.markdown.get(path).map(Vec::as_slice) == Some(blob)
+    }
+}
+
 pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result {
     CheckoutConfigs::default().for_path(repo_root, tree, path)
 }
@@ -74,6 +107,20 @@ fn config_for_directory(repo_root: &Path, tree: &str, parent: &Path) -> Result<(
     Ok((dir.to_owned(), config))
 }
 
+// ls-tree and ls-files --stage emit three ASCII fields, a tab, and the raw path.
+fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3])> {
+    let tab = record
+        .iter()
+        .position(|&byte| byte == b'\t')
+        .ok_or_else(|| YamarkError::new("invalid Git entry record"))?;
+    let mut fields = record[..tab].split(|&byte| byte == b' ');
+    let [Some(first), Some(second), Some(third), None] = std::array::from_fn(|_| fields.next())
+    else {
+        return Err(YamarkError::new("invalid Git entry metadata"));
+    };
+    Ok((&record[tab + 1..], [first, second, third]))
+}
+
 /// Candidates are ordered nearest first. Use literal pathspecs and NUL-delimited
 /// Git records so filenames are never treated as globs or display-quoted text.
 fn nearest_entry(
@@ -120,31 +167,21 @@ fn nearest_entry(
     let records = git_stdout_bytes(repo, args).map_err(YamarkError::new)?;
     let mut nearest = None;
     for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-        let tab = record
-            .iter()
-            .position(|&byte| byte == b'\t')
-            .ok_or_else(|| YamarkError::new("invalid Git entry record"))?;
-        let path = Path::new(
-            native_path(&record[tab + 1..]).map_err(|err| YamarkError::new(err.to_string()))?,
-        );
+        let (filename, [mode, second, third]) = entry_fields(record)?;
+        let path =
+            Path::new(native_path(filename).map_err(|err| YamarkError::new(err.to_string()))?);
         let Some(rank) = candidates.iter().position(|candidate| candidate == path) else {
             continue;
         };
-        let fields = record[..tab]
-            .split(|&byte| byte == b' ')
-            .collect::>();
-        let [mode, second, third] = fields.as_slice() else {
-            return Err(YamarkError::new("invalid Git entry metadata"));
-        };
         let oid = if tree.is_empty() {
-            if *third != b"0" {
+            if third != b"0" {
                 continue;
             }
             second
         } else {
             third
         };
-        if !matches!(*mode, b"100644" | b"100755" | b"120000") {
+        if !matches!(mode, b"100644" | b"100755" | b"120000") {
             continue;
         }
         if nearest.as_ref().is_none_or(|(best, _)| rank < *best) {
@@ -153,7 +190,7 @@ fn nearest_entry(
                 rank,
                 Entry {
                     oid: oid.to_owned(),
-                    symlink: *mode == b"120000",
+                    symlink: mode == b"120000",
                 },
             ));
         }
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 24a5e6c8..65d11257 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -8,7 +8,7 @@ use std::io::{self, BufRead, Read, Write};
 use std::path::{Path, PathBuf};
 use std::process::{Command, ExitCode, Stdio};
 
-use super::checkout::CheckoutConfigs;
+use super::checkout::{CheckoutConfigs, IndexSnapshot};
 use crate::config::{Config, discover_config_path};
 use crate::core::document::{FileKind, MarkdownWrap};
 
@@ -101,9 +101,26 @@ enum Driver {
 struct FilterConfigs {
     worktree: HashMap,
     checkout: CheckoutConfigs,
+    index: Option,
 }
 
 impl FilterConfigs {
+    fn index_matches(
+        &mut self,
+        path: &Path,
+        blob: Option<&[u8]>,
+    ) -> crate::diagnostic::Result {
+        let Some(blob) = blob else { return Ok(false) };
+        if self.index.is_none() {
+            self.index = Some(IndexSnapshot::load(Path::new("."))?);
+        }
+        Ok(self
+            .index
+            .as_ref()
+            .expect("loaded index")
+            .matches_blob(path, blob))
+    }
+
     fn for_path(&mut self, path: &Path, tree: Option<&str>) -> crate::diagnostic::Result {
         if let Some(tree) = tree {
             return self.checkout.for_path(Path::new("."), tree, path);
@@ -140,7 +157,6 @@ fn filter_file(
     let path = field(b"pathname=").ok_or_else(|| io::Error::other("missing pathname"))?;
     let (command, tree) = match field(b"command=") {
         Some(b"clean") => (clean, None),
-        // Without a tree (e.g. checkout-index), Git smudges from the index.
         Some(b"smudge") => (smudge, Some(field(b"treeish=").unwrap_or(b""))),
         _ => return Err(io::Error::other("unknown filter command")),
     };
@@ -158,6 +174,13 @@ fn filter_file(
                     path.display()
                 )));
             }
+            if tree == Some("")
+                && !configs
+                    .index_matches(path, field(b"blob="))
+                    .map_err(io::Error::other)?
+            {
+                return Ok(contents);
+            }
             let config = configs.for_path(path, tree).map_err(io::Error::other)?;
             if config.excludes(path) {
                 return Ok(contents);
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 27e09b14..055082d6 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -68,7 +68,7 @@ The `external_formatter_*.case` transcripts cover formatters that remove only th
 
 `external_formatter_early_stdin_close.case` covers a successful formatter that closes stdin before reading it. The public CLI specifications repeat this with input larger than a pipe buffer and check that nonzero status, stderr, invalid UTF-8, and unsafe fence output still fail.
 
-Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
+Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Set `"setup-filter": true` to run `yamark git-filter setup` after the fixture commit. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
 
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
diff --git a/tests/cases/git_filter_process_treeless_smudge.case b/tests/cases/git_filter_process_treeless_smudge.case
new file mode 100644
index 00000000..50900c85
--- /dev/null
+++ b/tests/cases/git_filter_process_treeless_smudge.case
@@ -0,0 +1,27 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {"doc.md": "# Base\n"},
+  "setup-filter": true
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "command=smudge\n", "pathname=doc.md\n", "blob=18facc4e56a8bce5e46541f709ee6f884bb0350c\n", null,
+  "#   Incoming\n", null,
+  "command=smudge\n", "pathname=doc.md\n", null,
+  "#   Incoming\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "status=success\n", null, "#   Incoming\n", null, null,
+  "status=success\n", null, "#   Incoming\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 37331252..08abd4f8 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -252,6 +252,14 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
         }
     }
     git(&["commit", "-q", "-m", "fixture"]);
+    if fixture["setup-filter"].as_bool() == Some(true) {
+        Command::cargo_bin("yamark")
+            .unwrap()
+            .current_dir(repo.path())
+            .args(["git-filter", "setup"])
+            .assert()
+            .success();
+    }
     Some(repo)
 }
 
diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index 16016b07..5f5ec6be 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -211,6 +211,7 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     // checkout-index supplies a blob without a source tree. Select its staged
     // config even while both files are absent from the working directory.
     fs::remove_file(copy.path().join("NEWS.md")).unwrap();
+    fs::remove_file(copy.path().join("post.md")).unwrap();
     fs::remove_file(copy.path().join("yamark.toml")).unwrap();
     Command::cargo_bin("yamark")
         .unwrap()
@@ -226,9 +227,14 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
         "checkout-index",
         "--",
         "NEWS.md",
+        "post.md",
         "yamark.toml",
     ]);
     assert_eq!(fs::read(copy.path().join("NEWS.md")).unwrap(), utf16);
+    assert_eq!(
+        fs::read(copy.path().join("post.md")).unwrap(),
+        b"First sentence. Second sentence?\n"
+    );
 
     Command::cargo_bin("yamark")
         .unwrap()
@@ -339,6 +345,61 @@ fn restores_under_pathspec_flags_use_literal_filter_config_paths() {
     }
 }
 
+#[test]
+fn non_fast_forward_merge_preserves_newly_excluded_bytes() {
+    check_incoming_exclusion(&["merge", "--no-ff", "--no-edit", "incoming"]);
+}
+
+#[test]
+fn cherry_pick_preserves_newly_excluded_bytes() {
+    check_incoming_exclusion(&["cherry-pick", "incoming"]);
+}
+
+fn check_incoming_exclusion(integrate: &[&str]) {
+    let dir = tempdir().unwrap();
+    let repo = dir.path();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(repo)
+            .args(args)
+            .assert()
+            .success()
+            .get_output()
+            .stdout
+            .clone()
+    };
+    git(&["init", "-q"]);
+    git(&["config", "user.name", "Git Filter Test"]);
+    git(&["config", "user.email", "git-filter@example.test"]);
+    git(&["config", "commit.gpgSign", "false"]);
+    git(&["config", "core.autocrlf", "false"]);
+    fs::write(repo.join("doc.md"), "# Base\n").unwrap();
+    git(&["add", "doc.md"]);
+    git(&["commit", "-qm", "base"]);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(repo)
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+    git(&["branch", "local"]);
+    git(&["checkout", "-qb", "incoming"]);
+    let incoming = b"#   Leave this heading alone\n";
+    fs::write(repo.join("yamark.toml"), "[format]\nexclude = ['doc.md']\n").unwrap();
+    fs::write(repo.join("doc.md"), incoming).unwrap();
+    git(&["add", "doc.md", "yamark.toml"]);
+    git(&["commit", "-qm", "exclude doc"]);
+    assert_eq!(git(&["show", "HEAD:doc.md"]), incoming);
+    git(&["checkout", "-q", "local"]);
+    fs::write(repo.join("other.txt"), "unrelated\n").unwrap();
+    git(&["add", "other.txt"]);
+    git(&["commit", "-qm", "diverge"]);
+
+    git(integrate);
+    assert_eq!(fs::read(repo.join("doc.md")).unwrap(), incoming);
+    assert_eq!(git(&["status", "--porcelain"]), b"");
+}
+
 #[test]
 fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
     let dir = tempdir().unwrap();

From 145d6fb6558e9f443797b788f8fc4d5bdf4983ae Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:52:08 -0500
Subject: [PATCH 24/64] Share regular staged blob selection across Git filter
 operations

---
 src/cli/git_filter.rs          | 13 +++----------
 src/cli/git_filter/checkout.rs | 27 ++++++---------------------
 src/cli/git_filter/process.rs  | 25 +++++++++++++++++++++++++
 3 files changed, 34 insertions(+), 31 deletions(-)

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 536e56c3..131a488a 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -587,19 +587,12 @@ fn tracked_yamark_filter_paths(repo_root: &Path) -> Result, String>
         .split(|byte| *byte == 0)
         .filter(|entry| !entry.is_empty())
     {
-        let tab = entry
-            .iter()
-            .position(|byte| *byte == b'\t')
-            .ok_or("missing path in git ls-files --stage output")?;
-        let metadata = &entry[..tab];
         // Only regular, stage-zero blobs belong in the worktree write set.
-        if !(metadata.starts_with(b"100644 ") || metadata.starts_with(b"100755 "))
-            || !metadata.ends_with(b" 0")
-        {
+        let Some(blob) = process::regular_index_blob(entry)? else {
             continue;
-        }
+        };
         let path = PathBuf::from(
-            driver::native_path(&entry[tab + 1..])
+            driver::native_path(blob.path)
                 .map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
         if crate::core::document::FileKind::for_path(&path)
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index bcfb7655..4ad262a8 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -7,7 +7,7 @@ use std::path::{Component, Path, PathBuf};
 use std::process::{Command, Stdio};
 
 use super::driver::{native_path, run_with_input};
-use super::process::{git_query, git_stdout, git_stdout_bytes};
+use super::process::{entry_fields, git_query, git_stdout, git_stdout_bytes, regular_index_blob};
 use crate::config::Config;
 use crate::core::document::FileKind;
 use crate::diagnostic::{Result, YamarkError};
@@ -29,15 +29,14 @@ impl IndexSnapshot {
             .map_err(YamarkError::new)?;
         let mut markdown = HashMap::new();
         for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-            let (filename, [mode, oid, stage]) = entry_fields(record)?;
-            if stage != b"0" || !matches!(mode, b"100644" | b"100755") {
+            let Some(blob) = regular_index_blob(record).map_err(YamarkError::new)? else {
                 continue;
-            }
+            };
             // The rest of the index may include paths this OS cannot represent.
-            if let Ok(filename) = native_path(filename) {
+            if let Ok(filename) = native_path(blob.path) {
                 let path = Path::new(filename);
                 if FileKind::for_path(path) == FileKind::Markdown {
-                    markdown.insert(path.to_owned(), oid.to_vec());
+                    markdown.insert(path.to_owned(), blob.oid.to_vec());
                 }
             }
         }
@@ -107,20 +106,6 @@ fn config_for_directory(repo_root: &Path, tree: &str, parent: &Path) -> Result<(
     Ok((dir.to_owned(), config))
 }
 
-// ls-tree and ls-files --stage emit three ASCII fields, a tab, and the raw path.
-fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3])> {
-    let tab = record
-        .iter()
-        .position(|&byte| byte == b'\t')
-        .ok_or_else(|| YamarkError::new("invalid Git entry record"))?;
-    let mut fields = record[..tab].split(|&byte| byte == b' ');
-    let [Some(first), Some(second), Some(third), None] = std::array::from_fn(|_| fields.next())
-    else {
-        return Err(YamarkError::new("invalid Git entry metadata"));
-    };
-    Ok((&record[tab + 1..], [first, second, third]))
-}
-
 /// Candidates are ordered nearest first. Use literal pathspecs and NUL-delimited
 /// Git records so filenames are never treated as globs or display-quoted text.
 fn nearest_entry(
@@ -167,7 +152,7 @@ fn nearest_entry(
     let records = git_stdout_bytes(repo, args).map_err(YamarkError::new)?;
     let mut nearest = None;
     for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-        let (filename, [mode, second, third]) = entry_fields(record)?;
+        let (filename, [mode, second, third]) = entry_fields(record).map_err(YamarkError::new)?;
         let path =
             Path::new(native_path(filename).map_err(|err| YamarkError::new(err.to_string()))?);
         let Some(rank) = candidates.iter().position(|candidate| candidate == path) else {
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index 5f9b46db..25e4fd9e 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -59,6 +59,31 @@ pub(super) fn git_stdout_bytes(
     Ok(output.stdout)
 }
 
+// ls-tree and ls-files --stage emit three ASCII fields, a tab, and the raw path.
+pub(super) fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3]), &'static str> {
+    let tab = record
+        .iter()
+        .position(|&byte| byte == b'\t')
+        .ok_or("invalid Git entry record")?;
+    let mut fields = record[..tab].split(|&byte| byte == b' ');
+    let [Some(first), Some(second), Some(third), None] = std::array::from_fn(|_| fields.next())
+    else {
+        return Err("invalid Git entry metadata");
+    };
+    Ok((&record[tab + 1..], [first, second, third]))
+}
+
+/// Path and object ID of a regular, stage-zero blob from ls-files --stage.
+pub(super) struct IndexBlob<'a> {
+    pub(super) path: &'a [u8],
+    pub(super) oid: &'a [u8],
+}
+
+pub(super) fn regular_index_blob(record: &[u8]) -> Result>, &'static str> {
+    let (path, [mode, oid, stage]) = entry_fields(record)?;
+    Ok((stage == b"0" && matches!(mode, b"100644" | b"100755")).then_some(IndexBlob { path, oid }))
+}
+
 pub(super) fn local_git_config_count(repo_root: &Path, key: &str) -> Result {
     let output = ProcessCommand::new("git")
         .arg("-C")

From 992501497e58515f3752d14ea1a906b2ae53ef89 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:53:56 -0500
Subject: [PATCH 25/64] Reuse checkout configuration throughout round-trip
 verification

---
 src/cli/git_filter.rs | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 131a488a..a23c6163 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -632,9 +632,11 @@ fn verify_roundtrip(
     width: usize,
 ) -> Result<(), String> {
     let mut failures = Vec::new();
+    let mut configs = checkout::CheckoutConfigs::default();
     for path in paths {
         let source_path = repo_root.join(path);
-        let config = checkout::config_for_path(repo_root, source.tree(), path)
+        let config = configs
+            .for_path(repo_root, source.tree(), path)
             .map_err(|err| err.diagnostic.render())?;
         if config.excludes(&source_path) {
             continue;

From e65ceaa5372ae3a72c7521dddd15fd3a8b943ace Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:54:06 -0500
Subject: [PATCH 26/64] Document how Git conversions select configuration

---
 docs/ARCHITECTURE.md   | 4 +++-
 website/git-filter.qmd | 4 ++--
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 7a3be8ba..ea21f14a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,7 +98,9 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter delegates each request to the configured clean or smudge command, including per-invocation Git overrides. Smudge finds the nearest tracked `yamark.toml` in the tree supplied by Git or in the index when Git omits the tree. Reading this configuration before decoding the blob keeps exclusions independent of checkout order. Clean and direct smudge invocations without `--source-tree` discover configuration in the working tree.
+The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, Yamark uses staged settings only if the supplied blob matches the path's stage-zero entry. Otherwise it preserves the incoming bytes. Direct smudge invocations without a checkout source use the working-tree configuration.
+
+The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files before verification and writing.
 
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 0d16731b..42628373 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -31,8 +31,8 @@ output to keep storage diffs small.
 
 Yamark's clean and smudge commands and its round-trip checks skip external embedded formatters. Checkout applies the revision's formatting settings even before its tools are available. To format embedded code with those tools, run `yamark format ` in a trusted checkout. Git still runs custom clean or smudge commands you configure in your local Git settings.
 
-During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
-looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
+During checkout, Git 2.27 and later can send the incoming tree to the process
+filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
 `NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies
 no tree, smudge uses the staged configuration if Git identifies the file's
 staged blob. If the blob is missing or differs from the staged blob, as can

From e35432302341ca35c50c0fae16af6479906f1c0e Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:53:38 -0500
Subject: [PATCH 27/64] Pass double-quoted Git filter paths as one argument

---
 src/cli/git_filter/driver.rs                  |  5 ++--
 ...filter_process_double_quoted_filename.case | 23 +++++++++++++++++++
 website/git-filter.qmd                        |  2 ++
 3 files changed, 28 insertions(+), 2 deletions(-)
 create mode 100644 tests/cases/git_filter_process_double_quoted_filename.case

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 65d11257..53f12a49 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -235,11 +235,12 @@ fn driver_command(key: &str) -> io::Result> {
 
 fn custom_alias(mut template: &str) -> String {
     let mut alias = String::from("alias.yamark-single-file=!");
-    // Keep path bytes in the environment. A filter may already surround its
-    // standalone %f with single quotes; replace the entire word in that case.
+    // Replace a standalone filename argument together with its optional quotes
+    // so the environment expansion always has exactly one layer of quoting.
     while !template.is_empty() {
         if let Some(rest) = template
             .strip_prefix("'%f'")
+            .or_else(|| template.strip_prefix("\"%f\""))
             .or_else(|| template.strip_prefix("%f"))
         {
             alias.push_str("\"$YAMARK_GIT_FILTER_PATH\"");
diff --git a/tests/cases/git_filter_process_double_quoted_filename.case b/tests/cases/git_filter_process_double_quoted_filename.case
new file mode 100644
index 00000000..c354ff9a
--- /dev/null
+++ b/tests/cases/git_filter_process_double_quoted_filename.case
@@ -0,0 +1,23 @@
+-- git-fixture
+{
+  "config": {"filter.yamark-md.clean": "printf '%%s\\n' \"%f\""},
+  "files": {"two notes.md": "Notes\n"}
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=clean\n", "pathname=two notes.md\n", null,
+  "Notes\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", null,
+  "status=success\n", null, "two notes.md\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 42628373..e8e613b8 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -163,6 +163,8 @@ git config filter.yamark-md.required true
 git config merge.renormalize true
 ```
 
+Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
+
 For personal use, add attributes to `.git/info/attributes`. For shared project
 storage, use `yamark git-filter adopt` so the attributes and normalized blobs
 land in the same commit. The shared attributes look like:

From 85f40a19598962eed36c300c0c7dc74c14189995 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:54:08 -0500
Subject: [PATCH 28/64] Preserve unverified smudge input through custom Yamark
 commands

---
 src/cli/git_filter.rs                         | 21 ++++++++++---
 src/cli/git_filter/driver.rs                  | 19 ++++++++----
 tests/cases/README.md                         |  2 +-
 ...filter_process_custom_treeless_smudge.case | 31 +++++++++++++++++++
 tests/cli_cases.rs                            |  1 +
 5 files changed, 62 insertions(+), 12 deletions(-)
 create mode 100644 tests/cases/git_filter_process_custom_treeless_smudge.case

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index a23c6163..841ca9e9 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -158,11 +158,22 @@ pub(super) fn run(command: GitFilterCommand) -> ExitCode {
             stdin_filename,
             markdown_wrap_at_column,
             source_tree,
-        } => run_git_filter(
-            stdin_filename,
-            MarkdownWrap::Column(markdown_wrap_at_column),
-            source_tree.or_else(|| env::var(driver::SOURCE_TREE_ENV).ok()),
-        ),
+        } => {
+            if source_tree.is_none() && env::var_os(driver::UNVERIFIED_SOURCE_ENV).is_some() {
+                return match io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()) {
+                    Ok(_) => ExitCode::SUCCESS,
+                    Err(err) => {
+                        eprintln!("{}:1:1: error: {err}", stdin_filename.display());
+                        ExitCode::FAILURE
+                    }
+                };
+            }
+            run_git_filter(
+                stdin_filename,
+                MarkdownWrap::Column(markdown_wrap_at_column),
+                source_tree.or_else(|| env::var(driver::SOURCE_TREE_ENV).ok()),
+            )
+        }
         GitFilterCommand::Process => driver::run(),
         GitFilterCommand::Adopt {
             repo,
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 53f12a49..623b2375 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -12,6 +12,7 @@ use super::checkout::{CheckoutConfigs, IndexSnapshot};
 use crate::config::{Config, discover_config_path};
 use crate::core::document::{FileKind, MarkdownWrap};
 
+pub(super) const UNVERIFIED_SOURCE_ENV: &str = "YAMARK_GIT_FILTER_UNVERIFIED_SOURCE";
 pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
 
 pub(super) fn run() -> ExitCode {
@@ -166,6 +167,10 @@ fn filter_file(
         .map(std::str::from_utf8)
         .transpose()
         .map_err(io::Error::other)?;
+    let unverified_source = tree == Some("")
+        && !configs
+            .index_matches(path, field(b"blob="))
+            .map_err(io::Error::other)?;
     let command = match command {
         Driver::Yamark(wrap) => {
             if FileKind::for_path(path) != FileKind::Markdown {
@@ -174,11 +179,7 @@ fn filter_file(
                     path.display()
                 )));
             }
-            if tree == Some("")
-                && !configs
-                    .index_matches(path, field(b"blob="))
-                    .map_err(io::Error::other)?
-            {
+            if unverified_source {
                 return Ok(contents);
             }
             let config = configs.for_path(path, tree).map_err(io::Error::other)?;
@@ -202,7 +203,13 @@ fn filter_file(
         .arg(command)
         .arg("yamark-single-file")
         .env("YAMARK_GIT_FILTER_PATH", path)
-        .env_remove(SOURCE_TREE_ENV);
+        .env_remove(SOURCE_TREE_ENV)
+        .env_remove(UNVERIFIED_SOURCE_ENV);
+    // A custom command may delegate to Yamark. Give it the same checkout
+    // context as the in-process driver while still running the custom command.
+    if unverified_source {
+        child.env(UNVERIFIED_SOURCE_ENV, "1");
+    }
     if let Some(tree) = tree {
         child.env(SOURCE_TREE_ENV, tree);
     }
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 055082d6..66e86ab8 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -21,7 +21,7 @@ An optional `-- env` section supplies a JSON object of environment variables for
 
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
-For the Git process filter, `-- stdin-packets` and `-- stdout-packets` record an exact stream of Git packet lines as a JSON array. Each string is one packet payload, including any trailing newline. A `null` is a flush packet.
+For the Git process filter, `-- stdin-packets` and `-- stdout-packets` record an exact stream of Git packet lines as a JSON array. Custom commands in a case can invoke the binary under test with `"$YAMARK_CASE_BIN"`. Each string is one packet payload, including any trailing newline. A `null` is a flush packet.
 
 ## Running selected cases
 
diff --git a/tests/cases/git_filter_process_custom_treeless_smudge.case b/tests/cases/git_filter_process_custom_treeless_smudge.case
new file mode 100644
index 00000000..a383183a
--- /dev/null
+++ b/tests/cases/git_filter_process_custom_treeless_smudge.case
@@ -0,0 +1,31 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false",
+    "filter.yamark-md.smudge": "\"$YAMARK_CASE_BIN\" git-filter smudge --stdin-filename '%f'"
+  },
+  "files": {
+    "doc.md": "# Base\n"
+  }
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "command=smudge\n", "pathname=doc.md\n", "blob=18facc4e56a8bce5e46541f709ee6f884bb0350c\n", null,
+  "#   Incoming\n", null,
+  "command=smudge\n", "pathname=doc.md\n", null,
+  "#   Incoming\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "status=success\n", null, "#   Incoming\n", null, null,
+  "status=success\n", null, "#   Incoming\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 08abd4f8..896f1a9b 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -58,6 +58,7 @@ fn cli_cases() {
             None
         };
         let mut command = Command::cargo_bin("yamark").unwrap();
+        command.env("YAMARK_CASE_BIN", env!("CARGO_BIN_EXE_yamark"));
         if let Some(repo) = &repo {
             let cwd = case.git_fixture.as_ref().unwrap()["cwd"]
                 .as_str()

From d2a638a4cfe2af9bfe9eaaadfcd1b2896fa429e9 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 10:54:50 -0500
Subject: [PATCH 29/64] Refresh the rendered Git filter guide

---
 website/git-filter.html.md | 37 +++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)

diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index f11fd4db..e8e613b8 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -29,12 +29,16 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
-During checkout, Git 2.27 and later tell the process filter which tree it is reading. Yamark
-looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
-`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git runs the
-filter without specifying a tree, as with `git checkout-index`, smudge reads
-the staged configuration. If `yamark.toml` is a symbolic link, its target
-must also be present in that tree or index. Clean reads the working-tree config.
+Yamark's clean and smudge commands and its round-trip checks skip external embedded formatters. Checkout applies the revision's formatting settings even before its tools are available. To format embedded code with those tools, run `yamark format ` in a trusted checkout. Git still runs custom clean or smudge commands you configure in your local Git settings.
+
+During checkout, Git 2.27 and later can send the incoming tree to the process
+filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
+`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies
+no tree, smudge uses the staged configuration if Git identifies the file's
+staged blob. If the blob is missing or differs from the staged blob, as can
+happen during a merge or cherry-pick, smudge returns the incoming bytes
+unchanged. If `yamark.toml` is a symbolic link, its target must also be present
+in the selected tree or index. Clean reads the working-tree config.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.
@@ -83,6 +87,9 @@ files, and checks the codec invariant:
 clean(smudge(blob)) == blob
 ```
 
+`adopt` and `join` process regular files in Git's index. Both skip symbolic links
+and submodules.
+
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:
 
@@ -156,6 +163,8 @@ git config filter.yamark-md.required true
 git config merge.renormalize true
 ```
 
+Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
+
 For personal use, add attributes to `.git/info/attributes`. For shared project
 storage, use `yamark git-filter adopt` so the attributes and normalized blobs
 land in the same commit. The shared attributes look like:
@@ -219,6 +228,22 @@ pass through the filter but Yamark should preserve its contents. A file matched
 by [`exclude`](reference-config.qmd#excluded-files) in `yamark.toml` also passes
 through the filter byte for byte, so it need not be UTF-8.
 
+### Refresh a file after changing exclusions
+
+If two commits differ only in `yamark.toml`, Git can leave an unchanged
+Markdown blob on disk with its old wrapping. The next `git add` can then stage
+that wrapping as an edit to a newly excluded file.
+
+To see the working-tree version produced by the staged rules, run:
+
+```sh
+git checkout-index --temp -- NEWS.md
+```
+
+Git writes a temporary file and prints its name alongside `NEWS.md`. Compare
+the two files. If you have local edits, copy them into the temporary file
+before replacing `NEWS.md` with it. This refresh leaves the index intact.
+
 ## Diff shape
 
 Without the filter, editing one sentence inside a wrapped paragraph can modify

From a435ae82e1167f200366d52e114139a7bd6668e8 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:26:34 -0500
Subject: [PATCH 30/64] Leave merge renormalization under repository control

---
 RELEASE_NOTES.md                             |  2 +
 external-tests/cli/test_git_filter.py        | 39 ++++++++++++++++++--
 src/cli/git_filter.rs                        |  5 +--
 tests/cases/git_filter_teardown_legacy.case  |  2 +-
 tests/cases/git_filter_teardown_process.case |  2 +-
 website/git-filter.qmd                       |  7 +++-
 6 files changed, 47 insertions(+), 10 deletions(-)

diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 84380103..1752bf08 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -8,4 +8,6 @@ The experimental Git filter now reads the tracked `yamark.toml` from the tree be
 
 Git clean, smudge, and round-trip checks now skip external embedded formatters. Use `yamark format ` in a trusted checkout to format embedded code with your project's tools.
 
+Git filter setup leaves `merge.renormalize` under your control. If an earlier Yamark installation enabled it, run `git config --local --unset merge.renormalize` in that clone. With Git's default merge settings, an incoming branch can exclude a file and preserve its formatting when both branches edited it.
+
 `[paths]` overrides now match a `--stdin-file-path` that does not exist on disk on Windows, or when the path passes through a symlinked directory. Previously these paths could fail to match the config directory.
diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index 4b2be3aa..ea7903d0 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -367,6 +367,37 @@ def test_git_filter_check_rejects_non_roundtripping_committed_blob() -> None:
         assert "clean(smudge(blob)) != blob" in result.stderr
 
 
+def test_merge_preserves_newly_excluded_heading_and_local_paragraph(tmp_path: Path) -> None:
+    repo = tmp_path
+    init_repo(repo)
+    run_git(repo, "config", "core.autocrlf", "false")
+    run_git(repo, "config", "merge.renormalize", "false")
+    run_yamark(repo, "git-filter", "setup")
+    doc = repo / "doc.md"
+    base = b"# Base\n\nContext.\n\nOriginal ending.\n"
+    doc.write_bytes(base)
+    run_git(repo, "add", "doc.md")
+    run_git(repo, "commit", "-qm", "base")
+
+    run_git(repo, "checkout", "-qb", "incoming")
+    (repo / "yamark.toml").write_bytes(b"[format]\nexclude = ['doc.md']\n")
+    incoming = base.replace(b"# Base", b"#    Keep")
+    doc.write_bytes(incoming)
+    run_git(repo, "add", "doc.md", "yamark.toml")
+    run_git(repo, "commit", "-qm", "exclude the heading")
+    assert run_git(repo, "show", "HEAD:doc.md").stdout == incoming.decode()
+
+    run_git(repo, "checkout", "-q", "main")
+    doc.write_bytes(base.replace(b"Original ending.", b"Local ending."))
+    run_git(repo, "add", "doc.md")
+    run_git(repo, "commit", "-qm", "edit the ending")
+    run_git(repo, "merge", "--no-edit", "incoming")
+    merged = incoming.replace(b"Original ending.", b"Local ending.")
+    assert run_git(repo, "show", "HEAD:doc.md").stdout == merged.decode()
+    assert doc.read_bytes() == merged
+    assert run_git(repo, "status", "--porcelain").stdout == ""
+
+
 def test_git_filter_setup_configures_current_repo_for_specific_path() -> None:
     with TemporaryDirectory(prefix="yamark-pytest-git-") as temp:
         repo = Path(temp)
@@ -393,7 +424,8 @@ def test_git_filter_setup_configures_current_repo_for_specific_path() -> None:
         attributes = (repo / ".git/info/attributes").read_text(encoding="utf-8")
         assert attributes == f"{path} filter=yamark-md\n"
         assert run_git(repo, "config", "filter.yamark-md.required").stdout == "true\n"
-        assert run_git(repo, "config", "merge.renormalize").stdout == "true\n"
+        local_keys = run_git(repo, "config", "--local", "--name-only", "--list")
+        assert "merge.renormalize" not in local_keys.stdout.splitlines()
         assert (
             "git-filter clean --stdin-filename %f"
             in run_git(repo, "config", "filter.yamark-md.clean").stdout
@@ -419,6 +451,7 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         path = "content/blog/post/index.md"
 
         run_git(repo, "init")
+        run_git(repo, "config", "merge.renormalize", "false")
         target = repo / path
         target.parent.mkdir(parents=True)
         target.write_text("First sentence. Second sentence?\n", encoding="utf-8")
@@ -432,7 +465,8 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         result = run_yamark(repo, "git-filter", "teardown")
 
         assert "Removed yamark Git filter setup" in result.stdout
-        assert "Unset 5 local Git config value(s)" in result.stdout
+        assert "Unset 4 local Git config value(s)" in result.stdout
+        assert run_git(repo, "config", "--local", "merge.renormalize").stdout == "false\n"
         assert "Removed 1 yamark attribute pattern(s)" in result.stdout
         assert attributes_path.read_text(encoding="utf-8") == (
             "NEWS.md -filter\n"
@@ -448,7 +482,6 @@ def test_git_filter_teardown_removes_local_setup() -> None:
             "filter.yamark-md.smudge",
             "filter.yamark-md.process",
             "filter.yamark-md.required",
-            "merge.renormalize",
         ]:
             missing = subprocess.run(
                 ["git", "config", "--local", "--get", key],
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 841ca9e9..1168a416 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -485,8 +485,7 @@ fn configure_git_filter(
         repo_root,
         "filter.yamark-md.process",
         &format!("{yamark} git-filter process"),
-    )?;
-    run_git_config(repo_root, "merge.renormalize", "true")
+    )
 }
 
 fn default_clean_command(yamark: &str) -> String {
@@ -528,7 +527,6 @@ fn ensure_no_local_yamark_filter_setup(
         "filter.yamark-md.smudge",
         "filter.yamark-md.process",
         "filter.yamark-md.required",
-        "merge.renormalize",
     ] {
         if local_git_config_count(repo_root, key)? > 0 {
             return Err(format!(
@@ -792,7 +790,6 @@ fn unset_git_filter_config(repo_root: &Path) -> Result {
         "filter.yamark-md.smudge",
         "filter.yamark-md.process",
         "filter.yamark-md.required",
-        "merge.renormalize",
     ]
     .into_iter()
     .map(|key| unset_git_config_key(repo_root, key))
diff --git a/tests/cases/git_filter_teardown_legacy.case b/tests/cases/git_filter_teardown_legacy.case
index 94a972f7..fcf9c625 100644
--- a/tests/cases/git_filter_teardown_legacy.case
+++ b/tests/cases/git_filter_teardown_legacy.case
@@ -17,7 +17,7 @@ git-filter teardown
 -- stdin
 -- stdout
 Removed yamark Git filter setup from {{repo}}
-Unset 4 local Git config value(s)
+Unset 3 local Git config value(s)
 Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
 
 Tracked files keep their current index content until staged again. Run:
diff --git a/tests/cases/git_filter_teardown_process.case b/tests/cases/git_filter_teardown_process.case
index 5e00f77d..b2c38b14 100644
--- a/tests/cases/git_filter_teardown_process.case
+++ b/tests/cases/git_filter_teardown_process.case
@@ -18,7 +18,7 @@ git-filter teardown
 -- stdin
 -- stdout
 Removed yamark Git filter setup from {{repo}}
-Unset 5 local Git config value(s)
+Unset 4 local Git config value(s)
 Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
 
 Tracked files keep their current index content until staged again. Run:
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index e8e613b8..f2023c3e 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -160,9 +160,14 @@ git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
 git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
-git config merge.renormalize true
 ```
 
+Leave Git's `merge.renormalize` disabled when exclusions can differ between
+branches. During a two-sided merge, renormalization can run historical blobs
+through the current branch's clean filter and rewrite a file that the incoming
+branch excludes. If an earlier Yamark installation set this option in your
+clone, remove its setting with `git config --local --unset merge.renormalize`.
+
 Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
 
 For personal use, add attributes to `.git/info/attributes`. For shared project

From 09ea5f0597cc1e678eabaf45bda53dc96e2eb912 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:26:34 -0500
Subject: [PATCH 31/64] Accept Git filter headers with or without LF

---
 src/cli/git_filter/driver.rs                  | 31 +++++++++----------
 .../cases/git_filter_process_optional_lf.case | 22 +++++++++++++
 2 files changed, 36 insertions(+), 17 deletions(-)
 create mode 100644 tests/cases/git_filter_process_optional_lf.case

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 623b2375..1dec1212 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -28,9 +28,9 @@ pub(super) fn run() -> ExitCode {
 fn serve() -> io::Result<()> {
     let mut input = io::stdin().lock();
     let mut output = io::stdout().lock();
-    let hello = read_section(&mut input)?;
-    if hello.first().map(Vec::as_slice) != Some(b"git-filter-client\n")
-        || !hello.iter().any(|line| line == b"version=2\n")
+    let hello = read_headers(&mut input)?;
+    if hello.first().map(Vec::as_slice) != Some(b"git-filter-client")
+        || !hello.iter().any(|line| line == b"version=2")
     {
         return Err(io::Error::other("expected git-filter-client version 2"));
     }
@@ -54,19 +54,19 @@ fn serve() -> io::Result<()> {
         }
     });
     let mut configs = FilterConfigs::default();
-    let caps = read_section(&mut input)?;
+    let caps = read_headers(&mut input)?;
     let accepted: Vec<_> = caps
         .iter()
-        .map(Vec::as_slice)
-        .filter(|&cap| {
-            (cap == b"capability=clean\n" && clean.is_some())
-                || (cap == b"capability=smudge\n" && smudge.is_some())
+        .filter_map(|cap| match cap.as_slice() {
+            b"capability=clean" if clean.is_some() => Some(b"capability=clean\n".as_slice()),
+            b"capability=smudge" if smudge.is_some() => Some(b"capability=smudge\n".as_slice()),
+            _ => None,
         })
         .collect();
     write_section(&mut output, &accepted)?;
 
     while !input.fill_buf()?.is_empty() {
-        let fields = read_section(&mut input)?;
+        let fields = read_headers(&mut input)?;
         let mut contents = Vec::new();
         while read_packet(&mut input, &mut contents)? {}
         match filter_file(
@@ -148,13 +148,7 @@ fn filter_file(
     smudge: Option<&Driver>,
     configs: &mut FilterConfigs,
 ) -> io::Result> {
-    let field = |prefix: &[u8]| {
-        fields.iter().find_map(|line| {
-            line.strip_suffix(b"\n")
-                .unwrap_or(line)
-                .strip_prefix(prefix)
-        })
-    };
+    let field = |prefix: &[u8]| fields.iter().find_map(|line| line.strip_prefix(prefix));
     let path = field(b"pathname=").ok_or_else(|| io::Error::other("missing pathname"))?;
     let (command, tree) = match field(b"command=") {
         Some(b"clean") => (clean, None),
@@ -300,13 +294,16 @@ pub(super) fn run_with_input(
     })
 }
 
-fn read_section(reader: &mut impl Read) -> io::Result>> {
+fn read_headers(reader: &mut impl Read) -> io::Result>> {
     let mut packets = Vec::new();
     loop {
         let mut bytes = Vec::new();
         if !read_packet(reader, &mut bytes)? {
             return Ok(packets);
         }
+        if bytes.last() == Some(&b'\n') {
+            bytes.pop();
+        }
         packets.push(bytes);
     }
 }
diff --git a/tests/cases/git_filter_process_optional_lf.case b/tests/cases/git_filter_process_optional_lf.case
new file mode 100644
index 00000000..4a6b03f1
--- /dev/null
+++ b/tests/cases/git_filter_process_optional_lf.case
@@ -0,0 +1,22 @@
+-- git-fixture
+{
+  "config": {"filter.yamark-md.clean": "cat", "filter.yamark-md.smudge": "cat"},
+  "files": {"notes.md": "Notes\n"}
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client", "version=2", null,
+  "capability=clean", "capability=smudge", null,
+  "command=clean", "pathname=notes.md", null, "No final newline", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "status=success\n", null, "No final newline", null, null
+]
+-- stderr
+-- status
+0

From cb801e01fdeb4f35bb347cfbc2580d878eb0e0e7 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:27:47 -0500
Subject: [PATCH 32/64] Validate delegated smudge filenames before byte
 passthrough

---
 external-tests/cli/test_git_filter.py         | 24 ++++++++++
 src/cli.rs                                    |  8 ++--
 src/cli/git_filter.rs                         | 44 ++++++++++++-------
 ..._filter_smudge_unverified_unsupported.case | 11 +++++
 4 files changed, 67 insertions(+), 20 deletions(-)
 create mode 100644 tests/cases/git_filter_smudge_unverified_unsupported.case

diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index ea7903d0..ecf184cd 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -347,6 +347,30 @@ def test_git_filter_join_installs_local_config_and_keeps_checkout_clean(
         ).encode("utf-8")
 
 
+def test_delegated_smudge_rejects_unsupported_index_path(tmp_path: Path) -> None:
+    repo = tmp_path
+    init_repo(repo)
+    (repo / "file.txt").write_bytes(b"original\n")
+    run_git(repo, "add", "file.txt")
+    run_yamark(repo, "git-filter", "setup")
+    (repo / ".git/info/attributes").write_bytes(b"file.txt filter=yamark-md\n")
+    result = subprocess.run(
+        [
+            "git",
+            "-c",
+            'filter.yamark-md.smudge="$YAMARK_BIN" git-filter smudge --stdin-filename %f',
+            "cat-file",
+            "--filters",
+            ":file.txt",
+        ],
+        cwd=repo,
+        capture_output=True,
+    )
+    assert result.returncode != 0
+    assert b"file.txt:1:1: error: unsupported Git filter path" in result.stderr
+    assert result.stdout == b""
+
+
 def test_git_filter_check_rejects_non_roundtripping_committed_blob() -> None:
     with TemporaryDirectory(prefix="yamark-pytest-git-") as temp:
         repo = Path(temp)
diff --git a/src/cli.rs b/src/cli.rs
index 0e5f652c..2e50119f 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -365,7 +365,7 @@ fn run_format(
     if let Some(path) = stdin_file_path {
         return run_stdin(
             path,
-            |path| load_config_for_formatted_path(path, config.as_deref()),
+            |path| load_config_for_formatted_path(path, config.as_deref()).map(Some),
             options,
             execution,
         );
@@ -423,7 +423,7 @@ fn run_format(
 
 fn run_stdin(
     path: PathBuf,
-    load_config: impl FnOnce(&Path) -> crate::diagnostic::Result,
+    load_config: impl FnOnce(&Path) -> crate::diagnostic::Result>,
     options: FormatOptions,
     execution: FormatExecutionOptions,
 ) -> ExitCode {
@@ -435,7 +435,9 @@ fn run_stdin(
         }
     };
     let config = match load_config(&path) {
-        Ok(config) => config,
+        Ok(Some(config)) => config,
+        // Git could not identify the configuration that belongs to these bytes.
+        Ok(None) => return write_stdout(&path, &input),
         Err(err) => {
             eprintln!("{}", err.diagnostic.render());
             return ExitCode::from(1);
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 1168a416..a21a648b 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -151,27 +151,28 @@ pub(super) enum GitFilterCommand {
 
 pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     match command {
-        GitFilterCommand::Clean { stdin_filename } => {
-            run_git_filter(stdin_filename, MarkdownWrap::Sentence, None)
-        }
+        GitFilterCommand::Clean { stdin_filename } => run_git_filter(
+            stdin_filename,
+            MarkdownWrap::Sentence,
+            FilterSource::Worktree,
+        ),
         GitFilterCommand::Smudge {
             stdin_filename,
             markdown_wrap_at_column,
             source_tree,
         } => {
-            if source_tree.is_none() && env::var_os(driver::UNVERIFIED_SOURCE_ENV).is_some() {
-                return match io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()) {
-                    Ok(_) => ExitCode::SUCCESS,
-                    Err(err) => {
-                        eprintln!("{}:1:1: error: {err}", stdin_filename.display());
-                        ExitCode::FAILURE
-                    }
-                };
-            }
+            let source = match source_tree {
+                Some(tree) => FilterSource::Checkout(tree),
+                None if env::var_os(driver::UNVERIFIED_SOURCE_ENV).is_some() => {
+                    FilterSource::Unverified
+                }
+                None => env::var(driver::SOURCE_TREE_ENV)
+                    .map_or(FilterSource::Worktree, FilterSource::Checkout),
+            };
             run_git_filter(
                 stdin_filename,
                 MarkdownWrap::Column(markdown_wrap_at_column),
-                source_tree.or_else(|| env::var(driver::SOURCE_TREE_ENV).ok()),
+                source,
             )
         }
         GitFilterCommand::Process => driver::run(),
@@ -212,7 +213,13 @@ fn filter_options(wrap: MarkdownWrap) -> FormatOptions {
     }
 }
 
-fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source_tree: Option) -> ExitCode {
+enum FilterSource {
+    Worktree,
+    Checkout(String),
+    Unverified,
+}
+
+fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> ExitCode {
     if crate::core::document::FileKind::for_path(&path) != crate::core::document::FileKind::Markdown
     {
         eprintln!("{}:1:1: error: unsupported Git filter path", path.display());
@@ -220,9 +227,12 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source_tree: Option
     }
     run_stdin(
         path,
-        |path| match source_tree {
-            Some(tree) => checkout::config_for_path(Path::new("."), &tree, path),
-            None => load_config_for_formatted_path(path, None),
+        |path| match source {
+            FilterSource::Worktree => load_config_for_formatted_path(path, None).map(Some),
+            FilterSource::Checkout(tree) => {
+                checkout::config_for_path(Path::new("."), &tree, path).map(Some)
+            }
+            FilterSource::Unverified => Ok(None),
         },
         filter_options(wrap),
         FormatExecutionOptions {
diff --git a/tests/cases/git_filter_smudge_unverified_unsupported.case b/tests/cases/git_filter_smudge_unverified_unsupported.case
new file mode 100644
index 00000000..06f26dea
--- /dev/null
+++ b/tests/cases/git_filter_smudge_unverified_unsupported.case
@@ -0,0 +1,11 @@
+-- args
+git-filter smudge --stdin-filename file.txt
+-- env
+{"YAMARK_GIT_FILTER_UNVERIFIED_SOURCE": "1"}
+-- stdin
+Original content.
+-- stdout
+-- stderr
+file.txt:1:1: error: unsupported Git filter path
+-- status
+1

From 5b31414a0f0257cdb5359cfe3b0db1bc14fc0888 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:26:47 -0500
Subject: [PATCH 33/64] Rediscover working-tree settings for each Git clean
 request

---
 src/cli/git_filter/driver.rs                  | 21 ++--------
 .../git_filter_process_worktree_change.case   | 39 +++++++++++++++++++
 2 files changed, 43 insertions(+), 17 deletions(-)
 create mode 100644 tests/cases/git_filter_process_worktree_change.case

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 1dec1212..81a8dfd5 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -1,16 +1,15 @@
 //! Git's v2 process filter supplies the tree being checked out for each smudge.
 //! Keep the configured single-file commands authoritative, including -c overrides.
 
-use std::collections::HashMap;
-use std::collections::hash_map::Entry;
 use std::ffi::OsStr;
 use std::io::{self, BufRead, Read, Write};
-use std::path::{Path, PathBuf};
+use std::path::Path;
 use std::process::{Command, ExitCode, Stdio};
 
 use super::checkout::{CheckoutConfigs, IndexSnapshot};
-use crate::config::{Config, discover_config_path};
+use crate::config::Config;
 use crate::core::document::{FileKind, MarkdownWrap};
+use crate::workspace::load_config_for_formatted_path;
 
 pub(super) const UNVERIFIED_SOURCE_ENV: &str = "YAMARK_GIT_FILTER_UNVERIFIED_SOURCE";
 pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
@@ -100,7 +99,6 @@ enum Driver {
 
 #[derive(Default)]
 struct FilterConfigs {
-    worktree: HashMap,
     checkout: CheckoutConfigs,
     index: Option,
 }
@@ -126,18 +124,7 @@ impl FilterConfigs {
         if let Some(tree) = tree {
             return self.checkout.for_path(Path::new("."), tree, path);
         }
-        let parent = path.parent().unwrap_or_else(|| Path::new("."));
-        let base = match self.worktree.entry(parent.to_owned()) {
-            Entry::Occupied(entry) => entry.into_mut(),
-            Entry::Vacant(entry) => {
-                let config = discover_config_path(path)
-                    .map(|path| Config::from_path(&path))
-                    .transpose()?
-                    .unwrap_or_default();
-                entry.insert(config)
-            }
-        };
-        Ok(base.for_formatted_path(path))
+        load_config_for_formatted_path(path, None)
     }
 }
 
diff --git a/tests/cases/git_filter_process_worktree_change.case b/tests/cases/git_filter_process_worktree_change.case
new file mode 100644
index 00000000..660d9614
--- /dev/null
+++ b/tests/cases/git_filter_process_worktree_change.case
@@ -0,0 +1,39 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "docs/doc.md": "#   Keep\n",
+    "next.toml": "[format]\nexclude = ['doc.md']\n",
+    "yamark.toml": "[format]\nexclude = ['unrelated.md']\n"
+  },
+  "setup-filter": true
+}
+-- env
+{
+  "GIT_CONFIG_COUNT": "1",
+  "GIT_CONFIG_KEY_0": "filter.yamark-md.smudge",
+  "GIT_CONFIG_VALUE_0": "cp next.toml docs/yamark.toml && cat"
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=clean\n", "pathname=docs/doc.md\n", null, "#   Keep\n", null,
+  "command=smudge\n", "pathname=docs/doc.md\n", null, "edit config\n", null,
+  "command=clean\n", "pathname=docs/doc.md\n", null, "#   Keep\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "status=success\n", null, "# Keep\n", null, null,
+  "status=success\n", null, "edit config\n", null, null,
+  "status=success\n", null, "#   Keep\n", null, null
+]
+-- stderr
+-- status
+0

From b56691caf60b8e6a48473df259206e04c52e42ac Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:29:00 -0500
Subject: [PATCH 34/64] Check filtered files and attributes from the committed
 tree

---
 Cargo.toml                                    |  2 +-
 src/cli/git_filter.rs                         | 77 +++++++++++--------
 src/cli/git_filter/process.rs                 | 32 +++++++-
 tests/cases/README.md                         |  2 +
 .../git_filter_check_committed_selection.case | 24 ++++++
 .../git_filter_check_removed_attributes.case  | 17 ++++
 tests/cli_cases.rs                            | 11 +++
 website/git-filter.qmd                        |  4 +-
 8 files changed, 129 insertions(+), 40 deletions(-)
 create mode 100644 tests/cases/git_filter_check_committed_selection.case
 create mode 100644 tests/cases/git_filter_check_removed_attributes.case

diff --git a/Cargo.toml b/Cargo.toml
index 119fd4e2..9861a961 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,6 +32,7 @@ jsonc-parser = { version = "0.33.2", default-features = false }
 memchr = "2.8.3"
 num-bigint = "0.5.1"
 serde_json = "1.0.151"
+tempfile = "3.27.0"
 thiserror = "2.0.20"
 toml = "1.1.6"
 unicode-general-category = "1.1.0"
@@ -39,7 +40,6 @@ unicode-width = "0.2.2"
 
 [dev-dependencies]
 assert_cmd = "2.2.2"
-tempfile = "3.27.0"
 
 [profile.release]
 codegen-units = 1
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index a21a648b..eb425427 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -370,7 +370,7 @@ fn adopt_git_filter_inner(
     configure_git_filter(repo_root, yamark, width)?;
     let patterns = git_filter_attribute_patterns(repo_root, paths)?;
     let added = append_missing_attribute_lines(attributes_path, &patterns)?;
-    let targets = tracked_yamark_filter_paths(repo_root)?;
+    let targets = tracked_yamark_filter_paths(repo_root, BlobSource::Index)?;
     if targets.is_empty() {
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
@@ -406,7 +406,7 @@ fn join_git_filter(
     ensure_shared_yamark_attributes(&repo_root)?;
     configure_git_filter(&repo_root, yamark, width)?;
 
-    let targets = tracked_yamark_filter_paths(&repo_root)?;
+    let targets = tracked_yamark_filter_paths(&repo_root, BlobSource::Index)?;
     if targets.is_empty() {
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
@@ -424,7 +424,7 @@ fn join_git_filter(
 fn check_git_filter(repo: Option, width: usize) -> Result {
     let (repo_root, _) = git_filter_repo_paths(repo)?;
     ensure_shared_yamark_attributes(&repo_root)?;
-    let targets = tracked_yamark_filter_paths(&repo_root)?;
+    let targets = tracked_yamark_filter_paths(&repo_root, BlobSource::Head)?;
     if targets.is_empty() {
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
@@ -580,57 +580,66 @@ fn ensure_not_behind_upstream(repo_root: &Path) -> Result<(), String> {
 }
 
 fn ensure_shared_yamark_attributes(repo_root: &Path) -> Result<(), String> {
-    let attributes_path = repo_root.join(".gitattributes");
-    let attributes = fs::read_to_string(&attributes_path).map_err(|err| {
-        format!(
-            "{}: failed to read shared Git attributes: {err}",
-            attributes_path.display()
-        )
-    })?;
+    let attributes = git_stdout(repo_root, ["cat-file", "blob", "HEAD:.gitattributes"])?;
     if attributes.lines().any(line_has_yamark_filter_attribute) {
         Ok(())
     } else {
-        Err(format!(
-            "{} does not contain filter=yamark-md; run yamark git-filter adopt in the maintainer checkout first",
-            attributes_path.display()
-        ))
+        Err("HEAD:.gitattributes does not contain filter=yamark-md; run yamark git-filter adopt in the maintainer checkout first".to_owned())
     }
 }
 
-fn tracked_yamark_filter_paths(repo_root: &Path) -> Result, String> {
+fn tracked_yamark_filter_paths(
+    repo_root: &Path,
+    source: BlobSource,
+) -> Result, String> {
     // NUL records contain native filename bytes, not UTF-8 text or Git's
     // presentation quoting. Each check-attr response is path, name, then value.
-    let tracked = git_stdout_bytes(repo_root, ["ls-files", "--stage", "-z"])?;
-    let mut paths = Vec::new();
+    let index = match source {
+        BlobSource::Head => Some(process::TreeIndex::read_tree(repo_root, "HEAD")?),
+        BlobSource::Index => None,
+    };
+    let git = || match &index {
+        Some(snapshot) => snapshot.git(repo_root),
+        None => process::git_query(repo_root),
+    };
+    let tracked = process::checked_stdout(git().args(["ls-files", "--stage", "-z"]).output())?;
+    let mut names = Vec::new();
     for entry in tracked
         .split(|byte| *byte == 0)
         .filter(|entry| !entry.is_empty())
     {
-        // Only regular, stage-zero blobs belong in the worktree write set.
         let Some(blob) = process::regular_index_blob(entry)? else {
             continue;
         };
-        let path = PathBuf::from(
+        let path = Path::new(
             driver::native_path(blob.path)
                 .map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
-        if crate::core::document::FileKind::for_path(&path)
-            != crate::core::document::FileKind::Markdown
+        if crate::core::document::FileKind::for_path(path)
+            == crate::core::document::FileKind::Markdown
         {
-            continue;
+            names.extend_from_slice(blob.path);
+            names.push(0);
         }
-        let output = git_stdout_bytes(
-            repo_root,
-            [
-                OsString::from("check-attr"),
-                OsString::from("-z"),
-                OsString::from("filter"),
-                OsString::from("--"),
-                path.as_os_str().to_owned(),
-            ],
-        )?;
-        if output.split(|byte| *byte == 0).nth(2) == Some(b"yamark-md") {
-            paths.push(path);
+    }
+    let mut attr = git();
+    attr.arg("check-attr");
+    if index.is_some() {
+        attr.arg("--cached");
+    }
+    attr.args(["-z", "--stdin", "filter"])
+        .stderr(std::process::Stdio::piped());
+    let output = process::checked_stdout(driver::run_with_input(&mut attr, &names))?;
+    let mut fields = output.split(|&byte| byte == 0);
+    let mut paths = Vec::new();
+    while let Some(name) = fields.next().filter(|name| !name.is_empty()) {
+        let (Some(b"filter"), Some(value)) = (fields.next(), fields.next()) else {
+            return Err("invalid git check-attr record".to_owned());
+        };
+        if value == b"yamark-md" {
+            paths.push(PathBuf::from(
+                driver::native_path(name).map_err(|err| err.to_string())?,
+            ));
         }
     }
     Ok(paths)
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index 25e4fd9e..c134a554 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -49,16 +49,40 @@ pub(super) fn git_stdout_bytes(
     repo_root: &Path,
     args: impl IntoIterator>,
 ) -> Result, String> {
-    let output = git_query(repo_root)
-        .args(args)
-        .output()
-        .map_err(|err| format!("failed to run git: {err}"))?;
+    checked_stdout(git_query(repo_root).args(args).output())
+}
+
+pub(super) fn checked_stdout(
+    output: std::io::Result,
+) -> Result, String> {
+    let output = output.map_err(|err| format!("failed to run git: {err}"))?;
     if !output.status.success() {
         return Err(format_git_error("git", output));
     }
     Ok(output.stdout)
 }
 
+/// An index containing exactly one tree's entries, independent of staged
+/// changes and working-tree stat data.
+pub(super) struct TreeIndex(tempfile::TempDir);
+
+impl TreeIndex {
+    pub(super) fn read_tree(repo: &Path, tree: &str) -> Result {
+        let index = Self(
+            tempfile::tempdir()
+                .map_err(|err| format!("failed to create temporary index directory: {err}"))?,
+        );
+        checked_stdout(index.git(repo).args(["read-tree", tree]).output())?;
+        Ok(index)
+    }
+
+    pub(super) fn git(&self, repo: &Path) -> ProcessCommand {
+        let mut command = git_query(repo);
+        command.env("GIT_INDEX_FILE", self.0.path().join("index"));
+        command
+    }
+}
+
 // ls-tree and ls-files --stage emit three ASCII fields, a tab, and the raw path.
 pub(super) fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3]), &'static str> {
     let tab = record
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 66e86ab8..9cfcec93 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -73,3 +73,5 @@ Git integration transcripts can add a `-- git-fixture` JSON object with `config`
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
 The `git_filter_adopt_*.case` transcripts cover adoption with automatic CRLF conversion, LF checkouts, and explicit `eol` attributes overriding `core.autocrlf`. They record the staged status and use `-- git-index` and `-- git-worktree` JSON file mappings to check exact staged and checkout bytes. JSON newline escapes make the expected CRLF/LF distinction visible in the transcript.
+
+Use `git-after-commit` in a Git fixture to run an ordered list of Git argument arrays after creating its commit. The `git_filter_check_committed_selection` and `git_filter_check_removed_attributes` cases use it to change the index and checkout while verifying the original commit.
diff --git a/tests/cases/git_filter_check_committed_selection.case b/tests/cases/git_filter_check_committed_selection.case
new file mode 100644
index 00000000..cebaf5a6
--- /dev/null
+++ b/tests/cases/git_filter_check_committed_selection.case
@@ -0,0 +1,24 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "staged-attributes": "good.md filter=yamark-md\n",
+    "bad.md": "#    Bad\n",
+    "good.md": "# Good\n",
+    "other.md": "#    Also bad\n"
+  },
+  "git-after-commit": [
+    ["rm", "--cached", "--", "bad.md"],
+    ["mv", "-f", "staged-attributes", ".gitattributes"]
+  ]
+}
+-- args
+git-filter check
+-- stdin
+-- stdout
+-- stderr
+error: bad.md: roundtrip failure: clean(smudge(blob)) != blob
+other.md: roundtrip failure: clean(smudge(blob)) != blob
+-- status
+1
diff --git a/tests/cases/git_filter_check_removed_attributes.case b/tests/cases/git_filter_check_removed_attributes.case
new file mode 100644
index 00000000..923c85a9
--- /dev/null
+++ b/tests/cases/git_filter_check_removed_attributes.case
@@ -0,0 +1,17 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "good.md": "# Good\n"
+  },
+  "git-after-commit": [["rm", ".gitattributes"]]
+}
+-- args
+git-filter check
+-- stdin
+-- stdout
+yamark Git filter check passed for 1 Markdown file(s).
+-- stderr
+-- status
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 896f1a9b..e9d14dcb 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -253,6 +253,17 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
         }
     }
     git(&["commit", "-q", "-m", "fixture"]);
+    if let Some(commands) = fixture.get("git-after-commit") {
+        for args in commands.as_array().unwrap() {
+            let args: Vec<&str> = args
+                .as_array()
+                .unwrap()
+                .iter()
+                .map(|arg| arg.as_str().unwrap())
+                .collect();
+            git(&args);
+        }
+    }
     if fixture["setup-filter"].as_bool() == Some(true) {
         Command::cargo_bin("yamark")
             .unwrap()
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index f2023c3e..b101437a 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -121,7 +121,9 @@ contract:
 yamark git-filter check
 ```
 
-It fails if any tracked Markdown file selected by `.gitattributes` violates:
+It checks the regular Markdown files in `HEAD`, using the committed versions of
+`.gitattributes` and `yamark.toml`. Staged edits, removals, and replacements do
+not change what the command checks. It fails if any selected file violates:
 
 ```text
 clean(smudge(blob)) == blob

From bbad252419aa5a7fabafc559d9642043a368be5b Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:30:59 -0500
Subject: [PATCH 35/64] Match configuration exclusions with Git wildmatch

---
 Cargo.lock                                    | 128 ++++++++++++++-
 Cargo.toml                                    |   1 +
 src/config.rs                                 | 103 +-----------
 src/config/exclude.rs                         | 149 ++++++++++++++++++
 .../config_exclude_character_classes.case     |  34 ++++
 tests/cases/config_exclude_posix_class.case   |   6 +-
 .../cases/config_exclude_unclosed_class.case  |  14 ++
 website/reference-config.html.md              |   6 +-
 website/reference-config.qmd                  |   6 +-
 9 files changed, 341 insertions(+), 106 deletions(-)
 create mode 100644 src/config/exclude.rs
 create mode 100644 tests/cases/config_exclude_character_classes.case
 create mode 100644 tests/cases/config_exclude_unclosed_class.case

diff --git a/Cargo.lock b/Cargo.lock
index 89c8c7fd..acf97d4c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -215,6 +215,104 @@ dependencies = [
  "r-efi",
 ]
 
+[[package]]
+name = "gix-error"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
+dependencies = [
+ "bstr",
+]
+
+[[package]]
+name = "gix-fs"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "516aec0f136bdfb26420ced8e43e1d5b36b967cd94aa1c763036208f25b8e888"
+dependencies = [
+ "bstr",
+ "gix-error",
+ "gix-macros",
+ "gix-parallel",
+ "gix-path",
+ "gix-utils",
+ "libc",
+]
+
+[[package]]
+name = "gix-glob"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48b4b3c2353cc9f9709a49d8c3b9c7a7a0188d43eeb756ac9a5a36bc397b013c"
+dependencies = [
+ "bitflags",
+ "bstr",
+ "gix-fs",
+ "gix-path",
+ "gix-trace",
+ "gix-utils",
+]
+
+[[package]]
+name = "gix-macros"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79ca2ec664aea06d549444f9cd35546dd1732b2ea188b48159cea4fbf2a05848"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "gix-parallel"
+version = "0.50.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
+dependencies = [
+ "gix-trace",
+]
+
+[[package]]
+name = "gix-path"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
+dependencies = [
+ "bstr",
+ "gix-error",
+ "gix-trace",
+ "gix-validate",
+ "winreg",
+]
+
+[[package]]
+name = "gix-trace"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
+
+[[package]]
+name = "gix-utils"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
+dependencies = [
+ "fastrand",
+ "getrandom",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "gix-validate"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
+dependencies = [
+ "bstr",
+ "gix-error",
+]
+
 [[package]]
 name = "globset"
 version = "0.4.20"
@@ -506,9 +604,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
 name = "syn"
-version = "3.0.5"
+version = "3.0.10"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -554,6 +652,12 @@ dependencies = [
  "syn",
 ]
 
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
 [[package]]
 name = "toml"
 version = "1.1.6+spec-1.1.0"
@@ -605,6 +709,15 @@ version = "1.0.24"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
 
+[[package]]
+name = "unicode-normalization"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
+dependencies = [
+ "tinyvec",
+]
+
 [[package]]
 name = "unicode-width"
 version = "0.2.2"
@@ -666,12 +779,23 @@ version = "1.0.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
 
+[[package]]
+name = "winreg"
+version = "0.56.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
+dependencies = [
+ "cfg-if",
+ "windows-sys",
+]
+
 [[package]]
 name = "yamark"
 version = "0.6.1+dev"
 dependencies = [
  "assert_cmd",
  "clap",
+ "gix-glob",
  "ignore",
  "json-five",
  "jsonc-parser",
diff --git a/Cargo.toml b/Cargo.toml
index 9861a961..89a17de8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,6 +26,7 @@ path = "src/main.rs"
 
 [dependencies]
 clap = { version = "4.6.6", features = ["derive"] }
+gix-glob = "0.30.0"
 ignore = "0.4.33"
 json-five = { version = "=0.3.1", default-features = false }
 jsonc-parser = { version = "0.33.2", default-features = false }
diff --git a/src/config.rs b/src/config.rs
index 46001058..d5e6d843 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -2,9 +2,10 @@ use std::collections::BTreeMap;
 use std::env;
 use std::fs;
 use std::path::{Component, Path, PathBuf};
-use std::sync::Arc;
 
-use ignore::gitignore::{Gitignore, GitignoreBuilder};
+mod exclude;
+
+pub use exclude::ExcludePatterns;
 
 use crate::core::directives::TemplateDelimiter;
 use crate::core::document::{AbbreviationOverrides, MarkdownTableWidths, MarkdownWrap};
@@ -42,11 +43,6 @@ pub struct FormatConfig {
     pub exclude: Option,
 }
 
-/// Exclusion patterns parsed from `[format] exclude` and matched relative to
-/// the config directory.
-#[derive(Debug, Clone)]
-pub struct ExcludePatterns(Arc);
-
 #[derive(Debug, Clone)]
 pub struct PathConfig {
     pub path: PathBuf,
@@ -167,20 +163,13 @@ impl Config {
     /// Whether `[format] exclude` matches `path`. Patterns are relative to the
     /// config directory, so they never match a path outside it.
     pub fn excludes(&self, path: &Path) -> bool {
-        let Some(ExcludePatterns(exclude)) = &self.format.exclude else {
+        let Some(exclude) = &self.format.exclude else {
             return false;
         };
         let Some(relative) = self.written_path_below_config_dir(path) else {
             return false;
         };
-        // As in Git, a `!` pattern cannot re-include a file below an excluded
-        // directory. Check ancestors before matching the file itself.
-        relative
-            .ancestors()
-            .skip(1)
-            .filter(|dir| !dir.as_os_str().is_empty())
-            .any(|dir| exclude.matched(dir, true).is_ignore())
-            || exclude.matched(&relative, false).is_ignore()
+        exclude.excludes(&relative)
     }
 
     /// Returns the path below the config directory, or `None` outside it.
@@ -407,91 +396,11 @@ fn apply_format_layer(value: &toml::Value, format: &mut FormatConfig) -> Result<
         format.abbreviations = parse_abbreviations(value)?;
     }
     if let Some(value) = table.get("exclude") {
-        format.exclude = Some(ExcludePatterns(Arc::new(parse_exclude(value)?)));
+        format.exclude = Some(ExcludePatterns::parse(value)?);
     }
     Ok(())
 }
 
-fn parse_exclude(value: &toml::Value) -> Result {
-    let patterns = value
-        .as_array()
-        .and_then(|patterns| {
-            patterns
-                .iter()
-                .map(toml::Value::as_str)
-                .collect::>>()
-        })
-        .ok_or_else(|| YamarkError::new("format.exclude must be an array of strings"))?;
-    // The empty root matches patterns against paths that are already relative
-    // to the config directory, which is unknown while parsing TOML text.
-    let mut builder = GitignoreBuilder::new("");
-    for pattern in patterns {
-        builder
-            .add_line(None, &gitignore_pattern(pattern)?)
-            .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))?;
-    }
-    builder
-        .build()
-        .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))
-}
-
-/// Adapt Git's literal braces and diagnose named classes the glob matcher
-/// would silently interpret as ordinary bracket expressions.
-fn gitignore_pattern(pattern: &str) -> Result {
-    if pattern.starts_with('#') {
-        return Ok(pattern.to_owned());
-    }
-    let mut out = String::with_capacity(pattern.len());
-    let mut chars = pattern.chars();
-    let mut may_have_class = true;
-    while let Some(c) = chars.next() {
-        if matches!(c, '{' | '}') {
-            out.push('\\');
-        }
-        out.push(c);
-        match c {
-            '\\' => out.extend(chars.next()),
-            '[' if may_have_class => {
-                // Braces inside a character class already match literally.
-                // A leading ']' (after optional negation) is a class member.
-                let rest = chars.as_str();
-                let members = rest.strip_prefix(['!', '^']).unwrap_or(rest);
-                let members = members.strip_prefix(']').unwrap_or(members);
-                let mut scan = members.chars();
-                let end = loop {
-                    match scan.next() {
-                        Some(']') => break Some(scan.as_str()),
-                        Some('\\') => {
-                            scan.next();
-                        }
-                        Some('[') => {
-                            if let Some(name) = scan.as_str().strip_prefix(':')
-                                && let Some((name, _)) = name.split_once(":]")
-                                && !name.is_empty()
-                                && name.bytes().all(|b| b.is_ascii_alphabetic())
-                            {
-                                return Err(YamarkError::new(format!(
-                                    "format.exclude: POSIX character class [:{name}:] is unsupported in '{pattern}'"
-                                )));
-                            }
-                        }
-                        Some(_) => {}
-                        None => break None,
-                    }
-                };
-                if let Some(after) = end {
-                    out.push_str(&rest[..rest.len() - after.len()]);
-                    chars = after.chars();
-                } else {
-                    may_have_class = false;
-                }
-            }
-            _ => {}
-        }
-    }
-    Ok(out)
-}
-
 fn parse_abbreviations(value: &toml::Value) -> Result {
     let table = value
         .as_table()
diff --git a/src/config/exclude.rs b/src/config/exclude.rs
new file mode 100644
index 00000000..98d7270c
--- /dev/null
+++ b/src/config/exclude.rs
@@ -0,0 +1,149 @@
+//! Git-style patterns for the config's explicit file exclusions.
+
+use std::path::Path;
+use std::sync::Arc;
+
+use gix_glob::{Pattern, pattern::Case, wildmatch};
+
+use crate::diagnostic::{Result, YamarkError};
+
+/// Exclusion patterns parsed from `[format] exclude` and matched relative to
+/// the config directory.
+#[derive(Debug, Clone)]
+pub struct ExcludePatterns(Arc<[Pattern]>);
+
+impl ExcludePatterns {
+    pub(super) fn parse(value: &toml::Value) -> Result {
+        let invalid = || YamarkError::new("format.exclude must be an array of strings");
+        let mut patterns = Vec::new();
+        for value in value.as_array().ok_or_else(invalid)? {
+            let mut text = value.as_str().ok_or_else(invalid)?;
+            if text.starts_with('#') {
+                continue;
+            }
+            // Only unescaped trailing spaces are insignificant in a Git pattern.
+            while let Some(prefix) = text.strip_suffix(' ') {
+                if prefix.bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1 {
+                    break;
+                }
+                text = prefix;
+            }
+            if let Some(pattern) = Pattern::from_bytes(text.as_bytes()) {
+                validate_classes(text)?;
+                patterns.push(pattern);
+            }
+        }
+        Ok(Self(patterns.into()))
+    }
+
+    pub(super) fn excludes(&self, relative: &Path) -> bool {
+        let path = relative.as_os_str().as_encoded_bytes();
+        #[cfg(windows)]
+        let normalized = path
+            .iter()
+            .map(|&b| if b == b'\\' { b'/' } else { b })
+            .collect::>();
+        #[cfg(windows)]
+        let path = normalized.as_slice();
+        let mut path = path;
+        let mut is_dir = false;
+        // At each level the last matching pattern wins. An excluded parent
+        // directory keeps the file excluded regardless of a file-level '!'.
+        while !path.is_empty() {
+            let slash = path.iter().rposition(|&b| b == b'/');
+            if let Some(pattern) = self.0.iter().rev().find(|pattern| {
+                pattern.matches_repo_relative_path(
+                    path.into(),
+                    slash.map(|pos| pos + 1),
+                    Some(is_dir),
+                    Case::Sensitive,
+                    wildmatch::Mode::NO_MATCH_SLASH_LITERAL,
+                )
+            }) && !pattern.is_negative()
+            {
+                return true;
+            }
+            let Some(slash) = slash else { break };
+            path = &path[..slash];
+            is_dir = true;
+        }
+        false
+    }
+}
+
+// Wildmatch treats malformed classes as nonmatches. Diagnose them while loading
+// the config so a typo in an exclusion cannot silently allow an in-place write.
+fn validate_classes(pattern: &str) -> Result<()> {
+    let error = |msg: &str| {
+        YamarkError::new(format!(
+            "format.exclude: error parsing glob '{pattern}': {msg}"
+        ))
+    };
+    let mut bytes = pattern.as_bytes().iter();
+    let next_member = |bytes: &mut std::slice::Iter<'_, u8>| {
+        bytes
+            .next()
+            .copied()
+            .ok_or_else(|| error("unclosed character class"))
+    };
+    while let Some(&byte) = bytes.next() {
+        if byte == b'\\' {
+            bytes.next().ok_or_else(|| error("dangling escape"))?;
+            continue;
+        }
+        if byte != b'[' {
+            continue;
+        }
+        if matches!(bytes.as_slice().first(), Some(b'!' | b'^')) {
+            bytes.next();
+        }
+        let mut previous = None;
+        let mut first = true;
+        loop {
+            let byte = next_member(&mut bytes)?;
+            if byte == b']' && !first {
+                break;
+            }
+            first = false;
+            if byte == b'['
+                && let Some(posix) = bytes.as_slice().strip_prefix(b":")
+                && let Some(close) = posix.iter().position(|&b| b == b']')
+                && let Some(name) = posix[..close].strip_suffix(b":")
+            {
+                const CLASSES: &str =
+                    "alnum alpha blank cntrl digit graph lower print punct space upper xdigit";
+                if !CLASSES
+                    .split_ascii_whitespace()
+                    .any(|class| class.as_bytes() == name)
+                {
+                    return Err(error(&format!(
+                        "unknown POSIX character class [:{}:]",
+                        String::from_utf8_lossy(name)
+                    )));
+                }
+                bytes = posix[close + 1..].iter();
+                previous = None;
+            } else if byte == b'-'
+                && let Some(start) = previous.take()
+                && bytes.as_slice().first() != Some(&b']')
+            {
+                let mut end = next_member(&mut bytes)?;
+                if end == b'\\' {
+                    end = next_member(&mut bytes)?;
+                }
+                if start > end {
+                    return Err(error(&format!(
+                        "invalid range; '{}' > '{}'",
+                        char::from(start),
+                        char::from(end)
+                    )));
+                }
+            } else if byte == b'\\' {
+                previous = Some(next_member(&mut bytes)?);
+            } else {
+                previous = Some(byte);
+            }
+        }
+    }
+    Ok(())
+}
diff --git a/tests/cases/config_exclude_character_classes.case b/tests/cases/config_exclude_character_classes.case
new file mode 100644
index 00000000..612eded4
--- /dev/null
+++ b/tests/cases/config_exclude_character_classes.case
@@ -0,0 +1,34 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nexclude = ['[a\\-c].md', '/docs[!0-9]*.md', 'sub/[-0].md']\n",
+    "-.md": "#   dash\n",
+    "a.md": "#   a\n",
+    "b.md": "#   b\n",
+    "c.md": "#   c\n",
+    "docs-a.md": "#   dash\n",
+    "docs1.md": "#   digit\n",
+    "docs/notes.md": "#   nested\n",
+    "sub/0.md": "#   zero\n"
+  }
+}
+-- args
+format .
+-- stdin
+-- stdout
+9 files scanned, 3 formatted, 0 unchanged, 6 skipped, 0 failed
+-- stderr
+-- git-worktree
+{
+  "-.md": "#   dash\n",
+  "a.md": "#   a\n",
+  "b.md": "# b\n",
+  "c.md": "#   c\n",
+  "docs-a.md": "#   dash\n",
+  "docs1.md": "# digit\n",
+  "docs/notes.md": "# nested\n",
+  "sub/0.md": "#   zero\n"
+}
+-- status
+0
diff --git a/tests/cases/config_exclude_posix_class.case b/tests/cases/config_exclude_posix_class.case
index 92036ff2..538e0732 100644
--- a/tests/cases/config_exclude_posix_class.case
+++ b/tests/cases/config_exclude_posix_class.case
@@ -11,12 +11,12 @@
 format --config yamark.toml 1-report.md letter.md
 -- stdin
 -- stdout
+2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
 -- stderr
-yamark.toml:1:1: error: format.exclude: POSIX character class [:digit:] is unsupported in '[[:digit:]]*.md'
 -- git-worktree
 {
   "1-report.md": "#   Report\n",
-  "letter.md": "#   Letter\n"
+  "letter.md": "# Letter\n"
 }
 -- status
-1
+0
diff --git a/tests/cases/config_exclude_unclosed_class.case b/tests/cases/config_exclude_unclosed_class.case
new file mode 100644
index 00000000..baec6a8d
--- /dev/null
+++ b/tests/cases/config_exclude_unclosed_class.case
@@ -0,0 +1,14 @@
+-- git-fixture
+{
+  "config": {},
+  "files": {"yamark.toml": "[format]\nexclude = ['[0-9.md']\n"}
+}
+-- args
+format --config yamark.toml --stdin-file-path input.md
+-- stdin
+#   Heading
+-- stdout
+-- stderr
+yamark.toml:1:1: error: format.exclude: error parsing glob '[0-9.md': unclosed character class
+-- status
+1
diff --git a/website/reference-config.html.md b/website/reference-config.html.md
index 55342b6e..858ce6fe 100644
--- a/website/reference-config.html.md
+++ b/website/reference-config.html.md
@@ -53,8 +53,10 @@ Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
-For ASCII digits, use a range such as `[0-9]*.md`. POSIX named character
-classes such as `[[:digit:]]` cause a configuration error before formatting.
+Character classes match one byte within a path component. For example,
+`[[:digit:]]*.md` matches `1-report.md`, and `[a\-c].md` matches `a.md`,
+`-.md`, and `c.md`. A negated class such as `[!0-9]` cannot match a path
+separator. Yamark reports malformed classes before formatting.
 
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:
diff --git a/website/reference-config.qmd b/website/reference-config.qmd
index 55342b6e..858ce6fe 100644
--- a/website/reference-config.qmd
+++ b/website/reference-config.qmd
@@ -53,8 +53,10 @@ Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
-For ASCII digits, use a range such as `[0-9]*.md`. POSIX named character
-classes such as `[[:digit:]]` cause a configuration error before formatting.
+Character classes match one byte within a path component. For example,
+`[[:digit:]]*.md` matches `1-report.md`, and `[a\-c].md` matches `a.md`,
+`-.md`, and `c.md`. A negated class such as `[!0-9]` cannot match a path
+separator. Yamark reports malformed classes before formatting.
 
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:

From e38de8ebd323e2dd50c32ce4149222018d7d0f2b Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:31:55 -0500
Subject: [PATCH 36/64] Clarify attribute precedence during committed-blob
 checks

---
 website/git-filter.qmd | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index b101437a..9b8190ce 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -122,8 +122,9 @@ yamark git-filter check
 ```
 
 It checks the regular Markdown files in `HEAD`, using the committed versions of
-`.gitattributes` and `yamark.toml`. Staged edits, removals, and replacements do
-not change what the command checks. It fails if any selected file violates:
+`.gitattributes` and `yamark.toml`. Git still applies its usual attribute
+precedence, including overrides in `.git/info/attributes`. The check fails
+if any selected file violates:
 
 ```text
 clean(smudge(blob)) == blob

From 8615aefa308484ce09c33f68b7b4c7a81e1ab1e0 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:31:45 -0500
Subject: [PATCH 37/64] Read staged settings and blob identity from the same
 Git index

---
 Cargo.lock                                    |   1 +
 Cargo.toml                                    |   1 +
 docs/ARCHITECTURE.md                          |   2 +-
 external-tests/cli/test_git_filter.py         |  43 +++
 src/cli/git_filter.rs                         |  45 ++-
 src/cli/git_filter/checkout.rs                | 315 ++++++++++--------
 src/cli/git_filter/driver.rs                  |  66 ++--
 src/cli/git_filter/process.rs                 |  13 +-
 .../git_filter_process_conflicted_config.case |  47 +++
 .../git_filter_process_index_change.case      |  44 +++
 ..._filter_smudge_unverified_unsupported.case |   2 +-
 tests/git_filter_process.rs                   |  52 +++
 website/git-filter.qmd                        |   6 +-
 13 files changed, 427 insertions(+), 210 deletions(-)
 create mode 100644 tests/cases/git_filter_process_conflicted_config.case
 create mode 100644 tests/cases/git_filter_process_index_change.case

diff --git a/Cargo.lock b/Cargo.lock
index acf97d4c..0d7a01af 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -801,6 +801,7 @@ dependencies = [
  "jsonc-parser",
  "memchr",
  "num-bigint",
+ "same-file",
  "serde_json",
  "tempfile",
  "thiserror",
diff --git a/Cargo.toml b/Cargo.toml
index 89a17de8..ac6645b1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,6 +32,7 @@ json-five = { version = "=0.3.1", default-features = false }
 jsonc-parser = { version = "0.33.2", default-features = false }
 memchr = "2.8.3"
 num-bigint = "0.5.1"
+same-file = "1.0.6"
 serde_json = "1.0.151"
 tempfile = "3.27.0"
 thiserror = "2.0.20"
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ea21f14a..ff115de0 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,7 +98,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, Yamark uses staged settings only if the supplied blob matches the path's stage-zero entry. Otherwise it preserves the incoming bytes. Direct smudge invocations without a checkout source use the working-tree configuration.
+The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree on every request. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when Git replaces the index file. Direct smudge invocations without a checkout source use the working-tree configuration.
 
 The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files before verification and writing.
 
diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index ecf184cd..9f0ff318 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -347,6 +347,49 @@ def test_git_filter_join_installs_local_config_and_keeps_checkout_clean(
         ).encode("utf-8")
 
 
+@pytest.mark.parametrize("direction", ["clean", "smudge"])
+def test_persistent_git_filter_observes_config_changes(tmp_path: Path, direction: str) -> None:
+    repo = tmp_path
+    init_repo(repo)
+    run_git(repo, "config", "core.autocrlf", "false")
+    original = b"#   Keep\n"
+    formatted = b"# Keep\n"
+    (repo / "doc.md").write_bytes(original)
+    run_git(repo, "add", "doc.md")
+    run_yamark(repo, "git-filter", "setup")
+    if direction == "clean":
+        args = ["hash-object", "--stdin-paths"]
+        request = b"doc.md\n"
+    else:
+        args = ["cat-file", "--batch=%(objecttype)", "--filters"]
+        oid = run_git(repo, "rev-parse", ":doc.md").stdout.strip()
+        request = f"{oid} doc.md\n".encode()
+
+    with subprocess.Popen(
+        ["git", *args], cwd=repo, stdin=subprocess.PIPE, stdout=subprocess.PIPE
+    ) as git:
+        def check_response(expected: bytes) -> None:
+            assert git.stdin is not None and git.stdout is not None
+            git.stdin.write(request)
+            git.stdin.flush()
+            if direction == "clean":
+                digest = subprocess.check_output(
+                    ["git", "hash-object", "--stdin"], cwd=repo, input=expected
+                )
+                assert git.stdout.readline() == digest
+            else:
+                assert git.stdout.readline() == b"blob\n"
+                assert git.stdout.readline() == expected
+                assert git.stdout.readline() == b"\n"
+
+        check_response(formatted)
+        (repo / "yamark.toml").write_bytes(b"[format]\nexclude = ['doc.md']\n")
+        if direction == "smudge":
+            run_git(repo, "add", "yamark.toml")
+        check_response(original)
+    assert git.returncode == 0
+
+
 def test_delegated_smudge_rejects_unsupported_index_path(tmp_path: Path) -> None:
     repo = tmp_path
     init_repo(repo)
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index eb425427..c183f2e3 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -162,12 +162,14 @@ pub(super) fn run(command: GitFilterCommand) -> ExitCode {
             source_tree,
         } => {
             let source = match source_tree {
-                Some(tree) => FilterSource::Checkout(tree),
-                None if env::var_os(driver::UNVERIFIED_SOURCE_ENV).is_some() => {
-                    FilterSource::Unverified
-                }
-                None => env::var(driver::SOURCE_TREE_ENV)
-                    .map_or(FilterSource::Worktree, FilterSource::Checkout),
+                Some(tree) => FilterSource::Tree(tree),
+                None => match env::var(driver::SOURCE_TREE_ENV) {
+                    Ok(tree) if tree.is_empty() => {
+                        FilterSource::StagedBlob(env::var(driver::SOURCE_BLOB_ENV).ok())
+                    }
+                    Ok(tree) => FilterSource::Tree(tree),
+                    Err(_) => FilterSource::Worktree,
+                },
             };
             run_git_filter(
                 stdin_filename,
@@ -215,8 +217,8 @@ fn filter_options(wrap: MarkdownWrap) -> FormatOptions {
 
 enum FilterSource {
     Worktree,
-    Checkout(String),
-    Unverified,
+    Tree(String),
+    StagedBlob(Option),
 }
 
 fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> ExitCode {
@@ -228,11 +230,13 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
     run_stdin(
         path,
         |path| match source {
+            FilterSource::Tree(tree) => checkout::config_for_path(Path::new("."), &tree, path),
+            FilterSource::StagedBlob(blob) => checkout::CheckoutConfigs::default().for_staged_blob(
+                Path::new("."),
+                path,
+                blob.as_ref().map(String::as_bytes),
+            ),
             FilterSource::Worktree => load_config_for_formatted_path(path, None).map(Some),
-            FilterSource::Checkout(tree) => {
-                checkout::config_for_path(Path::new("."), &tree, path).map(Some)
-            }
-            FilterSource::Unverified => Ok(None),
         },
         filter_options(wrap),
         FormatExecutionOptions {
@@ -608,17 +612,16 @@ fn tracked_yamark_filter_paths(
         .split(|byte| *byte == 0)
         .filter(|entry| !entry.is_empty())
     {
-        let Some(blob) = process::regular_index_blob(entry)? else {
+        let Some(name) = process::regular_index_path(entry)? else {
             continue;
         };
         let path = Path::new(
-            driver::native_path(blob.path)
-                .map_err(|err| format!("git path was not UTF-8: {err}"))?,
+            driver::native_path(name).map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
         if crate::core::document::FileKind::for_path(path)
             == crate::core::document::FileKind::Markdown
         {
-            names.extend_from_slice(blob.path);
+            names.extend_from_slice(name);
             names.push(0);
         }
     }
@@ -663,9 +666,15 @@ fn verify_roundtrip(
     let mut configs = checkout::CheckoutConfigs::default();
     for path in paths {
         let source_path = repo_root.join(path);
-        let config = configs
+        let Some(config) = configs
             .for_path(repo_root, source.tree(), path)
-            .map_err(|err| err.diagnostic.render())?;
+            .map_err(|err| err.diagnostic.render())?
+        else {
+            return Err(format!(
+                "{}: cannot verify a blob with conflicted settings",
+                path.display()
+            ));
+        };
         if config.excludes(&source_path) {
             continue;
         }
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index 4ad262a8..3a9ec464 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -1,64 +1,128 @@
 //! Resolve checkout configuration from the incoming Git tree or stage-zero index.
 //! Git may invoke smudge before materializing the configuration in the worktree.
 
-use std::collections::{HashMap, VecDeque};
+use std::collections::{BTreeMap, HashMap, VecDeque};
 use std::ffi::OsString;
 use std::path::{Component, Path, PathBuf};
-use std::process::{Command, Stdio};
+use std::process::Command;
 
 use super::driver::{native_path, run_with_input};
-use super::process::{entry_fields, git_query, git_stdout, git_stdout_bytes, regular_index_blob};
+use super::process::{entry_fields, git_stdout, git_stdout_bytes};
 use crate::config::Config;
-use crate::core::document::FileKind;
 use crate::diagnostic::{Result, YamarkError};
 
-struct Entry {
-    oid: String,
-    symlink: bool,
+/// A Git index update replaces the file atomically. Keep its handle open
+/// while caching the entries so its identity cannot be reused.
+struct IndexSnapshot {
+    handle: Option,
+    entries: BTreeMap,
 }
 
-/// Git may report a blob but no tree during checkout-index, merges, and
-/// cherry-picks. Only use staged settings for a file whose staged blob agrees.
-pub(super) struct IndexSnapshot {
-    markdown: HashMap>,
+#[derive(Clone)]
+enum Entry {
+    File(String),
+    Link(String),
+    Conflict,
 }
 
 impl IndexSnapshot {
-    pub(super) fn load(repo: &Path) -> Result {
+    fn load(repo: &Path, handle: Option) -> Result {
         let records = git_stdout_bytes(repo, ["ls-files", "--stage", "--full-name", "-z"])
             .map_err(YamarkError::new)?;
-        let mut markdown = HashMap::new();
+        let mut entries = BTreeMap::new();
         for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-            let Some(blob) = regular_index_blob(record).map_err(YamarkError::new)? else {
+            let (name, [mode, oid, stage]) = entry_fields(record).map_err(YamarkError::new)?;
+            let Ok(name) = native_path(name) else {
                 continue;
             };
-            // The rest of the index may include paths this OS cannot represent.
-            if let Ok(filename) = native_path(blob.path) {
-                let path = Path::new(filename);
-                if FileKind::for_path(path) == FileKind::Markdown {
-                    markdown.insert(path.to_owned(), blob.oid.to_vec());
-                }
-            }
+            let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
+            let entry = match (stage, mode) {
+                (b"0", b"100644" | b"100755") => Entry::File(oid.to_owned()),
+                (b"0", b"120000") => Entry::Link(oid.to_owned()),
+                (b"0", _) => continue,
+                _ => Entry::Conflict,
+            };
+            entries.insert(PathBuf::from(name), entry);
         }
-        Ok(Self { markdown })
-    }
-
-    pub(super) fn matches_blob(&self, path: &Path, blob: &[u8]) -> bool {
-        self.markdown.get(path).map(Vec::as_slice) == Some(blob)
+        Ok(Self { handle, entries })
     }
 }
 
-pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result {
+pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result> {
     CheckoutConfigs::default().for_path(repo_root, tree, path)
 }
 
+type DirectoryConfig = Option<(PathBuf, Config)>;
+
 #[derive(Default)]
 pub(super) struct CheckoutConfigs {
-    directories: HashMap<(String, PathBuf), (PathBuf, Config)>,
+    directories: HashMap<(String, PathBuf), DirectoryConfig>,
+    index_path: Option,
+    index: Option,
 }
 
 impl CheckoutConfigs {
-    pub(super) fn for_path(&mut self, repo: &Path, tree: &str, path: &Path) -> Result {
+    fn refresh_index(&mut self, repo: &Path) -> Result<()> {
+        let index_path = match &self.index_path {
+            Some(path) => path,
+            None => {
+                let bytes = git_stdout_bytes(repo, ["rev-parse", "--git-path", "index"])
+                    .map_err(YamarkError::new)?;
+                let path = native_path(bytes.strip_suffix(b"\n").unwrap_or(&bytes))
+                    .map_err(|err| YamarkError::new(err.to_string()))?;
+                self.index_path.insert(repo.join(path))
+            }
+        };
+        let handle = match same_file::Handle::from_path(index_path) {
+            Ok(handle) => Some(handle),
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
+            Err(err) => return Err(YamarkError::new(err.to_string()).with_path(index_path)),
+        };
+        if self
+            .index
+            .as_ref()
+            .is_none_or(|index| index.handle != handle)
+        {
+            self.index = Some(IndexSnapshot::load(repo, handle)?);
+            self.directories.retain(|(tree, _), _| !tree.is_empty());
+        }
+        Ok(())
+    }
+
+    pub(super) fn for_staged_blob(
+        &mut self,
+        repo: &Path,
+        path: &Path,
+        blob: Option<&[u8]>,
+    ) -> Result> {
+        let Some(blob) = blob else { return Ok(None) };
+        self.refresh_index(repo)?;
+        let index = self.index.as_ref().expect("refreshed index");
+        if matches!(index.entries.get(path), Some(Entry::File(oid)) if oid.as_bytes() == blob) {
+            self.for_selected_source(repo, "", path)
+        } else {
+            Ok(None)
+        }
+    }
+
+    pub(super) fn for_path(
+        &mut self,
+        repo: &Path,
+        tree: &str,
+        path: &Path,
+    ) -> Result> {
+        if tree.is_empty() {
+            self.refresh_index(repo)?;
+        }
+        self.for_selected_source(repo, tree, path)
+    }
+
+    fn for_selected_source(
+        &mut self,
+        repo: &Path,
+        tree: &str,
+        path: &Path,
+    ) -> Result> {
         let path = path.strip_prefix(".").unwrap_or(path);
         if path.as_os_str().is_empty()
             || !path
@@ -72,112 +136,95 @@ impl CheckoutConfigs {
         let parent = path.parent().expect("nonempty relative path");
         let key = (tree.to_owned(), parent.to_owned());
         use std::collections::hash_map::Entry;
-        let (dir, config) = match self.directories.entry(key) {
+        let base = match self.directories.entry(key) {
             Entry::Occupied(entry) => entry.into_mut(),
-            Entry::Vacant(entry) => entry.insert(config_for_directory(repo, tree, parent)?),
+            Entry::Vacant(entry) => entry.insert(config_for_directory(
+                repo,
+                tree,
+                parent,
+                self.index.as_ref(),
+            )?),
         };
-        Ok(config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor")))
+        Ok(base.as_ref().map(|(dir, config)| {
+            config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor"))
+        }))
     }
 }
 
-fn config_for_directory(repo_root: &Path, tree: &str, parent: &Path) -> Result<(PathBuf, Config)> {
-    let candidates: Vec<_> = parent
-        .ancestors()
-        .map(|dir| dir.join("yamark.toml"))
-        .collect();
-    let Some((config_path, entry)) = nearest_entry(repo_root, tree, &candidates)? else {
-        return Ok((PathBuf::new(), Config::default()));
-    };
-    let bytes = if entry.symlink && !tree.is_empty() {
-        tree_symlink_contents(repo_root, tree, &config_path)
+fn config_for_directory(
+    repo: &Path,
+    tree: &str,
+    parent: &Path,
+    index: Option<&IndexSnapshot>,
+) -> Result {
+    let mut candidates = parent.ancestors().map(|dir| dir.join("yamark.toml"));
+    let selected = if tree.is_empty() {
+        let index = index.expect("staged configuration needs an index snapshot");
+        candidates.find_map(|path| index.entries.get(&path).cloned().map(|entry| (path, entry)))
     } else {
-        blob_contents(repo_root, &config_path, entry)
+        nearest_tree_entry(repo, tree, &candidates.collect::>())?
+    };
+    let Some((config_path, entry)) = selected else {
+        return Ok(Some((PathBuf::new(), Config::default())));
+    };
+    let bytes = match entry {
+        Entry::Conflict => return Ok(None),
+        Entry::File(oid) => git_stdout_bytes(repo, ["cat-file", "blob", &oid])
+            .map(Some)
+            .map_err(YamarkError::new),
+        Entry::Link(oid) if tree.is_empty() => {
+            index_link_contents(repo, index.expect("staged config"), &config_path, &oid)
+        }
+        Entry::Link(_) => tree_symlink_contents(repo, tree, &config_path).map(Some),
     }
     .map_err(|err| err.with_path(&config_path))?;
+    let Some(bytes) = bytes else { return Ok(None) };
     let input = std::str::from_utf8(&bytes).map_err(|err| {
         YamarkError::new(format!("invalid config encoding: {err}")).with_path(&config_path)
     })?;
     let mut config = Config::from_toml_str(input).map_err(|err| err.with_path(&config_path))?;
     // Git paths start at the worktree root. The nested directory itself may
     // still be absent, or contain a symlink from the checkout being replaced.
-    let root = std::fs::canonicalize(repo_root).map_err(|err| YamarkError::new(err.to_string()))?;
+    let root = std::fs::canonicalize(repo).map_err(|err| YamarkError::new(err.to_string()))?;
     let dir = config_path.parent().expect("a config has a parent");
     config.config_dir = Some(root.join(dir));
-    Ok((dir.to_owned(), config))
+    Ok(Some((dir.to_owned(), config)))
 }
 
-/// Candidates are ordered nearest first. Use literal pathspecs and NUL-delimited
-/// Git records so filenames are never treated as globs or display-quoted text.
-fn nearest_entry(
+fn nearest_tree_entry(
     repo: &Path,
     tree: &str,
     candidates: &[PathBuf],
 ) -> Result> {
-    let mut args = Vec::new();
-    if tree.is_empty() {
-        args.extend(
-            ["--no-literal-pathspecs", "ls-files", "--stage", "-z", "--"].map(OsString::from),
-        );
-        for path in candidates {
-            let mut literal = OsString::from(":(top,literal)");
-            literal.push(git_path(path));
-            args.push(literal);
-            if !candidates
-                .iter()
-                .any(|other| other != path && other.starts_with(path))
-            {
-                // An exact directory argument to ls-files would list every
-                // tracked descendant. We need only a stage-zero file entry.
-                let mut descendants = OsString::from(":(top,exclude,literal)");
-                descendants.push(git_path(path));
-                descendants.push("/");
-                args.push(descendants);
-            }
-        }
-    } else {
-        args.extend(
-            [
-                "--literal-pathspecs",
-                "ls-tree",
-                "--full-tree",
-                "-z",
-                "--end-of-options",
-                tree,
-                "--",
-            ]
-            .map(OsString::from),
-        );
-        args.extend(candidates.iter().map(|path| git_path(path)));
-    }
+    let mut args = [
+        "--literal-pathspecs",
+        "ls-tree",
+        "--full-tree",
+        "-z",
+        "--end-of-options",
+        tree,
+        "--",
+    ]
+    .map(OsString::from)
+    .to_vec();
+    args.extend(candidates.iter().map(|path| git_path(path)));
     let records = git_stdout_bytes(repo, args).map_err(YamarkError::new)?;
     let mut nearest = None;
     for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-        let (filename, [mode, second, third]) = entry_fields(record).map_err(YamarkError::new)?;
+        let (filename, [mode, _, oid]) = entry_fields(record).map_err(YamarkError::new)?;
         let path =
             Path::new(native_path(filename).map_err(|err| YamarkError::new(err.to_string()))?);
         let Some(rank) = candidates.iter().position(|candidate| candidate == path) else {
             continue;
         };
-        let oid = if tree.is_empty() {
-            if third != b"0" {
-                continue;
-            }
-            second
-        } else {
-            third
+        let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
+        let entry = match mode {
+            b"100644" | b"100755" => Entry::File(oid.to_owned()),
+            b"120000" => Entry::Link(oid.to_owned()),
+            _ => continue,
         };
-        if !matches!(mode, b"100644" | b"100755" | b"120000") {
-            continue;
-        }
         if nearest.as_ref().is_none_or(|(best, _)| rank < *best) {
-            let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
-            nearest = Some((
-                rank,
-                Entry {
-                    oid: oid.to_owned(),
-                    symlink: mode == b"120000",
-                },
-            ));
+            nearest = Some((rank, entry));
         }
     }
     Ok(nearest.map(|(rank, entry)| (candidates[rank].clone(), entry)))
@@ -223,22 +270,17 @@ fn tree_symlink_contents(repo: &Path, tree: &str, path: &Path) -> Result
         .ok_or_else(|| YamarkError::new("config symlink has no file target in checkout"))
 }
 
-fn blob_contents(repo: &Path, path: &Path, mut entry: Entry) -> Result> {
-    // cat-file --follow-symlinks handles tree paths, but :path returns the
-    // link blob itself. Resolve staged links exclusively against the index.
+fn index_link_contents<'a>(
+    repo: &Path,
+    index: &'a IndexSnapshot,
+    path: &Path,
+    mut oid: &'a str,
+) -> Result>> {
     let mut current = path.to_path_buf();
     let mut pending = VecDeque::new();
     let mut links = 0;
     loop {
-        let bytes =
-            git_stdout_bytes(repo, ["cat-file", "blob", &entry.oid]).map_err(YamarkError::new)?;
-        if !entry.symlink {
-            return if pending.is_empty() {
-                Ok(bytes)
-            } else {
-                Err(YamarkError::new("config symlink traverses a regular file"))
-            };
-        }
+        let bytes = git_stdout_bytes(repo, ["cat-file", "blob", oid]).map_err(YamarkError::new)?;
         links += 1;
         if links > 40 {
             return Err(YamarkError::new("too many config symlinks in checkout"));
@@ -256,21 +298,16 @@ fn blob_contents(repo: &Path, path: &Path, mut entry: Entry) -> Result>
             match Path::new(&next).components().next() {
                 Some(Component::CurDir) => continue,
                 Some(Component::ParentDir) if !current.as_os_str().is_empty() => {
-                    // A directory removed by '..' must exist too. Ancestors of
-                    // the staged config already have a tracked descendant.
-                    if !path.starts_with(¤t) {
-                        let status = git_query(repo)
-                            .args(["--literal-pathspecs", "ls-files", "--error-unmatch", "--"])
-                            .arg(git_path(¤t))
-                            .stdout(Stdio::null())
-                            .stderr(Stdio::null())
-                            .status()
-                            .map_err(|err| YamarkError::new(err.to_string()))?;
-                        if !status.success() {
-                            return Err(YamarkError::new(
-                                "config symlink traverses a missing directory",
-                            ));
-                        }
+                    // An index represents a directory by its tracked descendants.
+                    if !index
+                        .entries
+                        .range(current.clone()..)
+                        .next()
+                        .is_some_and(|(path, _)| path.starts_with(¤t))
+                    {
+                        return Err(YamarkError::new(
+                            "config symlink traverses a missing directory",
+                        ));
                     }
                     current.pop();
                     continue;
@@ -282,9 +319,21 @@ fn blob_contents(repo: &Path, path: &Path, mut entry: Entry) -> Result>
                     ));
                 }
             }
-            if let Some((_, found)) = nearest_entry(repo, "", std::slice::from_ref(¤t))? {
-                entry = found;
-                break;
+            match index.entries.get(¤t) {
+                Some(Entry::Conflict) => return Ok(None),
+                Some(Entry::File(oid)) if pending.is_empty() => {
+                    return git_stdout_bytes(repo, ["cat-file", "blob", oid])
+                        .map(Some)
+                        .map_err(YamarkError::new);
+                }
+                Some(Entry::File(_)) => {
+                    return Err(YamarkError::new("config symlink traverses a regular file"));
+                }
+                Some(Entry::Link(next)) => {
+                    oid = next;
+                    break;
+                }
+                None => {}
             }
         }
     }
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 81a8dfd5..8120cf15 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -6,12 +6,11 @@ use std::io::{self, BufRead, Read, Write};
 use std::path::Path;
 use std::process::{Command, ExitCode, Stdio};
 
-use super::checkout::{CheckoutConfigs, IndexSnapshot};
-use crate::config::Config;
+use super::checkout::CheckoutConfigs;
 use crate::core::document::{FileKind, MarkdownWrap};
 use crate::workspace::load_config_for_formatted_path;
 
-pub(super) const UNVERIFIED_SOURCE_ENV: &str = "YAMARK_GIT_FILTER_UNVERIFIED_SOURCE";
+pub(super) const SOURCE_BLOB_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_BLOB";
 pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
 
 pub(super) fn run() -> ExitCode {
@@ -52,7 +51,7 @@ fn serve() -> io::Result<()> {
             Driver::Custom(custom_alias(&command))
         }
     });
-    let mut configs = FilterConfigs::default();
+    let mut configs = CheckoutConfigs::default();
     let caps = read_headers(&mut input)?;
     let accepted: Vec<_> = caps
         .iter()
@@ -97,43 +96,12 @@ enum Driver {
     Custom(String),
 }
 
-#[derive(Default)]
-struct FilterConfigs {
-    checkout: CheckoutConfigs,
-    index: Option,
-}
-
-impl FilterConfigs {
-    fn index_matches(
-        &mut self,
-        path: &Path,
-        blob: Option<&[u8]>,
-    ) -> crate::diagnostic::Result {
-        let Some(blob) = blob else { return Ok(false) };
-        if self.index.is_none() {
-            self.index = Some(IndexSnapshot::load(Path::new("."))?);
-        }
-        Ok(self
-            .index
-            .as_ref()
-            .expect("loaded index")
-            .matches_blob(path, blob))
-    }
-
-    fn for_path(&mut self, path: &Path, tree: Option<&str>) -> crate::diagnostic::Result {
-        if let Some(tree) = tree {
-            return self.checkout.for_path(Path::new("."), tree, path);
-        }
-        load_config_for_formatted_path(path, None)
-    }
-}
-
 fn filter_file(
     fields: &[Vec],
     contents: Vec,
     clean: Option<&Driver>,
     smudge: Option<&Driver>,
-    configs: &mut FilterConfigs,
+    configs: &mut CheckoutConfigs,
 ) -> io::Result> {
     let field = |prefix: &[u8]| fields.iter().find_map(|line| line.strip_prefix(prefix));
     let path = field(b"pathname=").ok_or_else(|| io::Error::other("missing pathname"))?;
@@ -148,10 +116,6 @@ fn filter_file(
         .map(std::str::from_utf8)
         .transpose()
         .map_err(io::Error::other)?;
-    let unverified_source = tree == Some("")
-        && !configs
-            .index_matches(path, field(b"blob="))
-            .map_err(io::Error::other)?;
     let command = match command {
         Driver::Yamark(wrap) => {
             if FileKind::for_path(path) != FileKind::Markdown {
@@ -160,10 +124,15 @@ fn filter_file(
                     path.display()
                 )));
             }
-            if unverified_source {
-                return Ok(contents);
+            let config = match tree {
+                Some("") => configs.for_staged_blob(Path::new("."), path, field(b"blob=")),
+                Some(tree) => configs.for_path(Path::new("."), tree, path),
+                None => load_config_for_formatted_path(path, None).map(Some),
             }
-            let config = configs.for_path(path, tree).map_err(io::Error::other)?;
+            .map_err(io::Error::other)?;
+            let Some(config) = config else {
+                return Ok(contents);
+            };
             if config.excludes(path) {
                 return Ok(contents);
             }
@@ -185,11 +154,16 @@ fn filter_file(
         .arg("yamark-single-file")
         .env("YAMARK_GIT_FILTER_PATH", path)
         .env_remove(SOURCE_TREE_ENV)
-        .env_remove(UNVERIFIED_SOURCE_ENV);
+        .env_remove(SOURCE_BLOB_ENV);
     // A custom command may delegate to Yamark. Give it the same checkout
     // context as the in-process driver while still running the custom command.
-    if unverified_source {
-        child.env(UNVERIFIED_SOURCE_ENV, "1");
+    if tree == Some("")
+        && let Some(blob) = field(b"blob=")
+    {
+        child.env(
+            SOURCE_BLOB_ENV,
+            std::str::from_utf8(blob).map_err(io::Error::other)?,
+        );
     }
     if let Some(tree) = tree {
         child.env(SOURCE_TREE_ENV, tree);
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index c134a554..817028c4 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -97,15 +97,10 @@ pub(super) fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3]), &'stati
     Ok((&record[tab + 1..], [first, second, third]))
 }
 
-/// Path and object ID of a regular, stage-zero blob from ls-files --stage.
-pub(super) struct IndexBlob<'a> {
-    pub(super) path: &'a [u8],
-    pub(super) oid: &'a [u8],
-}
-
-pub(super) fn regular_index_blob(record: &[u8]) -> Result>, &'static str> {
-    let (path, [mode, oid, stage]) = entry_fields(record)?;
-    Ok((stage == b"0" && matches!(mode, b"100644" | b"100755")).then_some(IndexBlob { path, oid }))
+/// Path of a regular stage-zero blob from ls-files --stage.
+pub(super) fn regular_index_path(record: &[u8]) -> Result, &'static str> {
+    let (path, [mode, _, stage]) = entry_fields(record)?;
+    Ok((stage == b"0" && matches!(mode, b"100644" | b"100755")).then_some(path))
 }
 
 pub(super) fn local_git_config_count(repo_root: &Path, key: &str) -> Result {
diff --git a/tests/cases/git_filter_process_conflicted_config.case b/tests/cases/git_filter_process_conflicted_config.case
new file mode 100644
index 00000000..389260e7
--- /dev/null
+++ b/tests/cases/git_filter_process_conflicted_config.case
@@ -0,0 +1,47 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "base/docs/doc.md": "#   Keep\n",
+    "base/yamark.toml": "[format]\nexclude = ['other.md']\n",
+    "base/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'base.md']\n",
+    "ours/docs/doc.md": "#   Keep\n",
+    "ours/yamark.toml": "[format]\nexclude = ['other.md']\n",
+    "ours/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'ours.md']\n",
+    "theirs/docs/doc.md": "#   Keep\n",
+    "theirs/yamark.toml": "[format]\nexclude = ['other.md']\n",
+    "theirs/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'theirs.md']\n"
+  },
+  "git-after-commit": [
+    ["read-tree", "HEAD:ours"],
+    [
+      "read-tree",
+      "-i",
+      "-m",
+      "HEAD:base",
+      "HEAD:ours",
+      "HEAD:theirs"
+    ]
+  ],
+  "setup-filter": true
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "command=smudge\n", "pathname=docs/doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null,
+  "#   Keep\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=smudge\n", null,
+  "status=success\n", null, "#   Keep\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_process_index_change.case b/tests/cases/git_filter_process_index_change.case
new file mode 100644
index 00000000..a03469f3
--- /dev/null
+++ b/tests/cases/git_filter_process_index_change.case
@@ -0,0 +1,44 @@
+-- git-fixture
+{
+  "config": {
+    "core.autocrlf": "false"
+  },
+  "files": {
+    "also.md": "#   Keep\n",
+    "next/also.md": "# Changed in the index\n",
+    "next/doc.md": "#   Keep\n",
+    "next/yamark.toml": "[format]\nexclude = ['doc.md']\n",
+    "doc.md": "#   Keep\n",
+    "yamark.toml": "[format]\nexclude = ['unrelated.md']\n"
+  },
+  "setup-filter": true
+}
+-- env
+{
+  "GIT_CONFIG_COUNT": "1",
+  "GIT_CONFIG_KEY_0": "filter.yamark-md.clean",
+  "GIT_CONFIG_VALUE_0": "git read-tree HEAD:next && cat"
+}
+-- args
+git-filter process
+-- stdin-packets
+[
+  "git-filter-client\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "command=smudge\n", "pathname=doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null,
+  "command=clean\n", "pathname=doc.md\n", null, "edit config\n", null,
+  "command=smudge\n", "pathname=doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null,
+  "command=smudge\n", "pathname=also.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null
+]
+-- stdout-packets
+[
+  "git-filter-server\n", "version=2\n", null,
+  "capability=clean\n", "capability=smudge\n", null,
+  "status=success\n", null, "# Keep\n", null, null,
+  "status=success\n", null, "edit config\n", null, null,
+  "status=success\n", null, "#   Keep\n", null, null,
+  "status=success\n", null, "#   Keep\n", null, null
+]
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_smudge_unverified_unsupported.case b/tests/cases/git_filter_smudge_unverified_unsupported.case
index 06f26dea..f20834da 100644
--- a/tests/cases/git_filter_smudge_unverified_unsupported.case
+++ b/tests/cases/git_filter_smudge_unverified_unsupported.case
@@ -1,7 +1,7 @@
 -- args
 git-filter smudge --stdin-filename file.txt
 -- env
-{"YAMARK_GIT_FILTER_UNVERIFIED_SOURCE": "1"}
+{"YAMARK_GIT_FILTER_SOURCE_TREE": ""}
 -- stdin
 Original content.
 -- stdout
diff --git a/tests/git_filter_process.rs b/tests/git_filter_process.rs
index 387a5bf5..a565c771 100644
--- a/tests/git_filter_process.rs
+++ b/tests/git_filter_process.rs
@@ -65,3 +65,55 @@ fn default_filters_reuse_configuration_for_files_in_one_directory() {
         assert_eq!(fs::read_to_string(root.join(name)).unwrap(), expected);
     }
 }
+
+#[test]
+fn an_unmerged_config_preserves_utf16_on_checkout_from_the_index() {
+    let repo = tempdir().unwrap();
+    let root = repo.path();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(root)
+            .args(args)
+            .assert()
+            .success()
+            .get_output()
+            .stdout
+            .clone()
+    };
+    git(&["init", "-q"]);
+    git(&["config", "core.autocrlf", "false"]);
+    let original = [0xff, 0xfe, b'#', 0, b' ', 0, b'1', 0, b'\n', 0];
+    fs::write(root.join("doc.md"), original).unwrap();
+    fs::write(root.join("yamark.toml"), "[format]\nexclude = ['doc.md']\n").unwrap();
+    git(&["add", "."]);
+    let oid = String::from_utf8(git(&["rev-parse", ":yamark.toml"])).unwrap();
+    git(&["update-index", "--force-remove", "yamark.toml"]);
+    // An add/add conflict has no stage zero for the config. Both stages
+    // exclude doc.md, even though they differ on a second path.
+    let theirs = Command::new("git")
+        .current_dir(root)
+        .args(["hash-object", "-w", "--stdin"])
+        .write_stdin("[format]\nexclude = ['doc.md', 'also.md']\n")
+        .assert()
+        .success();
+    let theirs = std::str::from_utf8(&theirs.get_output().stdout).unwrap();
+    Command::new("git")
+        .current_dir(root)
+        .args(["update-index", "--index-info"])
+        .write_stdin(format!(
+            "100644 {} 2\tyamark.toml\n100644 {} 3\tyamark.toml\n",
+            oid.trim(),
+            theirs.trim()
+        ))
+        .assert()
+        .success();
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(root)
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+    let output = String::from_utf8(git(&["checkout-index", "--temp", "--", "doc.md"])).unwrap();
+    let temporary = output.strip_suffix("\tdoc.md\n").unwrap();
+    assert_eq!(fs::read(root.join(temporary)).unwrap(), original);
+}
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 9b8190ce..e37a8fc6 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -37,8 +37,10 @@ filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an ex
 no tree, smudge uses the staged configuration if Git identifies the file's
 staged blob. If the blob is missing or differs from the staged blob, as can
 happen during a merge or cherry-pick, smudge returns the incoming bytes
-unchanged. If `yamark.toml` is a symbolic link, its target must also be present
-in the selected tree or index. Clean reads the working-tree config.
+unchanged. A merge conflict in the nearest staged config or its symlink target
+also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
+symbolic link, its target must be present in the selected tree or index. Clean
+reads the current working-tree config on each request.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.

From a07aad77e53e81caa0da98603feacabcd0d215f9 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:35:02 -0500
Subject: [PATCH 38/64] Batch worktree conversions during filter adoption and
 join

---
 src/cli/git_filter.rs       | 66 +++++++++++++++++----------
 tests/git_filter_process.rs | 91 +++++++++++++++++++++++++++++++++++++
 2 files changed, 133 insertions(+), 24 deletions(-)

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index c183f2e3..d68a656b 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -26,8 +26,8 @@ use attributes::{
     remove_yamark_filter_attribute_lines,
 };
 use process::{
-    git_stdout, git_stdout_bytes, local_git_config_count, run_git_config, run_git_os,
-    run_git_with_paths, unset_git_config_key,
+    git_stdout, local_git_config_count, run_git_config, run_git_os, run_git_with_paths,
+    unset_git_config_key,
 };
 
 #[derive(Debug, Subcommand)]
@@ -702,33 +702,51 @@ fn verify_roundtrip(
 }
 
 fn write_smudged_worktree(repo_root: &Path, paths: &[PathBuf]) -> Result<(), String> {
-    // Let Git apply text/eol attributes and core.autocrlf before the configured
-    // smudge filter. Writing formatted blob bytes directly bypasses that step.
+    // Even --force can skip stat-clean files. Check out all targets to a fresh
+    // prefix so Git applies its conversions and leaves originals intact if
+    // one of the filters fails.
+    let converted = tempfile::tempdir().map_err(|err| err.to_string())?;
+    let mut prefix = OsString::from("--prefix=");
+    prefix.push(converted.path());
+    prefix.push("/");
+    let mut names = Vec::new();
     for path in paths {
-        // Excluded files returned by the smudge filter may not be UTF-8.
-        let smudged = git_stdout_bytes(
-            repo_root,
-            [
-                OsString::from("cat-file"),
-                OsString::from("--filters"),
-                BlobSource::Index.spec(path),
-            ],
-        )?;
-        let worktree_path = repo_root.join(path);
-        fs::write(&worktree_path, smudged).map_err(|err| {
+        names.extend_from_slice(path.as_os_str().as_encoded_bytes());
+        names.push(0);
+    }
+    let checkout = |option: OsString| {
+        let mut git = process::git_query(repo_root);
+        git.arg("checkout-index")
+            .arg(option)
+            .args(["--force", "-z", "--stdin"])
+            .stderr(std::process::Stdio::piped());
+        process::checked_stdout(driver::run_with_input(&mut git, &names))
+    };
+    checkout(prefix)?;
+
+    for path in paths {
+        let target = repo_root.join(path);
+        replace_with_checkout_file(&converted.path().join(path), &target).map_err(|err| {
             format!(
-                "{}: failed to write smudged working-tree file: {err}",
-                worktree_path.display()
+                "{}: failed to install smudged file: {err}",
+                target.display()
             )
         })?;
     }
-    // Refresh Git's cached file metadata as part of checkout. A plain write can
-    // leave a CRLF file marked dirty even when its cleaned blob is unchanged.
-    run_git_with_paths(
-        repo_root,
-        &["checkout-index", "--force", "--index", "--"],
-        paths,
-    )
+    // Refresh the real index as part of checkout so CRLF files also acquire
+    // their correct worktree stat data.
+    checkout(OsString::from("--index"))?;
+    Ok(())
+}
+
+/// Install the complete regular file without writing through a link. Stage
+/// the replacement beside its target, which can be on a different filesystem.
+fn replace_with_checkout_file(source: &Path, target: &Path) -> io::Result<()> {
+    let pending =
+        tempfile::NamedTempFile::new_in(target.parent().expect("tracked file has a parent"))?;
+    fs::copy(source, pending.path())?;
+    pending.persist(target)?;
+    Ok(())
 }
 
 fn git_blob(repo_root: &Path, source: BlobSource, path: &Path) -> Result {
diff --git a/tests/git_filter_process.rs b/tests/git_filter_process.rs
index a565c771..f687c44b 100644
--- a/tests/git_filter_process.rs
+++ b/tests/git_filter_process.rs
@@ -117,3 +117,94 @@ fn an_unmerged_config_preserves_utf16_on_checkout_from_the_index() {
     let temporary = output.strip_suffix("\tdoc.md\n").unwrap();
     assert_eq!(fs::read(root.join(temporary)).unwrap(), original);
 }
+
+#[test]
+fn adoption_and_join_batch_worktree_conversions() {
+    for action in ["adopt", "join"] {
+        let count_checkouts = |files: &[&str]| {
+            let repo = tempdir().unwrap();
+            let root = repo.path();
+            if action == "join" {
+                fs::write(root.join(".gitattributes"), "*.md filter=yamark-md\n").unwrap();
+            }
+            for name in files {
+                fs::write(root.join(name), "First sentence.\nSecond sentence?\n").unwrap();
+            }
+            commit_files(root);
+
+            let traces = tempdir().unwrap();
+            let trace = traces.path().join("filter-events.jsonl");
+            Command::cargo_bin("yamark")
+                .unwrap()
+                .current_dir(root)
+                .env("GIT_TRACE2_EVENT", &trace)
+                .args(["git-filter", action])
+                .assert()
+                .success();
+            for name in files {
+                assert_eq!(
+                    fs::read(root.join(name)).unwrap(),
+                    b"First sentence. Second sentence?\n"
+                );
+            }
+            fs::read_to_string(trace)
+                .unwrap()
+                .lines()
+                .map(|line| serde_json::from_str::(line).unwrap())
+                .filter(|event| {
+                    // Count Git checkout invocations, including filtered blob
+                    // reads. Later status checks may run a clean filter when
+                    // Git considers an entry racily clean on this filesystem.
+                    if event["event"] != "start" {
+                        return false;
+                    }
+                    let args = event["argv"].as_array().unwrap();
+                    args.iter().any(|arg| arg == "checkout-index")
+                        || (args.iter().any(|arg| arg == "cat-file")
+                            && args.iter().any(|arg| arg == "--filters"))
+                })
+                .count()
+        };
+
+        let one = count_checkouts(&["one.md"]);
+        let three = count_checkouts(&["one.md", "two.md", "three.md"]);
+        assert!(one > 0);
+        assert_eq!(
+            three, one,
+            "{action} dispatched new checkouts for additional targets"
+        );
+    }
+}
+
+#[test]
+fn failed_join_checkout_preserves_existing_files() {
+    let dir = tempdir().unwrap();
+    let repo = dir.path();
+    fs::write(repo.join(".gitattributes"), "*.md filter=yamark-md\n").unwrap();
+    fs::write(repo.join("keep.md"), "# Keep\n").unwrap();
+    commit_files(repo);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(repo)
+        .args(["git-filter", "join", "--yamark"])
+        .arg(repo.join("missing-yamark"))
+        .assert()
+        .failure();
+    assert_eq!(fs::read(repo.join("keep.md")).unwrap(), b"# Keep\n");
+}
+fn commit_files(repo: &Path) {
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(repo)
+            .args(args)
+            .assert()
+            .success();
+    };
+    git(&["init", "-q"]);
+    git(&["config", "user.name", "Git Filter Test"]);
+    git(&["config", "user.email", "git-filter@example.test"]);
+    git(&["config", "commit.gpgSign", "false"]);
+    git(&["config", "core.autocrlf", "false"]);
+    git(&["add", "."]);
+    git(&["commit", "-qm", "fixture"]);
+}

From 76d5a800bc4febac8c40ee852543bebd78b1dccf Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:34:43 -0500
Subject: [PATCH 39/64] Detect index changes without keeping the index file
 open

---
 Cargo.lock                                    |  1 -
 Cargo.toml                                    |  1 -
 docs/ARCHITECTURE.md                          |  2 +-
 external-tests/cli/test_git_filter.py         |  9 +++-
 src/cli/git_filter/checkout.rs                | 54 ++++++++++++++-----
 .../git_filter_process_index_change.case      |  3 +-
 6 files changed, 52 insertions(+), 18 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 0d7a01af..acf97d4c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -801,7 +801,6 @@ dependencies = [
  "jsonc-parser",
  "memchr",
  "num-bigint",
- "same-file",
  "serde_json",
  "tempfile",
  "thiserror",
diff --git a/Cargo.toml b/Cargo.toml
index ac6645b1..89a17de8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,7 +32,6 @@ json-five = { version = "=0.3.1", default-features = false }
 jsonc-parser = { version = "0.33.2", default-features = false }
 memchr = "2.8.3"
 num-bigint = "0.5.1"
-same-file = "1.0.6"
 serde_json = "1.0.151"
 tempfile = "3.27.0"
 thiserror = "2.0.20"
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ff115de0..ce0f008a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,7 +98,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree on every request. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when Git replaces the index file. Direct smudge invocations without a checkout source use the working-tree configuration.
+The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree on every request. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
 The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files before verification and writing.
 
diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index 9f0ff318..8d3bbad4 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -347,11 +347,16 @@ def test_git_filter_join_installs_local_config_and_keeps_checkout_clean(
         ).encode("utf-8")
 
 
-@pytest.mark.parametrize("direction", ["clean", "smudge"])
-def test_persistent_git_filter_observes_config_changes(tmp_path: Path, direction: str) -> None:
+@pytest.mark.parametrize(
+    ("direction", "skip_hash"), [("clean", False), ("smudge", False), ("smudge", True)]
+)
+def test_persistent_git_filter_observes_config_changes(
+    tmp_path: Path, direction: str, skip_hash: bool,
+) -> None:
     repo = tmp_path
     init_repo(repo)
     run_git(repo, "config", "core.autocrlf", "false")
+    run_git(repo, "config", "index.skipHash", str(skip_hash).lower())
     original = b"#   Keep\n"
     formatted = b"# Keep\n"
     (repo / "doc.md").write_bytes(original)
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index 3a9ec464..f5662e4a 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -3,6 +3,8 @@
 
 use std::collections::{BTreeMap, HashMap, VecDeque};
 use std::ffi::OsString;
+use std::fs::File;
+use std::io::{self, Read, Seek, SeekFrom};
 use std::path::{Component, Path, PathBuf};
 use std::process::Command;
 
@@ -11,13 +13,42 @@ use super::process::{entry_fields, git_stdout, git_stdout_bytes};
 use crate::config::Config;
 use crate::diagnostic::{Result, YamarkError};
 
-/// A Git index update replaces the file atomically. Keep its handle open
-/// while caching the entries so its identity cannot be reused.
 struct IndexSnapshot {
-    handle: Option,
+    version: IndexVersion,
     entries: BTreeMap,
 }
 
+#[derive(PartialEq)]
+enum IndexVersion {
+    Missing,
+    Trailer([u8; 32]),
+    Unhashed(Vec),
+}
+
+impl IndexVersion {
+    fn read(path: &Path) -> io::Result {
+        let mut index = match File::open(path) {
+            Ok(file) => file,
+            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::Missing),
+            Err(err) => return Err(err),
+        };
+        // Even an empty index has a 12-byte header and a SHA-1 or SHA-256
+        // checksum. Its final 32 bytes include the entire checksum for either.
+        let mut trailer = [0; 32];
+        index.seek(SeekFrom::End(-32))?;
+        index.read_exact(&mut trailer)?;
+        if trailer[12..] != [0; 20] {
+            return Ok(Self::Trailer(trailer));
+        }
+        // index.skipHash writes zeroes. Compare those indexes by content so
+        // equal sizes and filesystem timestamps cannot conceal an edit.
+        index.rewind()?;
+        let mut bytes = Vec::new();
+        index.read_to_end(&mut bytes)?;
+        Ok(Self::Unhashed(bytes))
+    }
+}
+
 #[derive(Clone)]
 enum Entry {
     File(String),
@@ -26,7 +57,7 @@ enum Entry {
 }
 
 impl IndexSnapshot {
-    fn load(repo: &Path, handle: Option) -> Result {
+    fn load(repo: &Path, version: IndexVersion) -> Result {
         let records = git_stdout_bytes(repo, ["ls-files", "--stage", "--full-name", "-z"])
             .map_err(YamarkError::new)?;
         let mut entries = BTreeMap::new();
@@ -44,7 +75,7 @@ impl IndexSnapshot {
             };
             entries.insert(PathBuf::from(name), entry);
         }
-        Ok(Self { handle, entries })
+        Ok(Self { version, entries })
     }
 }
 
@@ -73,17 +104,16 @@ impl CheckoutConfigs {
                 self.index_path.insert(repo.join(path))
             }
         };
-        let handle = match same_file::Handle::from_path(index_path) {
-            Ok(handle) => Some(handle),
-            Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
-            Err(err) => return Err(YamarkError::new(err.to_string()).with_path(index_path)),
-        };
+        // Close the handle before invoking Git. An open index can prevent
+        // another process from replacing it on Windows.
+        let version = IndexVersion::read(index_path)
+            .map_err(|err| YamarkError::new(err.to_string()).with_path(index_path))?;
         if self
             .index
             .as_ref()
-            .is_none_or(|index| index.handle != handle)
+            .is_none_or(|index| index.version != version)
         {
-            self.index = Some(IndexSnapshot::load(repo, handle)?);
+            self.index = Some(IndexSnapshot::load(repo, version)?);
             self.directories.retain(|(tree, _), _| !tree.is_empty());
         }
         Ok(())
diff --git a/tests/cases/git_filter_process_index_change.case b/tests/cases/git_filter_process_index_change.case
index a03469f3..9764b463 100644
--- a/tests/cases/git_filter_process_index_change.case
+++ b/tests/cases/git_filter_process_index_change.case
@@ -1,7 +1,8 @@
 -- git-fixture
 {
   "config": {
-    "core.autocrlf": "false"
+    "core.autocrlf": "false",
+    "index.skipHash": "true"
   },
   "files": {
     "also.md": "#   Keep\n",

From 151293645c4c6099833227c87f499a59696ab093 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:36:55 -0500
Subject: [PATCH 40/64] Refresh the Git filter guide for merges and committed
 checks

---
 website/git-filter.html.md | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index e8e613b8..e37a8fc6 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -37,8 +37,10 @@ filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an ex
 no tree, smudge uses the staged configuration if Git identifies the file's
 staged blob. If the blob is missing or differs from the staged blob, as can
 happen during a merge or cherry-pick, smudge returns the incoming bytes
-unchanged. If `yamark.toml` is a symbolic link, its target must also be present
-in the selected tree or index. Clean reads the working-tree config.
+unchanged. A merge conflict in the nearest staged config or its symlink target
+also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
+symbolic link, its target must be present in the selected tree or index. Clean
+reads the current working-tree config on each request.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.
@@ -121,7 +123,10 @@ contract:
 yamark git-filter check
 ```
 
-It fails if any tracked Markdown file selected by `.gitattributes` violates:
+It checks the regular Markdown files in `HEAD`, using the committed versions of
+`.gitattributes` and `yamark.toml`. Git still applies its usual attribute
+precedence, including overrides in `.git/info/attributes`. The check fails
+if any selected file violates:
 
 ```text
 clean(smudge(blob)) == blob
@@ -160,9 +165,14 @@ git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
 git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
-git config merge.renormalize true
 ```
 
+Leave Git's `merge.renormalize` disabled when exclusions can differ between
+branches. During a two-sided merge, renormalization can run historical blobs
+through the current branch's clean filter and rewrite a file that the incoming
+branch excludes. If an earlier Yamark installation set this option in your
+clone, remove its setting with `git config --local --unset merge.renormalize`.
+
 Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
 
 For personal use, add attributes to `.git/info/attributes`. For shared project

From 87bcacc09ad4faea8ba8b1628fe982a5136e99ea Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:38:41 -0500
Subject: [PATCH 41/64] Restore converted files when Git cannot refresh
 checkout metadata

---
 src/cli/git_filter.rs                         | 29 ++++++++++++-------
 .../git_filter_join_refresh_failure.case      | 28 ++++++++++++++++++
 2 files changed, 47 insertions(+), 10 deletions(-)
 create mode 100644 tests/cases/git_filter_join_refresh_failure.case

diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index d68a656b..3bffa058 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -724,18 +724,27 @@ fn write_smudged_worktree(repo_root: &Path, paths: &[PathBuf]) -> Result<(), Str
     };
     checkout(prefix)?;
 
-    for path in paths {
-        let target = repo_root.join(path);
-        replace_with_checkout_file(&converted.path().join(path), &target).map_err(|err| {
-            format!(
-                "{}: failed to install smudged file: {err}",
-                target.display()
-            )
-        })?;
-    }
+    let install = || {
+        paths.iter().try_for_each(|path| {
+            let target = repo_root.join(path);
+            replace_with_checkout_file(&converted.path().join(path), &target).map_err(|err| {
+                format!(
+                    "{}: failed to install smudged file: {err}",
+                    target.display()
+                )
+            })
+        })
+    };
+    install()?;
     // Refresh the real index as part of checkout so CRLF files also acquire
     // their correct worktree stat data.
-    checkout(OsString::from("--index"))?;
+    if let Err(error) = checkout(OsString::from("--index")) {
+        // Git can unlink a path before reporting a failed smudge. Restore the
+        // entire known-good batch, including paths already visited by Git.
+        install()
+            .map_err(|restore| format!("{error}\nFailed to restore converted files: {restore}"))?;
+        return Err(error);
+    }
     Ok(())
 }
 
diff --git a/tests/cases/git_filter_join_refresh_failure.case b/tests/cases/git_filter_join_refresh_failure.case
new file mode 100644
index 00000000..9e2514cc
--- /dev/null
+++ b/tests/cases/git_filter_join_refresh_failure.case
@@ -0,0 +1,28 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "post.md": "# Keep\n"
+  }
+}
+-- args
+git-filter join
+-- env
+{
+  "GIT_CONFIG_COUNT": "2",
+  "GIT_CONFIG_KEY_0": "filter.yamark-md.process",
+  "GIT_CONFIG_VALUE_0": "\"$YAMARK_CASE_BIN\" git-filter process 2>/dev/null",
+  "GIT_CONFIG_KEY_1": "filter.yamark-md.smudge",
+  "GIT_CONFIG_VALUE_1": "test ! -f .git/smudged && touch .git/smudged && echo '#    Keep'"
+}
+-- stdin
+-- stdout
+-- stderr
+error: git failed: fatal: post.md: smudge filter yamark-md failed
+-- git-index
+{"post.md": "# Keep\n"}
+-- git-worktree
+{"post.md": "#    Keep\n"}
+-- status
+1

From e033e5d57e99e65575e996d90ca8b942a5d09507 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 11:40:10 -0500
Subject: [PATCH 42/64] Document the lifetime of the checkout batch

---
 docs/ARCHITECTURE.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ce0f008a..930da372 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -100,7 +100,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree on every request. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
-The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files before verification and writing.
+The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory before replacing any working files. They retain the converted batch until Git refreshes the index's file metadata because a failed smudge during that refresh can remove a working file.
 
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 

From 5b8a2e68f4109d50d79a25572ce07c907c81403b Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:08:17 -0500
Subject: [PATCH 43/64] Suppress index-change hooks during committed-blob
 verification

---
 src/cli/git_filter/process.rs                 | 19 ++++++++++-
 .../git_filter_check_private_index_hooks.case | 33 +++++++++++++++++++
 2 files changed, 51 insertions(+), 1 deletion(-)
 create mode 100644 tests/cases/git_filter_check_private_index_hooks.case

diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index 817028c4..f494fb47 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -72,7 +72,24 @@ impl TreeIndex {
             tempfile::tempdir()
                 .map_err(|err| format!("failed to create temporary index directory: {err}"))?,
         );
-        checked_stdout(index.git(repo).args(["read-tree", tree]).output())?;
+        // Loading a private index is not a change to the user's index. Older
+        // Git discovers hooks by directory; newer Git can also configure
+        // hook commands directly for the event.
+        let mut hooks_path = OsString::from("core.hooksPath=");
+        hooks_path.push(index.0.path());
+        checked_stdout(
+            index
+                .git(repo)
+                .arg("-c")
+                .arg(hooks_path)
+                .args([
+                    "-c",
+                    "hook.post-index-change.enabled=false",
+                    "read-tree",
+                    tree,
+                ])
+                .output(),
+        )?;
         Ok(index)
     }
 
diff --git a/tests/cases/git_filter_check_private_index_hooks.case b/tests/cases/git_filter_check_private_index_hooks.case
new file mode 100644
index 00000000..0adbff5d
--- /dev/null
+++ b/tests/cases/git_filter_check_private_index_hooks.case
@@ -0,0 +1,33 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "doc.md": "# Checked\n",
+    "hooks/post-index-change": "#!/bin/sh\necho changed >>index-events\n",
+    "index-events": ""
+  },
+  "git-after-commit": [
+    ["-c", "alias.enable-hook=!chmod +x hooks/post-index-change", "enable-hook"],
+    ["config", "core.hooksPath", "hooks"],
+    ["read-tree", "HEAD"]
+  ]
+}
+-- args
+git-filter check
+-- env
+{
+  "GIT_CONFIG_COUNT": "2",
+  "GIT_CONFIG_KEY_0": "hook.record-index.event",
+  "GIT_CONFIG_VALUE_0": "post-index-change",
+  "GIT_CONFIG_KEY_1": "hook.record-index.command",
+  "GIT_CONFIG_VALUE_1": "echo configured >>index-events"
+}
+-- stdin
+-- stdout
+yamark Git filter check passed for 1 Markdown file(s).
+-- stderr
+-- git-worktree
+{"index-events": "changed\n"}
+-- status
+0

From 0aa77801793ecf4ed9dd1b3e3ff686c5394a31fe Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:11:26 -0500
Subject: [PATCH 44/64] Pin Git transcript inputs that depend on locale and
 object format

---
 tests/cases/README.md                                      | 2 ++
 tests/cases/git_filter_join_refresh_failure.case           | 1 +
 tests/cases/git_filter_process_conflicted_config.case      | 1 +
 tests/cases/git_filter_process_custom_treeless_smudge.case | 1 +
 tests/cases/git_filter_process_index_change.case           | 1 +
 tests/cases/git_filter_process_treeless_smudge.case        | 1 +
 tests/cli_cases.rs                                         | 6 +++++-
 7 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/tests/cases/README.md b/tests/cases/README.md
index 9cfcec93..603f8986 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -75,3 +75,5 @@ For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can a
 The `git_filter_adopt_*.case` transcripts cover adoption with automatic CRLF conversion, LF checkouts, and explicit `eol` attributes overriding `core.autocrlf`. They record the staged status and use `-- git-index` and `-- git-worktree` JSON file mappings to check exact staged and checkout bytes. JSON newline escapes make the expected CRLF/LF distinction visible in the transcript.
 
 Use `git-after-commit` in a Git fixture to run an ordered list of Git argument arrays after creating its commit. The `git_filter_check_committed_selection` and `git_filter_check_removed_attributes` cases use it to change the index and checkout while verifying the original commit.
+
+Set `"object-format": "sha1"` in a Git fixture when its protocol packets contain literal SHA-1 object IDs. Other fixtures use Git's default object format.
diff --git a/tests/cases/git_filter_join_refresh_failure.case b/tests/cases/git_filter_join_refresh_failure.case
index 9e2514cc..f0b2fbce 100644
--- a/tests/cases/git_filter_join_refresh_failure.case
+++ b/tests/cases/git_filter_join_refresh_failure.case
@@ -10,6 +10,7 @@
 git-filter join
 -- env
 {
+  "LC_ALL": "C",
   "GIT_CONFIG_COUNT": "2",
   "GIT_CONFIG_KEY_0": "filter.yamark-md.process",
   "GIT_CONFIG_VALUE_0": "\"$YAMARK_CASE_BIN\" git-filter process 2>/dev/null",
diff --git a/tests/cases/git_filter_process_conflicted_config.case b/tests/cases/git_filter_process_conflicted_config.case
index 389260e7..7f7fae0d 100644
--- a/tests/cases/git_filter_process_conflicted_config.case
+++ b/tests/cases/git_filter_process_conflicted_config.case
@@ -1,5 +1,6 @@
 -- git-fixture
 {
+  "object-format": "sha1",
   "config": {
     "core.autocrlf": "false"
   },
diff --git a/tests/cases/git_filter_process_custom_treeless_smudge.case b/tests/cases/git_filter_process_custom_treeless_smudge.case
index a383183a..7cc5f8a8 100644
--- a/tests/cases/git_filter_process_custom_treeless_smudge.case
+++ b/tests/cases/git_filter_process_custom_treeless_smudge.case
@@ -1,5 +1,6 @@
 -- git-fixture
 {
+  "object-format": "sha1",
   "config": {
     "core.autocrlf": "false",
     "filter.yamark-md.smudge": "\"$YAMARK_CASE_BIN\" git-filter smudge --stdin-filename '%f'"
diff --git a/tests/cases/git_filter_process_index_change.case b/tests/cases/git_filter_process_index_change.case
index 9764b463..9efe985a 100644
--- a/tests/cases/git_filter_process_index_change.case
+++ b/tests/cases/git_filter_process_index_change.case
@@ -1,5 +1,6 @@
 -- git-fixture
 {
+  "object-format": "sha1",
   "config": {
     "core.autocrlf": "false",
     "index.skipHash": "true"
diff --git a/tests/cases/git_filter_process_treeless_smudge.case b/tests/cases/git_filter_process_treeless_smudge.case
index 50900c85..3416bf06 100644
--- a/tests/cases/git_filter_process_treeless_smudge.case
+++ b/tests/cases/git_filter_process_treeless_smudge.case
@@ -1,5 +1,6 @@
 -- git-fixture
 {
+  "object-format": "sha1",
   "config": {"core.autocrlf": "false"},
   "files": {"doc.md": "# Base\n"},
   "setup-filter": true
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index e9d14dcb..48f3d05a 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -194,7 +194,11 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
             .assert()
             .success();
     };
-    git(&["init", "-q"]);
+    if let Some(format) = fixture["object-format"].as_str() {
+        git(&["init", "-q", &format!("--object-format={format}")]);
+    } else {
+        git(&["init", "-q"]);
+    }
     git(&["config", "user.name", "CLI Case"]);
     git(&["config", "user.email", "cli-case@example.test"]);
     git(&["config", "commit.gpgSign", "false"]);

From d96040eb78ba36a521e60e4de82a124287217f65 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:11:12 -0500
Subject: [PATCH 45/64] Limit Git clean configuration discovery to the worktree

---
 docs/ARCHITECTURE.md                          |  2 +-
 src/cli/git_filter.rs                         | 27 +++++++++++++---
 src/cli/git_filter/driver.rs                  |  3 +-
 src/config.rs                                 | 26 +++++++++-------
 .../git_filter_adopt_worktree_boundary.case   | 31 +++++++++++++++++++
 .../git_filter_clean_nested_worktree.case     | 20 ++++++++++++
 .../git_filter_clean_worktree_boundary.case   | 19 ++++++++++++
 website/git-filter.qmd                        |  3 +-
 8 files changed, 111 insertions(+), 20 deletions(-)
 create mode 100644 tests/cases/git_filter_adopt_worktree_boundary.case
 create mode 100644 tests/cases/git_filter_clean_nested_worktree.case
 create mode 100644 tests/cases/git_filter_clean_worktree_boundary.case

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 930da372..3f7f189f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,7 +98,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration in the working tree on every request. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
+The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
 The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory before replacing any working files. They retain the converted batch until Git refreshes the index's file metadata because a failed smudge during that refresh can remove a working file.
 
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 3bffa058..c847eeb8 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -15,11 +15,9 @@ use std::process::{Command as ProcessCommand, ExitCode};
 use clap::Subcommand;
 
 use super::{parse_positive_usize, run_stdin};
-use crate::config::Config;
+use crate::config::{Config, discover_config_within};
 use crate::core::document::{FormatOptions, MarkdownWrap};
-use crate::workspace::{
-    FormatExecutionOptions, format_source_with_config, load_config_for_formatted_path,
-};
+use crate::workspace::{FormatExecutionOptions, format_source_with_config};
 use attributes::{
     append_missing_attribute_lines, count_yamark_filter_attribute_lines,
     git_filter_attribute_patterns, line_has_yamark_filter_attribute,
@@ -236,7 +234,17 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
                 path,
                 blob.as_ref().map(String::as_bytes),
             ),
-            FilterSource::Worktree => load_config_for_formatted_path(path, None).map(Some),
+            FilterSource::Worktree => {
+                // Direct invocations may start in a subdirectory, or outside Git.
+                let cwd = env::current_dir()
+                    .map_err(|err| crate::diagnostic::YamarkError::new(err.to_string()))?;
+                let cdup = git_stdout(Path::new("."), ["rev-parse", "--show-cdup"]).ok();
+                let root = cdup.as_ref().and_then(|up| {
+                    cwd.ancestors()
+                        .nth(Path::new(up.trim_end()).components().count())
+                });
+                worktree_config(path, root).map(Some)
+            }
         },
         filter_options(wrap),
         FormatExecutionOptions {
@@ -246,6 +254,15 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
     )
 }
 
+fn worktree_config(path: &Path, root: Option<&Path>) -> crate::diagnostic::Result {
+    match discover_config_within(path, root) {
+        Some(candidate) => {
+            Config::from_path(&candidate).map(|config| config.for_formatted_path(path))
+        }
+        None => Ok(Config::default()),
+    }
+}
+
 fn run_git_filter_adopt(
     repo: Option,
     yamark: Option,
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 8120cf15..c26369d1 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -8,7 +8,6 @@ use std::process::{Command, ExitCode, Stdio};
 
 use super::checkout::CheckoutConfigs;
 use crate::core::document::{FileKind, MarkdownWrap};
-use crate::workspace::load_config_for_formatted_path;
 
 pub(super) const SOURCE_BLOB_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_BLOB";
 pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
@@ -127,7 +126,7 @@ fn filter_file(
             let config = match tree {
                 Some("") => configs.for_staged_blob(Path::new("."), path, field(b"blob=")),
                 Some(tree) => configs.for_path(Path::new("."), tree, path),
-                None => load_config_for_formatted_path(path, None).map(Some),
+                None => super::worktree_config(path, Some(&std::env::current_dir()?)).map(Some),
             }
             .map_err(io::Error::other)?;
             let Some(config) = config else {
diff --git a/src/config.rs b/src/config.rs
index d5e6d843..7c783941 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -297,18 +297,22 @@ fn default_template_delimiters() -> Vec {
 }
 
 pub fn discover_config_path(path: &Path) -> Option {
-    // Resolve relative paths before walking parents, including virtual stdin
-    // paths that do not exist. Otherwise discovery stops at the working directory.
+    discover_config_within(path, None)
+}
+
+pub(crate) fn discover_config_within(path: &Path, root: Option<&Path>) -> Option {
+    // Resolve relative paths before walking parents, including virtual stdin paths.
     let path = std::path::absolute(path).ok()?;
-    let mut dir = path.parent().unwrap_or_else(|| Path::new("."));
-    loop {
-        let candidate = dir.join("yamark.toml");
-        if candidate.is_file() {
-            return Some(candidate);
-        }
-        let parent = dir.parent()?;
-        dir = parent;
-    }
+    let path = if root.is_some() {
+        resolve_parent_components(&path)
+    } else {
+        path
+    };
+    path.parent()?
+        .ancestors()
+        .take_while(|dir| root.is_none_or(|root| dir.starts_with(root)))
+        .map(|dir| dir.join("yamark.toml"))
+        .find(|candidate| candidate.is_file())
 }
 
 fn apply_template_layer(
diff --git a/tests/cases/git_filter_adopt_worktree_boundary.case b/tests/cases/git_filter_adopt_worktree_boundary.case
new file mode 100644
index 00000000..624a6b59
--- /dev/null
+++ b/tests/cases/git_filter_adopt_worktree_boundary.case
@@ -0,0 +1,31 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
+    "project/docs/file.md": "- - -\n"
+  },
+  "git-after-commit": [
+    ["-C", "project", "init", "-q"],
+    ["-C", "project", "config", "core.autocrlf", "false"],
+    ["-C", "project", "add", "."],
+    ["-C", "project", "-c", "user.name=CLI Case", "-c", "user.email=cli-case@example.test", "-c", "commit.gpgSign=false", "commit", "-qm", "fixture"]
+  ],
+  "cwd": "project"
+}
+-- args
+git-filter adopt
+-- stdin
+-- stdout
+Adopted yamark Git filter in {{repo}}/project
+Updated .gitattributes with 4 new attribute pattern(s)
+Staged .gitattributes and 1 normalized Markdown file(s).
+
+Review and commit with:
+  git diff --cached
+  git commit -m "Normalize Markdown with yamark Git filter"
+-- stderr
+-- git-worktree
+{"project/docs/file.md": "---\n"}
+-- status
+0
diff --git a/tests/cases/git_filter_clean_nested_worktree.case b/tests/cases/git_filter_clean_nested_worktree.case
new file mode 100644
index 00000000..bd27f5e6
--- /dev/null
+++ b/tests/cases/git_filter_clean_nested_worktree.case
@@ -0,0 +1,20 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '---'\n",
+    "project/yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
+    "project/docs/file.md": "Body.\n"
+  },
+  "git-after-commit": [["-C", "project", "init", "-q"]],
+  "cwd": "project/docs"
+}
+-- args
+git-filter clean --stdin-filename file.md
+-- stdin
+- - -
+-- stdout
+***
+-- stderr
+-- status
+0
diff --git a/tests/cases/git_filter_clean_worktree_boundary.case b/tests/cases/git_filter_clean_worktree_boundary.case
new file mode 100644
index 00000000..18ee7f19
--- /dev/null
+++ b/tests/cases/git_filter_clean_worktree_boundary.case
@@ -0,0 +1,19 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
+    "project/docs/file.md": "Body.\n"
+  },
+  "git-after-commit": [["-C", "project", "init", "-q"]],
+  "cwd": "project/docs"
+}
+-- args
+git-filter clean --stdin-filename file.md
+-- stdin
+- - -
+-- stdout
+---
+-- stderr
+-- status
+0
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index e37a8fc6..48cee104 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -40,7 +40,8 @@ happen during a merge or cherry-pick, smudge returns the incoming bytes
 unchanged. A merge conflict in the nearest staged config or its symlink target
 also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
 symbolic link, its target must be present in the selected tree or index. Clean
-reads the current working-tree config on each request.
+reads the nearest working-tree config on each request. Discovery stops at the
+worktree root, and Yamark uses its defaults if it finds no config there or below.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.

From ab99d26b4a644a588dde2f366628158403c7dcad Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:10:56 -0500
Subject: [PATCH 46/64] Run PATH-based Yamark filter commands in the serving
 process

---
 src/cli/git_filter/driver.rs | 48 +++++++++++++++---
 tests/git_filter_process.rs  | 95 ++++++++++++++++++++++++++++++------
 2 files changed, 119 insertions(+), 24 deletions(-)

diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index c26369d1..7684e965 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -32,19 +32,34 @@ fn serve() -> io::Result<()> {
         return Err(io::Error::other("expected git-filter-client version 2"));
     }
     write_section(&mut output, &[b"git-filter-server\n", b"version=2\n"])?;
-    let exe = super::shell_quote_path(&std::env::current_exe()?).map_err(io::Error::other)?;
-    let clean = driver_command("filter.yamark-md.clean")?.map(|command| {
-        if command == super::default_clean_command(&exe) {
+    let clean = driver_command("filter.yamark-md.clean")?;
+    let smudge = driver_command("filter.yamark-md.smudge")?;
+    let exe = std::env::current_exe()?;
+    let quoted_exe = super::shell_quote_path(&exe).map_err(io::Error::other)?;
+    let mut names = vec![quoted_exe.as_str()];
+    if [clean.as_deref(), smudge.as_deref()]
+        .into_iter()
+        .flatten()
+        .any(|command| command.starts_with("yamark git-filter "))
+        && path_resolves_to_serving_yamark(&exe)?
+    {
+        names.push("yamark");
+    }
+    let clean = clean.map(|command| {
+        if names
+            .iter()
+            .any(|name| command == super::default_clean_command(name))
+        {
             Driver::Yamark(MarkdownWrap::Sentence)
         } else {
             Driver::Custom(custom_alias(&command))
         }
     });
-    let smudge_prefix = super::default_smudge_prefix(&exe);
-    let smudge = driver_command("filter.yamark-md.smudge")?.map(|command| {
-        if let Some(width) = command.strip_prefix(&smudge_prefix)
-            && let Ok(width) = super::super::parse_positive_usize(width)
-        {
+    let smudge = smudge.map(|command| {
+        if let Some(width) = names.iter().find_map(|name| {
+            let width = command.strip_prefix(&super::default_smudge_prefix(name))?;
+            super::super::parse_positive_usize(width).ok()
+        }) {
             Driver::Yamark(MarkdownWrap::Column(width))
         } else {
             Driver::Custom(custom_alias(&command))
@@ -95,6 +110,23 @@ enum Driver {
     Custom(String),
 }
 
+/// Resolve the documented bare command in the same shell Git uses to run it.
+/// The shell's file identity test also handles symlinks and Git for Windows paths.
+fn path_resolves_to_serving_yamark(exe: &Path) -> io::Result {
+    // A shell function is reported as the bare name, without a file path.
+    Ok(Command::new("git")
+        .args([
+            "-c",
+            r#"alias.yamark-lookup=!p=$(command -v yamark) && test "$p" != yamark && test "$p" -ef "$YAMARK_SERVING_EXE""#,
+            "yamark-lookup",
+        ])
+        .env("YAMARK_SERVING_EXE", exe)
+        .stdin(Stdio::null())
+        .stdout(Stdio::null())
+        .status()?
+        .success())
+}
+
 fn filter_file(
     fields: &[Vec],
     contents: Vec,
diff --git a/tests/git_filter_process.rs b/tests/git_filter_process.rs
index f687c44b..e08e58cc 100644
--- a/tests/git_filter_process.rs
+++ b/tests/git_filter_process.rs
@@ -4,6 +4,9 @@ use std::path::Path;
 use assert_cmd::Command;
 use tempfile::tempdir;
 
+#[path = "support/symlink.rs"]
+mod symlink;
+
 #[test]
 fn default_filters_reuse_configuration_for_files_in_one_directory() {
     let repo = tempdir().unwrap();
@@ -30,16 +33,19 @@ fn default_filters_reuse_configuration_for_files_in_one_directory() {
         .assert()
         .success();
 
-    let trace_dir = tempdir().unwrap();
-    let checkout = |files: &[&str], trace: &Path| {
-        for name in files {
-            fs::remove_file(root.join(name)).unwrap();
-        }
-        Command::new("git")
+    let exe = Path::new(env!("CARGO_BIN_EXE_yamark"));
+    let git_starts = |command: &mut Command, bin_directory: &Path| {
+        let trace_dir = tempdir().unwrap();
+        let trace = trace_dir.path().join("events.jsonl");
+        let inherited = std::env::var_os("PATH").unwrap();
+        let path = std::env::join_paths(
+            std::iter::once(bin_directory.to_owned()).chain(std::env::split_paths(&inherited)),
+        )
+        .unwrap();
+        command
             .current_dir(root)
-            .env("GIT_TRACE2_EVENT", trace)
-            .args(["checkout-index", "--"])
-            .args(files)
+            .env("GIT_TRACE2_EVENT", &trace)
+            .env("PATH", path)
             .assert()
             .success();
         fs::read_to_string(trace)
@@ -49,13 +55,58 @@ fn default_filters_reuse_configuration_for_files_in_one_directory() {
             .filter(|event| event["event"] == "start")
             .count()
     };
-    let single = checkout(&names[..1], &trace_dir.path().join("single.jsonl"));
-    let multiple = checkout(&names, &trace_dir.path().join("multiple.jsonl"));
-    assert!(single > 0);
-    assert_eq!(
-        multiple, single,
-        "extra Git processes for files sharing a config"
-    );
+    let checkout = |files: &[&str], bin: &Path| {
+        for name in files {
+            fs::remove_file(root.join(name)).unwrap();
+        }
+        git_starts(
+            Command::new("git")
+                .args(["checkout-index", "--"])
+                .args(files),
+            bin,
+        )
+    };
+    let hash = |files: &[&str], bin: &Path| {
+        git_starts(
+            Command::new("git")
+                .args(["hash-object", "--stdin-paths"])
+                .write_stdin(format!("{}\n", files.join("\n"))),
+            bin,
+        )
+    };
+    let assert_reuse = |bin: &Path| {
+        let single = checkout(&names[..1], bin);
+        let multiple = checkout(&names, bin);
+        assert!(single > 0);
+        assert_eq!(
+            multiple, single,
+            "extra Git processes for files sharing a config"
+        );
+        assert_eq!(
+            hash(&names, bin),
+            hash(&names[..1], bin),
+            "extra Git processes for clean"
+        );
+    };
+    assert_reuse(exe.parent().unwrap());
+    git(&[
+        "config",
+        "filter.yamark-md.clean",
+        "yamark git-filter clean --stdin-filename %f",
+    ]);
+    git(&[
+        "config",
+        "filter.yamark-md.smudge",
+        "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72",
+    ]);
+    assert_reuse(exe.parent().unwrap());
+    let links = tempfile::Builder::new()
+        .prefix("yamark bin ")
+        .tempdir()
+        .unwrap();
+    if symlink::make_symlink(exe, &links.path().join(exe.file_name().unwrap())) {
+        assert_reuse(links.path());
+    }
     for name in names {
         let expected = if name == "two.md" {
             "First sentence.\nSecond sentence?\n"
@@ -64,6 +115,18 @@ fn default_filters_reuse_configuration_for_files_in_one_directory() {
         };
         assert_eq!(fs::read_to_string(root.join(name)).unwrap(), expected);
     }
+
+    // The same command spelling can resolve to a local wrapper.
+    let alternate = tempdir().unwrap();
+    let wrapper = alternate.path().join("yamark");
+    fs::write(&wrapper, "#!/bin/sh\nprintf 'Separate driver\\n'\n").unwrap();
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+        fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
+    }
+    checkout(&names[..1], alternate.path());
+    assert_eq!(fs::read(root.join("one.md")).unwrap(), b"Separate driver\n");
 }
 
 #[test]

From fdaa505e10b4a3ce1eb8072819ff2fac765ed183 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:13:06 -0500
Subject: [PATCH 47/64] Keep temporary Git checkout and index directories
 private

---
 .../cli/test_git_filter_permissions.py        | 55 +++++++++++++++++++
 src/cli/git_filter.rs                         |  2 +-
 src/cli/git_filter/process.rs                 | 15 ++++-
 3 files changed, 70 insertions(+), 2 deletions(-)
 create mode 100644 external-tests/cli/test_git_filter_permissions.py

diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
new file mode 100644
index 00000000..0f298d85
--- /dev/null
+++ b/external-tests/cli/test_git_filter_permissions.py
@@ -0,0 +1,55 @@
+"""Permissions on the local files created while checking and joining a filter."""
+
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from test_git_filter import init_repo, run_git
+
+
+@pytest.mark.skipif(os.name != "posix", reason="Unix directory access modes")
+@pytest.mark.parametrize(("action", "operation"), [("check", "read-tree"), ("join", "checkout")])
+def test_filter_uses_private_scratch_directory(
+    tmp_path: Path, action: str, operation: str,
+) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir(mode=0o700)
+    init_repo(repo)
+    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
+    (repo / "doc.md").write_bytes(b"# Fixture\n")
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+    # Observe the directory at the Git invocation that will populate it.
+    program = tmp_path / "git"
+    program.write_text(
+        """#!/usr/bin/env python3
+import os, sys
+from pathlib import Path
+
+if 'read-tree' in sys.argv and 'GIT_INDEX_FILE' in os.environ:
+    directory = Path(os.environ['GIT_INDEX_FILE']).parent
+    print('read-tree', oct(directory.stat().st_mode & 0o777), file=open(os.environ['MODE_LOG'], 'a'))
+for arg in sys.argv:
+    if 'checkout-index' in sys.argv and arg.startswith('--prefix='):
+        directory = Path(arg.removeprefix('--prefix='))
+        print('checkout', oct(directory.stat().st_mode & 0o777), file=open(os.environ['MODE_LOG'], 'a'))
+os.execv(os.environ['REAL_GIT'], [os.environ['REAL_GIT'], *sys.argv[1:]])
+"""
+    )
+    program.chmod(0o700)
+    real_git = shutil.which("git")
+    assert real_git is not None
+    log = tmp_path / "modes"
+    subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", action],
+        cwd=repo,
+        check=True,
+        capture_output=True,
+        umask=0o022,
+        env={**os.environ, "REAL_GIT": real_git, "MODE_LOG": str(log),
+             "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
+    )
+    assert log.read_text().splitlines() == [f"{operation} 0o700"]
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index c847eeb8..0db32fd6 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -722,7 +722,7 @@ fn write_smudged_worktree(repo_root: &Path, paths: &[PathBuf]) -> Result<(), Str
     // Even --force can skip stat-clean files. Check out all targets to a fresh
     // prefix so Git applies its conversions and leaves originals intact if
     // one of the filters fails.
-    let converted = tempfile::tempdir().map_err(|err| err.to_string())?;
+    let converted = process::private_tempdir().map_err(|err| err.to_string())?;
     let mut prefix = OsString::from("--prefix=");
     prefix.push(converted.path());
     prefix.push("/");
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index f494fb47..e2f70753 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -62,6 +62,19 @@ pub(super) fn checked_stdout(
     Ok(output.stdout)
 }
 
+/// Git writes repository contents and object names inside this directory.
+pub(super) fn private_tempdir() -> std::io::Result {
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+        tempfile::Builder::new()
+            .permissions(std::fs::Permissions::from_mode(0o700))
+            .tempdir()
+    }
+    #[cfg(not(unix))]
+    tempfile::tempdir()
+}
+
 /// An index containing exactly one tree's entries, independent of staged
 /// changes and working-tree stat data.
 pub(super) struct TreeIndex(tempfile::TempDir);
@@ -69,7 +82,7 @@ pub(super) struct TreeIndex(tempfile::TempDir);
 impl TreeIndex {
     pub(super) fn read_tree(repo: &Path, tree: &str) -> Result {
         let index = Self(
-            tempfile::tempdir()
+            private_tempdir()
                 .map_err(|err| format!("failed to create temporary index directory: {err}"))?,
         );
         // Loading a private index is not a change to the user's index. Older

From 2444b7e2534acaf0afdfeafcaa85749c199738d0 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:15:54 -0500
Subject: [PATCH 48/64] Match checkout exclusions against snapshot-relative
 paths

---
 docs/ARCHITECTURE.md                          |  2 +-
 src/cli.rs                                    | 11 ++--
 src/cli/git_filter.rs                         | 59 ++++++++++---------
 src/cli/git_filter/checkout.rs                | 53 ++++++++++-------
 src/cli/git_filter/driver.rs                  | 17 +++---
 src/config/exclude.rs                         |  2 +-
 ...filter_check_missing_config_directory.case | 18 ++++++
 tests/git_filter_paths.rs                     | 57 ++++++++++++++++++
 8 files changed, 155 insertions(+), 64 deletions(-)
 create mode 100644 tests/cases/git_filter_check_missing_config_directory.case

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 3f7f189f..a5079f65 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,7 +98,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
+The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. Smudge and round-trip verification match exclusions against the filename relative to the configuration directory in the selected snapshot. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
 The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory before replacing any working files. They retain the converted batch until Git refreshes the index's file metadata because a failed smudge during that refresh can remove a working file.
 
diff --git a/src/cli.rs b/src/cli.rs
index 2e50119f..7cb49d5b 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -365,7 +365,10 @@ fn run_format(
     if let Some(path) = stdin_file_path {
         return run_stdin(
             path,
-            |path| load_config_for_formatted_path(path, config.as_deref()).map(Some),
+            |path| {
+                let config = load_config_for_formatted_path(path, config.as_deref())?;
+                Ok((!config.excludes(path)).then_some(config))
+            },
             options,
             execution,
         );
@@ -436,17 +439,13 @@ fn run_stdin(
     };
     let config = match load_config(&path) {
         Ok(Some(config)) => config,
-        // Git could not identify the configuration that belongs to these bytes.
+        // Preserve excluded input or an unverified Git blob without decoding it.
         Ok(None) => return write_stdout(&path, &input),
         Err(err) => {
             eprintln!("{}", err.diagnostic.render());
             return ExitCode::from(1);
         }
     };
-    // Editors and Git filters need excluded input back without decoding.
-    if config.excludes(&path) {
-        return write_stdout(&path, &input);
-    }
     let input = match decode_utf8(input) {
         Ok(input) => input,
         Err(message) => {
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 0db32fd6..beb176cd 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -227,24 +227,28 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
     }
     run_stdin(
         path,
-        |path| match source {
-            FilterSource::Tree(tree) => checkout::config_for_path(Path::new("."), &tree, path),
-            FilterSource::StagedBlob(blob) => checkout::CheckoutConfigs::default().for_staged_blob(
-                Path::new("."),
-                path,
-                blob.as_ref().map(String::as_bytes),
-            ),
-            FilterSource::Worktree => {
-                // Direct invocations may start in a subdirectory, or outside Git.
-                let cwd = env::current_dir()
-                    .map_err(|err| crate::diagnostic::YamarkError::new(err.to_string()))?;
-                let cdup = git_stdout(Path::new("."), ["rev-parse", "--show-cdup"]).ok();
-                let root = cdup.as_ref().and_then(|up| {
-                    cwd.ancestors()
-                        .nth(Path::new(up.trim_end()).components().count())
-                });
-                worktree_config(path, root).map(Some)
-            }
+        |path| {
+            let mut configs = checkout::CheckoutConfigs::default();
+            let file = match source {
+                FilterSource::Tree(tree) => configs.for_path(Path::new("."), &tree, path),
+                FilterSource::StagedBlob(blob) => configs.for_staged_blob(
+                    Path::new("."),
+                    path,
+                    blob.as_ref().map(String::as_bytes),
+                ),
+                FilterSource::Worktree => {
+                    // Direct invocations may start in a subdirectory, or outside Git.
+                    let cwd = env::current_dir()
+                        .map_err(|err| crate::diagnostic::YamarkError::new(err.to_string()))?;
+                    let cdup = git_stdout(Path::new("."), ["rev-parse", "--show-cdup"]).ok();
+                    let root = cdup.as_ref().and_then(|up| {
+                        cwd.ancestors()
+                            .nth(Path::new(up.trim_end()).components().count())
+                    });
+                    return worktree_config(path, root);
+                }
+            }?;
+            Ok(file.and_then(checkout::CheckoutPath::included))
         },
         filter_options(wrap),
         FormatExecutionOptions {
@@ -254,13 +258,12 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
     )
 }
 
-fn worktree_config(path: &Path, root: Option<&Path>) -> crate::diagnostic::Result {
-    match discover_config_within(path, root) {
-        Some(candidate) => {
-            Config::from_path(&candidate).map(|config| config.for_formatted_path(path))
-        }
-        None => Ok(Config::default()),
-    }
+fn worktree_config(path: &Path, root: Option<&Path>) -> crate::diagnostic::Result> {
+    let Some(candidate) = discover_config_within(path, root) else {
+        return Ok(Some(Config::default()));
+    };
+    let config = Config::from_path(&candidate)?;
+    Ok((!config.excludes(path)).then(|| config.for_formatted_path(path)))
 }
 
 fn run_git_filter_adopt(
@@ -683,7 +686,7 @@ fn verify_roundtrip(
     let mut configs = checkout::CheckoutConfigs::default();
     for path in paths {
         let source_path = repo_root.join(path);
-        let Some(config) = configs
+        let Some(file) = configs
             .for_path(repo_root, source.tree(), path)
             .map_err(|err| err.diagnostic.render())?
         else {
@@ -692,9 +695,9 @@ fn verify_roundtrip(
                 path.display()
             ));
         };
-        if config.excludes(&source_path) {
+        let Some(config) = file.included() else {
             continue;
-        }
+        };
         let blob = git_blob(repo_root, source, path)?;
         let smudged = format_git_filter_text(
             &source_path,
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
index f5662e4a..565d0cbe 100644
--- a/src/cli/git_filter/checkout.rs
+++ b/src/cli/git_filter/checkout.rs
@@ -79,8 +79,22 @@ impl IndexSnapshot {
     }
 }
 
-pub(super) fn config_for_path(repo_root: &Path, tree: &str, path: &Path) -> Result> {
-    CheckoutConfigs::default().for_path(repo_root, tree, path)
+/// A path and its nearest configuration, both from the same Git snapshot.
+pub(super) struct CheckoutPath<'a> {
+    config: &'a Config,
+    relative: &'a Path,
+}
+
+impl CheckoutPath<'_> {
+    pub(super) fn included(self) -> Option {
+        let excluded = self
+            .config
+            .format
+            .exclude
+            .as_ref()
+            .is_some_and(|patterns| patterns.excludes(self.relative));
+        (!excluded).then(|| self.config.for_relative_path(self.relative))
+    }
 }
 
 type DirectoryConfig = Option<(PathBuf, Config)>;
@@ -119,12 +133,12 @@ impl CheckoutConfigs {
         Ok(())
     }
 
-    pub(super) fn for_staged_blob(
-        &mut self,
+    pub(super) fn for_staged_blob<'a>(
+        &'a mut self,
         repo: &Path,
-        path: &Path,
+        path: &'a Path,
         blob: Option<&[u8]>,
-    ) -> Result> {
+    ) -> Result>> {
         let Some(blob) = blob else { return Ok(None) };
         self.refresh_index(repo)?;
         let index = self.index.as_ref().expect("refreshed index");
@@ -135,24 +149,24 @@ impl CheckoutConfigs {
         }
     }
 
-    pub(super) fn for_path(
-        &mut self,
+    pub(super) fn for_path<'a>(
+        &'a mut self,
         repo: &Path,
         tree: &str,
-        path: &Path,
-    ) -> Result> {
+        path: &'a Path,
+    ) -> Result>> {
         if tree.is_empty() {
             self.refresh_index(repo)?;
         }
         self.for_selected_source(repo, tree, path)
     }
 
-    fn for_selected_source(
-        &mut self,
+    fn for_selected_source<'a>(
+        &'a mut self,
         repo: &Path,
         tree: &str,
-        path: &Path,
-    ) -> Result> {
+        path: &'a Path,
+    ) -> Result>> {
         let path = path.strip_prefix(".").unwrap_or(path);
         if path.as_os_str().is_empty()
             || !path
@@ -175,8 +189,9 @@ impl CheckoutConfigs {
                 self.index.as_ref(),
             )?),
         };
-        Ok(base.as_ref().map(|(dir, config)| {
-            config.for_relative_path(path.strip_prefix(dir).expect("config is an ancestor"))
+        Ok(base.as_ref().map(|(dir, config)| CheckoutPath {
+            relative: path.strip_prefix(dir).expect("config is an ancestor"),
+            config,
         }))
     }
 }
@@ -212,12 +227,8 @@ fn config_for_directory(
     let input = std::str::from_utf8(&bytes).map_err(|err| {
         YamarkError::new(format!("invalid config encoding: {err}")).with_path(&config_path)
     })?;
-    let mut config = Config::from_toml_str(input).map_err(|err| err.with_path(&config_path))?;
-    // Git paths start at the worktree root. The nested directory itself may
-    // still be absent, or contain a symlink from the checkout being replaced.
-    let root = std::fs::canonicalize(repo).map_err(|err| YamarkError::new(err.to_string()))?;
+    let config = Config::from_toml_str(input).map_err(|err| err.with_path(&config_path))?;
     let dir = config_path.parent().expect("a config has a parent");
-    config.config_dir = Some(root.join(dir));
     Ok(Some((dir.to_owned(), config)))
 }
 
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
index 7684e965..ad86049c 100644
--- a/src/cli/git_filter/driver.rs
+++ b/src/cli/git_filter/driver.rs
@@ -6,7 +6,7 @@ use std::io::{self, BufRead, Read, Write};
 use std::path::Path;
 use std::process::{Command, ExitCode, Stdio};
 
-use super::checkout::CheckoutConfigs;
+use super::checkout::{CheckoutConfigs, CheckoutPath};
 use crate::core::document::{FileKind, MarkdownWrap};
 
 pub(super) const SOURCE_BLOB_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_BLOB";
@@ -156,17 +156,20 @@ fn filter_file(
                 )));
             }
             let config = match tree {
-                Some("") => configs.for_staged_blob(Path::new("."), path, field(b"blob=")),
-                Some(tree) => configs.for_path(Path::new("."), tree, path),
-                None => super::worktree_config(path, Some(&std::env::current_dir()?)).map(Some),
+                Some(tree) => {
+                    let file = if tree.is_empty() {
+                        configs.for_staged_blob(Path::new("."), path, field(b"blob="))
+                    } else {
+                        configs.for_path(Path::new("."), tree, path)
+                    };
+                    file.map(|file| file.and_then(CheckoutPath::included))
+                }
+                None => super::worktree_config(path, Some(&std::env::current_dir()?)),
             }
             .map_err(io::Error::other)?;
             let Some(config) = config else {
                 return Ok(contents);
             };
-            if config.excludes(path) {
-                return Ok(contents);
-            }
             let input = super::super::decode_utf8(contents).map_err(|message| {
                 io::Error::other(format!("{}:1:1: error: {message}", path.display()))
             })?;
diff --git a/src/config/exclude.rs b/src/config/exclude.rs
index 98d7270c..c097e158 100644
--- a/src/config/exclude.rs
+++ b/src/config/exclude.rs
@@ -36,7 +36,7 @@ impl ExcludePatterns {
         Ok(Self(patterns.into()))
     }
 
-    pub(super) fn excludes(&self, relative: &Path) -> bool {
+    pub(crate) fn excludes(&self, relative: &Path) -> bool {
         let path = relative.as_os_str().as_encoded_bytes();
         #[cfg(windows)]
         let normalized = path
diff --git a/tests/cases/git_filter_check_missing_config_directory.case b/tests/cases/git_filter_check_missing_config_directory.case
new file mode 100644
index 00000000..578ad793
--- /dev/null
+++ b/tests/cases/git_filter_check_missing_config_directory.case
@@ -0,0 +1,18 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "docs/yamark.toml": "[format]\nexclude = ['keep.md']\n",
+    "docs/keep.md": "#    Leave this heading alone\n"
+  },
+  "git-after-commit": [["rm", "-r", "--", "docs"]]
+}
+-- args
+git-filter check
+-- stdin
+-- stdout
+yamark Git filter check passed for 1 Markdown file(s).
+-- stderr
+-- status
+0
diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index 5f5ec6be..c9d8ca6f 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -474,6 +474,63 @@ fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
     );
 }
 
+#[test]
+fn check_and_smudge_exclude_a_blob_after_its_directory_is_deleted() {
+    let tmp = tempdir().unwrap();
+    let repo = tmp.path().join("repo");
+    let nested = repo.join("docs");
+    fs::create_dir_all(&nested).unwrap();
+    let git = |args: &[&str]| {
+        Command::new("git")
+            .current_dir(&repo)
+            .args(args)
+            .assert()
+            .success()
+    };
+    let utf16 = [0xff, 0xfe, b'#', 0, b'\n', 0];
+    fs::write(repo.join(".gitattributes"), "*.md -text filter=yamark-md\n").unwrap();
+    fs::write(
+        nested.join("yamark.toml"),
+        "[format]\nexclude = ['keep.md']\n",
+    )
+    .unwrap();
+    fs::write(nested.join("keep.md"), utf16).unwrap();
+    git(&["init", "-q"]);
+    git(&["add", "."]);
+    git(&[
+        "-c",
+        "user.name=Tester",
+        "-c",
+        "user.email=test@example.test",
+        "-c",
+        "commit.gpgSign=false",
+        "commit",
+        "-qm",
+        "fixture",
+    ]);
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(&repo)
+        .args(["git-filter", "setup"])
+        .assert()
+        .success();
+    fs::remove_dir_all(nested).unwrap();
+
+    // On case-insensitive volumes Git retains the worktree spelling supplied
+    // here, while canonicalization may restore the directory entry's case.
+    let alias = tmp.path().join("REPO");
+    let worktree = if alias.is_dir() { &alias } else { &repo };
+    Command::cargo_bin("yamark")
+        .unwrap()
+        .current_dir(&repo)
+        .env("GIT_WORK_TREE", worktree)
+        .args(["git-filter", "check"])
+        .assert()
+        .success()
+        .stderr("");
+    git(&["cat-file", "--filters", ":docs/keep.md"]).stdout(utf16.to_vec());
+}
+
 fn check_git_filter_paths(paths: &[&str]) {
     let dir = tempdir().unwrap();
     let git = |args: &[&str]| {

From aa1384ec0a33174041d4fabe480f95fb2646e032 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:18:20 -0500
Subject: [PATCH 49/64] Read committed attributes without writing an index on
 modern Git

---
 .../cli/test_git_filter_permissions.py        |  4 ++
 src/cli/git_filter.rs                         | 35 ++++++++++--------
 src/cli/git_filter/process.rs                 | 37 ++++++++++---------
 3 files changed, 44 insertions(+), 32 deletions(-)

diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
index 0f298d85..97aa3297 100644
--- a/external-tests/cli/test_git_filter_permissions.py
+++ b/external-tests/cli/test_git_filter_permissions.py
@@ -29,6 +29,10 @@ def test_filter_uses_private_scratch_directory(
 import os, sys
 from pathlib import Path
 
+# Git before 2.40 reads committed attributes from a private index.
+if 'check-attr' in sys.argv and '-h' in sys.argv:
+    print('usage: git check-attr [--cached] [--stdin]', file=sys.stderr)
+    sys.exit(129)
 if 'read-tree' in sys.argv and 'GIT_INDEX_FILE' in os.environ:
     directory = Path(os.environ['GIT_INDEX_FILE']).parent
     print('read-tree', oct(directory.stat().st_mode & 0o777), file=open(os.environ['MODE_LOG'], 'a'))
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index beb176cd..3fa55011 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -618,23 +618,33 @@ fn tracked_yamark_filter_paths(
 ) -> Result, String> {
     // NUL records contain native filename bytes, not UTF-8 text or Git's
     // presentation quoting. Each check-attr response is path, name, then value.
-    let index = match source {
-        BlobSource::Head => Some(process::TreeIndex::read_tree(repo_root, "HEAD")?),
-        BlobSource::Index => None,
-    };
-    let git = || match &index {
-        Some(snapshot) => snapshot.git(repo_root),
-        None => process::git_query(repo_root),
+    let mut attr = process::git_query(repo_root);
+    attr.arg("check-attr");
+    let legacy_index;
+    let tracked = match source {
+        BlobSource::Head => {
+            if process::supports_tree_attributes(repo_root)? {
+                attr.arg("--source=HEAD");
+            } else {
+                legacy_index = process::TreeIndex::read_tree(repo_root, "HEAD")?;
+                attr = legacy_index.git(repo_root);
+                attr.args(["check-attr", "--cached"]);
+            }
+            process::git_stdout_bytes(repo_root, ["ls-tree", "-rz", "--full-tree", "HEAD"])?
+        }
+        BlobSource::Index => process::git_stdout_bytes(repo_root, ["ls-files", "--stage", "-z"])?,
     };
-    let tracked = process::checked_stdout(git().args(["ls-files", "--stage", "-z"]).output())?;
     let mut names = Vec::new();
     for entry in tracked
         .split(|byte| *byte == 0)
         .filter(|entry| !entry.is_empty())
     {
-        let Some(name) = process::regular_index_path(entry)? else {
+        let (name, [mode, _, stage_or_oid]) = process::entry_fields(entry)?;
+        if !matches!(mode, b"100644" | b"100755")
+            || (matches!(source, BlobSource::Index) && stage_or_oid != b"0")
+        {
             continue;
-        };
+        }
         let path = Path::new(
             driver::native_path(name).map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
@@ -645,11 +655,6 @@ fn tracked_yamark_filter_paths(
             names.push(0);
         }
     }
-    let mut attr = git();
-    attr.arg("check-attr");
-    if index.is_some() {
-        attr.arg("--cached");
-    }
     attr.args(["-z", "--stdin", "filter"])
         .stderr(std::process::Stdio::piped());
     let output = process::checked_stdout(driver::run_with_input(&mut attr, &names))?;
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index e2f70753..5fa46eaa 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -75,8 +75,24 @@ pub(super) fn private_tempdir() -> std::io::Result {
     tempfile::tempdir()
 }
 
-/// An index containing exactly one tree's entries, independent of staged
-/// changes and working-tree stat data.
+/// Git 2.40 introduced `check-attr --source`. Query the command's advertised
+/// options so vendor builds with backported support can use the read-only path.
+pub(super) fn supports_tree_attributes(repo: &Path) -> Result {
+    // Older Git prints short usage on stderr and exits with status 129.
+    let help = git_query(repo)
+        .args(["check-attr", "-h"])
+        .output()
+        .map_err(|err| format!("failed to run git: {err}"))?;
+    if !help.status.success() && help.status.code() != Some(129) {
+        return Err(format_git_error("git check-attr", help));
+    }
+    Ok([help.stdout, help.stderr]
+        .iter()
+        .any(|text| String::from_utf8_lossy(text).contains("--source")))
+}
+
+/// Older Git reads committed attributes from a private index containing the
+/// tree's entries. These releases discover hooks in the hooks directory.
 pub(super) struct TreeIndex(tempfile::TempDir);
 
 impl TreeIndex {
@@ -85,9 +101,7 @@ impl TreeIndex {
             private_tempdir()
                 .map_err(|err| format!("failed to create temporary index directory: {err}"))?,
         );
-        // Loading a private index is not a change to the user's index. Older
-        // Git discovers hooks by directory; newer Git can also configure
-        // hook commands directly for the event.
+        // Loading a private index is not a change to the user's index.
         let mut hooks_path = OsString::from("core.hooksPath=");
         hooks_path.push(index.0.path());
         checked_stdout(
@@ -95,12 +109,7 @@ impl TreeIndex {
                 .git(repo)
                 .arg("-c")
                 .arg(hooks_path)
-                .args([
-                    "-c",
-                    "hook.post-index-change.enabled=false",
-                    "read-tree",
-                    tree,
-                ])
+                .args(["read-tree", tree])
                 .output(),
         )?;
         Ok(index)
@@ -127,12 +136,6 @@ pub(super) fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3]), &'stati
     Ok((&record[tab + 1..], [first, second, third]))
 }
 
-/// Path of a regular stage-zero blob from ls-files --stage.
-pub(super) fn regular_index_path(record: &[u8]) -> Result, &'static str> {
-    let (path, [mode, _, stage]) = entry_fields(record)?;
-    Ok((stage == b"0" && matches!(mode, b"100644" | b"100755")).then_some(path))
-}
-
 pub(super) fn local_git_config_count(repo_root: &Path, key: &str) -> Result {
     let output = ProcessCommand::new("git")
         .arg("-C")

From 8fa617aa25f59ddcf13b52946612bc69e84f83ce Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:20:10 -0500
Subject: [PATCH 50/64] Preserve working-file access during Git filter adoption
 and join

---
 Cargo.lock                                    |   3 +
 Cargo.toml                                    |   7 +
 docs/ARCHITECTURE.md                          |   2 +-
 .../cli/test_git_filter_permissions.py        | 103 +++++++++++
 src/cli/git_filter.rs                         |  83 +--------
 src/cli/git_filter/worktree.rs                | 167 ++++++++++++++++++
 tests/cases/README.md                         |   2 +-
 tests/cases/git_filter_join_hard_link.case    |  21 +++
 .../git_filter_join_refresh_failure.case      |   8 +-
 tests/cli_cases.rs                            |   9 +
 website/git-filter.qmd                        |   4 +-
 11 files changed, 325 insertions(+), 84 deletions(-)
 create mode 100644 src/cli/git_filter/worktree.rs
 create mode 100644 tests/cases/git_filter_join_hard_link.case

diff --git a/Cargo.lock b/Cargo.lock
index acf97d4c..673c52ec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -799,6 +799,7 @@ dependencies = [
  "ignore",
  "json-five",
  "jsonc-parser",
+ "libc",
  "memchr",
  "num-bigint",
  "serde_json",
@@ -807,6 +808,8 @@ dependencies = [
  "toml",
  "unicode-general-category",
  "unicode-width",
+ "winapi-util",
+ "windows-sys",
 ]
 
 [[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 89a17de8..47cf4a16 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,13 @@ toml = "1.1.6"
 unicode-general-category = "1.1.0"
 unicode-width = "0.2.2"
 
+[target.'cfg(unix)'.dependencies]
+libc = "0.2.189"
+
+[target.'cfg(windows)'.dependencies]
+winapi-util = "0.1.11"
+windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem"] }
+
 [dev-dependencies]
 assert_cmd = "2.2.2"
 
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index a5079f65..beff85a4 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -100,7 +100,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. Smudge and round-trip verification match exclusions against the filename relative to the configuration directory in the selected snapshot. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
-The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory before replacing any working files. They retain the converted batch until Git refreshes the index's file metadata because a failed smudge during that refresh can remove a working file.
+The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory with owner-only access on Unix. They write changed bytes through existing regular files to preserve local access controls and leave unchanged files in place. Git refreshes the stat data of changed index entries against their original modes and object IDs. Adoption keeps the previous working bytes until the refreshed checkout passes verification.
 
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 
diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
index 97aa3297..3dbe0136 100644
--- a/external-tests/cli/test_git_filter_permissions.py
+++ b/external-tests/cli/test_git_filter_permissions.py
@@ -57,3 +57,106 @@ def test_filter_uses_private_scratch_directory(
              "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
     )
     assert log.read_text().splitlines() == [f"{operation} 0o700"]
+
+
+@pytest.mark.skipif(os.name != "posix", reason="Unix file access modes")
+@pytest.mark.parametrize("action", ["adopt", "join"])
+def test_checkout_preserves_local_file_access(tmp_path: Path, action: str) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    init_repo(repo)
+    if action == "join":
+        (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
+    changed = repo / "changed.md"
+    changed.write_bytes(b"First sentence.\nSecond sentence?\n")
+    changed.chmod(0o600)
+    unchanged = repo / "unchanged.md"
+    unchanged.write_bytes(b"# Heading\n")
+    unchanged.chmod(0o750)
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+
+    before = [path.stat() for path in (changed, unchanged)]
+    subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", action],
+        cwd=repo, check=True, capture_output=True, umask=0o022,
+    )
+    assert changed.read_bytes() == b"First sentence. Second sentence?\n"
+    assert unchanged.read_bytes() == b"# Heading\n"
+    for path, original in zip((changed, unchanged), before):
+        assert path.stat().st_mode == original.st_mode
+        assert path.stat().st_ino == original.st_ino
+    assert run_git(repo, "diff", "--name-only").stdout == ""
+
+
+def test_join_preserves_hard_links(tmp_path: Path) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    init_repo(repo)
+    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
+    path = repo / "doc.md"
+    original = b"First sentence.\nSecond sentence?\n"
+    path.write_bytes(original)
+    alias = tmp_path / "alias"
+    os.link(path, alias)
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+    proc = subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", "join"],
+        cwd=repo, capture_output=True, text=True,
+    )
+    assert proc.returncode == 1
+    assert "cannot rewrite a file with multiple hard links" in proc.stderr
+    assert alias.samefile(path)
+    assert alias.read_bytes() == original
+
+
+@pytest.mark.skipif(os.name != "posix", reason="Unix file access modes")
+def test_failed_adoption_restores_local_bytes_and_access(tmp_path: Path) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    init_repo(repo)
+    original = b"First sentence.\nSecond sentence?\n"
+    first = repo / "a.md"
+    linked = repo / "z.md"
+    for path in (first, linked):
+        path.write_bytes(original)
+        path.chmod(0o600)
+    alias = tmp_path / "z-alias"
+    os.link(linked, alias)
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+
+    proc = subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", "adopt"],
+        cwd=repo, capture_output=True, text=True, umask=0o022,
+    )
+    assert proc.returncode == 1
+    assert "Rolled back" in proc.stderr
+    assert first.read_bytes() == original
+    assert first.stat().st_mode & 0o777 == 0o600
+    assert alias.samefile(linked)
+    assert run_git(repo, "status", "--porcelain").stdout == ""
+
+
+def test_join_refresh_keeps_staged_ids_and_flags(tmp_path: Path) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    init_repo(repo)
+    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
+    for name in ("ordinary.md", "assumed.md", "sparse.txt"):
+        (repo / name).write_bytes(b"First sentence.\nSecond sentence?\n")
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+    run_git(repo, "update-index", "--assume-unchanged", "--", "assumed.md")
+    run_git(repo, "update-index", "--skip-worktree", "--", "sparse.txt")
+    (repo / "sparse.txt").unlink()
+    before = run_git(repo, "ls-files", "-v", "--stage").stdout
+
+    subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", "join"],
+        cwd=repo, check=True, capture_output=True,
+    )
+    assert run_git(repo, "ls-files", "-v", "--stage").stdout == before
+    assert (repo / "assumed.md").read_bytes() == b"First sentence. Second sentence?\n"
+    assert not (repo / "sparse.txt").exists()
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 3fa55011..fbdf19d6 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -4,6 +4,7 @@ mod attributes;
 mod checkout;
 mod driver;
 mod process;
+mod worktree;
 
 use std::env;
 use std::ffi::OsString;
@@ -409,8 +410,7 @@ fn adopt_git_filter_inner(
     )?;
     run_git_with_paths(repo_root, &["add", "--renormalize", "--"], &targets)?;
     verify_index_roundtrip(repo_root, &targets, width)?;
-    write_smudged_worktree(repo_root, &targets)?;
-    ensure_no_unstaged_changes(repo_root)?;
+    worktree::Checkout::Adopt.install(repo_root, &targets)?;
 
     Ok(format!(
         "Adopted yamark Git filter in {}\nUpdated .gitattributes with {added} new attribute pattern(s)\nStaged .gitattributes and {} normalized Markdown file(s).\n\nReview and commit with:\n  git diff --cached\n  git commit -m \"Normalize Markdown with yamark Git filter\"",
@@ -435,8 +435,7 @@ fn join_git_filter(
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
     verify_head_roundtrip(&repo_root, &targets, width)?;
-    write_smudged_worktree(&repo_root, &targets)?;
-    ensure_clean_worktree(&repo_root)?;
+    worktree::Checkout::Join.install(&repo_root, &targets)?;
 
     Ok(format!(
         "Joined yamark Git filter in {}\nConfigured local filter driver and checked {} committed Markdown file(s).",
@@ -726,63 +725,6 @@ fn verify_roundtrip(
     }
 }
 
-fn write_smudged_worktree(repo_root: &Path, paths: &[PathBuf]) -> Result<(), String> {
-    // Even --force can skip stat-clean files. Check out all targets to a fresh
-    // prefix so Git applies its conversions and leaves originals intact if
-    // one of the filters fails.
-    let converted = process::private_tempdir().map_err(|err| err.to_string())?;
-    let mut prefix = OsString::from("--prefix=");
-    prefix.push(converted.path());
-    prefix.push("/");
-    let mut names = Vec::new();
-    for path in paths {
-        names.extend_from_slice(path.as_os_str().as_encoded_bytes());
-        names.push(0);
-    }
-    let checkout = |option: OsString| {
-        let mut git = process::git_query(repo_root);
-        git.arg("checkout-index")
-            .arg(option)
-            .args(["--force", "-z", "--stdin"])
-            .stderr(std::process::Stdio::piped());
-        process::checked_stdout(driver::run_with_input(&mut git, &names))
-    };
-    checkout(prefix)?;
-
-    let install = || {
-        paths.iter().try_for_each(|path| {
-            let target = repo_root.join(path);
-            replace_with_checkout_file(&converted.path().join(path), &target).map_err(|err| {
-                format!(
-                    "{}: failed to install smudged file: {err}",
-                    target.display()
-                )
-            })
-        })
-    };
-    install()?;
-    // Refresh the real index as part of checkout so CRLF files also acquire
-    // their correct worktree stat data.
-    if let Err(error) = checkout(OsString::from("--index")) {
-        // Git can unlink a path before reporting a failed smudge. Restore the
-        // entire known-good batch, including paths already visited by Git.
-        install()
-            .map_err(|restore| format!("{error}\nFailed to restore converted files: {restore}"))?;
-        return Err(error);
-    }
-    Ok(())
-}
-
-/// Install the complete regular file without writing through a link. Stage
-/// the replacement beside its target, which can be on a different filesystem.
-fn replace_with_checkout_file(source: &Path, target: &Path) -> io::Result<()> {
-    let pending =
-        tempfile::NamedTempFile::new_in(target.parent().expect("tracked file has a parent"))?;
-    fs::copy(source, pending.path())?;
-    pending.persist(target)?;
-    Ok(())
-}
-
 fn git_blob(repo_root: &Path, source: BlobSource, path: &Path) -> Result {
     git_stdout(repo_root, [OsString::from("show"), source.spec(path)])
 }
@@ -833,23 +775,8 @@ fn rollback_adopt(
     previous_attributes: Option,
 ) -> Result<(), String> {
     let mut errors = Vec::new();
-    for args in [
-        vec![
-            OsString::from("reset"),
-            OsString::from("-q"),
-            OsString::from("--mixed"),
-            OsString::from("HEAD"),
-        ],
-        vec![
-            OsString::from("checkout"),
-            OsString::from("-q"),
-            OsString::from("--"),
-            OsString::from("."),
-        ],
-    ] {
-        if let Err(err) = run_git_os(repo_root, &args) {
-            errors.push(err);
-        }
+    if let Err(err) = git_stdout(repo_root, ["reset", "-q", "--mixed", "HEAD"]) {
+        errors.push(err);
     }
     if let Err(err) = restore_optional_file(attributes_path, previous_attributes) {
         errors.push(err);
diff --git a/src/cli/git_filter/worktree.rs b/src/cli/git_filter/worktree.rs
new file mode 100644
index 00000000..b5382d74
--- /dev/null
+++ b/src/cli/git_filter/worktree.rs
@@ -0,0 +1,167 @@
+//! Install Git's working-tree conversion while retaining local file metadata.
+
+use std::collections::HashSet;
+use std::ffi::OsString;
+use std::fs;
+use std::io::{self, Read, Seek, Write};
+use std::path::{Path, PathBuf};
+
+use super::{driver, process};
+
+pub(super) enum Checkout {
+    Adopt,
+    Join,
+}
+
+impl Checkout {
+    pub(super) fn install(self, repo_root: &Path, paths: &[PathBuf]) -> Result<(), String> {
+        // Even --force can skip stat-clean files. Check out all targets to a fresh
+        // prefix so Git applies its conversions and leaves originals intact if
+        // one of the filters fails.
+        let converted = process::private_tempdir().map_err(|err| err.to_string())?;
+        let mut prefix = OsString::from("--prefix=");
+        prefix.push(converted.path());
+        prefix.push("/");
+        let mut names = Vec::new();
+        for path in paths {
+            names.extend_from_slice(path.as_os_str().as_encoded_bytes());
+            names.push(0);
+        }
+        let mut git = process::git_query(repo_root);
+        git.arg("checkout-index")
+            .arg(prefix)
+            .args(["--force", "-z", "--stdin"])
+            .stderr(std::process::Stdio::piped());
+        process::checked_stdout(driver::run_with_input(&mut git, &names))?;
+
+        let mut changed = Vec::new();
+        let result = (|| {
+            for path in paths {
+                let target = repo_root.join(path);
+                let source = converted.path().join(path);
+                let backup = match self {
+                    Self::Adopt => Some(source.as_path()),
+                    Self::Join => None,
+                };
+                if install_checkout_file(&source, &target, backup).map_err(|err| {
+                    format!(
+                        "{}: failed to install smudged file: {err}",
+                        target.display()
+                    )
+                })? {
+                    changed.push(path.as_path());
+                }
+            }
+            refresh_index(repo_root, &changed)?;
+            match self {
+                Self::Adopt => super::ensure_no_unstaged_changes(repo_root),
+                Self::Join => super::ensure_clean_worktree(repo_root),
+            }
+        })();
+        if let Err(err) = &result
+            && matches!(self, Self::Adopt)
+        {
+            for path in changed {
+                let target = repo_root.join(path);
+                install_checkout_file(&converted.path().join(path), &target, None).map_err(
+                    |restore| format!("{err}\nFailed to restore {}: {restore}", target.display()),
+                )?;
+            }
+        }
+        result
+    }
+}
+
+fn refresh_index(repo_root: &Path, changed: &[&Path]) -> Result<(), String> {
+    if changed.is_empty() {
+        return Ok(());
+    }
+    // With an old, nonzero cached size, Git may report CRLF files as modified
+    // without comparing their clean blobs. Reuse the staged mode and object ID
+    // to clear the stat data for changed ordinary entries. Leave skip-worktree
+    // and assume-unchanged entries (S/s/h) and unrelated paths alone.
+    let names: HashSet<_> = changed
+        .iter()
+        .map(|path| path.as_os_str().as_encoded_bytes())
+        .collect();
+    let entries = process::git_stdout_bytes(repo_root, ["ls-files", "-v", "--stage", "-z"])?;
+    let mut reset = Vec::new();
+    for record in entries.split(|&byte| byte == 0) {
+        let Some(entry) = record.strip_prefix(b"H ") else {
+            continue;
+        };
+        let (name, [mode, _, stage]) = process::entry_fields(entry)?;
+        if names.contains(name) && stage == b"0" && matches!(mode, b"100644" | b"100755") {
+            reset.extend_from_slice(entry);
+            reset.push(0);
+        }
+    }
+    if !reset.is_empty() {
+        let mut update = process::git_query(repo_root);
+        update
+            .args(["update-index", "-z", "--index-info"])
+            .stderr(std::process::Stdio::piped());
+        process::checked_stdout(driver::run_with_input(&mut update, &reset))?;
+        process::git_stdout_bytes(repo_root, ["update-index", "--refresh"])?;
+    }
+    Ok(())
+}
+
+/// Write through an existing regular file handle to preserve its ACL, owner
+/// and permissions. A hard-linked file can be kept as-is, but replacing its
+/// bytes in place would also edit another path.
+fn install_checkout_file(source: &Path, target: &Path, backup: Option<&Path>) -> io::Result {
+    let converted = fs::read(source)?;
+    let mut options = fs::OpenOptions::new();
+    options.read(true);
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::OpenOptionsExt;
+        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
+    }
+    #[cfg(windows)]
+    {
+        use std::os::windows::fs::OpenOptionsExt;
+        options.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);
+    }
+    let open = |options: &fs::OpenOptions| -> io::Result {
+        let file = options.open(target)?;
+        if !file.metadata()?.is_file() {
+            return Err(io::Error::other("expected a regular file"));
+        }
+        Ok(file)
+    };
+    let mut current = Vec::new();
+    open(&options)?.read_to_end(&mut current)?;
+    if current == converted {
+        return Ok(false);
+    }
+    let mut file = open(options.write(true))?;
+    #[cfg(unix)]
+    let links = std::os::unix::fs::MetadataExt::nlink(&file.metadata()?);
+    #[cfg(windows)]
+    let links = winapi_util::file::information(&file)?.number_of_links();
+    #[cfg(any(unix, windows))]
+    if links > 1 {
+        return Err(io::Error::other(
+            "cannot rewrite a file with multiple hard links",
+        ));
+    }
+    if let Some(backup) = backup {
+        fs::write(backup, ¤t)?;
+    }
+    let mut write = |bytes: &[u8]| -> io::Result<()> {
+        file.rewind()?;
+        file.write_all(bytes)?;
+        file.set_len(bytes.len() as u64)
+    };
+    if let Err(err) = write(&converted) {
+        write(¤t).map_err(|restore| {
+            io::Error::other(format!(
+                "{err}; failed to restore original bytes: {restore}"
+            ))
+        })?;
+        return Err(err);
+    }
+    Ok(true)
+}
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 603f8986..601449a1 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -68,7 +68,7 @@ The `external_formatter_*.case` transcripts cover formatters that remove only th
 
 `external_formatter_early_stdin_close.case` covers a successful formatter that closes stdin before reading it. The public CLI specifications repeat this with input larger than a pipe buffer and check that nonzero status, stderr, invalid UTF-8, and unsafe fence output still fail.
 
-Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Set `"setup-filter": true` to run `yamark git-filter setup` after the fixture commit. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
+Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Set `"setup-filter": true` to run `yamark git-filter setup` after the fixture commit. An optional `hard-links` mapping adds hard links from each key to its fixture file. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
 
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
diff --git a/tests/cases/git_filter_join_hard_link.case b/tests/cases/git_filter_join_hard_link.case
new file mode 100644
index 00000000..4c7d09f9
--- /dev/null
+++ b/tests/cases/git_filter_join_hard_link.case
@@ -0,0 +1,21 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {
+    ".gitattributes": "*.md filter=yamark-md\n",
+    "post.md": "First sentence.\nSecond sentence?\n"
+  },
+  "hard-links": {"backup.txt": "post.md"}
+}
+-- args
+git-filter join
+-- stdin
+-- stdout
+-- stderr
+error: {{repo}}/post.md: failed to install smudged file: cannot rewrite a file with multiple hard links
+-- git-index
+{"post.md": "First sentence.\nSecond sentence?\n"}
+-- git-worktree
+{"post.md": "First sentence.\nSecond sentence?\n", "backup.txt": "First sentence.\nSecond sentence?\n"}
+-- status
+1
diff --git a/tests/cases/git_filter_join_refresh_failure.case b/tests/cases/git_filter_join_refresh_failure.case
index f0b2fbce..8881c412 100644
--- a/tests/cases/git_filter_join_refresh_failure.case
+++ b/tests/cases/git_filter_join_refresh_failure.case
@@ -11,16 +11,18 @@ git-filter join
 -- env
 {
   "LC_ALL": "C",
-  "GIT_CONFIG_COUNT": "2",
+  "GIT_CONFIG_COUNT": "3",
   "GIT_CONFIG_KEY_0": "filter.yamark-md.process",
   "GIT_CONFIG_VALUE_0": "\"$YAMARK_CASE_BIN\" git-filter process 2>/dev/null",
   "GIT_CONFIG_KEY_1": "filter.yamark-md.smudge",
-  "GIT_CONFIG_VALUE_1": "test ! -f .git/smudged && touch .git/smudged && echo '#    Keep'"
+  "GIT_CONFIG_VALUE_1": "touch .git/smudged && echo '#    Keep'",
+  "GIT_CONFIG_KEY_2": "filter.yamark-md.clean",
+  "GIT_CONFIG_VALUE_2": "test ! -f .git/smudged && cat"
 }
 -- stdin
 -- stdout
 -- stderr
-error: git failed: fatal: post.md: smudge filter yamark-md failed
+error: git failed: fatal: post.md: clean filter 'yamark-md' failed
 -- git-index
 {"post.md": "# Keep\n"}
 -- git-worktree
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 48f3d05a..57289d89 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -243,6 +243,15 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
                 .success();
         }
     }
+    if let Some(links) = fixture.get("hard-links") {
+        for (name, target) in links.as_object().unwrap() {
+            fs::hard_link(
+                repo.path().join(target.as_str().unwrap()),
+                repo.path().join(name),
+            )
+            .unwrap();
+        }
+    }
     git(&["add", "."]);
     if let Some(links) = fixture.get("symlinks") {
         for (name, target) in links.as_object().unwrap() {
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 48cee104..d03483c7 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -91,7 +91,9 @@ clean(smudge(blob)) == blob
 ```
 
 `adopt` and `join` process regular files in Git's index. Both skip symbolic links
-and submodules.
+and submodules. Changed files retain their local permissions and ownership.
+If a file needs rewrapping and has multiple hard links, the command reports
+the path so you can separate the links before trying again.
 
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:

From d187aef2166265a9a8766d034f7af4e62838da18 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:22:27 -0500
Subject: [PATCH 51/64] Cover legacy hook isolation in the private-index check

---
 external-tests/cli/test_git_filter_permissions.py | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
index 3dbe0136..7f9b3e0b 100644
--- a/external-tests/cli/test_git_filter_permissions.py
+++ b/external-tests/cli/test_git_filter_permissions.py
@@ -22,6 +22,13 @@ def test_filter_uses_private_scratch_directory(
     (repo / "doc.md").write_bytes(b"# Fixture\n")
     run_git(repo, "add", ".")
     run_git(repo, "commit", "-qm", "fixture")
+    if action == "check":
+        hooks = repo / "hooks"
+        hooks.mkdir()
+        hook = hooks / "post-index-change"
+        hook.write_text("#!/bin/sh\necho changed >>index-events\n")
+        hook.chmod(0o700)
+        run_git(repo, "config", "core.hooksPath", "hooks")
     # Observe the directory at the Git invocation that will populate it.
     program = tmp_path / "git"
     program.write_text(
@@ -57,6 +64,8 @@ def test_filter_uses_private_scratch_directory(
              "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
     )
     assert log.read_text().splitlines() == [f"{operation} 0o700"]
+    if action == "check":
+        assert not (repo / "index-events").exists()
 
 
 @pytest.mark.skipif(os.name != "posix", reason="Unix file access modes")

From e506e22db60d65e1575f63ebee6ee6e26155acd1 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:23:03 -0500
Subject: [PATCH 52/64] Document checkout permissions and committed
 verification

---
 website/git-filter.html.md | 11 ++++++++---
 website/git-filter.qmd     |  4 +++-
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index e37a8fc6..a4682051 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -40,7 +40,8 @@ happen during a merge or cherry-pick, smudge returns the incoming bytes
 unchanged. A merge conflict in the nearest staged config or its symlink target
 also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
 symbolic link, its target must be present in the selected tree or index. Clean
-reads the current working-tree config on each request.
+reads the nearest working-tree config on each request. Discovery stops at the
+worktree root, and Yamark uses its defaults if it finds no config there or below.
 
 Invoking `yamark git-filter smudge` directly uses the working-tree config.
 Pass `--source-tree ` to read configuration from a particular tree.
@@ -90,7 +91,9 @@ clean(smudge(blob)) == blob
 ```
 
 `adopt` and `join` process regular files in Git's index. Both skip symbolic links
-and submodules.
+and submodules. Changed files retain their local permissions and ownership.
+If a file needs rewrapping and has multiple hard links, the command reports
+the path so you can separate the links before trying again.
 
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:
@@ -124,7 +127,9 @@ yamark git-filter check
 ```
 
 It checks the regular Markdown files in `HEAD`, using the committed versions of
-`.gitattributes` and `yamark.toml`. Git still applies its usual attribute
+`.gitattributes` and `yamark.toml`, even if the files are missing from the
+working tree. Checking a commit leaves the index alone and skips its
+`post-index-change` hooks. Git still applies its usual attribute
 precedence, including overrides in `.git/info/attributes`. The check fails
 if any selected file violates:
 
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index d03483c7..a4682051 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -127,7 +127,9 @@ yamark git-filter check
 ```
 
 It checks the regular Markdown files in `HEAD`, using the committed versions of
-`.gitattributes` and `yamark.toml`. Git still applies its usual attribute
+`.gitattributes` and `yamark.toml`, even if the files are missing from the
+working tree. Checking a commit leaves the index alone and skips its
+`post-index-change` hooks. Git still applies its usual attribute
 precedence, including overrides in `.git/info/attributes`. The check fails
 if any selected file violates:
 

From 0916cfe86cd818e9e5666f6454c56ba0657ee318 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:36:50 -0500
Subject: [PATCH 53/64] Commit Git index stat refreshes against their input
 snapshot

---
 docs/ARCHITECTURE.md                          |   2 +-
 .../cli/test_git_filter_permissions.py        |  97 +++++++++++++-
 src/cli/git_filter.rs                         |  27 ++--
 src/cli/git_filter/worktree.rs                |  64 ++++------
 src/cli/git_filter/worktree/index.rs          | 118 ++++++++++++++++++
 website/git-filter.qmd                        |   4 +-
 6 files changed, 259 insertions(+), 53 deletions(-)
 create mode 100644 src/cli/git_filter/worktree/index.rs

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index beff85a4..083a19f9 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -100,7 +100,7 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. Smudge and round-trip verification match exclusions against the filename relative to the configuration directory in the selected snapshot. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
 
-The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory with owner-only access on Unix. They write changed bytes through existing regular files to preserve local access controls and leave unchanged files in place. Git refreshes the stat data of changed index entries against their original modes and object IDs. Adoption keeps the previous working bytes until the refreshed checkout passes verification.
+The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory with owner-only access on Unix. They write changed bytes through existing regular files to preserve local access controls and leave unchanged files in place. Git refreshes the stat data of changed index entries against their original modes and object IDs in a private copy of the index. The refresh takes Git's index lock and publishes that copy only if the live index still matches the snapshot. Adoption keeps the previous working bytes until the refreshed checkout passes verification.
 
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 
diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
index 7f9b3e0b..636e9780 100644
--- a/external-tests/cli/test_git_filter_permissions.py
+++ b/external-tests/cli/test_git_filter_permissions.py
@@ -2,12 +2,13 @@
 
 import os
 import shutil
+import shlex
 import subprocess
 from pathlib import Path
 
 import pytest
 
-from test_git_filter import init_repo, run_git
+from test_git_filter import configure_git_user, init_repo, run_git
 
 
 @pytest.mark.skipif(os.name != "posix", reason="Unix directory access modes")
@@ -169,3 +170,97 @@ def test_join_refresh_keeps_staged_ids_and_flags(tmp_path: Path) -> None:
     assert run_git(repo, "ls-files", "-v", "--stage").stdout == before
     assert (repo / "assumed.md").read_bytes() == b"First sentence. Second sentence?\n"
     assert not (repo / "sparse.txt").exists()
+
+
+@pytest.mark.skipif(os.name != "posix", reason="Unix executable wrapper")
+@pytest.mark.parametrize("change", ["blob", "flag"])
+@pytest.mark.parametrize("action", ["adopt", "join"])
+def test_checkout_retains_concurrent_index_change(tmp_path: Path, change: str, action: str) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    init_repo(repo)
+    if action == "join":
+        (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
+    (repo / "doc.md").write_bytes(b"First sentence.\nSecond sentence?\n")
+    (repo / "saved.txt").write_bytes(b"Staged separately\n")
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+    oid = run_git(repo, "rev-parse", ":saved.txt").stdout.strip()
+
+    # Release a staged edit exactly after Git returns the selected entries.
+    program = tmp_path / "git"
+    program.write_text(
+        """#!/usr/bin/env python3
+import os, subprocess, sys
+
+git = os.environ['REAL_GIT']
+if 'ls-files' in sys.argv and '-v' in sys.argv:
+    result = subprocess.run([git, *sys.argv[1:]], capture_output=True, check=True)
+    env = dict(os.environ)
+    env.pop('GIT_INDEX_FILE', None)
+    args = (['--cacheinfo', '100644', os.environ['SAVED_OID'], 'doc.md']
+            if os.environ['STAGED_CHANGE'] == 'blob' else ['--assume-unchanged', 'doc.md'])
+    subprocess.run([git, '-C', os.environ['TEST_REPO'], 'update-index', *args], env=env, check=True)
+    sys.stdout.buffer.write(result.stdout)
+else:
+    os.execv(git, [git, *sys.argv[1:]])
+"""
+    )
+    program.chmod(0o700)
+    real_git = shutil.which("git")
+    assert real_git is not None
+    proc = subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", action],
+        cwd=repo, capture_output=True, text=True,
+        env={**os.environ, "REAL_GIT": real_git, "TEST_REPO": str(repo),
+             "SAVED_OID": oid, "STAGED_CHANGE": change,
+             "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
+    )
+    assert proc.returncode == 1
+    assert "index changed during refresh" in proc.stderr
+    if change == "blob":
+        assert run_git(repo, "rev-parse", ":doc.md").stdout.strip() == oid
+    else:
+        assert run_git(repo, "ls-files", "-v", "--", "doc.md").stdout == "h doc.md\n"
+
+
+@pytest.mark.skipif(os.name != "posix", reason="Unix raw path and permission bits")
+@pytest.mark.parametrize(("object_format", "split"), [("sha1", True), ("sha256", False)])
+def test_join_refresh_preserves_git_index_variants(
+    tmp_path: Path, object_format: str, split: bool,
+) -> None:
+    repo = tmp_path / "repo"
+    repo.mkdir()
+    run_git(repo, "init", "--object-format=" + object_format)
+    configure_git_user(repo)
+    run_git(repo, "config", "core.splitIndex", str(split).lower())
+    (repo / ".gitattributes").write_bytes(b"*.md filter=yamark-md\n")
+    path = repo / "notes \nü.md"
+    path.write_bytes(b"First sentence.\nSecond sentence?\n")
+    path.chmod(0o700)
+    run_git(repo, "add", ".")
+    run_git(repo, "commit", "-qm", "fixture")
+    hooks = tmp_path / "hooks"
+    hooks.mkdir()
+    observer = hooks / "post-index-change"
+    observer.write_text(
+        '#!/bin/sh\ncase "$GIT_INDEX_FILE" in ""|.git/index|"$ACTUAL_INDEX") ;; '
+        '*) printf "%s\\n" "$GIT_INDEX_FILE" >>"$UNEXPECTED_INDEX" ;; esac\n'
+    )
+    observer.chmod(0o700)
+    run_git(repo, "config", "core.hooksPath", str(hooks))
+    run_git(repo, "config", "hook.a=b.command", shlex.quote(str(observer)))
+    run_git(repo, "config", "hook.a=b.event", "post-index-change")
+    unexpected = tmp_path / "unexpected"
+    index = repo / ".git/index"
+    index.chmod(0o600)
+    before = run_git(repo, "ls-files", "-v", "--stage").stdout
+    subprocess.run(
+        [os.environ["YAMARK_BIN"], "git-filter", "join"],
+        cwd=repo, check=True, capture_output=True, umask=0o022,
+        env={**os.environ, "ACTUAL_INDEX": str(index), "UNEXPECTED_INDEX": str(unexpected)},
+    )
+    assert run_git(repo, "ls-files", "-v", "--stage").stdout == before
+    assert path.read_bytes() == b"First sentence. Second sentence?\n"
+    assert not unexpected.exists()
+    assert index.stat().st_mode & 0o777 == 0o600
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index fbdf19d6..20f9341f 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -372,17 +372,18 @@ fn adopt_git_filter(
 
     let attributes_path = repo_root.join(".gitattributes");
     let previous_attributes = read_optional_file(&attributes_path)?;
-    let result = adopt_git_filter_inner(&repo_root, yamark, width, paths, &attributes_path);
-    if let Err(err) = result {
-        let rollback = rollback_adopt(&repo_root, &attributes_path, previous_attributes);
-        return match rollback {
+    match adopt_git_filter_inner(&repo_root, yamark, width, paths, &attributes_path) {
+        Ok(summary) => Ok(summary),
+        Err(err @ worktree::InstallError::IndexBusy(_)) => Err(format!(
+            "{err}\nAdoption remains staged. Review the index and working tree before continuing."
+        )),
+        Err(err) => match rollback_adopt(&repo_root, &attributes_path, previous_attributes) {
             Ok(()) => Err(format!("{err}\nRolled back yamark Git filter adoption.")),
             Err(rollback_err) => Err(format!(
                 "{err}\nRollback failed: {rollback_err}\nReview the repository before continuing."
             )),
-        };
+        },
     }
-    result
 }
 
 fn adopt_git_filter_inner(
@@ -391,13 +392,15 @@ fn adopt_git_filter_inner(
     width: usize,
     paths: Vec,
     attributes_path: &Path,
-) -> Result {
+) -> Result {
     configure_git_filter(repo_root, yamark, width)?;
     let patterns = git_filter_attribute_patterns(repo_root, paths)?;
     let added = append_missing_attribute_lines(attributes_path, &patterns)?;
     let targets = tracked_yamark_filter_paths(repo_root, BlobSource::Index)?;
     if targets.is_empty() {
-        return Err("no tracked Markdown files match filter=yamark-md".to_owned());
+        return Err("no tracked Markdown files match filter=yamark-md"
+            .to_owned()
+            .into());
     }
 
     run_git_os(
@@ -435,7 +438,9 @@ fn join_git_filter(
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
     verify_head_roundtrip(&repo_root, &targets, width)?;
-    worktree::Checkout::Join.install(&repo_root, &targets)?;
+    worktree::Checkout::Join
+        .install(&repo_root, &targets)
+        .map_err(|err| err.to_string())?;
 
     Ok(format!(
         "Joined yamark Git filter in {}\nConfigured local filter driver and checked {} committed Markdown file(s).",
@@ -530,7 +535,7 @@ fn default_smudge_prefix(yamark: &str) -> String {
 }
 
 fn ensure_clean_worktree(repo_root: &Path) -> Result<(), String> {
-    let status = git_stdout(repo_root, ["status", "--porcelain"])?;
+    let status = git_stdout(repo_root, ["--no-optional-locks", "status", "--porcelain"])?;
     if status.is_empty() {
         Ok(())
     } else {
@@ -541,7 +546,7 @@ fn ensure_clean_worktree(repo_root: &Path) -> Result<(), String> {
 }
 
 fn ensure_no_unstaged_changes(repo_root: &Path) -> Result<(), String> {
-    let diff = git_stdout(repo_root, ["diff", "--name-only"])?;
+    let diff = git_stdout(repo_root, ["--no-optional-locks", "diff", "--name-only"])?;
     if diff.is_empty() {
         Ok(())
     } else {
diff --git a/src/cli/git_filter/worktree.rs b/src/cli/git_filter/worktree.rs
index b5382d74..7d814bcd 100644
--- a/src/cli/git_filter/worktree.rs
+++ b/src/cli/git_filter/worktree.rs
@@ -1,6 +1,6 @@
 //! Install Git's working-tree conversion while retaining local file metadata.
 
-use std::collections::HashSet;
+mod index;
 use std::ffi::OsString;
 use std::fs;
 use std::io::{self, Read, Seek, Write};
@@ -13,8 +13,28 @@ pub(super) enum Checkout {
     Join,
 }
 
+#[derive(Debug, thiserror::Error)]
+pub(super) enum InstallError {
+    #[error("{0}")]
+    Failed(String),
+    #[error("{0}. Staged changes were preserved.")]
+    IndexBusy(&'static str),
+}
+
+impl From for InstallError {
+    fn from(message: String) -> Self {
+        Self::Failed(message)
+    }
+}
+
+impl From for InstallError {
+    fn from(err: io::Error) -> Self {
+        Self::Failed(err.to_string())
+    }
+}
+
 impl Checkout {
-    pub(super) fn install(self, repo_root: &Path, paths: &[PathBuf]) -> Result<(), String> {
+    pub(super) fn install(self, repo_root: &Path, paths: &[PathBuf]) -> Result<(), InstallError> {
         // Even --force can skip stat-clean files. Check out all targets to a fresh
         // prefix so Git applies its conversions and leaves originals intact if
         // one of the filters fails.
@@ -52,13 +72,14 @@ impl Checkout {
                     changed.push(path.as_path());
                 }
             }
-            refresh_index(repo_root, &changed)?;
+            index::refresh(repo_root, &changed)?;
             match self {
                 Self::Adopt => super::ensure_no_unstaged_changes(repo_root),
                 Self::Join => super::ensure_clean_worktree(repo_root),
             }
+            .map_err(InstallError::from)
         })();
-        if let Err(err) = &result
+        if let Err(InstallError::Failed(err)) = &result
             && matches!(self, Self::Adopt)
         {
             for path in changed {
@@ -72,41 +93,6 @@ impl Checkout {
     }
 }
 
-fn refresh_index(repo_root: &Path, changed: &[&Path]) -> Result<(), String> {
-    if changed.is_empty() {
-        return Ok(());
-    }
-    // With an old, nonzero cached size, Git may report CRLF files as modified
-    // without comparing their clean blobs. Reuse the staged mode and object ID
-    // to clear the stat data for changed ordinary entries. Leave skip-worktree
-    // and assume-unchanged entries (S/s/h) and unrelated paths alone.
-    let names: HashSet<_> = changed
-        .iter()
-        .map(|path| path.as_os_str().as_encoded_bytes())
-        .collect();
-    let entries = process::git_stdout_bytes(repo_root, ["ls-files", "-v", "--stage", "-z"])?;
-    let mut reset = Vec::new();
-    for record in entries.split(|&byte| byte == 0) {
-        let Some(entry) = record.strip_prefix(b"H ") else {
-            continue;
-        };
-        let (name, [mode, _, stage]) = process::entry_fields(entry)?;
-        if names.contains(name) && stage == b"0" && matches!(mode, b"100644" | b"100755") {
-            reset.extend_from_slice(entry);
-            reset.push(0);
-        }
-    }
-    if !reset.is_empty() {
-        let mut update = process::git_query(repo_root);
-        update
-            .args(["update-index", "-z", "--index-info"])
-            .stderr(std::process::Stdio::piped());
-        process::checked_stdout(driver::run_with_input(&mut update, &reset))?;
-        process::git_stdout_bytes(repo_root, ["update-index", "--refresh"])?;
-    }
-    Ok(())
-}
-
 /// Write through an existing regular file handle to preserve its ACL, owner
 /// and permissions. A hard-linked file can be kept as-is, but replacing its
 /// bytes in place would also edit another path.
diff --git a/src/cli/git_filter/worktree/index.rs b/src/cli/git_filter/worktree/index.rs
new file mode 100644
index 00000000..7f860cd3
--- /dev/null
+++ b/src/cli/git_filter/worktree/index.rs
@@ -0,0 +1,118 @@
+//! Refresh working-tree stat data without restaging files or undoing a
+//! concurrent edit to the index.
+
+use std::collections::HashSet;
+use std::ffi::OsString;
+use std::fs;
+use std::io::{self, Read, Write};
+use std::path::Path;
+
+use super::{InstallError, driver, process};
+
+pub(super) fn refresh(repo_root: &Path, changed: &[&Path]) -> Result<(), InstallError> {
+    if changed.is_empty() {
+        return Ok(());
+    }
+    // Do both Git updates on a private copy. Only publish the completed
+    // stat refresh if the actual index still contains the input we used.
+    let path = process::git_stdout_bytes(repo_root, ["rev-parse", "--git-path", "index"])?;
+    let index = repo_root.join(
+        driver::native_path(path.strip_suffix(b"\n").unwrap_or(&path))
+            .map_err(|err| err.to_string())?,
+    );
+    let mut input = fs::File::open(&index)?;
+    let timestamp = input.metadata()?.modified()?;
+    let mut original = Vec::new();
+    input.read_to_end(&mut original)?;
+    drop(input);
+    let scratch = process::private_tempdir().map_err(|err| err.to_string())?;
+    let private_index = scratch.path().join("index");
+    let mut copy = fs::File::create(&private_index)?;
+    copy.write_all(&original)?;
+    // Git compares entry times to the index timestamp for racily clean files.
+    copy.set_modified(timestamp)?;
+    drop(copy);
+
+    // Git can register hooks in config as well as in the hooks directory.
+    // No repository hook should observe a write to the private index.
+    let mut hooks = OsString::from("core.hooksPath=");
+    hooks.push(scratch.path());
+    let mut overrides = vec![OsString::from("-c"), hooks];
+    let keys = process::git_stdout_bytes(repo_root, ["config", "--null", "--name-only", "--list"])?;
+    for key in keys.split(|&byte| byte == 0) {
+        if key.starts_with(b"hook.")
+            && let Some(name) = key.strip_suffix(b".command")
+        {
+            let mut disable = OsString::from("--config-env=");
+            disable.push(driver::native_path(name)?);
+            disable.push(".enabled=YAMARK_DISABLE_INDEX_HOOK");
+            overrides.push(disable);
+        }
+    }
+    let git = || {
+        let mut git = process::git_query(repo_root);
+        git.env("GIT_INDEX_FILE", &private_index)
+            .env("YAMARK_DISABLE_INDEX_HOOK", "false")
+            .args(&overrides);
+        git
+    };
+    // With an old, nonzero cached size, Git may report CRLF files as modified
+    // without comparing their clean blobs. Reuse the staged mode and object ID
+    // to clear the stat data for changed ordinary entries. Leave skip-worktree
+    // and assume-unchanged entries (S/s/h) and unrelated paths alone.
+    let names: HashSet<_> = changed
+        .iter()
+        .map(|path| path.as_os_str().as_encoded_bytes())
+        .collect();
+    let entries =
+        process::checked_stdout(git().args(["ls-files", "-v", "--stage", "-z"]).output())?;
+    let mut reset = Vec::new();
+    for record in entries.split(|&byte| byte == 0) {
+        let Some(entry) = record.strip_prefix(b"H ") else {
+            continue;
+        };
+        let (name, [mode, _, stage]) = process::entry_fields(entry).map_err(str::to_owned)?;
+        if names.contains(name) && stage == b"0" && matches!(mode, b"100644" | b"100755") {
+            reset.extend_from_slice(entry);
+            reset.push(0);
+        }
+    }
+    if !reset.is_empty() {
+        let mut update = git();
+        update
+            .args(["update-index", "-z", "--index-info"])
+            .stderr(std::process::Stdio::piped());
+        process::checked_stdout(driver::run_with_input(&mut update, &reset))?;
+        process::checked_stdout(git().args(["update-index", "--refresh"]).output())?;
+        publish_index(&index, &original, &private_index)?;
+    }
+    Ok(())
+}
+
+/// Use Git's lock-file convention: exclusive creation followed by an
+/// atomic rename. A failed comparison or write drops the lock untouched.
+fn publish_index(index: &Path, original: &[u8], update: &Path) -> Result<(), InstallError> {
+    let mut name = index.file_name().expect("index has a filename").to_owned();
+    name.push(".lock");
+    let mut lock = tempfile::Builder::new()
+        .prefix(&name)
+        .rand_bytes(0)
+        .tempfile_in(index.parent().expect("index has a parent directory"))
+        .map_err(|err| {
+            if err.kind() == io::ErrorKind::AlreadyExists {
+                InstallError::IndexBusy("index is locked during refresh")
+            } else {
+                err.into()
+            }
+        })?;
+    if fs::read(index)? != original {
+        return Err(InstallError::IndexBusy("index changed during refresh"));
+    }
+    io::copy(&mut fs::File::open(update)?, lock.as_file_mut())?;
+    lock.as_file()
+        .set_permissions(fs::metadata(index)?.permissions())?;
+    lock.as_file()
+        .set_modified(fs::metadata(update)?.modified()?)?;
+    lock.persist(index).map_err(|err| err.error)?;
+    Ok(())
+}
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index a4682051..7bdfb24d 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -93,7 +93,9 @@ clean(smudge(blob)) == blob
 `adopt` and `join` process regular files in Git's index. Both skip symbolic links
 and submodules. Changed files retain their local permissions and ownership.
 If a file needs rewrapping and has multiple hard links, the command reports
-the path so you can separate the links before trying again.
+the path so you can separate the links before trying again. If another Git
+operation changes or locks the index during the final refresh, adoption
+leaves the staged changes available for review.
 
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:

From c8e14f06b554c96eb91409b4b3ff2a7177ec7ca3 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:37:36 -0500
Subject: [PATCH 54/64] Record adoption stopping for a concurrent index change

---
 .../git_filter_adopt_concurrent_index.case    | 29 +++++++++++++++++++
 website/git-filter.html.md                    |  4 ++-
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 tests/cases/git_filter_adopt_concurrent_index.case

diff --git a/tests/cases/git_filter_adopt_concurrent_index.case b/tests/cases/git_filter_adopt_concurrent_index.case
new file mode 100644
index 00000000..11342da6
--- /dev/null
+++ b/tests/cases/git_filter_adopt_concurrent_index.case
@@ -0,0 +1,29 @@
+-- git-fixture
+{
+  "config": {"core.autocrlf": "false"},
+  "files": {"doc.md": "# Keep\n"}
+}
+-- args
+git-filter adopt
+-- env
+{
+  "LC_ALL": "C",
+  "GIT_CONFIG_COUNT": "2",
+  "GIT_CONFIG_KEY_0": "filter.yamark-md.smudge",
+  "GIT_CONFIG_VALUE_0": "touch .git/smudged && echo '#    Keep'",
+  "GIT_CONFIG_KEY_1": "filter.yamark-md.clean",
+  "GIT_CONFIG_VALUE_1": "if test -f .git/smudged; then (unset GIT_INDEX_FILE; git update-index --assume-unchanged -- doc.md) || exit 1; fi; \"$YAMARK_CASE_BIN\" git-filter clean --stdin-filename %f"
+}
+-- stdin
+-- stdout
+-- stderr
+error: index changed during refresh. Staged changes were preserved.
+Adoption remains staged. Review the index and working tree before continuing.
+-- git-status
+A  .gitattributes
+-- git-index
+{"doc.md": "# Keep\n"}
+-- git-worktree
+{"doc.md": "#    Keep\n"}
+-- status
+1
diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index a4682051..7bdfb24d 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -93,7 +93,9 @@ clean(smudge(blob)) == blob
 `adopt` and `join` process regular files in Git's index. Both skip symbolic links
 and submodules. Changed files retain their local permissions and ownership.
 If a file needs rewrapping and has multiple hard links, the command reports
-the path so you can separate the links before trying again.
+the path so you can separate the links before trying again. If another Git
+operation changes or locks the index during the final refresh, adoption
+leaves the staged changes available for review.
 
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:

From 4150d6ac32202e383932394f4c8bb855bd4896c8 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 12:51:08 -0500
Subject: [PATCH 55/64] Limit the path requirement to the format CLI arguments

---
 Cargo.lock                                    | 131 +-----
 Cargo.toml                                    |  10 +-
 RELEASE_NOTES.md                              |   6 -
 docs/ARCHITECTURE.md                          |   4 -
 external-tests/cli/test_git_filter.py         | 111 +----
 .../cli/test_git_filter_permissions.py        | 266 ------------
 src/cli.rs                                    |  36 +-
 src/cli/git_filter.rs                         | 366 +++++++---------
 src/cli/git_filter/checkout.rs                | 393 ------------------
 src/cli/git_filter/driver.rs                  | 335 ---------------
 src/cli/git_filter/process.rs                 | 101 +----
 src/cli/git_filter/worktree.rs                | 153 -------
 src/cli/git_filter/worktree/index.rs          | 118 ------
 src/config.rs                                 | 127 +++---
 src/config/exclude.rs                         | 149 -------
 src/workspace.rs                              |  17 +-
 src/workspace/paths.rs                        |  11 +-
 tests/cases/README.md                         |  12 +-
 .../config_exclude_character_classes.case     |  34 --
 tests/cases/config_exclude_digit_range.case   |  22 -
 ...fig_exclude_explicit_symlinked_config.case |  20 -
 .../cases/config_exclude_invalid_pattern.case |   4 +-
 .../cases/config_exclude_literal_braces.case  |  34 --
 tests/cases/config_exclude_posix_class.case   |  22 -
 ...nfig_exclude_symlink_parent_component.case |  27 --
 .../config_exclude_symlinked_config.case      |  19 -
 .../cases/config_exclude_unclosed_class.case  |  14 -
 .../config_exclude_unsupported_stdin.case     |  14 -
 .../config_virtual_stdin_path_override.case   |  20 -
 tests/cases/format_missing_path.case          |   7 +-
 .../format_missing_path_with_config.case      |   7 +-
 .../git_filter_adopt_concurrent_index.case    |  29 --
 .../git_filter_adopt_regular_entries.case     |  27 --
 .../git_filter_adopt_worktree_boundary.case   |  31 --
 .../git_filter_check_committed_selection.case |  24 --
 tests/cases/git_filter_check_declarative.case |  19 -
 ...filter_check_missing_config_directory.case |  18 -
 .../git_filter_check_private_index_hooks.case |  33 --
 .../git_filter_check_removed_attributes.case  |  17 -
 tests/cases/git_filter_clean_declarative.case |  26 --
 .../cases/git_filter_clean_leading_dash.case  |   9 -
 .../git_filter_clean_nested_worktree.case     |  20 -
 .../git_filter_clean_worktree_boundary.case   |  19 -
 tests/cases/git_filter_join_hard_link.case    |  21 -
 .../git_filter_join_refresh_failure.case      |  31 --
 .../cases/git_filter_process_clean_only.case  |  23 -
 .../git_filter_process_conflicted_config.case |  48 ---
 ...filter_process_custom_treeless_smudge.case |  32 --
 ...filter_process_double_quoted_filename.case |  23 -
 .../git_filter_process_index_change.case      |  46 --
 .../cases/git_filter_process_optional_lf.case |  22 -
 .../git_filter_process_quoted_filename.case   |  23 -
 .../cases/git_filter_process_smudge_only.case |  23 -
 .../git_filter_process_treeless_smudge.case   |  28 --
 .../git_filter_process_worktree_change.case   |  39 --
 .../cases/git_filter_smudge_declarative.case  |  42 --
 .../git_filter_smudge_inherited_pathspec.case |  18 -
 .../cases/git_filter_smudge_source_tree.case  |  20 -
 ..._filter_smudge_unverified_unsupported.case |  11 -
 tests/cases/git_filter_teardown_legacy.case   |  31 --
 tests/cases/git_filter_teardown_process.case  |  32 --
 tests/cli_cases.rs                            |  93 +----
 tests/config_discovery.rs                     |  17 -
 tests/git_filter_paths.rs                     | 325 +--------------
 tests/git_filter_process.rs                   | 273 ------------
 tests/spec_cli/workspace.rs                   |  32 +-
 tests/support/symlink.rs                      |  21 -
 tests/website.rs                              |  10 +-
 website/cli-help.html.md                      |  16 +-
 website/cli-help.qmd                          |  12 +-
 website/git-filter.html.md                    |  61 +--
 website/git-filter.qmd                        |  61 +--
 website/reference-config.html.md              |  16 +-
 website/reference-config.qmd                  |  16 +-
 website/reference-files.html.md               |   6 +-
 website/reference-files.qmd                   |   6 +-
 76 files changed, 329 insertions(+), 4011 deletions(-)
 delete mode 100644 external-tests/cli/test_git_filter_permissions.py
 delete mode 100644 src/cli/git_filter/checkout.rs
 delete mode 100644 src/cli/git_filter/driver.rs
 delete mode 100644 src/cli/git_filter/worktree.rs
 delete mode 100644 src/cli/git_filter/worktree/index.rs
 delete mode 100644 src/config/exclude.rs
 delete mode 100644 tests/cases/config_exclude_character_classes.case
 delete mode 100644 tests/cases/config_exclude_digit_range.case
 delete mode 100644 tests/cases/config_exclude_explicit_symlinked_config.case
 delete mode 100644 tests/cases/config_exclude_literal_braces.case
 delete mode 100644 tests/cases/config_exclude_posix_class.case
 delete mode 100644 tests/cases/config_exclude_symlink_parent_component.case
 delete mode 100644 tests/cases/config_exclude_symlinked_config.case
 delete mode 100644 tests/cases/config_exclude_unclosed_class.case
 delete mode 100644 tests/cases/config_exclude_unsupported_stdin.case
 delete mode 100644 tests/cases/config_virtual_stdin_path_override.case
 delete mode 100644 tests/cases/git_filter_adopt_concurrent_index.case
 delete mode 100644 tests/cases/git_filter_adopt_regular_entries.case
 delete mode 100644 tests/cases/git_filter_adopt_worktree_boundary.case
 delete mode 100644 tests/cases/git_filter_check_committed_selection.case
 delete mode 100644 tests/cases/git_filter_check_declarative.case
 delete mode 100644 tests/cases/git_filter_check_missing_config_directory.case
 delete mode 100644 tests/cases/git_filter_check_private_index_hooks.case
 delete mode 100644 tests/cases/git_filter_check_removed_attributes.case
 delete mode 100644 tests/cases/git_filter_clean_declarative.case
 delete mode 100644 tests/cases/git_filter_clean_leading_dash.case
 delete mode 100644 tests/cases/git_filter_clean_nested_worktree.case
 delete mode 100644 tests/cases/git_filter_clean_worktree_boundary.case
 delete mode 100644 tests/cases/git_filter_join_hard_link.case
 delete mode 100644 tests/cases/git_filter_join_refresh_failure.case
 delete mode 100644 tests/cases/git_filter_process_clean_only.case
 delete mode 100644 tests/cases/git_filter_process_conflicted_config.case
 delete mode 100644 tests/cases/git_filter_process_custom_treeless_smudge.case
 delete mode 100644 tests/cases/git_filter_process_double_quoted_filename.case
 delete mode 100644 tests/cases/git_filter_process_index_change.case
 delete mode 100644 tests/cases/git_filter_process_optional_lf.case
 delete mode 100644 tests/cases/git_filter_process_quoted_filename.case
 delete mode 100644 tests/cases/git_filter_process_smudge_only.case
 delete mode 100644 tests/cases/git_filter_process_treeless_smudge.case
 delete mode 100644 tests/cases/git_filter_process_worktree_change.case
 delete mode 100644 tests/cases/git_filter_smudge_declarative.case
 delete mode 100644 tests/cases/git_filter_smudge_inherited_pathspec.case
 delete mode 100644 tests/cases/git_filter_smudge_source_tree.case
 delete mode 100644 tests/cases/git_filter_smudge_unverified_unsupported.case
 delete mode 100644 tests/cases/git_filter_teardown_legacy.case
 delete mode 100644 tests/cases/git_filter_teardown_process.case
 delete mode 100644 tests/git_filter_process.rs
 delete mode 100644 tests/support/symlink.rs

diff --git a/Cargo.lock b/Cargo.lock
index 673c52ec..89c8c7fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -215,104 +215,6 @@ dependencies = [
  "r-efi",
 ]
 
-[[package]]
-name = "gix-error"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd"
-dependencies = [
- "bstr",
-]
-
-[[package]]
-name = "gix-fs"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "516aec0f136bdfb26420ced8e43e1d5b36b967cd94aa1c763036208f25b8e888"
-dependencies = [
- "bstr",
- "gix-error",
- "gix-macros",
- "gix-parallel",
- "gix-path",
- "gix-utils",
- "libc",
-]
-
-[[package]]
-name = "gix-glob"
-version = "0.30.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48b4b3c2353cc9f9709a49d8c3b9c7a7a0188d43eeb756ac9a5a36bc397b013c"
-dependencies = [
- "bitflags",
- "bstr",
- "gix-fs",
- "gix-path",
- "gix-trace",
- "gix-utils",
-]
-
-[[package]]
-name = "gix-macros"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79ca2ec664aea06d549444f9cd35546dd1732b2ea188b48159cea4fbf2a05848"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "gix-parallel"
-version = "0.50.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd"
-dependencies = [
- "gix-trace",
-]
-
-[[package]]
-name = "gix-path"
-version = "0.14.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a"
-dependencies = [
- "bstr",
- "gix-error",
- "gix-trace",
- "gix-validate",
- "winreg",
-]
-
-[[package]]
-name = "gix-trace"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8"
-
-[[package]]
-name = "gix-utils"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10"
-dependencies = [
- "fastrand",
- "getrandom",
- "unicode-normalization",
-]
-
-[[package]]
-name = "gix-validate"
-version = "0.13.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726"
-dependencies = [
- "bstr",
- "gix-error",
-]
-
 [[package]]
 name = "globset"
 version = "0.4.20"
@@ -604,9 +506,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
 name = "syn"
-version = "3.0.10"
+version = "3.0.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -652,12 +554,6 @@ dependencies = [
  "syn",
 ]
 
-[[package]]
-name = "tinyvec"
-version = "1.13.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
-
 [[package]]
 name = "toml"
 version = "1.1.6+spec-1.1.0"
@@ -709,15 +605,6 @@ version = "1.0.24"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
 
-[[package]]
-name = "unicode-normalization"
-version = "0.1.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
-dependencies = [
- "tinyvec",
-]
-
 [[package]]
 name = "unicode-width"
 version = "0.2.2"
@@ -779,27 +666,15 @@ version = "1.0.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
 
-[[package]]
-name = "winreg"
-version = "0.56.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
-dependencies = [
- "cfg-if",
- "windows-sys",
-]
-
 [[package]]
 name = "yamark"
 version = "0.6.1+dev"
 dependencies = [
  "assert_cmd",
  "clap",
- "gix-glob",
  "ignore",
  "json-five",
  "jsonc-parser",
- "libc",
  "memchr",
  "num-bigint",
  "serde_json",
@@ -808,8 +683,6 @@ dependencies = [
  "toml",
  "unicode-general-category",
  "unicode-width",
- "winapi-util",
- "windows-sys",
 ]
 
 [[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 47cf4a16..119fd4e2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,28 +26,20 @@ path = "src/main.rs"
 
 [dependencies]
 clap = { version = "4.6.6", features = ["derive"] }
-gix-glob = "0.30.0"
 ignore = "0.4.33"
 json-five = { version = "=0.3.1", default-features = false }
 jsonc-parser = { version = "0.33.2", default-features = false }
 memchr = "2.8.3"
 num-bigint = "0.5.1"
 serde_json = "1.0.151"
-tempfile = "3.27.0"
 thiserror = "2.0.20"
 toml = "1.1.6"
 unicode-general-category = "1.1.0"
 unicode-width = "0.2.2"
 
-[target.'cfg(unix)'.dependencies]
-libc = "0.2.189"
-
-[target.'cfg(windows)'.dependencies]
-winapi-util = "0.1.11"
-windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem"] }
-
 [dev-dependencies]
 assert_cmd = "2.2.2"
+tempfile = "3.27.0"
 
 [profile.release]
 codegen-units = 1
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 1752bf08..7d4a1782 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -4,10 +4,4 @@ To format the current directory in place, use `yamark format .`. Bare `yamark fo
 
 Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yamark formatting. Its gitignore-style patterns are relative to the config directory. Unlike `.gitignore` and `.ignore`, which affect only directory traversal, `exclude` also applies to explicit paths, `--stdin-file-path`, and Git clean and smudge filters. Excluded file paths are counted as skipped, and stdin for an excluded path passes through unchanged. This also applies to editor Format Document and format-on-save; a configured next formatter still runs.
 
-The experimental Git filter now reads the tracked `yamark.toml` from the tree being checked out, so excluded files keep their original bytes in a fresh worktree. New filter installations configure this automatically. To update an existing installation with `yamark` on your path, run `git config filter.yamark-md.process "yamark git-filter process"` in the repository.
-
-Git clean, smudge, and round-trip checks now skip external embedded formatters. Use `yamark format ` in a trusted checkout to format embedded code with your project's tools.
-
-Git filter setup leaves `merge.renormalize` under your control. If an earlier Yamark installation enabled it, run `git config --local --unset merge.renormalize` in that clone. With Git's default merge settings, an incoming branch can exclude a file and preserve its formatting when both branches edited it.
-
 `[paths]` overrides now match a `--stdin-file-path` that does not exist on disk on Windows, or when the path passes through a symlinked directory. Previously these paths could fail to match the config directory.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 083a19f9..8702420d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -98,10 +98,6 @@ Workspace traversal owns configuration discovery and writes. Format stdin uses i
 
 `[format] exclude` applies to each path after configuration discovery, so it covers explicit paths and stdin as well as directory walks. Excluded files are skipped before reading; excluded stdin is returned as bytes without decoding for editors and Git filters. Ignore files only prune directory walks. Patterns match names below the config directory as written, so a symbolic link matches by its own name, not its target's. They never exclude paths outside the config directory. `[paths]` keys match a file's resolved location.
 
-The Git process filter negotiates clean and smudge independently. It runs the installed Yamark commands in process, caches checkout configuration by source and directory, and delegates custom commands from Git settings. Clean discovers configuration on every request, from the file’s directory up to and including the worktree root. Smudge reads the nearest tracked `yamark.toml` from the incoming tree before decoding the file. When Git omits the tree, one index snapshot identifies the path’s stage-zero blob and the nearest configuration. Smudge and round-trip verification match exclusions against the filename relative to the configuration directory in the selected snapshot. A conflict in that configuration or a mismatch with the supplied blob preserves the incoming bytes. The filter discards the snapshot and its cached settings when the index checksum changes. If `index.skipHash` disables the checksum, detecting a change requires comparing the index bytes on each treeless request. Direct smudge invocations without a checkout source use the working-tree configuration.
-
-The built-in Git conversions and their round-trip checks use the same formatting options. They apply declarative settings and skip external embedded formatters, so checking out a revision does not require its executables. Adoption and join select regular stage-zero files and ask Git to convert the whole batch into a temporary directory with owner-only access on Unix. They write changed bytes through existing regular files to preserve local access controls and leave unchanged files in place. Git refreshes the stat data of changed index entries against their original modes and object IDs in a private copy of the index. The refresh takes Git's index lock and publishes that copy only if the live index still matches the snapshot. Adoption keeps the previous working bytes until the refreshed checkout passes verification.
-
 The plugin registry selects embedded formatters. External process code owns stdin/stdout exchange and diagnostics; recursive emitters own dedenting, reindenting, and restoring structural delimiters. Keep these responsibilities separate when changing an external formatter contract.
 
 The editor extension passes text to the CLI and applies returned edits. It does not maintain an independent Markdown or YAML formatter.
diff --git a/external-tests/cli/test_git_filter.py b/external-tests/cli/test_git_filter.py
index 8d3bbad4..b35ac99e 100644
--- a/external-tests/cli/test_git_filter.py
+++ b/external-tests/cli/test_git_filter.py
@@ -63,7 +63,6 @@ def test_git_filter_help_explains_git_config_and_attributes() -> None:
                 '"yamark git-filter smudge --stdin-filename %f '
                 '--markdown-wrap-at-column 72"'
             ),
-            'git config filter.yamark-md.process "yamark git-filter process"',
             "Git only runs the filter for paths matched by attributes",
             "*.md filter=yamark-md",
             "*.qmd filter=yamark-md",
@@ -347,78 +346,6 @@ def test_git_filter_join_installs_local_config_and_keeps_checkout_clean(
         ).encode("utf-8")
 
 
-@pytest.mark.parametrize(
-    ("direction", "skip_hash"), [("clean", False), ("smudge", False), ("smudge", True)]
-)
-def test_persistent_git_filter_observes_config_changes(
-    tmp_path: Path, direction: str, skip_hash: bool,
-) -> None:
-    repo = tmp_path
-    init_repo(repo)
-    run_git(repo, "config", "core.autocrlf", "false")
-    run_git(repo, "config", "index.skipHash", str(skip_hash).lower())
-    original = b"#   Keep\n"
-    formatted = b"# Keep\n"
-    (repo / "doc.md").write_bytes(original)
-    run_git(repo, "add", "doc.md")
-    run_yamark(repo, "git-filter", "setup")
-    if direction == "clean":
-        args = ["hash-object", "--stdin-paths"]
-        request = b"doc.md\n"
-    else:
-        args = ["cat-file", "--batch=%(objecttype)", "--filters"]
-        oid = run_git(repo, "rev-parse", ":doc.md").stdout.strip()
-        request = f"{oid} doc.md\n".encode()
-
-    with subprocess.Popen(
-        ["git", *args], cwd=repo, stdin=subprocess.PIPE, stdout=subprocess.PIPE
-    ) as git:
-        def check_response(expected: bytes) -> None:
-            assert git.stdin is not None and git.stdout is not None
-            git.stdin.write(request)
-            git.stdin.flush()
-            if direction == "clean":
-                digest = subprocess.check_output(
-                    ["git", "hash-object", "--stdin"], cwd=repo, input=expected
-                )
-                assert git.stdout.readline() == digest
-            else:
-                assert git.stdout.readline() == b"blob\n"
-                assert git.stdout.readline() == expected
-                assert git.stdout.readline() == b"\n"
-
-        check_response(formatted)
-        (repo / "yamark.toml").write_bytes(b"[format]\nexclude = ['doc.md']\n")
-        if direction == "smudge":
-            run_git(repo, "add", "yamark.toml")
-        check_response(original)
-    assert git.returncode == 0
-
-
-def test_delegated_smudge_rejects_unsupported_index_path(tmp_path: Path) -> None:
-    repo = tmp_path
-    init_repo(repo)
-    (repo / "file.txt").write_bytes(b"original\n")
-    run_git(repo, "add", "file.txt")
-    run_yamark(repo, "git-filter", "setup")
-    (repo / ".git/info/attributes").write_bytes(b"file.txt filter=yamark-md\n")
-    result = subprocess.run(
-        [
-            "git",
-            "-c",
-            'filter.yamark-md.smudge="$YAMARK_BIN" git-filter smudge --stdin-filename %f',
-            "cat-file",
-            "--filters",
-            ":file.txt",
-        ],
-        cwd=repo,
-        capture_output=True,
-    )
-    assert result.returncode != 0
-    assert b"file.txt:1:1: error: unsupported Git filter path" in result.stderr
-    assert result.stdout == b""
-
-
 def test_git_filter_check_rejects_non_roundtripping_committed_blob() -> None:
     with TemporaryDirectory(prefix="yamark-pytest-git-") as temp:
         repo = Path(temp)
@@ -439,37 +366,6 @@ def test_git_filter_check_rejects_non_roundtripping_committed_blob() -> None:
         assert "clean(smudge(blob)) != blob" in result.stderr
 
 
-def test_merge_preserves_newly_excluded_heading_and_local_paragraph(tmp_path: Path) -> None:
-    repo = tmp_path
-    init_repo(repo)
-    run_git(repo, "config", "core.autocrlf", "false")
-    run_git(repo, "config", "merge.renormalize", "false")
-    run_yamark(repo, "git-filter", "setup")
-    doc = repo / "doc.md"
-    base = b"# Base\n\nContext.\n\nOriginal ending.\n"
-    doc.write_bytes(base)
-    run_git(repo, "add", "doc.md")
-    run_git(repo, "commit", "-qm", "base")
-
-    run_git(repo, "checkout", "-qb", "incoming")
-    (repo / "yamark.toml").write_bytes(b"[format]\nexclude = ['doc.md']\n")
-    incoming = base.replace(b"# Base", b"#    Keep")
-    doc.write_bytes(incoming)
-    run_git(repo, "add", "doc.md", "yamark.toml")
-    run_git(repo, "commit", "-qm", "exclude the heading")
-    assert run_git(repo, "show", "HEAD:doc.md").stdout == incoming.decode()
-
-    run_git(repo, "checkout", "-q", "main")
-    doc.write_bytes(base.replace(b"Original ending.", b"Local ending."))
-    run_git(repo, "add", "doc.md")
-    run_git(repo, "commit", "-qm", "edit the ending")
-    run_git(repo, "merge", "--no-edit", "incoming")
-    merged = incoming.replace(b"Original ending.", b"Local ending.")
-    assert run_git(repo, "show", "HEAD:doc.md").stdout == merged.decode()
-    assert doc.read_bytes() == merged
-    assert run_git(repo, "status", "--porcelain").stdout == ""
-
-
 def test_git_filter_setup_configures_current_repo_for_specific_path() -> None:
     with TemporaryDirectory(prefix="yamark-pytest-git-") as temp:
         repo = Path(temp)
@@ -496,8 +392,7 @@ def test_git_filter_setup_configures_current_repo_for_specific_path() -> None:
         attributes = (repo / ".git/info/attributes").read_text(encoding="utf-8")
         assert attributes == f"{path} filter=yamark-md\n"
         assert run_git(repo, "config", "filter.yamark-md.required").stdout == "true\n"
-        local_keys = run_git(repo, "config", "--local", "--name-only", "--list")
-        assert "merge.renormalize" not in local_keys.stdout.splitlines()
+        assert run_git(repo, "config", "merge.renormalize").stdout == "true\n"
         assert (
             "git-filter clean --stdin-filename %f"
             in run_git(repo, "config", "filter.yamark-md.clean").stdout
@@ -523,7 +418,6 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         path = "content/blog/post/index.md"
 
         run_git(repo, "init")
-        run_git(repo, "config", "merge.renormalize", "false")
         target = repo / path
         target.parent.mkdir(parents=True)
         target.write_text("First sentence. Second sentence?\n", encoding="utf-8")
@@ -538,7 +432,6 @@ def test_git_filter_teardown_removes_local_setup() -> None:
 
         assert "Removed yamark Git filter setup" in result.stdout
         assert "Unset 4 local Git config value(s)" in result.stdout
-        assert run_git(repo, "config", "--local", "merge.renormalize").stdout == "false\n"
         assert "Removed 1 yamark attribute pattern(s)" in result.stdout
         assert attributes_path.read_text(encoding="utf-8") == (
             "NEWS.md -filter\n"
@@ -552,8 +445,8 @@ def test_git_filter_teardown_removes_local_setup() -> None:
         for key in [
             "filter.yamark-md.clean",
             "filter.yamark-md.smudge",
-            "filter.yamark-md.process",
             "filter.yamark-md.required",
+            "merge.renormalize",
         ]:
             missing = subprocess.run(
                 ["git", "config", "--local", "--get", key],
diff --git a/external-tests/cli/test_git_filter_permissions.py b/external-tests/cli/test_git_filter_permissions.py
deleted file mode 100644
index 636e9780..00000000
--- a/external-tests/cli/test_git_filter_permissions.py
+++ /dev/null
@@ -1,266 +0,0 @@
-"""Permissions on the local files created while checking and joining a filter."""
-
-import os
-import shutil
-import shlex
-import subprocess
-from pathlib import Path
-
-import pytest
-
-from test_git_filter import configure_git_user, init_repo, run_git
-
-
-@pytest.mark.skipif(os.name != "posix", reason="Unix directory access modes")
-@pytest.mark.parametrize(("action", "operation"), [("check", "read-tree"), ("join", "checkout")])
-def test_filter_uses_private_scratch_directory(
-    tmp_path: Path, action: str, operation: str,
-) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir(mode=0o700)
-    init_repo(repo)
-    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
-    (repo / "doc.md").write_bytes(b"# Fixture\n")
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-    if action == "check":
-        hooks = repo / "hooks"
-        hooks.mkdir()
-        hook = hooks / "post-index-change"
-        hook.write_text("#!/bin/sh\necho changed >>index-events\n")
-        hook.chmod(0o700)
-        run_git(repo, "config", "core.hooksPath", "hooks")
-    # Observe the directory at the Git invocation that will populate it.
-    program = tmp_path / "git"
-    program.write_text(
-        """#!/usr/bin/env python3
-import os, sys
-from pathlib import Path
-
-# Git before 2.40 reads committed attributes from a private index.
-if 'check-attr' in sys.argv and '-h' in sys.argv:
-    print('usage: git check-attr [--cached] [--stdin]', file=sys.stderr)
-    sys.exit(129)
-if 'read-tree' in sys.argv and 'GIT_INDEX_FILE' in os.environ:
-    directory = Path(os.environ['GIT_INDEX_FILE']).parent
-    print('read-tree', oct(directory.stat().st_mode & 0o777), file=open(os.environ['MODE_LOG'], 'a'))
-for arg in sys.argv:
-    if 'checkout-index' in sys.argv and arg.startswith('--prefix='):
-        directory = Path(arg.removeprefix('--prefix='))
-        print('checkout', oct(directory.stat().st_mode & 0o777), file=open(os.environ['MODE_LOG'], 'a'))
-os.execv(os.environ['REAL_GIT'], [os.environ['REAL_GIT'], *sys.argv[1:]])
-"""
-    )
-    program.chmod(0o700)
-    real_git = shutil.which("git")
-    assert real_git is not None
-    log = tmp_path / "modes"
-    subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", action],
-        cwd=repo,
-        check=True,
-        capture_output=True,
-        umask=0o022,
-        env={**os.environ, "REAL_GIT": real_git, "MODE_LOG": str(log),
-             "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
-    )
-    assert log.read_text().splitlines() == [f"{operation} 0o700"]
-    if action == "check":
-        assert not (repo / "index-events").exists()
-
-
-@pytest.mark.skipif(os.name != "posix", reason="Unix file access modes")
-@pytest.mark.parametrize("action", ["adopt", "join"])
-def test_checkout_preserves_local_file_access(tmp_path: Path, action: str) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    init_repo(repo)
-    if action == "join":
-        (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
-    changed = repo / "changed.md"
-    changed.write_bytes(b"First sentence.\nSecond sentence?\n")
-    changed.chmod(0o600)
-    unchanged = repo / "unchanged.md"
-    unchanged.write_bytes(b"# Heading\n")
-    unchanged.chmod(0o750)
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-
-    before = [path.stat() for path in (changed, unchanged)]
-    subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", action],
-        cwd=repo, check=True, capture_output=True, umask=0o022,
-    )
-    assert changed.read_bytes() == b"First sentence. Second sentence?\n"
-    assert unchanged.read_bytes() == b"# Heading\n"
-    for path, original in zip((changed, unchanged), before):
-        assert path.stat().st_mode == original.st_mode
-        assert path.stat().st_ino == original.st_ino
-    assert run_git(repo, "diff", "--name-only").stdout == ""
-
-
-def test_join_preserves_hard_links(tmp_path: Path) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    init_repo(repo)
-    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
-    path = repo / "doc.md"
-    original = b"First sentence.\nSecond sentence?\n"
-    path.write_bytes(original)
-    alias = tmp_path / "alias"
-    os.link(path, alias)
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-    proc = subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", "join"],
-        cwd=repo, capture_output=True, text=True,
-    )
-    assert proc.returncode == 1
-    assert "cannot rewrite a file with multiple hard links" in proc.stderr
-    assert alias.samefile(path)
-    assert alias.read_bytes() == original
-
-
-@pytest.mark.skipif(os.name != "posix", reason="Unix file access modes")
-def test_failed_adoption_restores_local_bytes_and_access(tmp_path: Path) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    init_repo(repo)
-    original = b"First sentence.\nSecond sentence?\n"
-    first = repo / "a.md"
-    linked = repo / "z.md"
-    for path in (first, linked):
-        path.write_bytes(original)
-        path.chmod(0o600)
-    alias = tmp_path / "z-alias"
-    os.link(linked, alias)
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-
-    proc = subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", "adopt"],
-        cwd=repo, capture_output=True, text=True, umask=0o022,
-    )
-    assert proc.returncode == 1
-    assert "Rolled back" in proc.stderr
-    assert first.read_bytes() == original
-    assert first.stat().st_mode & 0o777 == 0o600
-    assert alias.samefile(linked)
-    assert run_git(repo, "status", "--porcelain").stdout == ""
-
-
-def test_join_refresh_keeps_staged_ids_and_flags(tmp_path: Path) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    init_repo(repo)
-    (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
-    for name in ("ordinary.md", "assumed.md", "sparse.txt"):
-        (repo / name).write_bytes(b"First sentence.\nSecond sentence?\n")
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-    run_git(repo, "update-index", "--assume-unchanged", "--", "assumed.md")
-    run_git(repo, "update-index", "--skip-worktree", "--", "sparse.txt")
-    (repo / "sparse.txt").unlink()
-    before = run_git(repo, "ls-files", "-v", "--stage").stdout
-
-    subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", "join"],
-        cwd=repo, check=True, capture_output=True,
-    )
-    assert run_git(repo, "ls-files", "-v", "--stage").stdout == before
-    assert (repo / "assumed.md").read_bytes() == b"First sentence. Second sentence?\n"
-    assert not (repo / "sparse.txt").exists()
-
-
-@pytest.mark.skipif(os.name != "posix", reason="Unix executable wrapper")
-@pytest.mark.parametrize("change", ["blob", "flag"])
-@pytest.mark.parametrize("action", ["adopt", "join"])
-def test_checkout_retains_concurrent_index_change(tmp_path: Path, change: str, action: str) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    init_repo(repo)
-    if action == "join":
-        (repo / ".gitattributes").write_text("*.md filter=yamark-md\n")
-    (repo / "doc.md").write_bytes(b"First sentence.\nSecond sentence?\n")
-    (repo / "saved.txt").write_bytes(b"Staged separately\n")
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-    oid = run_git(repo, "rev-parse", ":saved.txt").stdout.strip()
-
-    # Release a staged edit exactly after Git returns the selected entries.
-    program = tmp_path / "git"
-    program.write_text(
-        """#!/usr/bin/env python3
-import os, subprocess, sys
-
-git = os.environ['REAL_GIT']
-if 'ls-files' in sys.argv and '-v' in sys.argv:
-    result = subprocess.run([git, *sys.argv[1:]], capture_output=True, check=True)
-    env = dict(os.environ)
-    env.pop('GIT_INDEX_FILE', None)
-    args = (['--cacheinfo', '100644', os.environ['SAVED_OID'], 'doc.md']
-            if os.environ['STAGED_CHANGE'] == 'blob' else ['--assume-unchanged', 'doc.md'])
-    subprocess.run([git, '-C', os.environ['TEST_REPO'], 'update-index', *args], env=env, check=True)
-    sys.stdout.buffer.write(result.stdout)
-else:
-    os.execv(git, [git, *sys.argv[1:]])
-"""
-    )
-    program.chmod(0o700)
-    real_git = shutil.which("git")
-    assert real_git is not None
-    proc = subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", action],
-        cwd=repo, capture_output=True, text=True,
-        env={**os.environ, "REAL_GIT": real_git, "TEST_REPO": str(repo),
-             "SAVED_OID": oid, "STAGED_CHANGE": change,
-             "PATH": os.pathsep.join([str(tmp_path), os.environ["PATH"]])},
-    )
-    assert proc.returncode == 1
-    assert "index changed during refresh" in proc.stderr
-    if change == "blob":
-        assert run_git(repo, "rev-parse", ":doc.md").stdout.strip() == oid
-    else:
-        assert run_git(repo, "ls-files", "-v", "--", "doc.md").stdout == "h doc.md\n"
-
-
-@pytest.mark.skipif(os.name != "posix", reason="Unix raw path and permission bits")
-@pytest.mark.parametrize(("object_format", "split"), [("sha1", True), ("sha256", False)])
-def test_join_refresh_preserves_git_index_variants(
-    tmp_path: Path, object_format: str, split: bool,
-) -> None:
-    repo = tmp_path / "repo"
-    repo.mkdir()
-    run_git(repo, "init", "--object-format=" + object_format)
-    configure_git_user(repo)
-    run_git(repo, "config", "core.splitIndex", str(split).lower())
-    (repo / ".gitattributes").write_bytes(b"*.md filter=yamark-md\n")
-    path = repo / "notes \nü.md"
-    path.write_bytes(b"First sentence.\nSecond sentence?\n")
-    path.chmod(0o700)
-    run_git(repo, "add", ".")
-    run_git(repo, "commit", "-qm", "fixture")
-    hooks = tmp_path / "hooks"
-    hooks.mkdir()
-    observer = hooks / "post-index-change"
-    observer.write_text(
-        '#!/bin/sh\ncase "$GIT_INDEX_FILE" in ""|.git/index|"$ACTUAL_INDEX") ;; '
-        '*) printf "%s\\n" "$GIT_INDEX_FILE" >>"$UNEXPECTED_INDEX" ;; esac\n'
-    )
-    observer.chmod(0o700)
-    run_git(repo, "config", "core.hooksPath", str(hooks))
-    run_git(repo, "config", "hook.a=b.command", shlex.quote(str(observer)))
-    run_git(repo, "config", "hook.a=b.event", "post-index-change")
-    unexpected = tmp_path / "unexpected"
-    index = repo / ".git/index"
-    index.chmod(0o600)
-    before = run_git(repo, "ls-files", "-v", "--stage").stdout
-    subprocess.run(
-        [os.environ["YAMARK_BIN"], "git-filter", "join"],
-        cwd=repo, check=True, capture_output=True, umask=0o022,
-        env={**os.environ, "ACTUAL_INDEX": str(index), "UNEXPECTED_INDEX": str(unexpected)},
-    )
-    assert run_git(repo, "ls-files", "-v", "--stage").stdout == before
-    assert path.read_bytes() == b"First sentence. Second sentence?\n"
-    assert not unexpected.exists()
-    assert index.stat().st_mode & 0o777 == 0o600
diff --git a/src/cli.rs b/src/cli.rs
index 7cb49d5b..a06ae382 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -81,7 +81,8 @@ enum Command {
         skip_embedded_formatters: bool,
         #[arg(
             value_name = "PATHS",
-            help = "Files or directories to format in place (required for writes). Use '.' for the current directory"
+            required_unless_present_any = ["check", "diff", "stdin_file_path"],
+            help = "Files or directories to format in place. Use '.' for the current directory"
         )]
         paths: Vec,
     },
@@ -116,7 +117,6 @@ Configure the filter driver with:
   yamark git-filter teardown
   git config filter.yamark-md.clean \"yamark git-filter clean --stdin-filename %f\"
   git config filter.yamark-md.smudge \"yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72\"
-  git config filter.yamark-md.process \"yamark git-filter process\"
 
 Git only runs the filter for paths matched by attributes. Put these patterns in
 .git/info/attributes for personal use or .gitattributes for a shared repo:
@@ -363,15 +363,7 @@ fn run_format(
     };
 
     if let Some(path) = stdin_file_path {
-        return run_stdin(
-            path,
-            |path| {
-                let config = load_config_for_formatted_path(path, config.as_deref())?;
-                Ok((!config.excludes(path)).then_some(config))
-            },
-            options,
-            execution,
-        );
+        return run_stdin(path, config, options, execution);
     }
 
     let mode = if diff {
@@ -381,16 +373,6 @@ fn run_format(
     } else {
         FormatMode::Write
     };
-    let paths = match mode.resolve_paths(paths) {
-        Ok(paths) => paths,
-        Err(message) => {
-            eprintln!("error: {message}\n");
-            eprintln!(
-                "Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin."
-            );
-            return ExitCode::from(2);
-        }
-    };
     match format_paths_with_trace_and_overrides(paths, options, mode, config, execution) {
         Ok(run) => {
             if mode == FormatMode::Diff {
@@ -426,7 +408,7 @@ fn run_format(
 
 fn run_stdin(
     path: PathBuf,
-    load_config: impl FnOnce(&Path) -> crate::diagnostic::Result>,
+    config: Option,
     options: FormatOptions,
     execution: FormatExecutionOptions,
 ) -> ExitCode {
@@ -437,15 +419,17 @@ fn run_stdin(
             return ExitCode::from(1);
         }
     };
-    let config = match load_config(&path) {
-        Ok(Some(config)) => config,
-        // Preserve excluded input or an unverified Git blob without decoding it.
-        Ok(None) => return write_stdout(&path, &input),
+    let config = match load_config_for_formatted_path(&path, config.as_deref()) {
+        Ok(config) => config,
         Err(err) => {
             eprintln!("{}", err.diagnostic.render());
             return ExitCode::from(1);
         }
     };
+    // Editors and Git filters need excluded input back without decoding.
+    if config.excludes(&path) {
+        return write_stdout(&path, &input);
+    }
     let input = match decode_utf8(input) {
         Ok(input) => input,
         Err(message) => {
diff --git a/src/cli/git_filter.rs b/src/cli/git_filter.rs
index 20f9341f..0dc0231f 100644
--- a/src/cli/git_filter.rs
+++ b/src/cli/git_filter.rs
@@ -1,10 +1,7 @@
 //! Git clean/smudge commands and repository adoption lifecycle.
 
 mod attributes;
-mod checkout;
-mod driver;
 mod process;
-mod worktree;
 
 use std::env;
 use std::ffi::OsString;
@@ -16,35 +13,32 @@ use std::process::{Command as ProcessCommand, ExitCode};
 use clap::Subcommand;
 
 use super::{parse_positive_usize, run_stdin};
-use crate::config::{Config, discover_config_within};
 use crate::core::document::{FormatOptions, MarkdownWrap};
-use crate::workspace::{FormatExecutionOptions, format_source_with_config};
+use crate::workspace::{
+    FormatExecutionOptions, format_source_for_path_with_overrides, load_config_for_formatted_path,
+};
 use attributes::{
     append_missing_attribute_lines, count_yamark_filter_attribute_lines,
     git_filter_attribute_patterns, line_has_yamark_filter_attribute,
     remove_yamark_filter_attribute_lines,
 };
 use process::{
-    git_stdout, local_git_config_count, run_git_config, run_git_os, run_git_with_paths,
-    unset_git_config_key,
+    git_stdout, git_stdout_bytes, local_git_config_count, run_git_config, run_git_os,
+    run_git_with_paths, unset_git_config_key,
 };
 
 #[derive(Debug, Subcommand)]
 pub(super) enum GitFilterCommand {
     Clean {
-        #[arg(long, allow_hyphen_values = true)]
+        #[arg(long)]
         stdin_filename: PathBuf,
     },
     Smudge {
-        #[arg(long, allow_hyphen_values = true)]
+        #[arg(long)]
         stdin_filename: PathBuf,
-        #[arg(long, help = "Read configuration from this Git tree during checkout")]
-        source_tree: Option,
         #[arg(long, default_value_t = 72, value_parser = parse_positive_usize)]
         markdown_wrap_at_column: usize,
     },
-    #[command(about = "Serve Git's process filter protocol for checkout-aware smudging")]
-    Process,
     #[command(about = "Adopt the yamark Git filter for a shared repository")]
     Adopt {
         #[arg(
@@ -150,33 +144,16 @@ pub(super) enum GitFilterCommand {
 
 pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     match command {
-        GitFilterCommand::Clean { stdin_filename } => run_git_filter(
-            stdin_filename,
-            MarkdownWrap::Sentence,
-            FilterSource::Worktree,
-        ),
+        GitFilterCommand::Clean { stdin_filename } => {
+            run_git_filter(stdin_filename, MarkdownWrap::Sentence)
+        }
         GitFilterCommand::Smudge {
             stdin_filename,
             markdown_wrap_at_column,
-            source_tree,
-        } => {
-            let source = match source_tree {
-                Some(tree) => FilterSource::Tree(tree),
-                None => match env::var(driver::SOURCE_TREE_ENV) {
-                    Ok(tree) if tree.is_empty() => {
-                        FilterSource::StagedBlob(env::var(driver::SOURCE_BLOB_ENV).ok())
-                    }
-                    Ok(tree) => FilterSource::Tree(tree),
-                    Err(_) => FilterSource::Worktree,
-                },
-            };
-            run_git_filter(
-                stdin_filename,
-                MarkdownWrap::Column(markdown_wrap_at_column),
-                source,
-            )
-        }
-        GitFilterCommand::Process => driver::run(),
+        } => run_git_filter(
+            stdin_filename,
+            MarkdownWrap::Column(markdown_wrap_at_column),
+        ),
         GitFilterCommand::Adopt {
             repo,
             yamark,
@@ -202,56 +179,22 @@ pub(super) fn run(command: GitFilterCommand) -> ExitCode {
     }
 }
 
-fn filter_options(wrap: MarkdownWrap) -> FormatOptions {
-    FormatOptions {
-        markdown_wrap: wrap,
-        markdown_compact_tables: true,
-        respect_frontmatter_markdown_options: false,
-        // Git can supply configuration from a revision before checkout.
-        // Keep both directions and round-trip checks independent of executables.
-        skip_embedded_formatters: true,
-        ..FormatOptions::default()
-    }
-}
-
-enum FilterSource {
-    Worktree,
-    Tree(String),
-    StagedBlob(Option),
-}
-
-fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> ExitCode {
+fn run_git_filter(path: PathBuf, wrap: MarkdownWrap) -> ExitCode {
     if crate::core::document::FileKind::for_path(&path) != crate::core::document::FileKind::Markdown
     {
         eprintln!("{}:1:1: error: unsupported Git filter path", path.display());
         return ExitCode::from(1);
     }
+    let options = FormatOptions {
+        markdown_wrap: wrap,
+        markdown_compact_tables: true,
+        respect_frontmatter_markdown_options: false,
+        ..FormatOptions::default()
+    };
     run_stdin(
         path,
-        |path| {
-            let mut configs = checkout::CheckoutConfigs::default();
-            let file = match source {
-                FilterSource::Tree(tree) => configs.for_path(Path::new("."), &tree, path),
-                FilterSource::StagedBlob(blob) => configs.for_staged_blob(
-                    Path::new("."),
-                    path,
-                    blob.as_ref().map(String::as_bytes),
-                ),
-                FilterSource::Worktree => {
-                    // Direct invocations may start in a subdirectory, or outside Git.
-                    let cwd = env::current_dir()
-                        .map_err(|err| crate::diagnostic::YamarkError::new(err.to_string()))?;
-                    let cdup = git_stdout(Path::new("."), ["rev-parse", "--show-cdup"]).ok();
-                    let root = cdup.as_ref().and_then(|up| {
-                        cwd.ancestors()
-                            .nth(Path::new(up.trim_end()).components().count())
-                    });
-                    return worktree_config(path, root);
-                }
-            }?;
-            Ok(file.and_then(checkout::CheckoutPath::included))
-        },
-        filter_options(wrap),
+        None,
+        options,
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
             ..FormatExecutionOptions::default()
@@ -259,14 +202,6 @@ fn run_git_filter(path: PathBuf, wrap: MarkdownWrap, source: FilterSource) -> Ex
     )
 }
 
-fn worktree_config(path: &Path, root: Option<&Path>) -> crate::diagnostic::Result> {
-    let Some(candidate) = discover_config_within(path, root) else {
-        return Ok(Some(Config::default()));
-    };
-    let config = Config::from_path(&candidate)?;
-    Ok((!config.excludes(path)).then(|| config.for_formatted_path(path)))
-}
-
 fn run_git_filter_adopt(
     repo: Option,
     yamark: Option,
@@ -372,18 +307,17 @@ fn adopt_git_filter(
 
     let attributes_path = repo_root.join(".gitattributes");
     let previous_attributes = read_optional_file(&attributes_path)?;
-    match adopt_git_filter_inner(&repo_root, yamark, width, paths, &attributes_path) {
-        Ok(summary) => Ok(summary),
-        Err(err @ worktree::InstallError::IndexBusy(_)) => Err(format!(
-            "{err}\nAdoption remains staged. Review the index and working tree before continuing."
-        )),
-        Err(err) => match rollback_adopt(&repo_root, &attributes_path, previous_attributes) {
+    let result = adopt_git_filter_inner(&repo_root, yamark, width, paths, &attributes_path);
+    if let Err(err) = result {
+        let rollback = rollback_adopt(&repo_root, &attributes_path, previous_attributes);
+        return match rollback {
             Ok(()) => Err(format!("{err}\nRolled back yamark Git filter adoption.")),
             Err(rollback_err) => Err(format!(
                 "{err}\nRollback failed: {rollback_err}\nReview the repository before continuing."
             )),
-        },
+        };
     }
+    result
 }
 
 fn adopt_git_filter_inner(
@@ -392,15 +326,13 @@ fn adopt_git_filter_inner(
     width: usize,
     paths: Vec,
     attributes_path: &Path,
-) -> Result {
+) -> Result {
     configure_git_filter(repo_root, yamark, width)?;
     let patterns = git_filter_attribute_patterns(repo_root, paths)?;
     let added = append_missing_attribute_lines(attributes_path, &patterns)?;
-    let targets = tracked_yamark_filter_paths(repo_root, BlobSource::Index)?;
+    let targets = tracked_yamark_filter_paths(repo_root)?;
     if targets.is_empty() {
-        return Err("no tracked Markdown files match filter=yamark-md"
-            .to_owned()
-            .into());
+        return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
 
     run_git_os(
@@ -413,7 +345,8 @@ fn adopt_git_filter_inner(
     )?;
     run_git_with_paths(repo_root, &["add", "--renormalize", "--"], &targets)?;
     verify_index_roundtrip(repo_root, &targets, width)?;
-    worktree::Checkout::Adopt.install(repo_root, &targets)?;
+    write_smudged_worktree(repo_root, &targets)?;
+    ensure_no_unstaged_changes(repo_root)?;
 
     Ok(format!(
         "Adopted yamark Git filter in {}\nUpdated .gitattributes with {added} new attribute pattern(s)\nStaged .gitattributes and {} normalized Markdown file(s).\n\nReview and commit with:\n  git diff --cached\n  git commit -m \"Normalize Markdown with yamark Git filter\"",
@@ -433,14 +366,13 @@ fn join_git_filter(
     ensure_shared_yamark_attributes(&repo_root)?;
     configure_git_filter(&repo_root, yamark, width)?;
 
-    let targets = tracked_yamark_filter_paths(&repo_root, BlobSource::Index)?;
+    let targets = tracked_yamark_filter_paths(&repo_root)?;
     if targets.is_empty() {
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
     verify_head_roundtrip(&repo_root, &targets, width)?;
-    worktree::Checkout::Join
-        .install(&repo_root, &targets)
-        .map_err(|err| err.to_string())?;
+    write_smudged_worktree(&repo_root, &targets)?;
+    ensure_clean_worktree(&repo_root)?;
 
     Ok(format!(
         "Joined yamark Git filter in {}\nConfigured local filter driver and checked {} committed Markdown file(s).",
@@ -452,7 +384,7 @@ fn join_git_filter(
 fn check_git_filter(repo: Option, width: usize) -> Result {
     let (repo_root, _) = git_filter_repo_paths(repo)?;
     ensure_shared_yamark_attributes(&repo_root)?;
-    let targets = tracked_yamark_filter_paths(&repo_root, BlobSource::Head)?;
+    let targets = tracked_yamark_filter_paths(&repo_root)?;
     if targets.is_empty() {
         return Err("no tracked Markdown files match filter=yamark-md".to_owned());
     }
@@ -481,16 +413,11 @@ enum BlobSource {
 }
 
 impl BlobSource {
-    fn tree(self) -> &'static str {
-        match self {
-            Self::Head => "HEAD",
-            Self::Index => "",
-        }
-    }
-
     fn spec(self, path: &Path) -> OsString {
-        let mut spec = OsString::from(self.tree());
-        spec.push(":");
+        let mut spec = OsString::from(match self {
+            Self::Head => "HEAD:",
+            Self::Index => ":",
+        });
         spec.push(path);
         spec
     }
@@ -511,31 +438,21 @@ fn configure_git_filter(
     run_git_config(
         repo_root,
         "filter.yamark-md.clean",
-        &default_clean_command(&yamark),
+        &format!("{yamark} git-filter clean --stdin-filename %f"),
     )?;
     run_git_config(
         repo_root,
         "filter.yamark-md.smudge",
-        &format!("{}{width}", default_smudge_prefix(&yamark)),
+        &format!(
+            "{yamark} git-filter smudge --stdin-filename %f --markdown-wrap-at-column {width}"
+        ),
     )?;
     run_git_config(repo_root, "filter.yamark-md.required", "true")?;
-    run_git_config(
-        repo_root,
-        "filter.yamark-md.process",
-        &format!("{yamark} git-filter process"),
-    )
-}
-
-fn default_clean_command(yamark: &str) -> String {
-    format!("{yamark} git-filter clean --stdin-filename %f")
-}
-
-fn default_smudge_prefix(yamark: &str) -> String {
-    format!("{yamark} git-filter smudge --stdin-filename %f --markdown-wrap-at-column ")
+    run_git_config(repo_root, "merge.renormalize", "true")
 }
 
 fn ensure_clean_worktree(repo_root: &Path) -> Result<(), String> {
-    let status = git_stdout(repo_root, ["--no-optional-locks", "status", "--porcelain"])?;
+    let status = git_stdout(repo_root, ["status", "--porcelain"])?;
     if status.is_empty() {
         Ok(())
     } else {
@@ -546,7 +463,7 @@ fn ensure_clean_worktree(repo_root: &Path) -> Result<(), String> {
 }
 
 fn ensure_no_unstaged_changes(repo_root: &Path) -> Result<(), String> {
-    let diff = git_stdout(repo_root, ["--no-optional-locks", "diff", "--name-only"])?;
+    let diff = git_stdout(repo_root, ["diff", "--name-only"])?;
     if diff.is_empty() {
         Ok(())
     } else {
@@ -563,8 +480,8 @@ fn ensure_no_local_yamark_filter_setup(
     for key in [
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
-        "filter.yamark-md.process",
         "filter.yamark-md.required",
+        "merge.renormalize",
     ] {
         if local_git_config_count(repo_root, key)? > 0 {
             return Err(format!(
@@ -608,70 +525,58 @@ fn ensure_not_behind_upstream(repo_root: &Path) -> Result<(), String> {
 }
 
 fn ensure_shared_yamark_attributes(repo_root: &Path) -> Result<(), String> {
-    let attributes = git_stdout(repo_root, ["cat-file", "blob", "HEAD:.gitattributes"])?;
+    let attributes_path = repo_root.join(".gitattributes");
+    let attributes = fs::read_to_string(&attributes_path).map_err(|err| {
+        format!(
+            "{}: failed to read shared Git attributes: {err}",
+            attributes_path.display()
+        )
+    })?;
     if attributes.lines().any(line_has_yamark_filter_attribute) {
         Ok(())
     } else {
-        Err("HEAD:.gitattributes does not contain filter=yamark-md; run yamark git-filter adopt in the maintainer checkout first".to_owned())
+        Err(format!(
+            "{} does not contain filter=yamark-md; run yamark git-filter adopt in the maintainer checkout first",
+            attributes_path.display()
+        ))
     }
 }
 
-fn tracked_yamark_filter_paths(
-    repo_root: &Path,
-    source: BlobSource,
-) -> Result, String> {
+fn tracked_yamark_filter_paths(repo_root: &Path) -> Result, String> {
     // NUL records contain native filename bytes, not UTF-8 text or Git's
     // presentation quoting. Each check-attr response is path, name, then value.
-    let mut attr = process::git_query(repo_root);
-    attr.arg("check-attr");
-    let legacy_index;
-    let tracked = match source {
-        BlobSource::Head => {
-            if process::supports_tree_attributes(repo_root)? {
-                attr.arg("--source=HEAD");
-            } else {
-                legacy_index = process::TreeIndex::read_tree(repo_root, "HEAD")?;
-                attr = legacy_index.git(repo_root);
-                attr.args(["check-attr", "--cached"]);
-            }
-            process::git_stdout_bytes(repo_root, ["ls-tree", "-rz", "--full-tree", "HEAD"])?
-        }
-        BlobSource::Index => process::git_stdout_bytes(repo_root, ["ls-files", "--stage", "-z"])?,
-    };
-    let mut names = Vec::new();
-    for entry in tracked
+    let tracked = git_stdout_bytes(repo_root, ["ls-files", "-z"])?;
+    let mut paths = Vec::new();
+    for path in tracked
         .split(|byte| *byte == 0)
-        .filter(|entry| !entry.is_empty())
+        .filter(|path| !path.is_empty())
     {
-        let (name, [mode, _, stage_or_oid]) = process::entry_fields(entry)?;
-        if !matches!(mode, b"100644" | b"100755")
-            || (matches!(source, BlobSource::Index) && stage_or_oid != b"0")
-        {
-            continue;
-        }
-        let path = Path::new(
-            driver::native_path(name).map_err(|err| format!("git path was not UTF-8: {err}"))?,
+        #[cfg(unix)]
+        let path = {
+            use std::os::unix::ffi::OsStrExt;
+            PathBuf::from(std::ffi::OsStr::from_bytes(path))
+        };
+        #[cfg(not(unix))]
+        let path = PathBuf::from(
+            std::str::from_utf8(path).map_err(|err| format!("git path was not UTF-8: {err}"))?,
         );
-        if crate::core::document::FileKind::for_path(path)
-            == crate::core::document::FileKind::Markdown
+        if crate::core::document::FileKind::for_path(&path)
+            != crate::core::document::FileKind::Markdown
         {
-            names.extend_from_slice(name);
-            names.push(0);
+            continue;
         }
-    }
-    attr.args(["-z", "--stdin", "filter"])
-        .stderr(std::process::Stdio::piped());
-    let output = process::checked_stdout(driver::run_with_input(&mut attr, &names))?;
-    let mut fields = output.split(|&byte| byte == 0);
-    let mut paths = Vec::new();
-    while let Some(name) = fields.next().filter(|name| !name.is_empty()) {
-        let (Some(b"filter"), Some(value)) = (fields.next(), fields.next()) else {
-            return Err("invalid git check-attr record".to_owned());
-        };
-        if value == b"yamark-md" {
-            paths.push(PathBuf::from(
-                driver::native_path(name).map_err(|err| err.to_string())?,
-            ));
+        let output = git_stdout_bytes(
+            repo_root,
+            [
+                OsString::from("check-attr"),
+                OsString::from("-z"),
+                OsString::from("filter"),
+                OsString::from("--"),
+                path.as_os_str().to_owned(),
+            ],
+        )?;
+        if output.split(|byte| *byte == 0).nth(2) == Some(b"yamark-md") {
+            paths.push(path);
         }
     }
     Ok(paths)
@@ -692,30 +597,21 @@ fn verify_roundtrip(
     width: usize,
 ) -> Result<(), String> {
     let mut failures = Vec::new();
-    let mut configs = checkout::CheckoutConfigs::default();
     for path in paths {
+        // Discover configuration beside the target file even when --repo
+        // selects a repository outside the caller's working directory.
         let source_path = repo_root.join(path);
-        let Some(file) = configs
-            .for_path(repo_root, source.tree(), path)
+        // Excluded files pass through the filters byte for byte.
+        let excluded = load_config_for_formatted_path(&source_path, None)
             .map_err(|err| err.diagnostic.render())?
-        else {
-            return Err(format!(
-                "{}: cannot verify a blob with conflicted settings",
-                path.display()
-            ));
-        };
-        let Some(config) = file.included() else {
+            .excludes(&source_path);
+        if excluded {
             continue;
-        };
+        }
         let blob = git_blob(repo_root, source, path)?;
-        let smudged = format_git_filter_text(
-            &source_path,
-            blob.clone(),
-            MarkdownWrap::Column(width),
-            &config,
-        )?;
-        let cleaned =
-            format_git_filter_text(&source_path, smudged, MarkdownWrap::Sentence, &config)?;
+        let smudged =
+            format_git_filter_text(&source_path, blob.clone(), MarkdownWrap::Column(width))?;
+        let cleaned = format_git_filter_text(&source_path, smudged, MarkdownWrap::Sentence)?;
         if cleaned != blob {
             failures.push(format!(
                 "{}: roundtrip failure: clean(smudge(blob)) != blob",
@@ -730,6 +626,36 @@ fn verify_roundtrip(
     }
 }
 
+fn write_smudged_worktree(repo_root: &Path, paths: &[PathBuf]) -> Result<(), String> {
+    // Let Git apply text/eol attributes and core.autocrlf before the configured
+    // smudge filter. Writing formatted blob bytes directly bypasses that step.
+    for path in paths {
+        // Excluded files returned by the smudge filter may not be UTF-8.
+        let smudged = git_stdout_bytes(
+            repo_root,
+            [
+                OsString::from("cat-file"),
+                OsString::from("--filters"),
+                BlobSource::Index.spec(path),
+            ],
+        )?;
+        let worktree_path = repo_root.join(path);
+        fs::write(&worktree_path, smudged).map_err(|err| {
+            format!(
+                "{}: failed to write smudged working-tree file: {err}",
+                worktree_path.display()
+            )
+        })?;
+    }
+    // Refresh Git's cached file metadata as part of checkout. A plain write can
+    // leave a CRLF file marked dirty even when its cleaned blob is unchanged.
+    run_git_with_paths(
+        repo_root,
+        &["checkout-index", "--force", "--index", "--"],
+        paths,
+    )
+}
+
 fn git_blob(repo_root: &Path, source: BlobSource, path: &Path) -> Result {
     git_stdout(repo_root, [OsString::from("show"), source.spec(path)])
 }
@@ -738,13 +664,18 @@ fn format_git_filter_text(
     path: &Path,
     input: String,
     wrap: MarkdownWrap,
-    config: &Config,
 ) -> Result {
-    format_source_with_config(
+    let options = FormatOptions {
+        markdown_wrap: wrap,
+        markdown_compact_tables: true,
+        respect_frontmatter_markdown_options: false,
+        ..FormatOptions::default()
+    };
+    format_source_for_path_with_overrides(
         path,
         input,
-        filter_options(wrap),
-        config,
+        options,
+        None,
         FormatExecutionOptions {
             markdown_wrap_override: Some(wrap),
             ..FormatExecutionOptions::default()
@@ -780,8 +711,23 @@ fn rollback_adopt(
     previous_attributes: Option,
 ) -> Result<(), String> {
     let mut errors = Vec::new();
-    if let Err(err) = git_stdout(repo_root, ["reset", "-q", "--mixed", "HEAD"]) {
-        errors.push(err);
+    for args in [
+        vec![
+            OsString::from("reset"),
+            OsString::from("-q"),
+            OsString::from("--mixed"),
+            OsString::from("HEAD"),
+        ],
+        vec![
+            OsString::from("checkout"),
+            OsString::from("-q"),
+            OsString::from("--"),
+            OsString::from("."),
+        ],
+    ] {
+        if let Err(err) = run_git_os(repo_root, &args) {
+            errors.push(err);
+        }
     }
     if let Err(err) = restore_optional_file(attributes_path, previous_attributes) {
         errors.push(err);
@@ -800,8 +746,8 @@ fn unset_git_filter_config(repo_root: &Path) -> Result {
     [
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
-        "filter.yamark-md.process",
         "filter.yamark-md.required",
+        "merge.renormalize",
     ]
     .into_iter()
     .map(|key| unset_git_config_key(repo_root, key))
diff --git a/src/cli/git_filter/checkout.rs b/src/cli/git_filter/checkout.rs
deleted file mode 100644
index 565d0cbe..00000000
--- a/src/cli/git_filter/checkout.rs
+++ /dev/null
@@ -1,393 +0,0 @@
-//! Resolve checkout configuration from the incoming Git tree or stage-zero index.
-//! Git may invoke smudge before materializing the configuration in the worktree.
-
-use std::collections::{BTreeMap, HashMap, VecDeque};
-use std::ffi::OsString;
-use std::fs::File;
-use std::io::{self, Read, Seek, SeekFrom};
-use std::path::{Component, Path, PathBuf};
-use std::process::Command;
-
-use super::driver::{native_path, run_with_input};
-use super::process::{entry_fields, git_stdout, git_stdout_bytes};
-use crate::config::Config;
-use crate::diagnostic::{Result, YamarkError};
-
-struct IndexSnapshot {
-    version: IndexVersion,
-    entries: BTreeMap,
-}
-
-#[derive(PartialEq)]
-enum IndexVersion {
-    Missing,
-    Trailer([u8; 32]),
-    Unhashed(Vec),
-}
-
-impl IndexVersion {
-    fn read(path: &Path) -> io::Result {
-        let mut index = match File::open(path) {
-            Ok(file) => file,
-            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::Missing),
-            Err(err) => return Err(err),
-        };
-        // Even an empty index has a 12-byte header and a SHA-1 or SHA-256
-        // checksum. Its final 32 bytes include the entire checksum for either.
-        let mut trailer = [0; 32];
-        index.seek(SeekFrom::End(-32))?;
-        index.read_exact(&mut trailer)?;
-        if trailer[12..] != [0; 20] {
-            return Ok(Self::Trailer(trailer));
-        }
-        // index.skipHash writes zeroes. Compare those indexes by content so
-        // equal sizes and filesystem timestamps cannot conceal an edit.
-        index.rewind()?;
-        let mut bytes = Vec::new();
-        index.read_to_end(&mut bytes)?;
-        Ok(Self::Unhashed(bytes))
-    }
-}
-
-#[derive(Clone)]
-enum Entry {
-    File(String),
-    Link(String),
-    Conflict,
-}
-
-impl IndexSnapshot {
-    fn load(repo: &Path, version: IndexVersion) -> Result {
-        let records = git_stdout_bytes(repo, ["ls-files", "--stage", "--full-name", "-z"])
-            .map_err(YamarkError::new)?;
-        let mut entries = BTreeMap::new();
-        for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-            let (name, [mode, oid, stage]) = entry_fields(record).map_err(YamarkError::new)?;
-            let Ok(name) = native_path(name) else {
-                continue;
-            };
-            let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
-            let entry = match (stage, mode) {
-                (b"0", b"100644" | b"100755") => Entry::File(oid.to_owned()),
-                (b"0", b"120000") => Entry::Link(oid.to_owned()),
-                (b"0", _) => continue,
-                _ => Entry::Conflict,
-            };
-            entries.insert(PathBuf::from(name), entry);
-        }
-        Ok(Self { version, entries })
-    }
-}
-
-/// A path and its nearest configuration, both from the same Git snapshot.
-pub(super) struct CheckoutPath<'a> {
-    config: &'a Config,
-    relative: &'a Path,
-}
-
-impl CheckoutPath<'_> {
-    pub(super) fn included(self) -> Option {
-        let excluded = self
-            .config
-            .format
-            .exclude
-            .as_ref()
-            .is_some_and(|patterns| patterns.excludes(self.relative));
-        (!excluded).then(|| self.config.for_relative_path(self.relative))
-    }
-}
-
-type DirectoryConfig = Option<(PathBuf, Config)>;
-
-#[derive(Default)]
-pub(super) struct CheckoutConfigs {
-    directories: HashMap<(String, PathBuf), DirectoryConfig>,
-    index_path: Option,
-    index: Option,
-}
-
-impl CheckoutConfigs {
-    fn refresh_index(&mut self, repo: &Path) -> Result<()> {
-        let index_path = match &self.index_path {
-            Some(path) => path,
-            None => {
-                let bytes = git_stdout_bytes(repo, ["rev-parse", "--git-path", "index"])
-                    .map_err(YamarkError::new)?;
-                let path = native_path(bytes.strip_suffix(b"\n").unwrap_or(&bytes))
-                    .map_err(|err| YamarkError::new(err.to_string()))?;
-                self.index_path.insert(repo.join(path))
-            }
-        };
-        // Close the handle before invoking Git. An open index can prevent
-        // another process from replacing it on Windows.
-        let version = IndexVersion::read(index_path)
-            .map_err(|err| YamarkError::new(err.to_string()).with_path(index_path))?;
-        if self
-            .index
-            .as_ref()
-            .is_none_or(|index| index.version != version)
-        {
-            self.index = Some(IndexSnapshot::load(repo, version)?);
-            self.directories.retain(|(tree, _), _| !tree.is_empty());
-        }
-        Ok(())
-    }
-
-    pub(super) fn for_staged_blob<'a>(
-        &'a mut self,
-        repo: &Path,
-        path: &'a Path,
-        blob: Option<&[u8]>,
-    ) -> Result>> {
-        let Some(blob) = blob else { return Ok(None) };
-        self.refresh_index(repo)?;
-        let index = self.index.as_ref().expect("refreshed index");
-        if matches!(index.entries.get(path), Some(Entry::File(oid)) if oid.as_bytes() == blob) {
-            self.for_selected_source(repo, "", path)
-        } else {
-            Ok(None)
-        }
-    }
-
-    pub(super) fn for_path<'a>(
-        &'a mut self,
-        repo: &Path,
-        tree: &str,
-        path: &'a Path,
-    ) -> Result>> {
-        if tree.is_empty() {
-            self.refresh_index(repo)?;
-        }
-        self.for_selected_source(repo, tree, path)
-    }
-
-    fn for_selected_source<'a>(
-        &'a mut self,
-        repo: &Path,
-        tree: &str,
-        path: &'a Path,
-    ) -> Result>> {
-        let path = path.strip_prefix(".").unwrap_or(path);
-        if path.as_os_str().is_empty()
-            || !path
-                .components()
-                .all(|part| matches!(part, Component::Normal(_)))
-        {
-            return Err(YamarkError::new(
-                "Git checkout requires a repository-relative filename",
-            ));
-        }
-        let parent = path.parent().expect("nonempty relative path");
-        let key = (tree.to_owned(), parent.to_owned());
-        use std::collections::hash_map::Entry;
-        let base = match self.directories.entry(key) {
-            Entry::Occupied(entry) => entry.into_mut(),
-            Entry::Vacant(entry) => entry.insert(config_for_directory(
-                repo,
-                tree,
-                parent,
-                self.index.as_ref(),
-            )?),
-        };
-        Ok(base.as_ref().map(|(dir, config)| CheckoutPath {
-            relative: path.strip_prefix(dir).expect("config is an ancestor"),
-            config,
-        }))
-    }
-}
-
-fn config_for_directory(
-    repo: &Path,
-    tree: &str,
-    parent: &Path,
-    index: Option<&IndexSnapshot>,
-) -> Result {
-    let mut candidates = parent.ancestors().map(|dir| dir.join("yamark.toml"));
-    let selected = if tree.is_empty() {
-        let index = index.expect("staged configuration needs an index snapshot");
-        candidates.find_map(|path| index.entries.get(&path).cloned().map(|entry| (path, entry)))
-    } else {
-        nearest_tree_entry(repo, tree, &candidates.collect::>())?
-    };
-    let Some((config_path, entry)) = selected else {
-        return Ok(Some((PathBuf::new(), Config::default())));
-    };
-    let bytes = match entry {
-        Entry::Conflict => return Ok(None),
-        Entry::File(oid) => git_stdout_bytes(repo, ["cat-file", "blob", &oid])
-            .map(Some)
-            .map_err(YamarkError::new),
-        Entry::Link(oid) if tree.is_empty() => {
-            index_link_contents(repo, index.expect("staged config"), &config_path, &oid)
-        }
-        Entry::Link(_) => tree_symlink_contents(repo, tree, &config_path).map(Some),
-    }
-    .map_err(|err| err.with_path(&config_path))?;
-    let Some(bytes) = bytes else { return Ok(None) };
-    let input = std::str::from_utf8(&bytes).map_err(|err| {
-        YamarkError::new(format!("invalid config encoding: {err}")).with_path(&config_path)
-    })?;
-    let config = Config::from_toml_str(input).map_err(|err| err.with_path(&config_path))?;
-    let dir = config_path.parent().expect("a config has a parent");
-    Ok(Some((dir.to_owned(), config)))
-}
-
-fn nearest_tree_entry(
-    repo: &Path,
-    tree: &str,
-    candidates: &[PathBuf],
-) -> Result> {
-    let mut args = [
-        "--literal-pathspecs",
-        "ls-tree",
-        "--full-tree",
-        "-z",
-        "--end-of-options",
-        tree,
-        "--",
-    ]
-    .map(OsString::from)
-    .to_vec();
-    args.extend(candidates.iter().map(|path| git_path(path)));
-    let records = git_stdout_bytes(repo, args).map_err(YamarkError::new)?;
-    let mut nearest = None;
-    for record in records.split(|&byte| byte == 0).filter(|r| !r.is_empty()) {
-        let (filename, [mode, _, oid]) = entry_fields(record).map_err(YamarkError::new)?;
-        let path =
-            Path::new(native_path(filename).map_err(|err| YamarkError::new(err.to_string()))?);
-        let Some(rank) = candidates.iter().position(|candidate| candidate == path) else {
-            continue;
-        };
-        let oid = std::str::from_utf8(oid).map_err(|err| YamarkError::new(err.to_string()))?;
-        let entry = match mode {
-            b"100644" | b"100755" => Entry::File(oid.to_owned()),
-            b"120000" => Entry::Link(oid.to_owned()),
-            _ => continue,
-        };
-        if nearest.as_ref().is_none_or(|(best, _)| rank < *best) {
-            nearest = Some((rank, entry));
-        }
-    }
-    Ok(nearest.map(|(rank, entry)| (candidates[rank].clone(), entry)))
-}
-
-fn tree_symlink_contents(repo: &Path, tree: &str, path: &Path) -> Result> {
-    // A tree expression can itself be a subtree, e.g. HEAD:docs. Use its OID
-    // before appending the Git path. NUL input also accepts literal newlines.
-    let tree = git_stdout(repo, ["rev-parse", "--verify", "--end-of-options", tree])
-        .map_err(YamarkError::new)?;
-    let mut query = tree.trim_end().as_bytes().to_vec();
-    query.push(b':');
-    query.extend_from_slice(git_path(path).as_encoded_bytes());
-    let mut command = Command::new("git");
-    command
-        .arg("-C")
-        .arg(repo)
-        .args(["cat-file", "--batch=%(objecttype)", "--follow-symlinks"]);
-    if query.contains(&b'\n') {
-        command.arg("-z");
-        query.push(0);
-    } else {
-        query.push(b'\n');
-    }
-    let output =
-        run_with_input(&mut command, &query).map_err(|err| YamarkError::new(err.to_string()))?;
-    if !output.status.success() {
-        return Err(YamarkError::new(format!(
-            "git cat-file failed with {}",
-            output.status
-        )));
-    }
-    if output.stdout.starts_with(b"symlink ") {
-        return Err(YamarkError::new(
-            "config symlink points outside the checkout",
-        ));
-    }
-    output
-        .stdout
-        .strip_prefix(b"blob\n")
-        .and_then(|data| data.strip_suffix(b"\n"))
-        .map(Vec::from)
-        .ok_or_else(|| YamarkError::new("config symlink has no file target in checkout"))
-}
-
-fn index_link_contents<'a>(
-    repo: &Path,
-    index: &'a IndexSnapshot,
-    path: &Path,
-    mut oid: &'a str,
-) -> Result>> {
-    let mut current = path.to_path_buf();
-    let mut pending = VecDeque::new();
-    let mut links = 0;
-    loop {
-        let bytes = git_stdout_bytes(repo, ["cat-file", "blob", oid]).map_err(YamarkError::new)?;
-        links += 1;
-        if links > 40 {
-            return Err(YamarkError::new("too many config symlinks in checkout"));
-        }
-        current.pop();
-        let target =
-            Path::new(native_path(&bytes).map_err(|err| YamarkError::new(err.to_string()))?);
-        for part in target.components().rev() {
-            pending.push_front(part.as_os_str().to_owned());
-        }
-        loop {
-            let next = pending
-                .pop_front()
-                .ok_or_else(|| YamarkError::new("config symlink has no file target in checkout"))?;
-            match Path::new(&next).components().next() {
-                Some(Component::CurDir) => continue,
-                Some(Component::ParentDir) if !current.as_os_str().is_empty() => {
-                    // An index represents a directory by its tracked descendants.
-                    if !index
-                        .entries
-                        .range(current.clone()..)
-                        .next()
-                        .is_some_and(|(path, _)| path.starts_with(¤t))
-                    {
-                        return Err(YamarkError::new(
-                            "config symlink traverses a missing directory",
-                        ));
-                    }
-                    current.pop();
-                    continue;
-                }
-                Some(Component::Normal(name)) => current.push(name),
-                _ => {
-                    return Err(YamarkError::new(
-                        "config symlink points outside the checkout",
-                    ));
-                }
-            }
-            match index.entries.get(¤t) {
-                Some(Entry::Conflict) => return Ok(None),
-                Some(Entry::File(oid)) if pending.is_empty() => {
-                    return git_stdout_bytes(repo, ["cat-file", "blob", oid])
-                        .map(Some)
-                        .map_err(YamarkError::new);
-                }
-                Some(Entry::File(_)) => {
-                    return Err(YamarkError::new("config symlink traverses a regular file"));
-                }
-                Some(Entry::Link(next)) => {
-                    oid = next;
-                    break;
-                }
-                None => {}
-            }
-        }
-    }
-}
-
-// Git object expressions and literal pathspecs use '/' on Windows as well.
-fn git_path(path: &Path) -> OsString {
-    let mut out = OsString::new();
-    for name in path.iter() {
-        if !out.is_empty() {
-            out.push("/");
-        }
-        out.push(name);
-    }
-    out
-}
diff --git a/src/cli/git_filter/driver.rs b/src/cli/git_filter/driver.rs
deleted file mode 100644
index ad86049c..00000000
--- a/src/cli/git_filter/driver.rs
+++ /dev/null
@@ -1,335 +0,0 @@
-//! Git's v2 process filter supplies the tree being checked out for each smudge.
-//! Keep the configured single-file commands authoritative, including -c overrides.
-
-use std::ffi::OsStr;
-use std::io::{self, BufRead, Read, Write};
-use std::path::Path;
-use std::process::{Command, ExitCode, Stdio};
-
-use super::checkout::{CheckoutConfigs, CheckoutPath};
-use crate::core::document::{FileKind, MarkdownWrap};
-
-pub(super) const SOURCE_BLOB_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_BLOB";
-pub(super) const SOURCE_TREE_ENV: &str = "YAMARK_GIT_FILTER_SOURCE_TREE";
-
-pub(super) fn run() -> ExitCode {
-    match serve() {
-        Ok(()) => ExitCode::SUCCESS,
-        Err(err) => {
-            eprintln!("error: Git filter process: {err}");
-            ExitCode::FAILURE
-        }
-    }
-}
-
-fn serve() -> io::Result<()> {
-    let mut input = io::stdin().lock();
-    let mut output = io::stdout().lock();
-    let hello = read_headers(&mut input)?;
-    if hello.first().map(Vec::as_slice) != Some(b"git-filter-client")
-        || !hello.iter().any(|line| line == b"version=2")
-    {
-        return Err(io::Error::other("expected git-filter-client version 2"));
-    }
-    write_section(&mut output, &[b"git-filter-server\n", b"version=2\n"])?;
-    let clean = driver_command("filter.yamark-md.clean")?;
-    let smudge = driver_command("filter.yamark-md.smudge")?;
-    let exe = std::env::current_exe()?;
-    let quoted_exe = super::shell_quote_path(&exe).map_err(io::Error::other)?;
-    let mut names = vec![quoted_exe.as_str()];
-    if [clean.as_deref(), smudge.as_deref()]
-        .into_iter()
-        .flatten()
-        .any(|command| command.starts_with("yamark git-filter "))
-        && path_resolves_to_serving_yamark(&exe)?
-    {
-        names.push("yamark");
-    }
-    let clean = clean.map(|command| {
-        if names
-            .iter()
-            .any(|name| command == super::default_clean_command(name))
-        {
-            Driver::Yamark(MarkdownWrap::Sentence)
-        } else {
-            Driver::Custom(custom_alias(&command))
-        }
-    });
-    let smudge = smudge.map(|command| {
-        if let Some(width) = names.iter().find_map(|name| {
-            let width = command.strip_prefix(&super::default_smudge_prefix(name))?;
-            super::super::parse_positive_usize(width).ok()
-        }) {
-            Driver::Yamark(MarkdownWrap::Column(width))
-        } else {
-            Driver::Custom(custom_alias(&command))
-        }
-    });
-    let mut configs = CheckoutConfigs::default();
-    let caps = read_headers(&mut input)?;
-    let accepted: Vec<_> = caps
-        .iter()
-        .filter_map(|cap| match cap.as_slice() {
-            b"capability=clean" if clean.is_some() => Some(b"capability=clean\n".as_slice()),
-            b"capability=smudge" if smudge.is_some() => Some(b"capability=smudge\n".as_slice()),
-            _ => None,
-        })
-        .collect();
-    write_section(&mut output, &accepted)?;
-
-    while !input.fill_buf()?.is_empty() {
-        let fields = read_headers(&mut input)?;
-        let mut contents = Vec::new();
-        while read_packet(&mut input, &mut contents)? {}
-        match filter_file(
-            &fields,
-            contents,
-            clean.as_ref(),
-            smudge.as_ref(),
-            &mut configs,
-        ) {
-            Ok(bytes) => {
-                write_section(&mut output, &[b"status=success\n"])?;
-                for chunk in bytes.chunks(65516) {
-                    write_packet(&mut output, chunk)?;
-                }
-                output.write_all(b"00000000")?;
-                output.flush()?;
-            }
-            Err(err) => {
-                eprintln!("error: Git filter process: {err}");
-                write_section(&mut output, &[b"status=error\n"])?;
-            }
-        }
-    }
-    Ok(())
-}
-
-enum Driver {
-    Yamark(MarkdownWrap),
-    Custom(String),
-}
-
-/// Resolve the documented bare command in the same shell Git uses to run it.
-/// The shell's file identity test also handles symlinks and Git for Windows paths.
-fn path_resolves_to_serving_yamark(exe: &Path) -> io::Result {
-    // A shell function is reported as the bare name, without a file path.
-    Ok(Command::new("git")
-        .args([
-            "-c",
-            r#"alias.yamark-lookup=!p=$(command -v yamark) && test "$p" != yamark && test "$p" -ef "$YAMARK_SERVING_EXE""#,
-            "yamark-lookup",
-        ])
-        .env("YAMARK_SERVING_EXE", exe)
-        .stdin(Stdio::null())
-        .stdout(Stdio::null())
-        .status()?
-        .success())
-}
-
-fn filter_file(
-    fields: &[Vec],
-    contents: Vec,
-    clean: Option<&Driver>,
-    smudge: Option<&Driver>,
-    configs: &mut CheckoutConfigs,
-) -> io::Result> {
-    let field = |prefix: &[u8]| fields.iter().find_map(|line| line.strip_prefix(prefix));
-    let path = field(b"pathname=").ok_or_else(|| io::Error::other("missing pathname"))?;
-    let (command, tree) = match field(b"command=") {
-        Some(b"clean") => (clean, None),
-        Some(b"smudge") => (smudge, Some(field(b"treeish=").unwrap_or(b""))),
-        _ => return Err(io::Error::other("unknown filter command")),
-    };
-    let command = command.ok_or_else(|| io::Error::other("filter command is not configured"))?;
-    let path = Path::new(native_path(path)?);
-    let tree = tree
-        .map(std::str::from_utf8)
-        .transpose()
-        .map_err(io::Error::other)?;
-    let command = match command {
-        Driver::Yamark(wrap) => {
-            if FileKind::for_path(path) != FileKind::Markdown {
-                return Err(io::Error::other(format!(
-                    "{}: unsupported Git filter path",
-                    path.display()
-                )));
-            }
-            let config = match tree {
-                Some(tree) => {
-                    let file = if tree.is_empty() {
-                        configs.for_staged_blob(Path::new("."), path, field(b"blob="))
-                    } else {
-                        configs.for_path(Path::new("."), tree, path)
-                    };
-                    file.map(|file| file.and_then(CheckoutPath::included))
-                }
-                None => super::worktree_config(path, Some(&std::env::current_dir()?)),
-            }
-            .map_err(io::Error::other)?;
-            let Some(config) = config else {
-                return Ok(contents);
-            };
-            let input = super::super::decode_utf8(contents).map_err(|message| {
-                io::Error::other(format!("{}:1:1: error: {message}", path.display()))
-            })?;
-            return super::format_git_filter_text(path, input, *wrap, &config)
-                .map(String::into_bytes)
-                .map_err(io::Error::other);
-        }
-        Driver::Custom(alias) => alias,
-    };
-    let mut child = Command::new("git");
-    // Git supplies the shell on every platform. Keep native path bytes
-    // out of shell source and expand them as one quoted argument.
-    child
-        .arg("-c")
-        .arg(command)
-        .arg("yamark-single-file")
-        .env("YAMARK_GIT_FILTER_PATH", path)
-        .env_remove(SOURCE_TREE_ENV)
-        .env_remove(SOURCE_BLOB_ENV);
-    // A custom command may delegate to Yamark. Give it the same checkout
-    // context as the in-process driver while still running the custom command.
-    if tree == Some("")
-        && let Some(blob) = field(b"blob=")
-    {
-        child.env(
-            SOURCE_BLOB_ENV,
-            std::str::from_utf8(blob).map_err(io::Error::other)?,
-        );
-    }
-    if let Some(tree) = tree {
-        child.env(SOURCE_TREE_ENV, tree);
-    }
-    let result = run_with_input(&mut child, &contents)?;
-    if !result.status.success() {
-        return Err(io::Error::other(format!(
-            "single-file filter exited with {}",
-            result.status
-        )));
-    }
-    Ok(result.stdout)
-}
-
-fn driver_command(key: &str) -> io::Result> {
-    let result = Command::new("git")
-        .args(["config", "--get", key])
-        .output()?;
-    if result.status.code() == Some(1) {
-        return Ok(None);
-    }
-    if !result.status.success() {
-        return Err(io::Error::other(String::from_utf8_lossy(&result.stderr)));
-    }
-    let text = String::from_utf8(result.stdout).map_err(io::Error::other)?;
-    if text == "\n" {
-        return Ok(None);
-    }
-    Ok(Some(text.trim_end_matches('\n').to_owned()))
-}
-
-fn custom_alias(mut template: &str) -> String {
-    let mut alias = String::from("alias.yamark-single-file=!");
-    // Replace a standalone filename argument together with its optional quotes
-    // so the environment expansion always has exactly one layer of quoting.
-    while !template.is_empty() {
-        if let Some(rest) = template
-            .strip_prefix("'%f'")
-            .or_else(|| template.strip_prefix("\"%f\""))
-            .or_else(|| template.strip_prefix("%f"))
-        {
-            alias.push_str("\"$YAMARK_GIT_FILTER_PATH\"");
-            template = rest;
-        } else if let Some(rest) = template.strip_prefix("%%") {
-            alias.push('%');
-            template = rest;
-        } else {
-            let ch = template.chars().next().expect("nonempty template");
-            alias.push(ch);
-            template = &template[ch.len_utf8()..];
-        }
-    }
-    alias
-}
-
-pub(super) fn native_path(bytes: &[u8]) -> io::Result<&OsStr> {
-    #[cfg(unix)]
-    {
-        use std::os::unix::ffi::OsStrExt;
-        Ok(OsStr::from_bytes(bytes))
-    }
-    #[cfg(not(unix))]
-    {
-        std::str::from_utf8(bytes)
-            .map(OsStr::new)
-            .map_err(io::Error::other)
-    }
-}
-
-pub(super) fn run_with_input(
-    command: &mut Command,
-    bytes: &[u8],
-) -> io::Result {
-    let mut child = command
-        .stdin(Stdio::piped())
-        .stdout(Stdio::piped())
-        .spawn()?;
-    let mut stdin = child.stdin.take().expect("piped stdin");
-    std::thread::scope(|scope| {
-        let writer = scope.spawn(move || stdin.write_all(bytes));
-        let output = child.wait_with_output()?;
-        let written = writer.join().expect("stdin writer panicked");
-        if let Err(err) = written
-            && err.kind() != io::ErrorKind::BrokenPipe
-        {
-            return Err(err);
-        }
-        Ok(output)
-    })
-}
-
-fn read_headers(reader: &mut impl Read) -> io::Result>> {
-    let mut packets = Vec::new();
-    loop {
-        let mut bytes = Vec::new();
-        if !read_packet(reader, &mut bytes)? {
-            return Ok(packets);
-        }
-        if bytes.last() == Some(&b'\n') {
-            bytes.pop();
-        }
-        packets.push(bytes);
-    }
-}
-
-/// Append one payload, or report the flush that terminates this section.
-fn read_packet(reader: &mut impl Read, bytes: &mut Vec) -> io::Result {
-    let mut header = [0; 4];
-    reader.read_exact(&mut header)?;
-    if &header == b"0000" {
-        return Ok(false);
-    }
-    let len = std::str::from_utf8(&header)
-        .ok()
-        .and_then(|s| usize::from_str_radix(s, 16).ok())
-        .filter(|len| (4..=65520).contains(len))
-        .ok_or_else(|| io::Error::other("invalid Git packet length"))?;
-    let start = bytes.len();
-    bytes.resize(start + (len - 4), 0);
-    reader.read_exact(&mut bytes[start..])?;
-    Ok(true)
-}
-
-fn write_packet(writer: &mut impl Write, bytes: &[u8]) -> io::Result<()> {
-    write!(writer, "{:04x}", bytes.len() + 4)?;
-    writer.write_all(bytes)
-}
-
-fn write_section(writer: &mut impl Write, lines: &[&[u8]]) -> io::Result<()> {
-    for line in lines {
-        write_packet(writer, line)?;
-    }
-    writer.write_all(b"0000")?;
-    writer.flush()
-}
diff --git a/src/cli/git_filter/process.rs b/src/cli/git_filter/process.rs
index 5fa46eaa..ed46fe8c 100644
--- a/src/cli/git_filter/process.rs
+++ b/src/cli/git_filter/process.rs
@@ -31,111 +31,22 @@ pub(super) fn run_git_os(repo_root: &Path, args: &[OsString]) -> Result<(), Stri
     }
 }
 
-// Git exports its caller's pathspec flags to filters. Each internal query
-// defines its own path selection, independent of the outer Git command.
-pub(super) fn git_query(repo: &Path) -> ProcessCommand {
-    let mut command = ProcessCommand::new("git");
-    command
-        .arg("-C")
-        .arg(repo)
-        .env_remove("GIT_LITERAL_PATHSPECS")
-        .env_remove("GIT_GLOB_PATHSPECS")
-        .env_remove("GIT_NOGLOB_PATHSPECS")
-        .env_remove("GIT_ICASE_PATHSPECS");
-    command
-}
-
 pub(super) fn git_stdout_bytes(
     repo_root: &Path,
     args: impl IntoIterator>,
 ) -> Result, String> {
-    checked_stdout(git_query(repo_root).args(args).output())
-}
-
-pub(super) fn checked_stdout(
-    output: std::io::Result,
-) -> Result, String> {
-    let output = output.map_err(|err| format!("failed to run git: {err}"))?;
+    let output = ProcessCommand::new("git")
+        .arg("-C")
+        .arg(repo_root)
+        .args(args)
+        .output()
+        .map_err(|err| format!("failed to run git: {err}"))?;
     if !output.status.success() {
         return Err(format_git_error("git", output));
     }
     Ok(output.stdout)
 }
 
-/// Git writes repository contents and object names inside this directory.
-pub(super) fn private_tempdir() -> std::io::Result {
-    #[cfg(unix)]
-    {
-        use std::os::unix::fs::PermissionsExt;
-        tempfile::Builder::new()
-            .permissions(std::fs::Permissions::from_mode(0o700))
-            .tempdir()
-    }
-    #[cfg(not(unix))]
-    tempfile::tempdir()
-}
-
-/// Git 2.40 introduced `check-attr --source`. Query the command's advertised
-/// options so vendor builds with backported support can use the read-only path.
-pub(super) fn supports_tree_attributes(repo: &Path) -> Result {
-    // Older Git prints short usage on stderr and exits with status 129.
-    let help = git_query(repo)
-        .args(["check-attr", "-h"])
-        .output()
-        .map_err(|err| format!("failed to run git: {err}"))?;
-    if !help.status.success() && help.status.code() != Some(129) {
-        return Err(format_git_error("git check-attr", help));
-    }
-    Ok([help.stdout, help.stderr]
-        .iter()
-        .any(|text| String::from_utf8_lossy(text).contains("--source")))
-}
-
-/// Older Git reads committed attributes from a private index containing the
-/// tree's entries. These releases discover hooks in the hooks directory.
-pub(super) struct TreeIndex(tempfile::TempDir);
-
-impl TreeIndex {
-    pub(super) fn read_tree(repo: &Path, tree: &str) -> Result {
-        let index = Self(
-            private_tempdir()
-                .map_err(|err| format!("failed to create temporary index directory: {err}"))?,
-        );
-        // Loading a private index is not a change to the user's index.
-        let mut hooks_path = OsString::from("core.hooksPath=");
-        hooks_path.push(index.0.path());
-        checked_stdout(
-            index
-                .git(repo)
-                .arg("-c")
-                .arg(hooks_path)
-                .args(["read-tree", tree])
-                .output(),
-        )?;
-        Ok(index)
-    }
-
-    pub(super) fn git(&self, repo: &Path) -> ProcessCommand {
-        let mut command = git_query(repo);
-        command.env("GIT_INDEX_FILE", self.0.path().join("index"));
-        command
-    }
-}
-
-// ls-tree and ls-files --stage emit three ASCII fields, a tab, and the raw path.
-pub(super) fn entry_fields(record: &[u8]) -> Result<(&[u8], [&[u8]; 3]), &'static str> {
-    let tab = record
-        .iter()
-        .position(|&byte| byte == b'\t')
-        .ok_or("invalid Git entry record")?;
-    let mut fields = record[..tab].split(|&byte| byte == b' ');
-    let [Some(first), Some(second), Some(third), None] = std::array::from_fn(|_| fields.next())
-    else {
-        return Err("invalid Git entry metadata");
-    };
-    Ok((&record[tab + 1..], [first, second, third]))
-}
-
 pub(super) fn local_git_config_count(repo_root: &Path, key: &str) -> Result {
     let output = ProcessCommand::new("git")
         .arg("-C")
diff --git a/src/cli/git_filter/worktree.rs b/src/cli/git_filter/worktree.rs
deleted file mode 100644
index 7d814bcd..00000000
--- a/src/cli/git_filter/worktree.rs
+++ /dev/null
@@ -1,153 +0,0 @@
-//! Install Git's working-tree conversion while retaining local file metadata.
-
-mod index;
-use std::ffi::OsString;
-use std::fs;
-use std::io::{self, Read, Seek, Write};
-use std::path::{Path, PathBuf};
-
-use super::{driver, process};
-
-pub(super) enum Checkout {
-    Adopt,
-    Join,
-}
-
-#[derive(Debug, thiserror::Error)]
-pub(super) enum InstallError {
-    #[error("{0}")]
-    Failed(String),
-    #[error("{0}. Staged changes were preserved.")]
-    IndexBusy(&'static str),
-}
-
-impl From for InstallError {
-    fn from(message: String) -> Self {
-        Self::Failed(message)
-    }
-}
-
-impl From for InstallError {
-    fn from(err: io::Error) -> Self {
-        Self::Failed(err.to_string())
-    }
-}
-
-impl Checkout {
-    pub(super) fn install(self, repo_root: &Path, paths: &[PathBuf]) -> Result<(), InstallError> {
-        // Even --force can skip stat-clean files. Check out all targets to a fresh
-        // prefix so Git applies its conversions and leaves originals intact if
-        // one of the filters fails.
-        let converted = process::private_tempdir().map_err(|err| err.to_string())?;
-        let mut prefix = OsString::from("--prefix=");
-        prefix.push(converted.path());
-        prefix.push("/");
-        let mut names = Vec::new();
-        for path in paths {
-            names.extend_from_slice(path.as_os_str().as_encoded_bytes());
-            names.push(0);
-        }
-        let mut git = process::git_query(repo_root);
-        git.arg("checkout-index")
-            .arg(prefix)
-            .args(["--force", "-z", "--stdin"])
-            .stderr(std::process::Stdio::piped());
-        process::checked_stdout(driver::run_with_input(&mut git, &names))?;
-
-        let mut changed = Vec::new();
-        let result = (|| {
-            for path in paths {
-                let target = repo_root.join(path);
-                let source = converted.path().join(path);
-                let backup = match self {
-                    Self::Adopt => Some(source.as_path()),
-                    Self::Join => None,
-                };
-                if install_checkout_file(&source, &target, backup).map_err(|err| {
-                    format!(
-                        "{}: failed to install smudged file: {err}",
-                        target.display()
-                    )
-                })? {
-                    changed.push(path.as_path());
-                }
-            }
-            index::refresh(repo_root, &changed)?;
-            match self {
-                Self::Adopt => super::ensure_no_unstaged_changes(repo_root),
-                Self::Join => super::ensure_clean_worktree(repo_root),
-            }
-            .map_err(InstallError::from)
-        })();
-        if let Err(InstallError::Failed(err)) = &result
-            && matches!(self, Self::Adopt)
-        {
-            for path in changed {
-                let target = repo_root.join(path);
-                install_checkout_file(&converted.path().join(path), &target, None).map_err(
-                    |restore| format!("{err}\nFailed to restore {}: {restore}", target.display()),
-                )?;
-            }
-        }
-        result
-    }
-}
-
-/// Write through an existing regular file handle to preserve its ACL, owner
-/// and permissions. A hard-linked file can be kept as-is, but replacing its
-/// bytes in place would also edit another path.
-fn install_checkout_file(source: &Path, target: &Path, backup: Option<&Path>) -> io::Result {
-    let converted = fs::read(source)?;
-    let mut options = fs::OpenOptions::new();
-    options.read(true);
-    #[cfg(unix)]
-    {
-        use std::os::unix::fs::OpenOptionsExt;
-        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
-    }
-    #[cfg(windows)]
-    {
-        use std::os::windows::fs::OpenOptionsExt;
-        options.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);
-    }
-    let open = |options: &fs::OpenOptions| -> io::Result {
-        let file = options.open(target)?;
-        if !file.metadata()?.is_file() {
-            return Err(io::Error::other("expected a regular file"));
-        }
-        Ok(file)
-    };
-    let mut current = Vec::new();
-    open(&options)?.read_to_end(&mut current)?;
-    if current == converted {
-        return Ok(false);
-    }
-    let mut file = open(options.write(true))?;
-    #[cfg(unix)]
-    let links = std::os::unix::fs::MetadataExt::nlink(&file.metadata()?);
-    #[cfg(windows)]
-    let links = winapi_util::file::information(&file)?.number_of_links();
-    #[cfg(any(unix, windows))]
-    if links > 1 {
-        return Err(io::Error::other(
-            "cannot rewrite a file with multiple hard links",
-        ));
-    }
-    if let Some(backup) = backup {
-        fs::write(backup, ¤t)?;
-    }
-    let mut write = |bytes: &[u8]| -> io::Result<()> {
-        file.rewind()?;
-        file.write_all(bytes)?;
-        file.set_len(bytes.len() as u64)
-    };
-    if let Err(err) = write(&converted) {
-        write(¤t).map_err(|restore| {
-            io::Error::other(format!(
-                "{err}; failed to restore original bytes: {restore}"
-            ))
-        })?;
-        return Err(err);
-    }
-    Ok(true)
-}
diff --git a/src/cli/git_filter/worktree/index.rs b/src/cli/git_filter/worktree/index.rs
deleted file mode 100644
index 7f860cd3..00000000
--- a/src/cli/git_filter/worktree/index.rs
+++ /dev/null
@@ -1,118 +0,0 @@
-//! Refresh working-tree stat data without restaging files or undoing a
-//! concurrent edit to the index.
-
-use std::collections::HashSet;
-use std::ffi::OsString;
-use std::fs;
-use std::io::{self, Read, Write};
-use std::path::Path;
-
-use super::{InstallError, driver, process};
-
-pub(super) fn refresh(repo_root: &Path, changed: &[&Path]) -> Result<(), InstallError> {
-    if changed.is_empty() {
-        return Ok(());
-    }
-    // Do both Git updates on a private copy. Only publish the completed
-    // stat refresh if the actual index still contains the input we used.
-    let path = process::git_stdout_bytes(repo_root, ["rev-parse", "--git-path", "index"])?;
-    let index = repo_root.join(
-        driver::native_path(path.strip_suffix(b"\n").unwrap_or(&path))
-            .map_err(|err| err.to_string())?,
-    );
-    let mut input = fs::File::open(&index)?;
-    let timestamp = input.metadata()?.modified()?;
-    let mut original = Vec::new();
-    input.read_to_end(&mut original)?;
-    drop(input);
-    let scratch = process::private_tempdir().map_err(|err| err.to_string())?;
-    let private_index = scratch.path().join("index");
-    let mut copy = fs::File::create(&private_index)?;
-    copy.write_all(&original)?;
-    // Git compares entry times to the index timestamp for racily clean files.
-    copy.set_modified(timestamp)?;
-    drop(copy);
-
-    // Git can register hooks in config as well as in the hooks directory.
-    // No repository hook should observe a write to the private index.
-    let mut hooks = OsString::from("core.hooksPath=");
-    hooks.push(scratch.path());
-    let mut overrides = vec![OsString::from("-c"), hooks];
-    let keys = process::git_stdout_bytes(repo_root, ["config", "--null", "--name-only", "--list"])?;
-    for key in keys.split(|&byte| byte == 0) {
-        if key.starts_with(b"hook.")
-            && let Some(name) = key.strip_suffix(b".command")
-        {
-            let mut disable = OsString::from("--config-env=");
-            disable.push(driver::native_path(name)?);
-            disable.push(".enabled=YAMARK_DISABLE_INDEX_HOOK");
-            overrides.push(disable);
-        }
-    }
-    let git = || {
-        let mut git = process::git_query(repo_root);
-        git.env("GIT_INDEX_FILE", &private_index)
-            .env("YAMARK_DISABLE_INDEX_HOOK", "false")
-            .args(&overrides);
-        git
-    };
-    // With an old, nonzero cached size, Git may report CRLF files as modified
-    // without comparing their clean blobs. Reuse the staged mode and object ID
-    // to clear the stat data for changed ordinary entries. Leave skip-worktree
-    // and assume-unchanged entries (S/s/h) and unrelated paths alone.
-    let names: HashSet<_> = changed
-        .iter()
-        .map(|path| path.as_os_str().as_encoded_bytes())
-        .collect();
-    let entries =
-        process::checked_stdout(git().args(["ls-files", "-v", "--stage", "-z"]).output())?;
-    let mut reset = Vec::new();
-    for record in entries.split(|&byte| byte == 0) {
-        let Some(entry) = record.strip_prefix(b"H ") else {
-            continue;
-        };
-        let (name, [mode, _, stage]) = process::entry_fields(entry).map_err(str::to_owned)?;
-        if names.contains(name) && stage == b"0" && matches!(mode, b"100644" | b"100755") {
-            reset.extend_from_slice(entry);
-            reset.push(0);
-        }
-    }
-    if !reset.is_empty() {
-        let mut update = git();
-        update
-            .args(["update-index", "-z", "--index-info"])
-            .stderr(std::process::Stdio::piped());
-        process::checked_stdout(driver::run_with_input(&mut update, &reset))?;
-        process::checked_stdout(git().args(["update-index", "--refresh"]).output())?;
-        publish_index(&index, &original, &private_index)?;
-    }
-    Ok(())
-}
-
-/// Use Git's lock-file convention: exclusive creation followed by an
-/// atomic rename. A failed comparison or write drops the lock untouched.
-fn publish_index(index: &Path, original: &[u8], update: &Path) -> Result<(), InstallError> {
-    let mut name = index.file_name().expect("index has a filename").to_owned();
-    name.push(".lock");
-    let mut lock = tempfile::Builder::new()
-        .prefix(&name)
-        .rand_bytes(0)
-        .tempfile_in(index.parent().expect("index has a parent directory"))
-        .map_err(|err| {
-            if err.kind() == io::ErrorKind::AlreadyExists {
-                InstallError::IndexBusy("index is locked during refresh")
-            } else {
-                err.into()
-            }
-        })?;
-    if fs::read(index)? != original {
-        return Err(InstallError::IndexBusy("index changed during refresh"));
-    }
-    io::copy(&mut fs::File::open(update)?, lock.as_file_mut())?;
-    lock.as_file()
-        .set_permissions(fs::metadata(index)?.permissions())?;
-    lock.as_file()
-        .set_modified(fs::metadata(update)?.modified()?)?;
-    lock.persist(index).map_err(|err| err.error)?;
-    Ok(())
-}
diff --git a/src/config.rs b/src/config.rs
index 7c783941..012bb7cb 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -2,10 +2,9 @@ use std::collections::BTreeMap;
 use std::env;
 use std::fs;
 use std::path::{Component, Path, PathBuf};
+use std::sync::Arc;
 
-mod exclude;
-
-pub use exclude::ExcludePatterns;
+use ignore::gitignore::{Gitignore, GitignoreBuilder};
 
 use crate::core::directives::TemplateDelimiter;
 use crate::core::document::{AbbreviationOverrides, MarkdownTableWidths, MarkdownWrap};
@@ -23,16 +22,6 @@ pub struct Config {
     pub config_dir: Option,
 }
 
-/// Formatting settings from the `[format]` table.
-///
-/// ```
-/// use yamark::config::FormatConfig;
-///
-/// let format = FormatConfig {
-///     compact: Some(true),
-///     ..Default::default()
-/// };
-/// ```
 #[derive(Debug, Clone, Default)]
 pub struct FormatConfig {
     pub compact: Option,
@@ -40,7 +29,9 @@ pub struct FormatConfig {
     pub markdown_table_widths: Option,
     pub markdown_horizontal_rule: Option<&'static str>,
     pub abbreviations: AbbreviationOverrides,
-    pub exclude: Option,
+    /// Compiled `exclude` patterns, matched against paths relative to the
+    /// config directory.
+    pub(crate) exclude: Option>,
 }
 
 #[derive(Debug, Clone)]
@@ -75,7 +66,8 @@ impl Config {
             )
         })?;
         let mut config = Self::from_toml_str(&input).map_err(|err| err.with_path(path))?;
-        config.config_dir = path.parent().map(absolute_normalized_path);
+        let absolute = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+        config.config_dir = absolute.parent().map(Path::to_path_buf);
         Ok(config)
     }
 
@@ -132,11 +124,8 @@ impl Config {
         if self.path_configs.is_empty() {
             return self.clone();
         }
-        self.for_relative_path(&self.relative_formatted_path(path))
-    }
-
-    pub(crate) fn for_relative_path(&self, relative: &Path) -> Self {
         let mut config = self.clone();
+        let relative = self.relative_formatted_path(path);
         let mut matching = self
             .path_configs
             .iter()
@@ -169,7 +158,14 @@ impl Config {
         let Some(relative) = self.written_path_below_config_dir(path) else {
             return false;
         };
-        exclude.excludes(&relative)
+        // As in Git, a `!` pattern cannot re-include a file below an excluded
+        // directory. Check ancestors before matching the file itself.
+        relative
+            .ancestors()
+            .skip(1)
+            .filter(|dir| !dir.as_os_str().is_empty())
+            .any(|dir| exclude.matched(dir, true).is_ignore())
+            || exclude.matched(&relative, false).is_ignore()
     }
 
     /// Returns the path below the config directory, or `None` outside it.
@@ -212,30 +208,24 @@ impl Config {
     }
 }
 
-/// Preserve written symlink names while resolving each `..` to its filesystem
-/// parent. A missing directory in a virtual stdin path has only a lexical parent.
+/// Resolves an absolute `path` through its last `..` component using the
+/// filesystem when possible, keeping later names as written.
+///
+/// The filesystem resolves `..` after following symlinks, so collapsing it
+/// lexically could name a different file.
 fn resolve_parent_components(path: &Path) -> PathBuf {
-    let mut written = PathBuf::new();
-    for component in path.components() {
-        if component != Component::ParentDir {
-            written.push(component.as_os_str());
-            continue;
-        }
-        let parent = fs::canonicalize(written.join(".."));
-        written.pop();
-        if let Ok(parent) = parent {
-            // A symlink followed by `..` can land elsewhere. Keep the deepest
-            // written prefix that still leads to this parent.
-            written = written
-                .ancestors()
-                .find_map(|prefix| {
-                    let resolved = fs::canonicalize(prefix).ok()?;
-                    Some(prefix.join(parent.strip_prefix(resolved).ok()?))
-                })
-                .unwrap_or(parent);
-        }
-    }
-    written
+    let components = path.components().collect::>();
+    let Some(last_parent) = components
+        .iter()
+        .rposition(|component| *component == Component::ParentDir)
+    else {
+        return push_normalized(PathBuf::new(), path);
+    };
+    let (resolved, written) = components.split_at(last_parent + 1);
+    push_normalized(
+        absolute_normalized_path(&resolved.iter().collect::()),
+        &written.iter().collect::(),
+    )
 }
 
 fn absolute_normalized_path(path: &Path) -> PathBuf {
@@ -297,22 +287,18 @@ fn default_template_delimiters() -> Vec {
 }
 
 pub fn discover_config_path(path: &Path) -> Option {
-    discover_config_within(path, None)
-}
-
-pub(crate) fn discover_config_within(path: &Path, root: Option<&Path>) -> Option {
-    // Resolve relative paths before walking parents, including virtual stdin paths.
+    // Resolve relative paths before walking parents, including virtual stdin
+    // paths that do not exist. Otherwise discovery stops at the working directory.
     let path = std::path::absolute(path).ok()?;
-    let path = if root.is_some() {
-        resolve_parent_components(&path)
-    } else {
-        path
-    };
-    path.parent()?
-        .ancestors()
-        .take_while(|dir| root.is_none_or(|root| dir.starts_with(root)))
-        .map(|dir| dir.join("yamark.toml"))
-        .find(|candidate| candidate.is_file())
+    let mut dir = path.parent().unwrap_or_else(|| Path::new("."));
+    loop {
+        let candidate = dir.join("yamark.toml");
+        if candidate.is_file() {
+            return Some(candidate);
+        }
+        let parent = dir.parent()?;
+        dir = parent;
+    }
 }
 
 fn apply_template_layer(
@@ -400,11 +386,34 @@ fn apply_format_layer(value: &toml::Value, format: &mut FormatConfig) -> Result<
         format.abbreviations = parse_abbreviations(value)?;
     }
     if let Some(value) = table.get("exclude") {
-        format.exclude = Some(ExcludePatterns::parse(value)?);
+        format.exclude = Some(Arc::new(parse_exclude(value)?));
     }
     Ok(())
 }
 
+fn parse_exclude(value: &toml::Value) -> Result {
+    let patterns = value
+        .as_array()
+        .and_then(|patterns| {
+            patterns
+                .iter()
+                .map(toml::Value::as_str)
+                .collect::>>()
+        })
+        .ok_or_else(|| YamarkError::new("format.exclude must be an array of strings"))?;
+    // The empty root matches patterns against paths that are already relative
+    // to the config directory, which is unknown while parsing TOML text.
+    let mut builder = GitignoreBuilder::new("");
+    for pattern in patterns {
+        builder
+            .add_line(None, pattern)
+            .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))?;
+    }
+    builder
+        .build()
+        .map_err(|err| YamarkError::new(format!("format.exclude: {err}")))
+}
+
 fn parse_abbreviations(value: &toml::Value) -> Result {
     let table = value
         .as_table()
diff --git a/src/config/exclude.rs b/src/config/exclude.rs
deleted file mode 100644
index c097e158..00000000
--- a/src/config/exclude.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-//! Git-style patterns for the config's explicit file exclusions.
-
-use std::path::Path;
-use std::sync::Arc;
-
-use gix_glob::{Pattern, pattern::Case, wildmatch};
-
-use crate::diagnostic::{Result, YamarkError};
-
-/// Exclusion patterns parsed from `[format] exclude` and matched relative to
-/// the config directory.
-#[derive(Debug, Clone)]
-pub struct ExcludePatterns(Arc<[Pattern]>);
-
-impl ExcludePatterns {
-    pub(super) fn parse(value: &toml::Value) -> Result {
-        let invalid = || YamarkError::new("format.exclude must be an array of strings");
-        let mut patterns = Vec::new();
-        for value in value.as_array().ok_or_else(invalid)? {
-            let mut text = value.as_str().ok_or_else(invalid)?;
-            if text.starts_with('#') {
-                continue;
-            }
-            // Only unescaped trailing spaces are insignificant in a Git pattern.
-            while let Some(prefix) = text.strip_suffix(' ') {
-                if prefix.bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1 {
-                    break;
-                }
-                text = prefix;
-            }
-            if let Some(pattern) = Pattern::from_bytes(text.as_bytes()) {
-                validate_classes(text)?;
-                patterns.push(pattern);
-            }
-        }
-        Ok(Self(patterns.into()))
-    }
-
-    pub(crate) fn excludes(&self, relative: &Path) -> bool {
-        let path = relative.as_os_str().as_encoded_bytes();
-        #[cfg(windows)]
-        let normalized = path
-            .iter()
-            .map(|&b| if b == b'\\' { b'/' } else { b })
-            .collect::>();
-        #[cfg(windows)]
-        let path = normalized.as_slice();
-        let mut path = path;
-        let mut is_dir = false;
-        // At each level the last matching pattern wins. An excluded parent
-        // directory keeps the file excluded regardless of a file-level '!'.
-        while !path.is_empty() {
-            let slash = path.iter().rposition(|&b| b == b'/');
-            if let Some(pattern) = self.0.iter().rev().find(|pattern| {
-                pattern.matches_repo_relative_path(
-                    path.into(),
-                    slash.map(|pos| pos + 1),
-                    Some(is_dir),
-                    Case::Sensitive,
-                    wildmatch::Mode::NO_MATCH_SLASH_LITERAL,
-                )
-            }) && !pattern.is_negative()
-            {
-                return true;
-            }
-            let Some(slash) = slash else { break };
-            path = &path[..slash];
-            is_dir = true;
-        }
-        false
-    }
-}
-
-// Wildmatch treats malformed classes as nonmatches. Diagnose them while loading
-// the config so a typo in an exclusion cannot silently allow an in-place write.
-fn validate_classes(pattern: &str) -> Result<()> {
-    let error = |msg: &str| {
-        YamarkError::new(format!(
-            "format.exclude: error parsing glob '{pattern}': {msg}"
-        ))
-    };
-    let mut bytes = pattern.as_bytes().iter();
-    let next_member = |bytes: &mut std::slice::Iter<'_, u8>| {
-        bytes
-            .next()
-            .copied()
-            .ok_or_else(|| error("unclosed character class"))
-    };
-    while let Some(&byte) = bytes.next() {
-        if byte == b'\\' {
-            bytes.next().ok_or_else(|| error("dangling escape"))?;
-            continue;
-        }
-        if byte != b'[' {
-            continue;
-        }
-        if matches!(bytes.as_slice().first(), Some(b'!' | b'^')) {
-            bytes.next();
-        }
-        let mut previous = None;
-        let mut first = true;
-        loop {
-            let byte = next_member(&mut bytes)?;
-            if byte == b']' && !first {
-                break;
-            }
-            first = false;
-            if byte == b'['
-                && let Some(posix) = bytes.as_slice().strip_prefix(b":")
-                && let Some(close) = posix.iter().position(|&b| b == b']')
-                && let Some(name) = posix[..close].strip_suffix(b":")
-            {
-                const CLASSES: &str =
-                    "alnum alpha blank cntrl digit graph lower print punct space upper xdigit";
-                if !CLASSES
-                    .split_ascii_whitespace()
-                    .any(|class| class.as_bytes() == name)
-                {
-                    return Err(error(&format!(
-                        "unknown POSIX character class [:{}:]",
-                        String::from_utf8_lossy(name)
-                    )));
-                }
-                bytes = posix[close + 1..].iter();
-                previous = None;
-            } else if byte == b'-'
-                && let Some(start) = previous.take()
-                && bytes.as_slice().first() != Some(&b']')
-            {
-                let mut end = next_member(&mut bytes)?;
-                if end == b'\\' {
-                    end = next_member(&mut bytes)?;
-                }
-                if start > end {
-                    return Err(error(&format!(
-                        "invalid range; '{}' > '{}'",
-                        char::from(start),
-                        char::from(end)
-                    )));
-                }
-            } else if byte == b'\\' {
-                previous = Some(next_member(&mut bytes)?);
-            } else {
-                previous = Some(byte);
-            }
-        }
-    }
-    Ok(())
-}
diff --git a/src/workspace.rs b/src/workspace.rs
index be989da6..f5e14c1a 100644
--- a/src/workspace.rs
+++ b/src/workspace.rs
@@ -35,21 +35,6 @@ pub enum FormatMode {
     Diff,
 }
 
-impl FormatMode {
-    pub(crate) fn resolve_paths(
-        self,
-        paths: Vec,
-    ) -> std::result::Result, &'static str> {
-        if !paths.is_empty() {
-            return Ok(paths);
-        }
-        match self {
-            Self::Write => Err("in-place formatting requires a file or directory path"),
-            Self::Check | Self::Diff => Ok(vec![PathBuf::from(".")]),
-        }
-    }
-}
-
 #[derive(Debug, Clone, Copy, Default)]
 pub(crate) struct FormatExecutionOptions {
     pub(crate) collect_trace: bool,
@@ -287,7 +272,7 @@ pub fn format_paths_with_trace(
     collect_trace: bool,
 ) -> Result {
     format_paths_with_trace_and_overrides(
-        mode.resolve_paths(paths).map_err(YamarkError::new)?,
+        paths,
         options,
         mode,
         config_path,
diff --git a/src/workspace/paths.rs b/src/workspace/paths.rs
index 166aa938..48d438dd 100644
--- a/src/workspace/paths.rs
+++ b/src/workspace/paths.rs
@@ -49,10 +49,10 @@ fn format_worker_count() -> usize {
 
 fn format_worker_count_for_roots(paths: &[PathBuf]) -> usize {
     let max_workers = format_worker_count();
-    if !paths.iter().all(|path| path_is_file_like(path)) {
+    if paths.is_empty() || !paths.iter().all(|path| path_is_file_like(path)) {
         return max_workers;
     }
-    max_workers.min(paths.len())
+    max_workers.min(paths.len()).max(1)
 }
 
 fn path_is_file_like(path: &Path) -> bool {
@@ -197,7 +197,12 @@ impl CandidateProducer {
     }
 
     fn stream(&mut self, paths: Vec) -> Result<()> {
-        for root in paths {
+        let roots = if paths.is_empty() {
+            vec![PathBuf::from(".")]
+        } else {
+            paths
+        };
+        for root in roots {
             self.stream_root(root)?;
         }
         Ok(())
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 601449a1..97fa0edd 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -17,12 +17,8 @@ expected stderr
 
 The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
 
-An optional `-- env` section supplies a JSON object of environment variables for the recorded command. The fixture setup uses the caller's environment.
-
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
-For the Git process filter, `-- stdin-packets` and `-- stdout-packets` record an exact stream of Git packet lines as a JSON array. Custom commands in a case can invoke the binary under test with `"$YAMARK_CASE_BIN"`. Each string is one packet payload, including any trailing newline. A `null` is a flush packet.
-
 ## Running selected cases
 
 Run the complete transcript suite with `cargo test --test cli_cases`. To run one case or a related group, set `YAMARK_CASE` for that command:
@@ -56,7 +52,7 @@ The `markdown_list_wide_marker_raw_boundary`, `markdown_list_child_headings`, an
 
 `markdown_sentence_no_answer` and `markdown_column_no_answer` cover both readings of `No.`: an answer ends a sentence and permits a line break, while `No.` before a number stays on the same line as the number. `tests/sentence_wrap.rs` checks both readings in sentence, column, and combined wrapping with LF, CRLF, and CR line endings, including second passes. `markdown_sentence_number_abbreviations` and `markdown_column_number_abbreviations` cover the other words that are abbreviations only before a number, such as `n.`, `p.`, and `sec.`, including a sentence-starting `c.` whose period is escaped because it would otherwise start a list. `markdown_sentence_technical_abbreviations` and `markdown_column_technical_abbreviations` cover the abbreviations Yamark adds to Pandoc's list, such as `Fig.` and `w.r.t.`, the case-sensitive boundary (`Etc.`), and both readings of `etc.` and `i.i.d.`, which are abbreviations only before a lowercase letter. `markdown_sentence_et_al` and `markdown_column_et_al` cover `al.`, which is an abbreviation unless the next whitespace-separated source token starts with an uppercase letter: `et al. We` ends a sentence, while `et al. (2020)`, `et al. showed`, an escaped `et al\.`, and `abbreviations.add "al."` do not. `markdown_sentence_abbreviation_closers` and `markdown_sentence_column_abbreviation_closers` cover abbreviations followed by closing quotation marks or brackets, such as `(e.g.)`: they do not end a sentence, and column wrapping may still break after them. The `markdown_*_period_reference` transcripts cover `.` as an explicit sentence end in sentence and combined wrapping, including after abbreviations and before closing brackets. They also record that an escaped `\.` and the hexadecimal form are ordinary text and that column wrapping alone keeps the reference without forcing a break. The `*_directive_abbreviations` transcripts cover `fmt: abbreviations.add` and `fmt: abbreviations.remove` in Markdown, YAML, Python, and R: each scope, a later directive overriding an earlier one, a correction that replaces a rule depending on the next token, and column wrapping. `markdown_directive_abbreviations_late_file_scope` applies file-scoped corrections to text before the directive. The `markdown_directive_abbreviations_unquoted`, `_no_words`, and `_no_period` transcripts record the errors for a missing or invalid word. `config_abbreviations` covers `[format.abbreviations]` in `yamark.toml` and a directive that overrides it. The `config_abbreviations_both_lists`, `_invalid_word`, `_not_strings`, and `_unknown_key` transcripts record the configuration errors.
 
-The `config_exclude_*` transcripts cover `exclude` in the `[format]` table of `yamark.toml`. `config_exclude_stdin` returns excluded stdin unchanged, and `config_exclude_stdin_unmatched` formats another file under the same config. `config_exclude_explicit_path` counts an excluded explicit path as skipped. `config_exclude_directory_walk` counts files below an excluded directory as skipped and checks that their contents are unchanged. `config_exclude_patterns` covers directory, glob, anchored, and negated patterns. `config_exclude_parent_directory` keeps a file below an excluded directory excluded whether its `!` pattern comes before or after the directory pattern. `config_exclude_relative_ancestor` and `config_exclude_explicit_config` cover patterns relative to a config discovered in an ancestor or passed with `--config`; the latter also formats a file outside the config directory. `git_filter_clean_excluded` passes an excluded file through the clean filter unchanged. The `config_exclude_not_strings` and `_invalid_pattern` transcripts record the configuration errors. For non-UTF-8 input, `tests/spec_cli/commands.rs` covers byte pass-through for excluded stdin, and `tests/git_filter_paths.rs` covers adopting and checking a repository with an excluded UTF-16 file.
+The `config_exclude_*` transcripts cover `exclude` in the `[format]` table of `yamark.toml`. `config_exclude_stdin` returns excluded stdin unchanged, and `config_exclude_stdin_unmatched` formats another file under the same config. `config_exclude_explicit_path` counts an excluded explicit path as skipped. `config_exclude_directory_walk` counts files below an excluded directory as skipped and checks that their contents are unchanged. `config_exclude_patterns` covers directory, glob, anchored, and negated patterns. `config_exclude_parent_directory` keeps a file below an excluded directory excluded whether its `!` pattern comes before or after the directory pattern. `config_exclude_relative_ancestor` and `config_exclude_explicit_config` cover patterns relative to a config discovered in an ancestor or passed with `--config`; the latter also formats a file outside the config directory. `git_filter_clean_excluded` passes an excluded file through the clean filter unchanged. The `config_exclude_not_strings` and `_invalid_pattern` transcripts record the configuration errors. Transcripts cannot create symbolic links or carry non-UTF-8 stdin, so `tests/spec_cli/workspace.rs` covers symlink names, `tests/spec_cli/commands.rs` covers byte pass-through for excluded stdin, and `tests/git_filter_paths.rs` covers adopting and checking a repository with an excluded UTF-16 file.
 
 The `markdown_bom_*` transcripts read a first line holding only a byte order mark and spaces as blank before thematic breaks, paragraphs, and directives. `markdown_feff_content_setext` keeps U+FEFF later in the file and at the start of blockquote and footnote content as setext heading text.
 
@@ -68,12 +64,8 @@ The `external_formatter_*.case` transcripts cover formatters that remove only th
 
 `external_formatter_early_stdin_close.case` covers a successful formatter that closes stdin before reading it. The public CLI specifications repeat this with input larger than a pipe buffer and check that nonzero status, stderr, invalid UTF-8, and unsafe fence output still fail.
 
-Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Set `"setup-filter": true` to run `yamark git-filter setup` after the fixture commit. An optional `hard-links` mapping adds hard links from each key to its fixture file. An optional `symlinks` mapping adds working-tree links. Set `track-symlinks` to true to include them in the fixture commit. Each key names a link and each value names an existing file or directory, both relative to the fixture root. Windows skips the case if it lacks symlink privileges. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
+Git integration transcripts can add a `-- git-fixture` JSON object with `config` and `files` mappings and an optional `cwd` relative to the repository root (default `.`). The harness creates a temporary repository, applies the local Git settings, writes and commits the supplied files, and runs the recorded invocation there. Output uses `{{repo}}` for that temporary repository's absolute path. An optional `-- git-status` section records the expected subsequent `git status --porcelain` output. `git_filter_join_crlf.case` verifies that joining the filter keeps a CRLF checkout clean when `core.autocrlf=true`. The LF and explicit `eol=lf` companion cases cover the corresponding compatibility boundaries.
 
 For Unix filename bytes that cannot be represented as UTF-8, `git-fixture` can also include a `unix-index-files` array. Each entry has `name_bytes` (an array of byte values) and `contents` (a string). The harness writes these files directly into Git's index and marks them `skip-worktree`, so the fixture does not depend on filesystem support for their names. Cases with this field run only on Unix. The `git_filter_*non_utf8*.case` transcripts cover unrelated filenames and committed Markdown validation; `tests/git_filter_paths.rs` checks the complete native-filename lifecycle on Linux, where the working tree can contain these names.
 
 The `git_filter_adopt_*.case` transcripts cover adoption with automatic CRLF conversion, LF checkouts, and explicit `eol` attributes overriding `core.autocrlf`. They record the staged status and use `-- git-index` and `-- git-worktree` JSON file mappings to check exact staged and checkout bytes. JSON newline escapes make the expected CRLF/LF distinction visible in the transcript.
-
-Use `git-after-commit` in a Git fixture to run an ordered list of Git argument arrays after creating its commit. The `git_filter_check_committed_selection` and `git_filter_check_removed_attributes` cases use it to change the index and checkout while verifying the original commit.
-
-Set `"object-format": "sha1"` in a Git fixture when its protocol packets contain literal SHA-1 object IDs. Other fixtures use Git's default object format.
diff --git a/tests/cases/config_exclude_character_classes.case b/tests/cases/config_exclude_character_classes.case
deleted file mode 100644
index 612eded4..00000000
--- a/tests/cases/config_exclude_character_classes.case
+++ /dev/null
@@ -1,34 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nexclude = ['[a\\-c].md', '/docs[!0-9]*.md', 'sub/[-0].md']\n",
-    "-.md": "#   dash\n",
-    "a.md": "#   a\n",
-    "b.md": "#   b\n",
-    "c.md": "#   c\n",
-    "docs-a.md": "#   dash\n",
-    "docs1.md": "#   digit\n",
-    "docs/notes.md": "#   nested\n",
-    "sub/0.md": "#   zero\n"
-  }
-}
--- args
-format .
--- stdin
--- stdout
-9 files scanned, 3 formatted, 0 unchanged, 6 skipped, 0 failed
--- stderr
--- git-worktree
-{
-  "-.md": "#   dash\n",
-  "a.md": "#   a\n",
-  "b.md": "# b\n",
-  "c.md": "#   c\n",
-  "docs-a.md": "#   dash\n",
-  "docs1.md": "# digit\n",
-  "docs/notes.md": "# nested\n",
-  "sub/0.md": "#   zero\n"
-}
--- status
-0
diff --git a/tests/cases/config_exclude_digit_range.case b/tests/cases/config_exclude_digit_range.case
deleted file mode 100644
index 352c3a3b..00000000
--- a/tests/cases/config_exclude_digit_range.case
+++ /dev/null
@@ -1,22 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nexclude = ['[0-9]*.md']\n",
-    "1-report.md": "#   Report\n",
-    "letter.md": "#   Letter\n"
-  }
-}
--- args
-format --config yamark.toml 1-report.md letter.md
--- stdin
--- stdout
-2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
--- stderr
--- git-worktree
-{
-  "1-report.md": "#   Report\n",
-  "letter.md": "# Letter\n"
-}
--- status
-0
diff --git a/tests/cases/config_exclude_explicit_symlinked_config.case b/tests/cases/config_exclude_explicit_symlinked_config.case
deleted file mode 100644
index 81906780..00000000
--- a/tests/cases/config_exclude_explicit_symlinked_config.case
+++ /dev/null
@@ -1,20 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "shared/settings.toml": "[format]\nexclude = [\"keep.md\"]\n",
-    "project/keep.md": "#   Project\n",
-    "shared/keep.md": "#   Shared\n"
-  },
-  "symlinks": {"project/config.toml": "shared/settings.toml"}
-}
--- args
-format --config project/config.toml project/keep.md shared/keep.md
--- stdin
--- stdout
-2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
--- stderr
--- git-worktree
-{"project/keep.md": "#   Project\n", "shared/keep.md": "# Shared\n"}
--- status
-0
diff --git a/tests/cases/config_exclude_invalid_pattern.case b/tests/cases/config_exclude_invalid_pattern.case
index c50dc2a0..204a48e4 100644
--- a/tests/cases/config_exclude_invalid_pattern.case
+++ b/tests/cases/config_exclude_invalid_pattern.case
@@ -2,7 +2,7 @@
 {
   "config": {"core.autocrlf": "false"},
   "files": {
-    "yamark.toml": "[format]\nexclude = [\"[z-a].md\"]\n"
+    "yamark.toml": "[format]\nexclude = [\"{deck.qmd\"]\n"
   }
 }
 -- args
@@ -11,6 +11,6 @@ format --config yamark.toml --stdin-file-path input.md
 #   Title
 -- stdout
 -- stderr
-yamark.toml:1:1: error: format.exclude: error parsing glob '[z-a].md': invalid range; 'z' > 'a'
+yamark.toml:1:1: error: format.exclude: error parsing glob '{deck.qmd': unclosed alternate group; missing '}' (maybe escape '{' with '[{]'?)
 -- status
 1
diff --git a/tests/cases/config_exclude_literal_braces.case b/tests/cases/config_exclude_literal_braces.case
deleted file mode 100644
index 3713f221..00000000
--- a/tests/cases/config_exclude_literal_braces.case
+++ /dev/null
@@ -1,34 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    "yamark.toml": "[format]\nexclude = ['{id}.md', '{a,b}.md', 'open{.md', 'escaped\\{x\\}.md', '[a-{]-range.md']\n",
-    "{id}.md": "#   Title\n",
-    "id.md": "#   Title\n",
-    "{a,b}.md": "#   Title\n",
-    "a.md": "#   Title\n",
-    "open{.md": "#   Title\n",
-    "escaped{x}.md": "#   Title\n",
-    "z-range.md": "#   Title\n"
-  }
-}
--- args
-format {id}.md id.md {a,b}.md a.md open{.md escaped{x}.md z-range.md
--- stdin
--- stdout
-7 files scanned, 2 formatted, 0 unchanged, 5 skipped, 0 failed
--- stderr
--- git-worktree
-{
-  "{id}.md": "#   Title\n",
-  "id.md": "# Title\n",
-  "{a,b}.md": "#   Title\n",
-  "a.md": "# Title\n",
-  "open{.md": "#   Title\n",
-  "escaped{x}.md": "#   Title\n",
-  "z-range.md": "#   Title\n"
-}
--- status
-0
diff --git a/tests/cases/config_exclude_posix_class.case b/tests/cases/config_exclude_posix_class.case
deleted file mode 100644
index 538e0732..00000000
--- a/tests/cases/config_exclude_posix_class.case
+++ /dev/null
@@ -1,22 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nexclude = ['[[:digit:]]*.md']\n",
-    "1-report.md": "#   Report\n",
-    "letter.md": "#   Letter\n"
-  }
-}
--- args
-format --config yamark.toml 1-report.md letter.md
--- stdin
--- stdout
-2 files scanned, 1 formatted, 0 unchanged, 1 skipped, 0 failed
--- stderr
--- git-worktree
-{
-  "1-report.md": "#   Report\n",
-  "letter.md": "# Letter\n"
-}
--- status
-0
diff --git a/tests/cases/config_exclude_symlink_parent_component.case b/tests/cases/config_exclude_symlink_parent_component.case
deleted file mode 100644
index f08f7d5a..00000000
--- a/tests/cases/config_exclude_symlink_parent_component.case
+++ /dev/null
@@ -1,27 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "project/yamark.toml": "[format]\nexclude = [\"/slides/\"]\n",
-    "assets/sub/.keep": "",
-    "assets/deck.md": "#   Slides\n",
-    "assets/handout.md": "#   Handout\n",
-    "assets/talk/handout.md": "#   Handout\n",
-    "assets/talk/notes/.keep": ""
-  },
-  "symlinks": {"project/slides": "assets", "assets/notes": "assets/talk/notes"}
-}
--- args
-format project/slides/sub/../deck.md project/slides/notes/../handout.md
--- stdin
--- stdout
-2 files scanned, 0 formatted, 0 unchanged, 2 skipped, 0 failed
--- stderr
--- git-worktree
-{
-  "assets/deck.md": "#   Slides\n",
-  "assets/handout.md": "#   Handout\n",
-  "assets/talk/handout.md": "#   Handout\n"
-}
--- status
-0
diff --git a/tests/cases/config_exclude_symlinked_config.case b/tests/cases/config_exclude_symlinked_config.case
deleted file mode 100644
index 2cf9594e..00000000
--- a/tests/cases/config_exclude_symlinked_config.case
+++ /dev/null
@@ -1,19 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "shared/settings.toml": "[format]\nexclude = [\"keep.md\"]\n",
-    "project/keep.md": "#   Keep\n"
-  },
-  "symlinks": {"project/yamark.toml": "shared/settings.toml"}
-}
--- args
-format project/keep.md
--- stdin
--- stdout
-1 files scanned, 0 formatted, 0 unchanged, 1 skipped, 0 failed
--- stderr
--- git-worktree
-{"project/keep.md": "#   Keep\n"}
--- status
-0
diff --git a/tests/cases/config_exclude_unclosed_class.case b/tests/cases/config_exclude_unclosed_class.case
deleted file mode 100644
index baec6a8d..00000000
--- a/tests/cases/config_exclude_unclosed_class.case
+++ /dev/null
@@ -1,14 +0,0 @@
--- git-fixture
-{
-  "config": {},
-  "files": {"yamark.toml": "[format]\nexclude = ['[0-9.md']\n"}
-}
--- args
-format --config yamark.toml --stdin-file-path input.md
--- stdin
-#   Heading
--- stdout
--- stderr
-yamark.toml:1:1: error: format.exclude: error parsing glob '[0-9.md': unclosed character class
--- status
-1
diff --git a/tests/cases/config_exclude_unsupported_stdin.case b/tests/cases/config_exclude_unsupported_stdin.case
deleted file mode 100644
index 5974e01a..00000000
--- a/tests/cases/config_exclude_unsupported_stdin.case
+++ /dev/null
@@ -1,14 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {"yamark.toml": "[format]\nexclude = [\"*.txt\"]\n"}
-}
--- args
-format --stdin-file-path notes.txt
--- stdin
-#   Notes
--- stdout
-#   Notes
--- stderr
--- status
-0
diff --git a/tests/cases/config_virtual_stdin_path_override.case b/tests/cases/config_virtual_stdin_path_override.case
deleted file mode 100644
index 9b4b187b..00000000
--- a/tests/cases/config_virtual_stdin_path_override.case
+++ /dev/null
@@ -1,20 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[paths.\"docs\".template]\nadd_delimiters = [{ open = \"<<\", close = \">>\" }]\n"
-  }
-}
--- args
-format --stdin-file-path docs/new.md
--- stdin
-#   Draft
-
-Keep << these   spaces >> here.
--- stdout
-# Draft
-
-Keep << these   spaces >> here.
--- stderr
--- status
-0
diff --git a/tests/cases/format_missing_path.case b/tests/cases/format_missing_path.case
index 1af8f46f..447c633b 100644
--- a/tests/cases/format_missing_path.case
+++ b/tests/cases/format_missing_path.case
@@ -8,9 +8,12 @@ format
 -- stdin
 -- stdout
 -- stderr
-error: in-place formatting requires a file or directory path
+error: the following required arguments were not provided:
+  ...
 
-Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin.
+Usage: yamark format ...
+
+For more information, try '--help'.
 -- git-worktree
 {"docs/input.md": "#   Title\n"}
 -- status
diff --git a/tests/cases/format_missing_path_with_config.case b/tests/cases/format_missing_path_with_config.case
index 63a39c69..234f2e3c 100644
--- a/tests/cases/format_missing_path_with_config.case
+++ b/tests/cases/format_missing_path_with_config.case
@@ -12,9 +12,12 @@ format --wrap 40
 #   Piped
 -- stdout
 -- stderr
-error: in-place formatting requires a file or directory path
+error: the following required arguments were not provided:
+  ...
 
-Use `yamark format .` to format the current directory or `yamark format --stdin-file-path PATH` to format stdin.
+Usage: yamark format --wrap  ...
+
+For more information, try '--help'.
 -- git-worktree
 {"docs/input.md": "#   Title\n"}
 -- status
diff --git a/tests/cases/git_filter_adopt_concurrent_index.case b/tests/cases/git_filter_adopt_concurrent_index.case
deleted file mode 100644
index 11342da6..00000000
--- a/tests/cases/git_filter_adopt_concurrent_index.case
+++ /dev/null
@@ -1,29 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {"doc.md": "# Keep\n"}
-}
--- args
-git-filter adopt
--- env
-{
-  "LC_ALL": "C",
-  "GIT_CONFIG_COUNT": "2",
-  "GIT_CONFIG_KEY_0": "filter.yamark-md.smudge",
-  "GIT_CONFIG_VALUE_0": "touch .git/smudged && echo '#    Keep'",
-  "GIT_CONFIG_KEY_1": "filter.yamark-md.clean",
-  "GIT_CONFIG_VALUE_1": "if test -f .git/smudged; then (unset GIT_INDEX_FILE; git update-index --assume-unchanged -- doc.md) || exit 1; fi; \"$YAMARK_CASE_BIN\" git-filter clean --stdin-filename %f"
-}
--- stdin
--- stdout
--- stderr
-error: index changed during refresh. Staged changes were preserved.
-Adoption remains staged. Review the index and working tree before continuing.
--- git-status
-A  .gitattributes
--- git-index
-{"doc.md": "# Keep\n"}
--- git-worktree
-{"doc.md": "#    Keep\n"}
--- status
-1
diff --git a/tests/cases/git_filter_adopt_regular_entries.case b/tests/cases/git_filter_adopt_regular_entries.case
deleted file mode 100644
index da39bfa1..00000000
--- a/tests/cases/git_filter_adopt_regular_entries.case
+++ /dev/null
@@ -1,27 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false", "core.symlinks": "true"},
-  "files": {
-    "post.md": "First sentence. Second sentence?\n",
-    "notes/keep.txt": "Keep this file.\n",
-    "yamark.toml": "[format]\nexclude = [\"link.md\"]\n"
-  },
-  "symlinks": {"link.md": "notes"},
-  "track-symlinks": true
-}
--- args
-git-filter adopt
--- stdin
--- stdout
-Adopted yamark Git filter in {{repo}}
-Updated .gitattributes with 4 new attribute pattern(s)
-Staged .gitattributes and 1 normalized Markdown file(s).
-
-Review and commit with:
-  git diff --cached
-  git commit -m "Normalize Markdown with yamark Git filter"
--- stderr
--- git-worktree
-{"link.md/keep.txt": "Keep this file.\n", "post.md": "First sentence. Second sentence?\n"}
--- status
-0
diff --git a/tests/cases/git_filter_adopt_worktree_boundary.case b/tests/cases/git_filter_adopt_worktree_boundary.case
deleted file mode 100644
index 624a6b59..00000000
--- a/tests/cases/git_filter_adopt_worktree_boundary.case
+++ /dev/null
@@ -1,31 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
-    "project/docs/file.md": "- - -\n"
-  },
-  "git-after-commit": [
-    ["-C", "project", "init", "-q"],
-    ["-C", "project", "config", "core.autocrlf", "false"],
-    ["-C", "project", "add", "."],
-    ["-C", "project", "-c", "user.name=CLI Case", "-c", "user.email=cli-case@example.test", "-c", "commit.gpgSign=false", "commit", "-qm", "fixture"]
-  ],
-  "cwd": "project"
-}
--- args
-git-filter adopt
--- stdin
--- stdout
-Adopted yamark Git filter in {{repo}}/project
-Updated .gitattributes with 4 new attribute pattern(s)
-Staged .gitattributes and 1 normalized Markdown file(s).
-
-Review and commit with:
-  git diff --cached
-  git commit -m "Normalize Markdown with yamark Git filter"
--- stderr
--- git-worktree
-{"project/docs/file.md": "---\n"}
--- status
-0
diff --git a/tests/cases/git_filter_check_committed_selection.case b/tests/cases/git_filter_check_committed_selection.case
deleted file mode 100644
index cebaf5a6..00000000
--- a/tests/cases/git_filter_check_committed_selection.case
+++ /dev/null
@@ -1,24 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "staged-attributes": "good.md filter=yamark-md\n",
-    "bad.md": "#    Bad\n",
-    "good.md": "# Good\n",
-    "other.md": "#    Also bad\n"
-  },
-  "git-after-commit": [
-    ["rm", "--cached", "--", "bad.md"],
-    ["mv", "-f", "staged-attributes", ".gitattributes"]
-  ]
-}
--- args
-git-filter check
--- stdin
--- stdout
--- stderr
-error: bad.md: roundtrip failure: clean(smudge(blob)) != blob
-other.md: roundtrip failure: clean(smudge(blob)) != blob
--- status
-1
diff --git a/tests/cases/git_filter_check_declarative.case b/tests/cases/git_filter_check_declarative.case
deleted file mode 100644
index e5ed412d..00000000
--- a/tests/cases/git_filter_check_declarative.case
+++ /dev/null
@@ -1,19 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n",
-    "post.md": "***\n\n```example\nunformatted  input\n```\n"
-  }
-}
--- args
-git-filter check
--- stdin
--- stdout
-yamark Git filter check passed for 1 Markdown file(s).
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_check_missing_config_directory.case b/tests/cases/git_filter_check_missing_config_directory.case
deleted file mode 100644
index 578ad793..00000000
--- a/tests/cases/git_filter_check_missing_config_directory.case
+++ /dev/null
@@ -1,18 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "docs/yamark.toml": "[format]\nexclude = ['keep.md']\n",
-    "docs/keep.md": "#    Leave this heading alone\n"
-  },
-  "git-after-commit": [["rm", "-r", "--", "docs"]]
-}
--- args
-git-filter check
--- stdin
--- stdout
-yamark Git filter check passed for 1 Markdown file(s).
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_check_private_index_hooks.case b/tests/cases/git_filter_check_private_index_hooks.case
deleted file mode 100644
index 0adbff5d..00000000
--- a/tests/cases/git_filter_check_private_index_hooks.case
+++ /dev/null
@@ -1,33 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "doc.md": "# Checked\n",
-    "hooks/post-index-change": "#!/bin/sh\necho changed >>index-events\n",
-    "index-events": ""
-  },
-  "git-after-commit": [
-    ["-c", "alias.enable-hook=!chmod +x hooks/post-index-change", "enable-hook"],
-    ["config", "core.hooksPath", "hooks"],
-    ["read-tree", "HEAD"]
-  ]
-}
--- args
-git-filter check
--- env
-{
-  "GIT_CONFIG_COUNT": "2",
-  "GIT_CONFIG_KEY_0": "hook.record-index.event",
-  "GIT_CONFIG_VALUE_0": "post-index-change",
-  "GIT_CONFIG_KEY_1": "hook.record-index.command",
-  "GIT_CONFIG_VALUE_1": "echo configured >>index-events"
-}
--- stdin
--- stdout
-yamark Git filter check passed for 1 Markdown file(s).
--- stderr
--- git-worktree
-{"index-events": "changed\n"}
--- status
-0
diff --git a/tests/cases/git_filter_check_removed_attributes.case b/tests/cases/git_filter_check_removed_attributes.case
deleted file mode 100644
index 923c85a9..00000000
--- a/tests/cases/git_filter_check_removed_attributes.case
+++ /dev/null
@@ -1,17 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "good.md": "# Good\n"
-  },
-  "git-after-commit": [["rm", ".gitattributes"]]
-}
--- args
-git-filter check
--- stdin
--- stdout
-yamark Git filter check passed for 1 Markdown file(s).
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_clean_declarative.case b/tests/cases/git_filter_clean_declarative.case
deleted file mode 100644
index 02da1143..00000000
--- a/tests/cases/git_filter_clean_declarative.case
+++ /dev/null
@@ -1,26 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    "yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n"
-  }
-}
--- args
-git-filter clean --stdin-filename post.md
--- stdin
-- - -
-
-```example
-unformatted  input
-```
--- stdout
-***
-
-```example
-unformatted  input
-```
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_clean_leading_dash.case b/tests/cases/git_filter_clean_leading_dash.case
deleted file mode 100644
index 93630907..00000000
--- a/tests/cases/git_filter_clean_leading_dash.case
+++ /dev/null
@@ -1,9 +0,0 @@
--- args
-git-filter clean --stdin-filename -leading.md
--- stdin
-#   Title
--- stdout
-# Title
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_clean_nested_worktree.case b/tests/cases/git_filter_clean_nested_worktree.case
deleted file mode 100644
index bd27f5e6..00000000
--- a/tests/cases/git_filter_clean_nested_worktree.case
+++ /dev/null
@@ -1,20 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '---'\n",
-    "project/yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
-    "project/docs/file.md": "Body.\n"
-  },
-  "git-after-commit": [["-C", "project", "init", "-q"]],
-  "cwd": "project/docs"
-}
--- args
-git-filter clean --stdin-filename file.md
--- stdin
-- - -
--- stdout
-***
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_clean_worktree_boundary.case b/tests/cases/git_filter_clean_worktree_boundary.case
deleted file mode 100644
index 18ee7f19..00000000
--- a/tests/cases/git_filter_clean_worktree_boundary.case
+++ /dev/null
@@ -1,19 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "yamark.toml": "[format]\nmarkdown_horizontal_rule = '***'\n",
-    "project/docs/file.md": "Body.\n"
-  },
-  "git-after-commit": [["-C", "project", "init", "-q"]],
-  "cwd": "project/docs"
-}
--- args
-git-filter clean --stdin-filename file.md
--- stdin
-- - -
--- stdout
----
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_join_hard_link.case b/tests/cases/git_filter_join_hard_link.case
deleted file mode 100644
index 4c7d09f9..00000000
--- a/tests/cases/git_filter_join_hard_link.case
+++ /dev/null
@@ -1,21 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "post.md": "First sentence.\nSecond sentence?\n"
-  },
-  "hard-links": {"backup.txt": "post.md"}
-}
--- args
-git-filter join
--- stdin
--- stdout
--- stderr
-error: {{repo}}/post.md: failed to install smudged file: cannot rewrite a file with multiple hard links
--- git-index
-{"post.md": "First sentence.\nSecond sentence?\n"}
--- git-worktree
-{"post.md": "First sentence.\nSecond sentence?\n", "backup.txt": "First sentence.\nSecond sentence?\n"}
--- status
-1
diff --git a/tests/cases/git_filter_join_refresh_failure.case b/tests/cases/git_filter_join_refresh_failure.case
deleted file mode 100644
index 8881c412..00000000
--- a/tests/cases/git_filter_join_refresh_failure.case
+++ /dev/null
@@ -1,31 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    ".gitattributes": "*.md filter=yamark-md\n",
-    "post.md": "# Keep\n"
-  }
-}
--- args
-git-filter join
--- env
-{
-  "LC_ALL": "C",
-  "GIT_CONFIG_COUNT": "3",
-  "GIT_CONFIG_KEY_0": "filter.yamark-md.process",
-  "GIT_CONFIG_VALUE_0": "\"$YAMARK_CASE_BIN\" git-filter process 2>/dev/null",
-  "GIT_CONFIG_KEY_1": "filter.yamark-md.smudge",
-  "GIT_CONFIG_VALUE_1": "touch .git/smudged && echo '#    Keep'",
-  "GIT_CONFIG_KEY_2": "filter.yamark-md.clean",
-  "GIT_CONFIG_VALUE_2": "test ! -f .git/smudged && cat"
-}
--- stdin
--- stdout
--- stderr
-error: git failed: fatal: post.md: clean filter 'yamark-md' failed
--- git-index
-{"post.md": "# Keep\n"}
--- git-worktree
-{"post.md": "#    Keep\n"}
--- status
-1
diff --git a/tests/cases/git_filter_process_clean_only.case b/tests/cases/git_filter_process_clean_only.case
deleted file mode 100644
index 04e71399..00000000
--- a/tests/cases/git_filter_process_clean_only.case
+++ /dev/null
@@ -1,23 +0,0 @@
--- git-fixture
-{
-  "config": {"filter.yamark-md.clean": "cat"},
-  "files": {"notes.md": "Notes\n"}
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=clean\n", "pathname=notes.md\n", null,
-  "Notes\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", null,
-  "status=success\n", null, "Notes\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_conflicted_config.case b/tests/cases/git_filter_process_conflicted_config.case
deleted file mode 100644
index 7f7fae0d..00000000
--- a/tests/cases/git_filter_process_conflicted_config.case
+++ /dev/null
@@ -1,48 +0,0 @@
--- git-fixture
-{
-  "object-format": "sha1",
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    "base/docs/doc.md": "#   Keep\n",
-    "base/yamark.toml": "[format]\nexclude = ['other.md']\n",
-    "base/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'base.md']\n",
-    "ours/docs/doc.md": "#   Keep\n",
-    "ours/yamark.toml": "[format]\nexclude = ['other.md']\n",
-    "ours/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'ours.md']\n",
-    "theirs/docs/doc.md": "#   Keep\n",
-    "theirs/yamark.toml": "[format]\nexclude = ['other.md']\n",
-    "theirs/docs/yamark.toml": "[format]\nexclude = ['doc.md', 'theirs.md']\n"
-  },
-  "git-after-commit": [
-    ["read-tree", "HEAD:ours"],
-    [
-      "read-tree",
-      "-i",
-      "-m",
-      "HEAD:base",
-      "HEAD:ours",
-      "HEAD:theirs"
-    ]
-  ],
-  "setup-filter": true
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "command=smudge\n", "pathname=docs/doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null,
-  "#   Keep\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "status=success\n", null, "#   Keep\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_custom_treeless_smudge.case b/tests/cases/git_filter_process_custom_treeless_smudge.case
deleted file mode 100644
index 7cc5f8a8..00000000
--- a/tests/cases/git_filter_process_custom_treeless_smudge.case
+++ /dev/null
@@ -1,32 +0,0 @@
--- git-fixture
-{
-  "object-format": "sha1",
-  "config": {
-    "core.autocrlf": "false",
-    "filter.yamark-md.smudge": "\"$YAMARK_CASE_BIN\" git-filter smudge --stdin-filename '%f'"
-  },
-  "files": {
-    "doc.md": "# Base\n"
-  }
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "command=smudge\n", "pathname=doc.md\n", "blob=18facc4e56a8bce5e46541f709ee6f884bb0350c\n", null,
-  "#   Incoming\n", null,
-  "command=smudge\n", "pathname=doc.md\n", null,
-  "#   Incoming\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "status=success\n", null, "#   Incoming\n", null, null,
-  "status=success\n", null, "#   Incoming\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_double_quoted_filename.case b/tests/cases/git_filter_process_double_quoted_filename.case
deleted file mode 100644
index c354ff9a..00000000
--- a/tests/cases/git_filter_process_double_quoted_filename.case
+++ /dev/null
@@ -1,23 +0,0 @@
--- git-fixture
-{
-  "config": {"filter.yamark-md.clean": "printf '%%s\\n' \"%f\""},
-  "files": {"two notes.md": "Notes\n"}
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=clean\n", "pathname=two notes.md\n", null,
-  "Notes\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", null,
-  "status=success\n", null, "two notes.md\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_index_change.case b/tests/cases/git_filter_process_index_change.case
deleted file mode 100644
index 9efe985a..00000000
--- a/tests/cases/git_filter_process_index_change.case
+++ /dev/null
@@ -1,46 +0,0 @@
--- git-fixture
-{
-  "object-format": "sha1",
-  "config": {
-    "core.autocrlf": "false",
-    "index.skipHash": "true"
-  },
-  "files": {
-    "also.md": "#   Keep\n",
-    "next/also.md": "# Changed in the index\n",
-    "next/doc.md": "#   Keep\n",
-    "next/yamark.toml": "[format]\nexclude = ['doc.md']\n",
-    "doc.md": "#   Keep\n",
-    "yamark.toml": "[format]\nexclude = ['unrelated.md']\n"
-  },
-  "setup-filter": true
-}
--- env
-{
-  "GIT_CONFIG_COUNT": "1",
-  "GIT_CONFIG_KEY_0": "filter.yamark-md.clean",
-  "GIT_CONFIG_VALUE_0": "git read-tree HEAD:next && cat"
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=smudge\n", "pathname=doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null,
-  "command=clean\n", "pathname=doc.md\n", null, "edit config\n", null,
-  "command=smudge\n", "pathname=doc.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null,
-  "command=smudge\n", "pathname=also.md\n", "blob=5c4bea764a03b8a772182846197cb177aa1b63ad\n", null, "#   Keep\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "status=success\n", null, "# Keep\n", null, null,
-  "status=success\n", null, "edit config\n", null, null,
-  "status=success\n", null, "#   Keep\n", null, null,
-  "status=success\n", null, "#   Keep\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_optional_lf.case b/tests/cases/git_filter_process_optional_lf.case
deleted file mode 100644
index 4a6b03f1..00000000
--- a/tests/cases/git_filter_process_optional_lf.case
+++ /dev/null
@@ -1,22 +0,0 @@
--- git-fixture
-{
-  "config": {"filter.yamark-md.clean": "cat", "filter.yamark-md.smudge": "cat"},
-  "files": {"notes.md": "Notes\n"}
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client", "version=2", null,
-  "capability=clean", "capability=smudge", null,
-  "command=clean", "pathname=notes.md", null, "No final newline", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "status=success\n", null, "No final newline", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_quoted_filename.case b/tests/cases/git_filter_process_quoted_filename.case
deleted file mode 100644
index 484eaea8..00000000
--- a/tests/cases/git_filter_process_quoted_filename.case
+++ /dev/null
@@ -1,23 +0,0 @@
--- git-fixture
-{
-  "config": {"filter.yamark-md.clean": "printf '%%s\\n' '%f'"},
-  "files": {"notes.md": "Notes\n"}
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=clean\n", "pathname=notes.md\n", null,
-  "Notes\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", null,
-  "status=success\n", null, "notes.md\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_smudge_only.case b/tests/cases/git_filter_process_smudge_only.case
deleted file mode 100644
index 7e0e0700..00000000
--- a/tests/cases/git_filter_process_smudge_only.case
+++ /dev/null
@@ -1,23 +0,0 @@
--- git-fixture
-{
-  "config": {"filter.yamark-md.smudge": "cat"},
-  "files": {"notes.md": "Notes\n"}
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=smudge\n", "pathname=notes.md\n", null,
-  "Notes\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "status=success\n", null, "Notes\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_treeless_smudge.case b/tests/cases/git_filter_process_treeless_smudge.case
deleted file mode 100644
index 3416bf06..00000000
--- a/tests/cases/git_filter_process_treeless_smudge.case
+++ /dev/null
@@ -1,28 +0,0 @@
--- git-fixture
-{
-  "object-format": "sha1",
-  "config": {"core.autocrlf": "false"},
-  "files": {"doc.md": "# Base\n"},
-  "setup-filter": true
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "command=smudge\n", "pathname=doc.md\n", "blob=18facc4e56a8bce5e46541f709ee6f884bb0350c\n", null,
-  "#   Incoming\n", null,
-  "command=smudge\n", "pathname=doc.md\n", null,
-  "#   Incoming\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=smudge\n", null,
-  "status=success\n", null, "#   Incoming\n", null, null,
-  "status=success\n", null, "#   Incoming\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_process_worktree_change.case b/tests/cases/git_filter_process_worktree_change.case
deleted file mode 100644
index 660d9614..00000000
--- a/tests/cases/git_filter_process_worktree_change.case
+++ /dev/null
@@ -1,39 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    "docs/doc.md": "#   Keep\n",
-    "next.toml": "[format]\nexclude = ['doc.md']\n",
-    "yamark.toml": "[format]\nexclude = ['unrelated.md']\n"
-  },
-  "setup-filter": true
-}
--- env
-{
-  "GIT_CONFIG_COUNT": "1",
-  "GIT_CONFIG_KEY_0": "filter.yamark-md.smudge",
-  "GIT_CONFIG_VALUE_0": "cp next.toml docs/yamark.toml && cat"
-}
--- args
-git-filter process
--- stdin-packets
-[
-  "git-filter-client\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "command=clean\n", "pathname=docs/doc.md\n", null, "#   Keep\n", null,
-  "command=smudge\n", "pathname=docs/doc.md\n", null, "edit config\n", null,
-  "command=clean\n", "pathname=docs/doc.md\n", null, "#   Keep\n", null
-]
--- stdout-packets
-[
-  "git-filter-server\n", "version=2\n", null,
-  "capability=clean\n", "capability=smudge\n", null,
-  "status=success\n", null, "# Keep\n", null, null,
-  "status=success\n", null, "edit config\n", null, null,
-  "status=success\n", null, "#   Keep\n", null, null
-]
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_smudge_declarative.case b/tests/cases/git_filter_smudge_declarative.case
deleted file mode 100644
index eb53f634..00000000
--- a/tests/cases/git_filter_smudge_declarative.case
+++ /dev/null
@@ -1,42 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false"
-  },
-  "files": {
-    "incoming/yamark.toml": "[format]\nmarkdown_horizontal_rule = \"***\"\n\n[embedded.example]\nformatter = { command = [\"yamark-test-formatter-not-installed\", \"{path}\"], path_suffix = \".txt\" }\n"
-  }
-}
--- args
-git-filter smudge --source-tree HEAD:incoming --stdin-filename post.md
--- stdin
----
-# fmt: example
-sample: |
-  unformatted  input
----
-
-# Draft
-
-- - -
-
-```example
-unformatted  input
-```
--- stdout
----
-# fmt: example
-sample: |
-  unformatted  input
----
-
-# Draft
-
-***
-
-```example
-unformatted  input
-```
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_smudge_inherited_pathspec.case b/tests/cases/git_filter_smudge_inherited_pathspec.case
deleted file mode 100644
index 85960ade..00000000
--- a/tests/cases/git_filter_smudge_inherited_pathspec.case
+++ /dev/null
@@ -1,18 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "[docs]/yamark.toml": "[format]\nexclude = [\"NEWS.md\"]\n"
-  }
-}
--- args
-git-filter smudge --source-tree HEAD --stdin-filename [docs]/NEWS.md
--- env
-{"GIT_ICASE_PATHSPECS": "1"}
--- stdin
-#   News
--- stdout
-#   News
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_smudge_source_tree.case b/tests/cases/git_filter_smudge_source_tree.case
deleted file mode 100644
index 706e18eb..00000000
--- a/tests/cases/git_filter_smudge_source_tree.case
+++ /dev/null
@@ -1,20 +0,0 @@
--- git-fixture
-{
-  "config": {"core.autocrlf": "false"},
-  "files": {
-    "incoming/docs/yamark.toml": "[format]\nexclude = [\"NEWS.md\"]\n"
-  }
-}
--- args
-git-filter smudge --source-tree HEAD:incoming --stdin-filename docs/NEWS.md
--- stdin
-#   News
-
-First sentence. Second sentence.
--- stdout
-#   News
-
-First sentence. Second sentence.
--- stderr
--- status
-0
diff --git a/tests/cases/git_filter_smudge_unverified_unsupported.case b/tests/cases/git_filter_smudge_unverified_unsupported.case
deleted file mode 100644
index f20834da..00000000
--- a/tests/cases/git_filter_smudge_unverified_unsupported.case
+++ /dev/null
@@ -1,11 +0,0 @@
--- args
-git-filter smudge --stdin-filename file.txt
--- env
-{"YAMARK_GIT_FILTER_SOURCE_TREE": ""}
--- stdin
-Original content.
--- stdout
--- stderr
-file.txt:1:1: error: unsupported Git filter path
--- status
-1
diff --git a/tests/cases/git_filter_teardown_legacy.case b/tests/cases/git_filter_teardown_legacy.case
deleted file mode 100644
index fcf9c625..00000000
--- a/tests/cases/git_filter_teardown_legacy.case
+++ /dev/null
@@ -1,31 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false",
-    "filter.yamark-md.clean": "cat",
-    "filter.yamark-md.smudge": "cat",
-    "filter.yamark-md.required": "true",
-    "merge.renormalize": "true"
-  },
-  "files": {
-    "file.txt": "fixture\n",
-    ".git/info/attributes": "*.md filter=yamark-md\n*.txt text\n"
-  }
-}
--- args
-git-filter teardown
--- stdin
--- stdout
-Removed yamark Git filter setup from {{repo}}
-Unset 3 local Git config value(s)
-Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
-
-Tracked files keep their current index content until staged again. Run:
-  git add --renormalize .
-if you want to restage them without the filter.
--- stderr
--- git-status
--- git-worktree
-{".git/info/attributes": "*.txt text\n"}
--- status
-0
diff --git a/tests/cases/git_filter_teardown_process.case b/tests/cases/git_filter_teardown_process.case
deleted file mode 100644
index b2c38b14..00000000
--- a/tests/cases/git_filter_teardown_process.case
+++ /dev/null
@@ -1,32 +0,0 @@
--- git-fixture
-{
-  "config": {
-    "core.autocrlf": "false",
-    "filter.yamark-md.clean": "cat",
-    "filter.yamark-md.smudge": "cat",
-    "filter.yamark-md.process": "yamark git-filter process",
-    "filter.yamark-md.required": "true",
-    "merge.renormalize": "true"
-  },
-  "files": {
-    "file.txt": "fixture\n",
-    ".git/info/attributes": "*.md filter=yamark-md\n*.txt text\n"
-  }
-}
--- args
-git-filter teardown
--- stdin
--- stdout
-Removed yamark Git filter setup from {{repo}}
-Unset 4 local Git config value(s)
-Removed 1 yamark attribute pattern(s) from {{repo}}/.git/info/attributes
-
-Tracked files keep their current index content until staged again. Run:
-  git add --renormalize .
-if you want to restage them without the filter.
--- stderr
--- git-status
--- git-worktree
-{".git/info/attributes": "*.txt text\n"}
--- status
-0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 57289d89..307682f3 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -4,13 +4,9 @@ use std::path::{Path, PathBuf};
 
 use assert_cmd::Command;
 
-#[path = "support/symlink.rs"]
-mod symlink;
-
 #[derive(Default)]
 struct Case {
     args: String,
-    env: BTreeMap,
     stdin: String,
     stdout: String,
     stderr: String,
@@ -49,23 +45,15 @@ fn cli_cases() {
         {
             continue;
         }
-        let repo = if let Some(fixture) = &case.git_fixture {
-            let Some(repo) = create_git_fixture(fixture) else {
-                continue;
-            };
-            Some(repo)
-        } else {
-            None
-        };
+        let repo = case.git_fixture.as_ref().map(create_git_fixture);
         let mut command = Command::cargo_bin("yamark").unwrap();
-        command.env("YAMARK_CASE_BIN", env!("CARGO_BIN_EXE_yamark"));
         if let Some(repo) = &repo {
             let cwd = case.git_fixture.as_ref().unwrap()["cwd"]
                 .as_str()
                 .unwrap_or(".");
             command.current_dir(repo.path().join(cwd));
         }
-        command.envs(&case.env).args(split_args(&case.args));
+        command.args(split_args(&case.args));
         command.write_stdin(case.stdin);
         let assert = command.assert().code(case.status);
         let output = assert.get_output();
@@ -185,7 +173,7 @@ fn case_selection_rejects_unmatched_filters() {
     }
 }
 
-fn create_git_fixture(fixture: &serde_json::Value) -> Option {
+fn create_git_fixture(fixture: &serde_json::Value) -> tempfile::TempDir {
     let repo = tempfile::tempdir().unwrap();
     let git = |args: &[&str]| {
         Command::new("git")
@@ -194,11 +182,7 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
             .assert()
             .success();
     };
-    if let Some(format) = fixture["object-format"].as_str() {
-        git(&["init", "-q", &format!("--object-format={format}")]);
-    } else {
-        git(&["init", "-q"]);
-    }
+    git(&["init", "-q"]);
     git(&["config", "user.name", "CLI Case"]);
     git(&["config", "user.email", "cli-case@example.test"]);
     git(&["config", "commit.gpgSign", "false"]);
@@ -243,49 +227,9 @@ fn create_git_fixture(fixture: &serde_json::Value) -> Option
                 .success();
         }
     }
-    if let Some(links) = fixture.get("hard-links") {
-        for (name, target) in links.as_object().unwrap() {
-            fs::hard_link(
-                repo.path().join(target.as_str().unwrap()),
-                repo.path().join(name),
-            )
-            .unwrap();
-        }
-    }
     git(&["add", "."]);
-    if let Some(links) = fixture.get("symlinks") {
-        for (name, target) in links.as_object().unwrap() {
-            let link = repo.path().join(name);
-            let target = repo.path().join(target.as_str().unwrap());
-            if !symlink::make_symlink(&target, &link) {
-                return None;
-            }
-            if fixture["track-symlinks"] == true {
-                git(&["add", "--", name]);
-            }
-        }
-    }
     git(&["commit", "-q", "-m", "fixture"]);
-    if let Some(commands) = fixture.get("git-after-commit") {
-        for args in commands.as_array().unwrap() {
-            let args: Vec<&str> = args
-                .as_array()
-                .unwrap()
-                .iter()
-                .map(|arg| arg.as_str().unwrap())
-                .collect();
-            git(&args);
-        }
-    }
-    if fixture["setup-filter"].as_bool() == Some(true) {
-        Command::cargo_bin("yamark")
-            .unwrap()
-            .current_dir(repo.path())
-            .args(["git-filter", "setup"])
-            .assert()
-            .success();
-    }
-    Some(repo)
+    repo
 }
 
 fn redact_repo(bytes: &[u8], repo: Option<&tempfile::TempDir>) -> String {
@@ -293,16 +237,8 @@ fn redact_repo(bytes: &[u8], repo: Option<&tempfile::TempDir>) -> String {
     let Some(repo) = repo else { return text };
     let root = repo.path().canonicalize().unwrap();
     let root = root.to_str().unwrap().trim_start_matches(r"\\?\");
-    let text = text
-        .replace(root, "{{repo}}")
-        .replace(&root.replace('\\', "/"), "{{repo}}");
-    // On Windows Path::join inserts a backslash between Git's
-    // slash-separated root and the relative path to info/attributes.
-    if cfg!(windows) {
-        text.replace(r"{{repo}}\", "{{repo}}/")
-    } else {
-        text
-    }
+    text.replace(root, "{{repo}}")
+        .replace(&root.replace('\\', "/"), "{{repo}}")
 }
 
 fn parse_case(input: &str) -> Case {
@@ -331,11 +267,8 @@ fn flush(case: &mut Case, section: &str, body: &str) {
     let value = body.strip_suffix('\n').unwrap_or(body);
     match section {
         "args" => case.args = value.to_owned(),
-        "env" => case.env = serde_json::from_str(value).unwrap(),
         "stdin" => case.stdin = body.to_owned(),
-        "stdin-packets" => case.stdin = packet_stream(value),
         "stdout" => case.stdout = body.to_owned(),
-        "stdout-packets" => case.stdout = packet_stream(value),
         "stderr" => case.stderr = body.to_owned(),
         "status" => case.status = value.trim().parse().unwrap(),
         "git-fixture" => case.git_fixture = Some(serde_json::from_str(value).unwrap()),
@@ -350,15 +283,3 @@ fn flush(case: &mut Case, section: &str, body: &str) {
 fn split_args(input: &str) -> Vec {
     input.split_whitespace().map(ToOwned::to_owned).collect()
 }
-
-fn packet_stream(json: &str) -> String {
-    use std::fmt::Write;
-    let mut stream = String::new();
-    for packet in serde_json::from_str::>>(json).unwrap() {
-        match packet {
-            Some(payload) => write!(stream, "{:04x}{payload}", payload.len() + 4).unwrap(),
-            None => stream.push_str("0000"),
-        }
-    }
-    stream
-}
diff --git a/tests/config_discovery.rs b/tests/config_discovery.rs
index 1cd25c30..6556d29f 100644
--- a/tests/config_discovery.rs
+++ b/tests/config_discovery.rs
@@ -2,23 +2,6 @@ use std::fs;
 
 use assert_cmd::Command;
 use tempfile::tempdir;
-use yamark::workspace::{FormatMode, format_paths};
-
-#[test]
-fn empty_write_paths_are_rejected_before_loading_config() {
-    let dir = tempdir().unwrap();
-    let error = format_paths(
-        vec![],
-        Default::default(),
-        FormatMode::Write,
-        Some(dir.path().join("missing.toml")),
-    )
-    .unwrap_err();
-    assert_eq!(
-        error.diagnostic.message,
-        "in-place formatting requires a file or directory path"
-    );
-}
 
 #[test]
 fn relative_file_and_directory_paths_discover_ancestor_config() {
diff --git a/tests/git_filter_paths.rs b/tests/git_filter_paths.rs
index c9d8ca6f..fc2349c4 100644
--- a/tests/git_filter_paths.rs
+++ b/tests/git_filter_paths.rs
@@ -5,7 +5,7 @@ use tempfile::tempdir;
 
 #[test]
 fn git_filter_adopts_quoted_names() {
-    check_git_filter_paths(&["café.md", "with space.md", "-it's $5!.md"]);
+    check_git_filter_paths(&["café.md", "with space.md"]);
 }
 
 // Windows filenames cannot contain line feeds, tabs, quotes, or backslashes.
@@ -192,50 +192,6 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     );
     git(&["commit", "-q", "-m", "adopt"]);
 
-    let copy = tempdir().unwrap();
-    git(&[
-        "worktree",
-        "add",
-        "-q",
-        "--detach",
-        copy.path().to_str().unwrap(),
-        "HEAD",
-    ]);
-    assert_eq!(fs::read(copy.path().join("NEWS.md")).unwrap(), utf16);
-    assert_eq!(
-        fs::read(copy.path().join("post.md")).unwrap(),
-        b"First sentence. Second sentence?\n"
-    );
-    assert!(git(&["-C", copy.path().to_str().unwrap(), "status", "--porcelain"]).is_empty());
-
-    // checkout-index supplies a blob without a source tree. Select its staged
-    // config even while both files are absent from the working directory.
-    fs::remove_file(copy.path().join("NEWS.md")).unwrap();
-    fs::remove_file(copy.path().join("post.md")).unwrap();
-    fs::remove_file(copy.path().join("yamark.toml")).unwrap();
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(dir.path())
-        .args(["git-filter", "check", "--repo"])
-        .arg(copy.path())
-        .assert()
-        .success()
-        .stderr("");
-    git(&[
-        "-C",
-        copy.path().to_str().unwrap(),
-        "checkout-index",
-        "--",
-        "NEWS.md",
-        "post.md",
-        "yamark.toml",
-    ]);
-    assert_eq!(fs::read(copy.path().join("NEWS.md")).unwrap(), utf16);
-    assert_eq!(
-        fs::read(copy.path().join("post.md")).unwrap(),
-        b"First sentence. Second sentence?\n"
-    );
-
     Command::cargo_bin("yamark")
         .unwrap()
         .current_dir(dir.path())
@@ -250,285 +206,6 @@ fn git_filter_adopts_a_repository_with_an_excluded_non_utf8_file() {
     fs::write(dir.path().join("NEWS.md"), revised).unwrap();
     git(&["add", "NEWS.md"]);
     assert_eq!(git(&["show", ":NEWS.md"]), revised);
-
-    // Switch both ways across a change to a nested config.
-    fs::create_dir(dir.path().join("docs")).unwrap();
-    let ordinary = b"First sentence. Second sentence?\n";
-    fs::write(dir.path().join("docs/notes.md"), ordinary).unwrap();
-    git(&["add", "docs"]);
-    git(&["commit", "-q", "-m", "selected notes"]);
-    let select = String::from_utf8(git(&["rev-parse", "HEAD"])).unwrap();
-    let copy_path = copy.path().to_str().unwrap();
-    git(&["-C", copy_path, "checkout", "-q", "--detach", select.trim()]);
-    assert_eq!(
-        fs::read(copy.path().join("docs/notes.md")).unwrap(),
-        ordinary
-    );
-    fs::write(
-        dir.path().join("docs/yamark.toml"),
-        "[format]\nexclude = [\"notes.md\"]\n",
-    )
-    .unwrap();
-    let excluded = b"#   New\n\nFirst sentence. Second sentence.\n";
-    fs::write(dir.path().join("docs/notes.md"), excluded).unwrap();
-    git(&["add", "docs"]);
-    git(&["commit", "-q", "-m", "excluded notes"]);
-    let skip = String::from_utf8(git(&["rev-parse", "HEAD"])).unwrap();
-    git(&["-C", copy_path, "checkout", "-q", "--detach", skip.trim()]);
-    assert_eq!(
-        fs::read(copy.path().join("docs/notes.md")).unwrap(),
-        excluded
-    );
-    assert!(git(&["-C", copy_path, "status", "--porcelain"]).is_empty());
-    git(&["-C", copy_path, "checkout", "-q", "--detach", select.trim()]);
-    assert_eq!(
-        fs::read(copy.path().join("docs/notes.md")).unwrap(),
-        ordinary
-    );
-    assert!(git(&["-C", copy_path, "status", "--porcelain"]).is_empty());
-
-    let unstaged = b"#   This spelling is intentional\n";
-    fs::write(copy.path().join("docs/notes.md"), unstaged).unwrap();
-    git(&[
-        "-C",
-        copy_path,
-        "-c",
-        "filter.yamark-md.clean=cat",
-        "add",
-        "docs/notes.md",
-    ]);
-    assert_eq!(git(&["-C", copy_path, "show", ":docs/notes.md"]), unstaged);
-}
-
-#[test]
-fn restores_under_pathspec_flags_use_literal_filter_config_paths() {
-    let dir = tempdir().unwrap();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(dir.path())
-            .args(args)
-            .assert()
-            .success();
-    };
-    git(&["init", "-q"]);
-    git(&["config", "user.name", "Git Filter Test"]);
-    git(&["config", "user.email", "git-filter@example.test"]);
-    git(&["config", "commit.gpgSign", "false"]);
-    git(&["config", "core.autocrlf", "false"]);
-    fs::create_dir(dir.path().join("[docs]")).unwrap();
-    fs::write(
-        dir.path().join("[docs]/yamark.toml"),
-        "[format]\nexclude = ['*.md']\n",
-    )
-    .unwrap();
-    let path = dir.path().join("[docs]/doc.md");
-    let original = b"#    Keep this spacing\n";
-    fs::write(&path, original).unwrap();
-    git(&["add", "."]);
-    git(&["commit", "-q", "-m", "fixture"]);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(dir.path())
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-    for flag in [
-        "--icase-pathspecs",
-        "--glob-pathspecs",
-        "--noglob-pathspecs",
-        "--literal-pathspecs",
-    ] {
-        fs::remove_file(&path).unwrap();
-        // "." is a directory selector under every pathspec mode.
-        git(&[flag, "restore", "--source=HEAD", "--worktree", "--", "."]);
-        assert_eq!(fs::read(&path).unwrap(), original, "{flag}");
-    }
-}
-
-#[test]
-fn non_fast_forward_merge_preserves_newly_excluded_bytes() {
-    check_incoming_exclusion(&["merge", "--no-ff", "--no-edit", "incoming"]);
-}
-
-#[test]
-fn cherry_pick_preserves_newly_excluded_bytes() {
-    check_incoming_exclusion(&["cherry-pick", "incoming"]);
-}
-
-fn check_incoming_exclusion(integrate: &[&str]) {
-    let dir = tempdir().unwrap();
-    let repo = dir.path();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(repo)
-            .args(args)
-            .assert()
-            .success()
-            .get_output()
-            .stdout
-            .clone()
-    };
-    git(&["init", "-q"]);
-    git(&["config", "user.name", "Git Filter Test"]);
-    git(&["config", "user.email", "git-filter@example.test"]);
-    git(&["config", "commit.gpgSign", "false"]);
-    git(&["config", "core.autocrlf", "false"]);
-    fs::write(repo.join("doc.md"), "# Base\n").unwrap();
-    git(&["add", "doc.md"]);
-    git(&["commit", "-qm", "base"]);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(repo)
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-    git(&["branch", "local"]);
-    git(&["checkout", "-qb", "incoming"]);
-    let incoming = b"#   Leave this heading alone\n";
-    fs::write(repo.join("yamark.toml"), "[format]\nexclude = ['doc.md']\n").unwrap();
-    fs::write(repo.join("doc.md"), incoming).unwrap();
-    git(&["add", "doc.md", "yamark.toml"]);
-    git(&["commit", "-qm", "exclude doc"]);
-    assert_eq!(git(&["show", "HEAD:doc.md"]), incoming);
-    git(&["checkout", "-q", "local"]);
-    fs::write(repo.join("other.txt"), "unrelated\n").unwrap();
-    git(&["add", "other.txt"]);
-    git(&["commit", "-qm", "diverge"]);
-
-    git(integrate);
-    assert_eq!(fs::read(repo.join("doc.md")).unwrap(), incoming);
-    assert_eq!(git(&["status", "--porcelain"]), b"");
-}
-
-#[test]
-fn smudge_anchors_a_stored_config_symlink_beside_its_name() {
-    let dir = tempdir().unwrap();
-    let repo = dir.path();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(repo)
-            .args(args)
-            .assert()
-            .success()
-            .get_output()
-            .stdout
-            .clone()
-    };
-    git(&["init", "-q"]);
-    // Git's own line-ending conversion is independent of the smudge filter.
-    fs::write(repo.join(".gitattributes"), "project/keep.md -text\n").unwrap();
-    fs::create_dir(repo.join("project")).unwrap();
-    fs::create_dir(repo.join("shared")).unwrap();
-    fs::write(repo.join("project/keep.md"), "#   Keep\n").unwrap();
-    fs::write(
-        repo.join("shared/settings.toml"),
-        "[format]\nexclude = [\"/keep.md\"]\n",
-    )
-    .unwrap();
-    git(&["add", ".gitattributes", "shared", "project"]);
-    // Stage a Git symlink without requiring the operating system to create one.
-    let link = Command::new("git")
-        .current_dir(repo)
-        .args(["hash-object", "-w", "--stdin"])
-        .write_stdin("../shared/settings.toml")
-        .assert()
-        .success()
-        .get_output()
-        .stdout
-        .clone();
-    let oid = std::str::from_utf8(&link).unwrap().trim();
-    git(&[
-        "update-index",
-        "--add",
-        "--cacheinfo",
-        "120000",
-        oid,
-        "project/yamark.toml",
-    ]);
-    let tree = git(&["write-tree"]);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(repo)
-        .args([
-            "git-filter",
-            "smudge",
-            "--source-tree",
-            std::str::from_utf8(&tree).unwrap().trim(),
-            "--stdin-filename",
-            "project/keep.md",
-        ])
-        .write_stdin("#   Keep\n")
-        .assert()
-        .success()
-        .stdout("#   Keep\n")
-        .stderr("");
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(repo)
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-    assert_eq!(
-        git(&["cat-file", "--filters", ":project/keep.md"]),
-        b"#   Keep\n"
-    );
-}
-
-#[test]
-fn check_and_smudge_exclude_a_blob_after_its_directory_is_deleted() {
-    let tmp = tempdir().unwrap();
-    let repo = tmp.path().join("repo");
-    let nested = repo.join("docs");
-    fs::create_dir_all(&nested).unwrap();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(&repo)
-            .args(args)
-            .assert()
-            .success()
-    };
-    let utf16 = [0xff, 0xfe, b'#', 0, b'\n', 0];
-    fs::write(repo.join(".gitattributes"), "*.md -text filter=yamark-md\n").unwrap();
-    fs::write(
-        nested.join("yamark.toml"),
-        "[format]\nexclude = ['keep.md']\n",
-    )
-    .unwrap();
-    fs::write(nested.join("keep.md"), utf16).unwrap();
-    git(&["init", "-q"]);
-    git(&["add", "."]);
-    git(&[
-        "-c",
-        "user.name=Tester",
-        "-c",
-        "user.email=test@example.test",
-        "-c",
-        "commit.gpgSign=false",
-        "commit",
-        "-qm",
-        "fixture",
-    ]);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(&repo)
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-    fs::remove_dir_all(nested).unwrap();
-
-    // On case-insensitive volumes Git retains the worktree spelling supplied
-    // here, while canonicalization may restore the directory entry's case.
-    let alias = tmp.path().join("REPO");
-    let worktree = if alias.is_dir() { &alias } else { &repo };
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(&repo)
-        .env("GIT_WORK_TREE", worktree)
-        .args(["git-filter", "check"])
-        .assert()
-        .success()
-        .stderr("");
-    git(&["cat-file", "--filters", ":docs/keep.md"]).stdout(utf16.to_vec());
 }
 
 fn check_git_filter_paths(paths: &[&str]) {
diff --git a/tests/git_filter_process.rs b/tests/git_filter_process.rs
deleted file mode 100644
index e08e58cc..00000000
--- a/tests/git_filter_process.rs
+++ /dev/null
@@ -1,273 +0,0 @@
-use std::fs;
-use std::path::Path;
-
-use assert_cmd::Command;
-use tempfile::tempdir;
-
-#[path = "support/symlink.rs"]
-mod symlink;
-
-#[test]
-fn default_filters_reuse_configuration_for_files_in_one_directory() {
-    let repo = tempdir().unwrap();
-    let root = repo.path();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(root)
-            .args(args)
-            .assert()
-            .success();
-    };
-    git(&["init", "-q"]);
-    git(&["config", "core.autocrlf", "false"]);
-    let names = ["one.md", "two.md", "three.md"];
-    fs::write(root.join("yamark.toml"), "[format]\nexclude = ['two.md']\n").unwrap();
-    for name in names {
-        fs::write(root.join(name), b"First sentence.\nSecond sentence?\n").unwrap();
-    }
-    git(&["add", "."]);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(root)
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-
-    let exe = Path::new(env!("CARGO_BIN_EXE_yamark"));
-    let git_starts = |command: &mut Command, bin_directory: &Path| {
-        let trace_dir = tempdir().unwrap();
-        let trace = trace_dir.path().join("events.jsonl");
-        let inherited = std::env::var_os("PATH").unwrap();
-        let path = std::env::join_paths(
-            std::iter::once(bin_directory.to_owned()).chain(std::env::split_paths(&inherited)),
-        )
-        .unwrap();
-        command
-            .current_dir(root)
-            .env("GIT_TRACE2_EVENT", &trace)
-            .env("PATH", path)
-            .assert()
-            .success();
-        fs::read_to_string(trace)
-            .unwrap()
-            .lines()
-            .map(|event| serde_json::from_str::(event).unwrap())
-            .filter(|event| event["event"] == "start")
-            .count()
-    };
-    let checkout = |files: &[&str], bin: &Path| {
-        for name in files {
-            fs::remove_file(root.join(name)).unwrap();
-        }
-        git_starts(
-            Command::new("git")
-                .args(["checkout-index", "--"])
-                .args(files),
-            bin,
-        )
-    };
-    let hash = |files: &[&str], bin: &Path| {
-        git_starts(
-            Command::new("git")
-                .args(["hash-object", "--stdin-paths"])
-                .write_stdin(format!("{}\n", files.join("\n"))),
-            bin,
-        )
-    };
-    let assert_reuse = |bin: &Path| {
-        let single = checkout(&names[..1], bin);
-        let multiple = checkout(&names, bin);
-        assert!(single > 0);
-        assert_eq!(
-            multiple, single,
-            "extra Git processes for files sharing a config"
-        );
-        assert_eq!(
-            hash(&names, bin),
-            hash(&names[..1], bin),
-            "extra Git processes for clean"
-        );
-    };
-    assert_reuse(exe.parent().unwrap());
-    git(&[
-        "config",
-        "filter.yamark-md.clean",
-        "yamark git-filter clean --stdin-filename %f",
-    ]);
-    git(&[
-        "config",
-        "filter.yamark-md.smudge",
-        "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72",
-    ]);
-    assert_reuse(exe.parent().unwrap());
-    let links = tempfile::Builder::new()
-        .prefix("yamark bin ")
-        .tempdir()
-        .unwrap();
-    if symlink::make_symlink(exe, &links.path().join(exe.file_name().unwrap())) {
-        assert_reuse(links.path());
-    }
-    for name in names {
-        let expected = if name == "two.md" {
-            "First sentence.\nSecond sentence?\n"
-        } else {
-            "First sentence. Second sentence?\n"
-        };
-        assert_eq!(fs::read_to_string(root.join(name)).unwrap(), expected);
-    }
-
-    // The same command spelling can resolve to a local wrapper.
-    let alternate = tempdir().unwrap();
-    let wrapper = alternate.path().join("yamark");
-    fs::write(&wrapper, "#!/bin/sh\nprintf 'Separate driver\\n'\n").unwrap();
-    #[cfg(unix)]
-    {
-        use std::os::unix::fs::PermissionsExt;
-        fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
-    }
-    checkout(&names[..1], alternate.path());
-    assert_eq!(fs::read(root.join("one.md")).unwrap(), b"Separate driver\n");
-}
-
-#[test]
-fn an_unmerged_config_preserves_utf16_on_checkout_from_the_index() {
-    let repo = tempdir().unwrap();
-    let root = repo.path();
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(root)
-            .args(args)
-            .assert()
-            .success()
-            .get_output()
-            .stdout
-            .clone()
-    };
-    git(&["init", "-q"]);
-    git(&["config", "core.autocrlf", "false"]);
-    let original = [0xff, 0xfe, b'#', 0, b' ', 0, b'1', 0, b'\n', 0];
-    fs::write(root.join("doc.md"), original).unwrap();
-    fs::write(root.join("yamark.toml"), "[format]\nexclude = ['doc.md']\n").unwrap();
-    git(&["add", "."]);
-    let oid = String::from_utf8(git(&["rev-parse", ":yamark.toml"])).unwrap();
-    git(&["update-index", "--force-remove", "yamark.toml"]);
-    // An add/add conflict has no stage zero for the config. Both stages
-    // exclude doc.md, even though they differ on a second path.
-    let theirs = Command::new("git")
-        .current_dir(root)
-        .args(["hash-object", "-w", "--stdin"])
-        .write_stdin("[format]\nexclude = ['doc.md', 'also.md']\n")
-        .assert()
-        .success();
-    let theirs = std::str::from_utf8(&theirs.get_output().stdout).unwrap();
-    Command::new("git")
-        .current_dir(root)
-        .args(["update-index", "--index-info"])
-        .write_stdin(format!(
-            "100644 {} 2\tyamark.toml\n100644 {} 3\tyamark.toml\n",
-            oid.trim(),
-            theirs.trim()
-        ))
-        .assert()
-        .success();
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(root)
-        .args(["git-filter", "setup"])
-        .assert()
-        .success();
-    let output = String::from_utf8(git(&["checkout-index", "--temp", "--", "doc.md"])).unwrap();
-    let temporary = output.strip_suffix("\tdoc.md\n").unwrap();
-    assert_eq!(fs::read(root.join(temporary)).unwrap(), original);
-}
-
-#[test]
-fn adoption_and_join_batch_worktree_conversions() {
-    for action in ["adopt", "join"] {
-        let count_checkouts = |files: &[&str]| {
-            let repo = tempdir().unwrap();
-            let root = repo.path();
-            if action == "join" {
-                fs::write(root.join(".gitattributes"), "*.md filter=yamark-md\n").unwrap();
-            }
-            for name in files {
-                fs::write(root.join(name), "First sentence.\nSecond sentence?\n").unwrap();
-            }
-            commit_files(root);
-
-            let traces = tempdir().unwrap();
-            let trace = traces.path().join("filter-events.jsonl");
-            Command::cargo_bin("yamark")
-                .unwrap()
-                .current_dir(root)
-                .env("GIT_TRACE2_EVENT", &trace)
-                .args(["git-filter", action])
-                .assert()
-                .success();
-            for name in files {
-                assert_eq!(
-                    fs::read(root.join(name)).unwrap(),
-                    b"First sentence. Second sentence?\n"
-                );
-            }
-            fs::read_to_string(trace)
-                .unwrap()
-                .lines()
-                .map(|line| serde_json::from_str::(line).unwrap())
-                .filter(|event| {
-                    // Count Git checkout invocations, including filtered blob
-                    // reads. Later status checks may run a clean filter when
-                    // Git considers an entry racily clean on this filesystem.
-                    if event["event"] != "start" {
-                        return false;
-                    }
-                    let args = event["argv"].as_array().unwrap();
-                    args.iter().any(|arg| arg == "checkout-index")
-                        || (args.iter().any(|arg| arg == "cat-file")
-                            && args.iter().any(|arg| arg == "--filters"))
-                })
-                .count()
-        };
-
-        let one = count_checkouts(&["one.md"]);
-        let three = count_checkouts(&["one.md", "two.md", "three.md"]);
-        assert!(one > 0);
-        assert_eq!(
-            three, one,
-            "{action} dispatched new checkouts for additional targets"
-        );
-    }
-}
-
-#[test]
-fn failed_join_checkout_preserves_existing_files() {
-    let dir = tempdir().unwrap();
-    let repo = dir.path();
-    fs::write(repo.join(".gitattributes"), "*.md filter=yamark-md\n").unwrap();
-    fs::write(repo.join("keep.md"), "# Keep\n").unwrap();
-    commit_files(repo);
-    Command::cargo_bin("yamark")
-        .unwrap()
-        .current_dir(repo)
-        .args(["git-filter", "join", "--yamark"])
-        .arg(repo.join("missing-yamark"))
-        .assert()
-        .failure();
-    assert_eq!(fs::read(repo.join("keep.md")).unwrap(), b"# Keep\n");
-}
-fn commit_files(repo: &Path) {
-    let git = |args: &[&str]| {
-        Command::new("git")
-            .current_dir(repo)
-            .args(args)
-            .assert()
-            .success();
-    };
-    git(&["init", "-q"]);
-    git(&["config", "user.name", "Git Filter Test"]);
-    git(&["config", "user.email", "git-filter@example.test"]);
-    git(&["config", "commit.gpgSign", "false"]);
-    git(&["config", "core.autocrlf", "false"]);
-    git(&["add", "."]);
-    git(&["commit", "-qm", "fixture"]);
-}
diff --git a/tests/spec_cli/workspace.rs b/tests/spec_cli/workspace.rs
index 11ab01b9..ad0b2a1a 100644
--- a/tests/spec_cli/workspace.rs
+++ b/tests/spec_cli/workspace.rs
@@ -1,8 +1,6 @@
 use super::support::{run_stdin, yamark};
-#[path = "../support/symlink.rs"]
-mod symlink;
 use std::fs;
-use symlink::make_symlink;
+use std::path::Path;
 use tempfile::tempdir;
 
 #[test]
@@ -632,14 +630,13 @@ fn exclude_matches_an_absolute_virtual_stdin_path() {
     assert_eq!((status, stdout.as_str(), stderr.as_str()), (0, input, ""));
 }
 
+#[cfg(unix)]
 #[test]
 fn exclude_matches_a_virtual_stdin_path_below_a_symlinked_directory() {
     let dir = tempdir().unwrap();
     let real = dir.path().join("real");
     fs::create_dir(&real).unwrap();
-    if !make_symlink(&real, &dir.path().join("link")) {
-        return;
-    }
+    std::os::unix::fs::symlink(&real, dir.path().join("link")).unwrap();
     fs::write(real.join("yamark.toml"), "[format]\nexclude = [\"new/\"]\n").unwrap();
     let path = dir.path().join("link").join("new").join("deck.qmd");
     let input = "#   Title\n";
@@ -682,6 +679,7 @@ fn exclude_matches_a_symlinked_file_by_its_own_name() {
     );
 }
 
+#[cfg(unix)]
 #[test]
 fn exclude_matches_a_symlinked_directory_by_its_own_name() {
     let dir = tempdir().unwrap();
@@ -693,9 +691,7 @@ fn exclude_matches_a_symlinked_directory_by_its_own_name() {
     .unwrap();
     let input = "#   Title\n";
     fs::write(outside.path().join("deck.md"), input).unwrap();
-    if !make_symlink(outside.path(), &dir.path().join("slides")) {
-        return;
-    }
+    std::os::unix::fs::symlink(outside.path(), dir.path().join("slides")).unwrap();
 
     let output = yamark()
         .current_dir(dir.path())
@@ -843,6 +839,24 @@ fn non_spec_hard_break_space_config_is_rejected() {
     );
 }
 
+#[cfg(unix)]
+fn make_symlink(path: &Path, link: &Path) -> bool {
+    std::os::unix::fs::symlink(path, link).unwrap();
+    true
+}
+
+#[cfg(windows)]
+fn make_symlink(path: &Path, link: &Path) -> bool {
+    match std::os::windows::fs::symlink_file(path, link) {
+        Ok(()) => true,
+        Err(err) if err.raw_os_error() == Some(1314) => {
+            eprintln!("symlink test requires Windows Developer Mode or symlink privileges: {err}");
+            false
+        }
+        Err(err) => panic!("failed to create symlink: {err}"),
+    }
+}
+
 #[test]
 fn template_delimiter_entries_reject_unknown_fields() {
     let dir = tempdir().unwrap();
diff --git a/tests/support/symlink.rs b/tests/support/symlink.rs
deleted file mode 100644
index bc1210a8..00000000
--- a/tests/support/symlink.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use std::path::Path;
-
-pub fn make_symlink(target: &Path, link: &Path) -> bool {
-    #[cfg(unix)]
-    let result = std::os::unix::fs::symlink(target, link);
-    #[cfg(windows)]
-    let result = if target.is_dir() {
-        std::os::windows::fs::symlink_dir(target, link)
-    } else {
-        std::os::windows::fs::symlink_file(target, link)
-    };
-    match result {
-        Ok(()) => true,
-        #[cfg(windows)]
-        Err(err) if err.raw_os_error() == Some(1314) => {
-            eprintln!("symlink test requires Windows Developer Mode or symlink privileges: {err}");
-            false
-        }
-        Err(err) => panic!("failed to create symlink {}: {err}", link.display()),
-    }
-}
diff --git a/tests/website.rs b/tests/website.rs
index 70966447..e38f07d6 100644
--- a/tests/website.rs
+++ b/tests/website.rs
@@ -1281,8 +1281,7 @@ fn website_documents_user_facing_references() {
         "A multi-file write run is not transactional",
         "Extension matching is ASCII case-insensitive",
         "unsupported extensions are counted as skipped and do not make the run fail",
-        "Yamark exits `1` for an unsupported extension unless the path is excluded",
-        "copies stdin to stdout byte for byte and exits `0`",
+        "unsupported `--stdin-file-path` is an error",
         "writes are direct rather than atomic",
         "does not promise rollback",
     ] {
@@ -1381,9 +1380,8 @@ fn website_documents_command_line_reference() {
             "`yamark format --stdin-file-path PATH`",
             "`yamark to-yaml --stdin-file-path PATH`",
             "Use `yamark format .` to format the current directory and its subdirectories.",
-            "With `--check` or `--diff`, omitting the path selects the current directory.",
-            "Yamark exits `1` for an unsupported extension unless the path is excluded",
-            "copies stdin to stdout byte for byte and exits `0`",
+            "With `--check` or `--diff`, omitting the path selects the current directory (`.`).",
+            "An unsupported `--stdin-file-path` is an error",
             "Unified diffs",
             "Formatted YAML only",
             "exits `1`",
@@ -1579,8 +1577,6 @@ fn website_documents_editor_and_git_filter_integrations() {
         "yamark git-filter check",
         "filter.yamark-md.clean",
         "filter.yamark-md.smudge",
-        "filter.yamark-md.process",
-        "--source-tree",
         ".gitattributes",
         "git add --renormalize .",
         "clean(smudge(blob)) == blob",
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index 5e0c3a3e..212e1922 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -22,7 +22,7 @@ generated from the current Yamark binary.
 | `yamark format PATHS` | Writes changed files. | Summary. | Failures and requested diagnostics. |
 | `yamark format --check PATHS` | Does not write. | - | Summary, failures, and requested diagnostics. |
 | `yamark format --diff PATHS` | Does not write. | Unified diffs. | Summary, failures, and requested diagnostics. |
-| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content or the original bytes for an excluded path. | Failures and requested diagnostics. |
+| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content only. | Failures and requested diagnostics. |
 | `yamark to-yaml --stdin-file-path PATH` | Does not read or write `PATH`; uses its JSON-family suffix to parse stdin. | Formatted YAML only. | Failures. |
 
 `--check` and `--diff` exit `1` when any selected file would change. Every mode
@@ -31,12 +31,10 @@ syntax exits `2`.
 
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
-With `--check` or `--diff`, omitting the path selects the current directory.
-
-Format path mode counts unsupported extensions as skipped without failing.
-With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
-the path is excluded. For an excluded path, it copies stdin to stdout byte for
-byte and exits `0`.
+With `--check` or `--diff`, omitting the path selects the current directory
+(`.`). Format path mode counts unsupported extensions as skipped without
+failing. An unsupported `--stdin-file-path` is an error because stdin mode
+requires a supported file type.
 
 Format stdin mode rejects additional paths and cannot be combined with
 `--check` or `--diff`. `yamark to-yaml` always reads stdin, requires a `.json`,
@@ -73,7 +71,7 @@ Run `yamark <COMMAND> --help` for command-level help.
 
Usage: yamark format [OPTIONS] [PATHS]...
 
 Arguments:
-  [PATHS]...  Files or directories to format in place (required for writes). Use '.' for the current directory
+  [PATHS]...  Files or directories to format in place. Use '.' for the current directory
 
 Options:
       --check
@@ -128,7 +126,6 @@ Configure the filter driver with:
   yamark git-filter teardown
   git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
   git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
-  git config filter.yamark-md.process "yamark git-filter process"
 
 Git only runs the filter for paths matched by attributes. Put these patterns in
 .git/info/attributes for personal use or .gitattributes for a shared repo:
@@ -142,7 +139,6 @@ Git only runs the filter for paths matched by attributes. Put these patterns in
 Commands:
   clean
   smudge
-  process   Serve Git's process filter protocol for checkout-aware smudging
   adopt     Adopt the yamark Git filter for a shared repository
   join      Join a repository that has already adopted the yamark Git filter
   check     Check committed yamark Git filter blobs round-trip safely
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index 2b17598e..cf14c87e 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -55,7 +55,7 @@ generated from the current Yamark binary.
 | `yamark format PATHS` | Writes changed files. | Summary. | Failures and requested diagnostics. |
 | `yamark format --check PATHS` | Does not write. | - | Summary, failures, and requested diagnostics. |
 | `yamark format --diff PATHS` | Does not write. | Unified diffs. | Summary, failures, and requested diagnostics. |
-| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content or the original bytes for an excluded path. | Failures and requested diagnostics. |
+| `yamark format --stdin-file-path PATH` | Does not read or write `PATH`; uses it to select file-aware behavior for stdin. | Formatted content only. | Failures and requested diagnostics. |
 | `yamark to-yaml --stdin-file-path PATH` | Does not read or write `PATH`; uses its JSON-family suffix to parse stdin. | Formatted YAML only. | Failures. |
 
 `--check` and `--diff` exit `1` when any selected file would change. Every mode
@@ -64,12 +64,10 @@ syntax exits `2`.
 
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
-With `--check` or `--diff`, omitting the path selects the current directory.
-
-Format path mode counts unsupported extensions as skipped without failing.
-With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
-the path is excluded. For an excluded path, it copies stdin to stdout byte for
-byte and exits `0`.
+With `--check` or `--diff`, omitting the path selects the current directory
+(`.`). Format path mode counts unsupported extensions as skipped without
+failing. An unsupported `--stdin-file-path` is an error because stdin mode
+requires a supported file type.
 
 Format stdin mode rejects additional paths and cannot be combined with
 `--check` or `--diff`. `yamark to-yaml` always reads stdin, requires a `.json`,
diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index 7bdfb24d..d7b7477f 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -29,23 +29,6 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
-Yamark's clean and smudge commands and its round-trip checks skip external embedded formatters. Checkout applies the revision's formatting settings even before its tools are available. To format embedded code with those tools, run `yamark format ` in a trusted checkout. Git still runs custom clean or smudge commands you configure in your local Git settings.
-
-During checkout, Git 2.27 and later can send the incoming tree to the process
-filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
-`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies
-no tree, smudge uses the staged configuration if Git identifies the file's
-staged blob. If the blob is missing or differs from the staged blob, as can
-happen during a merge or cherry-pick, smudge returns the incoming bytes
-unchanged. A merge conflict in the nearest staged config or its symlink target
-also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
-symbolic link, its target must be present in the selected tree or index. Clean
-reads the nearest working-tree config on each request. Discovery stops at the
-worktree root, and Yamark uses its defaults if it finds no config there or below.
-
-Invoking `yamark git-filter smudge` directly uses the working-tree config.
-Pass `--source-tree ` to read configuration from a particular tree.
-
 Unsupported paths fail. The filter is for Markdown-like files, not YAML or
 source files.
 
@@ -90,13 +73,6 @@ files, and checks the codec invariant:
 clean(smudge(blob)) == blob
 ```
 
-`adopt` and `join` process regular files in Git's index. Both skip symbolic links
-and submodules. Changed files retain their local permissions and ownership.
-If a file needs rewrapping and has multiple hard links, the command reports
-the path so you can separate the links before trying again. If another Git
-operation changes or locks the index during the final refresh, adoption
-leaves the staged changes available for review.
-
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:
 
@@ -128,12 +104,7 @@ contract:
 yamark git-filter check
 ```
 
-It checks the regular Markdown files in `HEAD`, using the committed versions of
-`.gitattributes` and `yamark.toml`, even if the files are missing from the
-working tree. Checking a commit leaves the index alone and skips its
-`post-index-change` hooks. Git still applies its usual attribute
-precedence, including overrides in `.git/info/attributes`. The check fails
-if any selected file violates:
+It fails if any tracked Markdown file selected by `.gitattributes` violates:
 
 ```text
 clean(smudge(blob)) == blob
@@ -161,27 +132,15 @@ Use `--repo path/to/repo` when running from outside the repository. Use
 Setup prints the local files and config keys it changed, plus the commands below
 for undoing or bypassing the filter.
 
-If you already have clean and smudge commands configured, add the
-`filter.yamark-md.process` setting below to use the checkout tree's config.
-`adopt`, `join`, and `setup` install this setting automatically.
-
 To configure the same pieces manually, set the filter driver:
 
 ```sh
 git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
-git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
+git config merge.renormalize true
 ```
 
-Leave Git's `merge.renormalize` disabled when exclusions can differ between
-branches. During a two-sided merge, renormalization can run historical blobs
-through the current branch's clean filter and rewrite a file that the incoming
-branch excludes. If an earlier Yamark installation set this option in your
-clone, remove its setting with `git config --local --unset merge.renormalize`.
-
-Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
-
 For personal use, add attributes to `.git/info/attributes`. For shared project
 storage, use `yamark git-filter adopt` so the attributes and normalized blobs
 land in the same commit. The shared attributes look like:
@@ -245,22 +204,6 @@ pass through the filter but Yamark should preserve its contents. A file matched
 by [`exclude`](reference-config.qmd#excluded-files) in `yamark.toml` also passes
 through the filter byte for byte, so it need not be UTF-8.
 
-### Refresh a file after changing exclusions
-
-If two commits differ only in `yamark.toml`, Git can leave an unchanged
-Markdown blob on disk with its old wrapping. The next `git add` can then stage
-that wrapping as an edit to a newly excluded file.
-
-To see the working-tree version produced by the staged rules, run:
-
-```sh
-git checkout-index --temp -- NEWS.md
-```
-
-Git writes a temporary file and prints its name alongside `NEWS.md`. Compare
-the two files. If you have local edits, copy them into the temporary file
-before replacing `NEWS.md` with it. This refresh leaves the index intact.
-
 ## Diff shape
 
 Without the filter, editing one sentence inside a wrapped paragraph can modify
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index 7bdfb24d..d7b7477f 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -29,23 +29,6 @@ yamark git-filter smudge --stdin-filename docs/file.md --markdown-wrap-at-column
 It formats Markdown with column wrapping. Both directions use compact pipe-table
 output to keep storage diffs small.
 
-Yamark's clean and smudge commands and its round-trip checks skip external embedded formatters. Checkout applies the revision's formatting settings even before its tools are available. To format embedded code with those tools, run `yamark format ` in a trusted checkout. Git still runs custom clean or smudge commands you configure in your local Git settings.
-
-During checkout, Git 2.27 and later can send the incoming tree to the process
-filter. Yamark looks up the nearest tracked `yamark.toml` in that tree, so an exclusion for
-`NEWS.md` applies even if Git checks out `NEWS.md` first. When Git supplies
-no tree, smudge uses the staged configuration if Git identifies the file's
-staged blob. If the blob is missing or differs from the staged blob, as can
-happen during a merge or cherry-pick, smudge returns the incoming bytes
-unchanged. A merge conflict in the nearest staged config or its symlink target
-also preserves the bytes until you resolve the conflict. If `yamark.toml` is a
-symbolic link, its target must be present in the selected tree or index. Clean
-reads the nearest working-tree config on each request. Discovery stops at the
-worktree root, and Yamark uses its defaults if it finds no config there or below.
-
-Invoking `yamark git-filter smudge` directly uses the working-tree config.
-Pass `--source-tree ` to read configuration from a particular tree.
-
 Unsupported paths fail. The filter is for Markdown-like files, not YAML or
 source files.
 
@@ -90,13 +73,6 @@ files, and checks the codec invariant:
 clean(smudge(blob)) == blob
 ```
 
-`adopt` and `join` process regular files in Git's index. Both skip symbolic links
-and submodules. Changed files retain their local permissions and ownership.
-If a file needs rewrapping and has multiple hard links, the command reports
-the path so you can separate the links before trying again. If another Git
-operation changes or locks the index during the final refresh, adoption
-leaves the staged changes available for review.
-
 Use `--markdown-wrap-at-column ` to change the working-tree wrap width. Pass
 paths to adopt only specific Markdown files:
 
@@ -128,12 +104,7 @@ contract:
 yamark git-filter check
 ```
 
-It checks the regular Markdown files in `HEAD`, using the committed versions of
-`.gitattributes` and `yamark.toml`, even if the files are missing from the
-working tree. Checking a commit leaves the index alone and skips its
-`post-index-change` hooks. Git still applies its usual attribute
-precedence, including overrides in `.git/info/attributes`. The check fails
-if any selected file violates:
+It fails if any tracked Markdown file selected by `.gitattributes` violates:
 
 ```text
 clean(smudge(blob)) == blob
@@ -161,27 +132,15 @@ Use `--repo path/to/repo` when running from outside the repository. Use
 Setup prints the local files and config keys it changed, plus the commands below
 for undoing or bypassing the filter.
 
-If you already have clean and smudge commands configured, add the
-`filter.yamark-md.process` setting below to use the checkout tree's config.
-`adopt`, `join`, and `setup` install this setting automatically.
-
 To configure the same pieces manually, set the filter driver:
 
 ```sh
 git config filter.yamark-md.clean "yamark git-filter clean --stdin-filename %f"
 git config filter.yamark-md.smudge "yamark git-filter smudge --stdin-filename %f --markdown-wrap-at-column 72"
-git config filter.yamark-md.process "yamark git-filter process"
 git config filter.yamark-md.required true
+git config merge.renormalize true
 ```
 
-Leave Git's `merge.renormalize` disabled when exclusions can differ between
-branches. During a two-sided merge, renormalization can run historical blobs
-through the current branch's clean filter and rewrite a file that the incoming
-branch excludes. If an earlier Yamark installation set this option in your
-clone, remove its setting with `git config --local --unset merge.renormalize`.
-
-Use Git's usual unquoted `%f` as a separate filename argument in a custom clean or smudge command. Yamark's process filter also accepts `'%f'` and `"%f"` as whole arguments and passes a filename with spaces as one argument in all three forms. If a command relies on Git's substitution within a larger quoted shell expression, use Git's single-file drivers by running `git config --local --unset filter.yamark-md.process`. The configured clean and smudge commands then handle each file directly.
-
 For personal use, add attributes to `.git/info/attributes`. For shared project
 storage, use `yamark git-filter adopt` so the attributes and normalized blobs
 land in the same commit. The shared attributes look like:
@@ -245,22 +204,6 @@ pass through the filter but Yamark should preserve its contents. A file matched
 by [`exclude`](reference-config.qmd#excluded-files) in `yamark.toml` also passes
 through the filter byte for byte, so it need not be UTF-8.
 
-### Refresh a file after changing exclusions
-
-If two commits differ only in `yamark.toml`, Git can leave an unchanged
-Markdown blob on disk with its old wrapping. The next `git add` can then stage
-that wrapping as an edit to a newly excluded file.
-
-To see the working-tree version produced by the staged rules, run:
-
-```sh
-git checkout-index --temp -- NEWS.md
-```
-
-Git writes a temporary file and prints its name alongside `NEWS.md`. Compare
-the two files. If you have local edits, copy them into the temporary file
-before replacing `NEWS.md` with it. This refresh leaves the index intact.
-
 ## Diff shape
 
 Without the filter, editing one sentence inside a wrapped paragraph can modify
diff --git a/website/reference-config.html.md b/website/reference-config.html.md
index 858ce6fe..e502354b 100644
--- a/website/reference-config.html.md
+++ b/website/reference-config.html.md
@@ -41,23 +41,15 @@ exclude = ["slides/", "*.generated.md", "/NEWS.md"]
 `exclude` lists files that `yamark format` leaves unchanged. Patterns use
 [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) and are
 relative to the directory containing `yamark.toml` or the file passed with
-`--config`. For example, if `project/yamark.toml` is a symbolic link to shared
-settings, `/NEWS.md` selects `project/NEWS.md`. Names below the config
-directory match as written, including symbolic link names.
-
-A pattern without a slash matches at any depth. Braces match literally, so
-`{id}.md` selects files named `{id}.md`. A leading slash anchors the pattern to
-the config directory, and a trailing slash matches a directory and everything below it. A
+`--config`. Names below that directory are matched as written, so a symbolic
+link matches by its own name, not its target's. A pattern without a slash
+matches at any depth. A leading slash anchors the pattern to the config
+directory, and a trailing slash matches a directory and everything below it. A
 later `!` pattern re-includes a file matched by a file-level pattern. As in
 Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
-Character classes match one byte within a path component. For example,
-`[[:digit:]]*.md` matches `1-report.md`, and `[a\-c].md` matches `a.md`,
-`-.md`, and `c.md`. A negated class such as `[!0-9]` cannot match a path
-separator. Yamark reports malformed classes before formatting.
-
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:
 
diff --git a/website/reference-config.qmd b/website/reference-config.qmd
index 858ce6fe..e502354b 100644
--- a/website/reference-config.qmd
+++ b/website/reference-config.qmd
@@ -41,23 +41,15 @@ exclude = ["slides/", "*.generated.md", "/NEWS.md"]
 `exclude` lists files that `yamark format` leaves unchanged. Patterns use
 [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) and are
 relative to the directory containing `yamark.toml` or the file passed with
-`--config`. For example, if `project/yamark.toml` is a symbolic link to shared
-settings, `/NEWS.md` selects `project/NEWS.md`. Names below the config
-directory match as written, including symbolic link names.
-
-A pattern without a slash matches at any depth. Braces match literally, so
-`{id}.md` selects files named `{id}.md`. A leading slash anchors the pattern to
-the config directory, and a trailing slash matches a directory and everything below it. A
+`--config`. Names below that directory are matched as written, so a symbolic
+link matches by its own name, not its target's. A pattern without a slash
+matches at any depth. A leading slash anchors the pattern to the config
+directory, and a trailing slash matches a directory and everything below it. A
 later `!` pattern re-includes a file matched by a file-level pattern. As in
 Git, a `!` pattern cannot re-include a file below an excluded directory,
 regardless of pattern order. Patterns never match a file outside the config
 directory.
 
-Character classes match one byte within a path component. For example,
-`[[:digit:]]*.md` matches `1-report.md`, and `[a\-c].md` matches `a.md`,
-`-.md`, and `c.md`. A negated class such as `[!0-9]` cannot match a path
-separator. Yamark reports malformed classes before formatting.
-
 Ignore files such as `.gitignore` and `.ignore` affect only directory traversal.
 `exclude` also applies to explicit paths and stdin:
 
diff --git a/website/reference-files.html.md b/website/reference-files.html.md
index 0b3088ba..eb41f913 100644
--- a/website/reference-files.html.md
+++ b/website/reference-files.html.md
@@ -22,10 +22,8 @@ the output.
 | YAML literal scalars following `# fmt: ` or `# fmt: embedded ` | The scalar value through a built-in or configured embedded formatter. | Explicit directive. |
 
 Extension matching is ASCII case-insensitive. In path mode, unsupported
-extensions are counted as skipped and do not make the run fail.
-With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
-the path is excluded. For an excluded path, it copies stdin to stdout byte for
-byte and exits `0`.
+extensions are counted as skipped and do not make the run fail. An unsupported
+`--stdin-file-path` is an error because stdin mode requires file-aware behavior.
 
 Directory traversal skips hidden paths and respects `.gitignore`, `.ignore`,
 and global Git ignore files. Passing a hidden path explicitly selects it. To
diff --git a/website/reference-files.qmd b/website/reference-files.qmd
index 0b3088ba..eb41f913 100644
--- a/website/reference-files.qmd
+++ b/website/reference-files.qmd
@@ -22,10 +22,8 @@ the output.
 | YAML literal scalars following `# fmt: ` or `# fmt: embedded ` | The scalar value through a built-in or configured embedded formatter. | Explicit directive. |
 
 Extension matching is ASCII case-insensitive. In path mode, unsupported
-extensions are counted as skipped and do not make the run fail.
-With `--stdin-file-path`, Yamark exits `1` for an unsupported extension unless
-the path is excluded. For an excluded path, it copies stdin to stdout byte for
-byte and exits `0`.
+extensions are counted as skipped and do not make the run fail. An unsupported
+`--stdin-file-path` is an error because stdin mode requires file-aware behavior.
 
 Directory traversal skips hidden paths and respects `.gitignore`, `.ignore`,
 and global Git ignore files. Passing a hidden path explicitly selects it. To

From 021f7817be4b0e0e6c06660aeb600c4a01563513 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 16:02:47 -0500
Subject: [PATCH 56/64] Keep missing-path CLI transcripts portable

---
 tests/cases/README.md                            |  2 +-
 tests/cases/format_missing_path.case             |  2 +-
 tests/cases/format_missing_path_with_config.case |  2 +-
 tests/cli_cases.rs                               | 10 ++++++++--
 4 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/tests/cases/README.md b/tests/cases/README.md
index 97fa0edd..9a4052eb 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -1,6 +1,6 @@
 # CLI case files
 
-Each `.case` file is executed through the compiled `yamark` binary. The format is:
+Each `.case` file runs the compiled `yamark` binary with `NO_COLOR=1`. In expected stdout and stderr, `{{exe}}` expands to the executable's basename (for example, `yamark.exe` on Windows). The format is:
 
 ```text
 -- args
diff --git a/tests/cases/format_missing_path.case b/tests/cases/format_missing_path.case
index 447c633b..0e2110ee 100644
--- a/tests/cases/format_missing_path.case
+++ b/tests/cases/format_missing_path.case
@@ -11,7 +11,7 @@ format
 error: the following required arguments were not provided:
   ...
 
-Usage: yamark format ...
+Usage: {{exe}} format ...
 
 For more information, try '--help'.
 -- git-worktree
diff --git a/tests/cases/format_missing_path_with_config.case b/tests/cases/format_missing_path_with_config.case
index 234f2e3c..16d74a61 100644
--- a/tests/cases/format_missing_path_with_config.case
+++ b/tests/cases/format_missing_path_with_config.case
@@ -15,7 +15,7 @@ format --wrap 40
 error: the following required arguments were not provided:
   ...
 
-Usage: yamark format --wrap  ...
+Usage: {{exe}} format --wrap  ...
 
 For more information, try '--help'.
 -- git-worktree
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 307682f3..d80498e0 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -55,17 +55,23 @@ fn cli_cases() {
         }
         command.args(split_args(&case.args));
         command.write_stdin(case.stdin);
+        command.env("NO_COLOR", "1");
         let assert = command.assert().code(case.status);
         let output = assert.get_output();
+        let exe = Path::new(command.get_program())
+            .file_name()
+            .unwrap()
+            .to_str()
+            .unwrap();
         assert_eq!(
             redact_repo(&output.stdout, repo.as_ref()),
-            case.stdout,
+            case.stdout.replace("{{exe}}", exe),
             "stdout mismatch in {}",
             path.display()
         );
         assert_eq!(
             redact_repo(&output.stderr, repo.as_ref()),
-            case.stderr,
+            case.stderr.replace("{{exe}}", exe),
             "stderr mismatch in {}",
             path.display()
         );

From 61dcf04642d1e55b5aebee8bfd6a20a8aea3d69e Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 16:18:19 -0500
Subject: [PATCH 57/64] Resolve the Yamark basename only in transcript usage
 lines

---
 tests/cases/README.md                         |  2 +-
 tests/cases/markdown_template_bare_basic.case |  4 ++++
 tests/cli_cases.rs                            | 16 +++++++++-------
 3 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/tests/cases/README.md b/tests/cases/README.md
index 9a4052eb..66fc0ab5 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -1,6 +1,6 @@
 # CLI case files
 
-Each `.case` file runs the compiled `yamark` binary with `NO_COLOR=1`. In expected stdout and stderr, `{{exe}}` expands to the executable's basename (for example, `yamark.exe` on Windows). The format is:
+Each `.case` file runs the compiled `yamark` binary with `NO_COLOR=1`. Use `{{exe}}` for the executable name in a `Usage:` line in expected stderr. It matches the Yamark binary's basename, such as `yamark.exe` on Windows. Everywhere else, `{{exe}}` is literal. The format is:
 
 ```text
 -- args
diff --git a/tests/cases/markdown_template_bare_basic.case b/tests/cases/markdown_template_bare_basic.case
index 8c26669a..a5673b42 100644
--- a/tests/cases/markdown_template_bare_basic.case
+++ b/tests/cases/markdown_template_bare_basic.case
@@ -4,9 +4,13 @@ format --wrap sentence --stdin-file-path input.md
 First
 sentence with {{ foo }}. Second
 sentence.
+
+Keep {{exe}} here.
 -- stdout
 First sentence with {{ foo }}.
 Second sentence.
+
+Keep {{exe}} here.
 -- stderr
 -- status
 0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index d80498e0..48ac9e91 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -1,4 +1,5 @@
 use std::collections::BTreeMap;
+use std::fmt::Write;
 use std::fs;
 use std::path::{Path, PathBuf};
 
@@ -58,20 +59,15 @@ fn cli_cases() {
         command.env("NO_COLOR", "1");
         let assert = command.assert().code(case.status);
         let output = assert.get_output();
-        let exe = Path::new(command.get_program())
-            .file_name()
-            .unwrap()
-            .to_str()
-            .unwrap();
         assert_eq!(
             redact_repo(&output.stdout, repo.as_ref()),
-            case.stdout.replace("{{exe}}", exe),
+            case.stdout,
             "stdout mismatch in {}",
             path.display()
         );
         assert_eq!(
             redact_repo(&output.stderr, repo.as_ref()),
-            case.stderr.replace("{{exe}}", exe),
+            case.stderr,
             "stderr mismatch in {}",
             path.display()
         );
@@ -260,6 +256,12 @@ fn parse_case(input: &str) -> Case {
             flush(&mut case, §ion, &body);
             section = name.trim().to_owned();
             body.clear();
+        } else if section == "stderr"
+            && let Some(args) = line.strip_prefix("Usage: {{exe}} ")
+        {
+            let binary = assert_cmd::cargo::cargo_bin("yamark");
+            let name = binary.file_name().unwrap().to_str().unwrap();
+            writeln!(body, "Usage: {name} {args}").unwrap();
         } else {
             body.push_str(line);
             body.push('\n');

From 2257a5174172cce6cb9d602fa0df355c321113f8 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 16:48:11 -0500
Subject: [PATCH 58/64] Show explicit paths in check and diff examples

---
 RELEASE_NOTES.md           | 2 +-
 tests/website.rs           | 2 ++
 website/cli-help.html.md   | 2 ++
 website/cli-help.qmd       | 2 ++
 website/directives.html.md | 2 +-
 website/directives.qmd     | 2 +-
 website/git-filter.html.md | 4 ++--
 website/git-filter.qmd     | 4 ++--
 8 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 7d4a1782..09d54888 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,6 +1,6 @@
 
 
-To format the current directory in place, use `yamark format .`. Bare `yamark format` now exits with a usage error, even when the directory contains a `yamark.toml`. Both `yamark format --check` and `yamark format --diff` still default to the current directory.
+To format the current directory in place, use `yamark format .`. Bare `yamark format` now exits with a usage error, even when the directory contains a `yamark.toml`. To check or preview changes, use `yamark format --check .` or `yamark format --diff .`. Both still default to the current directory when the path is omitted.
 
 Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yamark formatting. Its gitignore-style patterns are relative to the config directory. Unlike `.gitignore` and `.ignore`, which affect only directory traversal, `exclude` also applies to explicit paths, `--stdin-file-path`, and Git clean and smudge filters. Excluded file paths are counted as skipped, and stdin for an excluded path passes through unchanged. This also applies to editor Format Document and format-on-save; a configured next formatter still runs.
 
diff --git a/tests/website.rs b/tests/website.rs
index e38f07d6..47175202 100644
--- a/tests/website.rs
+++ b/tests/website.rs
@@ -1380,6 +1380,8 @@ fn website_documents_command_line_reference() {
             "`yamark format --stdin-file-path PATH`",
             "`yamark to-yaml --stdin-file-path PATH`",
             "Use `yamark format .` to format the current directory and its subdirectories.",
+            "`yamark format --check .`",
+            "`yamark format --diff .`",
             "With `--check` or `--diff`, omitting the path selects the current directory (`.`).",
             "An unsupported `--stdin-file-path` is an error",
             "Unified diffs",
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index 212e1922..e4b318df 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -31,6 +31,8 @@ syntax exits `2`.
 
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
+Use `yamark format --check .` to check those files or `yamark format --diff .`
+to preview changes.
 With `--check` or `--diff`, omitting the path selects the current directory
 (`.`). Format path mode counts unsupported extensions as skipped without
 failing. An unsupported `--stdin-file-path` is an error because stdin mode
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index cf14c87e..65a179e6 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -64,6 +64,8 @@ syntax exits `2`.
 
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
+Use `yamark format --check .` to check those files or `yamark format --diff .`
+to preview changes.
 With `--check` or `--diff`, omitting the path selects the current directory
 (`.`). Format path mode counts unsupported extensions as skipped without
 failing. An unsupported `--stdin-file-path` is an error because stdin mode
diff --git a/website/directives.html.md b/website/directives.html.md
index 8fcce1a3..7f10d2af 100644
--- a/website/directives.html.md
+++ b/website/directives.html.md
@@ -249,7 +249,7 @@ workflow:
   the VS Code and Positron settings. This is the most direct way to see a
   directive take effect while editing.
 - In a pre-commit hook, run `yamark format .`. In CI, use
-  `yamark format --check` to verify files without changing them.
+  `yamark format --check .` to verify files without changing them.
 
 The experimental [Git Filter](git-filter.qmd) serves a narrower workflow: it
 stores selected Markdown files sentence-per-line while keeping the working tree
diff --git a/website/directives.qmd b/website/directives.qmd
index 8fcce1a3..7f10d2af 100644
--- a/website/directives.qmd
+++ b/website/directives.qmd
@@ -249,7 +249,7 @@ workflow:
   the VS Code and Positron settings. This is the most direct way to see a
   directive take effect while editing.
 - In a pre-commit hook, run `yamark format .`. In CI, use
-  `yamark format --check` to verify files without changing them.
+  `yamark format --check .` to verify files without changing them.
 
 The experimental [Git Filter](git-filter.qmd) serves a narrower workflow: it
 stores selected Markdown files sentence-per-line while keeping the working tree
diff --git a/website/git-filter.html.md b/website/git-filter.html.md
index d7b7477f..18624900 100644
--- a/website/git-filter.html.md
+++ b/website/git-filter.html.md
@@ -232,5 +232,5 @@ Every clone that wants the working-tree view needs the `git config` commands.
 The `.gitattributes` file selects paths, but it does not define the filter
 driver by itself.
 
-Use a pre-commit hook or CI `yamark format --check` instead when you want the
-repository storage form to match the working-tree form.
+To keep the repository storage form the same as the working-tree form, use a
+pre-commit hook or run `yamark format --check .` in CI.
diff --git a/website/git-filter.qmd b/website/git-filter.qmd
index d7b7477f..18624900 100644
--- a/website/git-filter.qmd
+++ b/website/git-filter.qmd
@@ -232,5 +232,5 @@ Every clone that wants the working-tree view needs the `git config` commands.
 The `.gitattributes` file selects paths, but it does not define the filter
 driver by itself.
 
-Use a pre-commit hook or CI `yamark format --check` instead when you want the
-repository storage form to match the working-tree form.
+To keep the repository storage form the same as the working-tree form, use a
+pre-commit hook or run `yamark format --check .` in CI.

From 756f605a28dccbeb5c35f6b1eff80524ea559cd9 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 17:19:39 -0500
Subject: [PATCH 59/64] Show format help when invoked without arguments

---
 RELEASE_NOTES.md                                     |  2 +-
 src/cli.rs                                           |  5 ++++-
 tests/cases/README.md                                |  2 ++
 ...ormat_missing_path.case => format_bare_help.case} | 12 ++++--------
 tests/cli_cases.rs                                   | 10 ++++++++++
 website/cli-help.html.md                             |  1 +
 website/cli-help.qmd                                 |  1 +
 7 files changed, 23 insertions(+), 10 deletions(-)
 rename tests/cases/{format_missing_path.case => format_bare_help.case} (55%)

diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 09d54888..34458981 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,6 +1,6 @@
 
 
-To format the current directory in place, use `yamark format .`. Bare `yamark format` now exits with a usage error, even when the directory contains a `yamark.toml`. To check or preview changes, use `yamark format --check .` or `yamark format --diff .`. Both still default to the current directory when the path is omitted.
+To format the current directory in place, use `yamark format .`. Running `yamark format` by itself now shows help. In-place writes require a path, even when the directory contains a `yamark.toml`. To check or preview changes, use `yamark format --check .` or `yamark format --diff .`. Both still default to the current directory when the path is omitted.
 
 Use `exclude` in the `[format]` table of `yamark.toml` to keep files out of Yamark formatting. Its gitignore-style patterns are relative to the config directory. Unlike `.gitignore` and `.ignore`, which affect only directory traversal, `exclude` also applies to explicit paths, `--stdin-file-path`, and Git clean and smudge filters. Excluded file paths are counted as skipped, and stdin for an excluded path passes through unchanged. This also applies to editor Format Document and format-on-save; a configured next formatter still runs.
 
diff --git a/src/cli.rs b/src/cli.rs
index a06ae382..75ed5336 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -135,7 +135,10 @@ pub fn run(args: I) -> ExitCode
 where
     I: IntoIterator,
 {
-    let args = args.into_iter().collect::>();
+    let mut args = args.into_iter().collect::>();
+    if matches!(args.as_slice(), [_, subcommand] if subcommand == "format") {
+        args.push(OsString::from("--help"));
+    }
     if let Some(path) = default_format_path(&args) {
         return run_format(
             false,
diff --git a/tests/cases/README.md b/tests/cases/README.md
index 66fc0ab5..f2565452 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -17,6 +17,8 @@ expected stderr
 
 The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
 
+For a command that prints subcommand help, use `-- stdout-from-help` in place of `-- stdout` and name the subcommand on the next line. The harness compares stdout byte-for-byte with that binary's ` --help` output.
+
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
 ## Running selected cases
diff --git a/tests/cases/format_missing_path.case b/tests/cases/format_bare_help.case
similarity index 55%
rename from tests/cases/format_missing_path.case
rename to tests/cases/format_bare_help.case
index 0e2110ee..054415a5 100644
--- a/tests/cases/format_missing_path.case
+++ b/tests/cases/format_bare_help.case
@@ -6,15 +6,11 @@
 -- args
 format
 -- stdin
--- stdout
+#   Piped
+-- stdout-from-help
+format
 -- stderr
-error: the following required arguments were not provided:
-  ...
-
-Usage: {{exe}} format ...
-
-For more information, try '--help'.
 -- git-worktree
 {"docs/input.md": "#   Title\n"}
 -- status
-2
+0
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 48ac9e91..930c8197 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -277,6 +277,16 @@ fn flush(case: &mut Case, section: &str, body: &str) {
         "args" => case.args = value.to_owned(),
         "stdin" => case.stdin = body.to_owned(),
         "stdout" => case.stdout = body.to_owned(),
+        "stdout-from-help" => {
+            let help = Command::cargo_bin("yamark")
+                .unwrap()
+                .args([value, "--help"])
+                .env("NO_COLOR", "1")
+                .assert()
+                .success()
+                .stderr("");
+            case.stdout = String::from_utf8(help.get_output().stdout.clone()).unwrap();
+        }
         "stderr" => case.stderr = body.to_owned(),
         "status" => case.status = value.trim().parse().unwrap(),
         "git-fixture" => case.git_fixture = Some(serde_json::from_str(value).unwrap()),
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index e4b318df..4a86c2f9 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -29,6 +29,7 @@ generated from the current Yamark binary.
 exits `1` when formatting fails and `0` on success otherwise. Invalid command
 syntax exits `2`.
 
+Running `yamark format` by itself shows the same help as `yamark format --help`.
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 Use `yamark format --check .` to check those files or `yamark format --diff .`
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index 65a179e6..a7885446 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -62,6 +62,7 @@ generated from the current Yamark binary.
 exits `1` when formatting fails and `0` on success otherwise. Invalid command
 syntax exits `2`.
 
+Running `yamark format` by itself shows the same help as `yamark format --help`.
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 Use `yamark format --check .` to check those files or `yamark format --diff .`

From 3e8acbd1d7d9d41d26487acf0755ea5995c662ed Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 17:20:35 -0500
Subject: [PATCH 60/64] Keep help transcript changes independent of Git filter
 fixtures

---
 tests/cases/README.md | 4 ++--
 tests/cli_cases.rs    | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/tests/cases/README.md b/tests/cases/README.md
index f2565452..ffcdd683 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -15,10 +15,10 @@ expected stderr
 0
 ```
 
-The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
-
 For a command that prints subcommand help, use `-- stdout-from-help` in place of `-- stdout` and name the subcommand on the next line. The harness compares stdout byte-for-byte with that binary's ` --help` output.
 
+The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
+
 Feature-specific Markdown decision transcripts live in `cases/format-trace/` and are run by `cargo test --features format-trace --test format_trace`. They use the same exact invocation/input/output/status sections; keeping them separate lets the ordinary transcript suite run without feature-dependent output. They check that retained preservation and unavailable layout plans are reported as skipped, including when the node has a nominal formatting emit variant.
 
 ## Running selected cases
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index 930c8197..dba3b8cb 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -277,6 +277,8 @@ fn flush(case: &mut Case, section: &str, body: &str) {
         "args" => case.args = value.to_owned(),
         "stdin" => case.stdin = body.to_owned(),
         "stdout" => case.stdout = body.to_owned(),
+        "stderr" => case.stderr = body.to_owned(),
+        "status" => case.status = value.trim().parse().unwrap(),
         "stdout-from-help" => {
             let help = Command::cargo_bin("yamark")
                 .unwrap()
@@ -287,8 +289,6 @@ fn flush(case: &mut Case, section: &str, body: &str) {
                 .stderr("");
             case.stdout = String::from_utf8(help.get_output().stdout.clone()).unwrap();
         }
-        "stderr" => case.stderr = body.to_owned(),
-        "status" => case.status = value.trim().parse().unwrap(),
         "git-fixture" => case.git_fixture = Some(serde_json::from_str(value).unwrap()),
         "git-status" => case.git_status = Some(body.to_owned()),
         "git-index" => case.git_index = Some(serde_json::from_str(value).unwrap()),

From 9a54a992cdd2e64bc7e078a629ca39458a2343c4 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 18:14:19 -0500
Subject: [PATCH 61/64] Record exact help and diff output in isolated format
 fixtures

---
 external-tests/cli/test_help.py               |  5 +++
 tests/cases/README.md                         |  4 +--
 tests/cases/format_bare_help.case             | 32 +++++++++++++++--
 tests/cases/format_default_check_path.case    |  5 ++-
 tests/cases/format_default_diff_path.case     | 20 ++++++++---
 .../format_missing_path_with_config.case      | 17 +++++----
 tests/cli_cases.rs                            | 36 ++++++++++---------
 7 files changed, 86 insertions(+), 33 deletions(-)

diff --git a/external-tests/cli/test_help.py b/external-tests/cli/test_help.py
index cd8dd83e..9702fd9b 100644
--- a/external-tests/cli/test_help.py
+++ b/external-tests/cli/test_help.py
@@ -7,6 +7,11 @@
 from _support import decode_output, run_cli_case
 
 
+def test_bare_format_matches_explicit_help() -> None:
+    help_output = run_cli_case("yamark format --help").stdout
+    assert run_cli_case("yamark format").stdout == help_output
+
+
 def test_debug_format_help_shows_verify_and_omits_compat_flag() -> None:
     result = run_cli_case("yamark format --help", stderr="")
     stdout = decode_output(result.stdout)
diff --git a/tests/cases/README.md b/tests/cases/README.md
index ffcdd683..119fbb7d 100644
--- a/tests/cases/README.md
+++ b/tests/cases/README.md
@@ -1,6 +1,6 @@
 # CLI case files
 
-Each `.case` file runs the compiled `yamark` binary with `NO_COLOR=1`. Use `{{exe}}` for the executable name in a `Usage:` line in expected stderr. It matches the Yamark binary's basename, such as `yamark.exe` on Windows. Everywhere else, `{{exe}}` is literal. The format is:
+Each `.case` file runs the compiled `yamark` binary with `NO_COLOR=1`. The format is:
 
 ```text
 -- args
@@ -15,7 +15,7 @@ expected stderr
 0
 ```
 
-For a command that prints subcommand help, use `-- stdout-from-help` in place of `-- stdout` and name the subcommand on the next line. The harness compares stdout byte-for-byte with that binary's ` --help` output.
+When output varies by platform or build profile, use `-- stdout-template` or `-- stderr-template` to record a JSON array of lines. Each quoted line preserves its trailing spaces and ends with a newline. Within these sections, `{{exe}}` stands for the Yamark binary's basename, `{{sep}}` for the native path separator, and a `{{debug-only}}` prefix includes the line only in builds with debug assertions. Ordinary `-- stdout` and `-- stderr` treat these markers literally.
 
 The test harness intentionally avoids calling library internals. This keeps the public CLI contract readable and prevents implementation details from becoming part of the test API.
 
diff --git a/tests/cases/format_bare_help.case b/tests/cases/format_bare_help.case
index 054415a5..674ad77f 100644
--- a/tests/cases/format_bare_help.case
+++ b/tests/cases/format_bare_help.case
@@ -1,14 +1,40 @@
 -- git-fixture
 {
   "config": {"core.autocrlf": "false"},
-  "files": {"docs/input.md": "#   Title\n"}
+  "files": {
+    ".gitignore": "!/docs/\n!/docs/input.md\n",
+    "docs/input.md": "#   Title\n"
+  }
 }
 -- args
 format
 -- stdin
 #   Piped
--- stdout-from-help
-format
+-- stdout-template
+[
+  "Usage: {{exe}} format [OPTIONS] [PATHS]...",
+  "",
+  "Arguments:",
+  "  [PATHS]...  Files or directories to format in place. Use '.' for the current directory",
+  "",
+  "Options:",
+  "      --check                        ",
+  "      --diff                         ",
+  "      --diagnostics                  ",
+  "{{debug-only}}      --verify                       Reparse changed YAML and reject invalid or value-changing output",
+  "      --stdin-file-path        ",
+  "      --config                 ",
+  "      --wrap                   [default: 72]",
+  "      --table-widths   Table widths: fit contents or preserve source widths [default: fit]",
+  "      --canonical                    ",
+  "      --preserve-footnotes           ",
+  "      --line-width       [default: 80]",
+  "      --prose-width     [default: 72]",
+  "      --indent-width   [default: 2]",
+  "      --compact                      ",
+  "      --skip-embedded-formatters     ",
+  "  -h, --help                         Print help"
+]
 -- stderr
 -- git-worktree
 {"docs/input.md": "#   Title\n"}
diff --git a/tests/cases/format_default_check_path.case b/tests/cases/format_default_check_path.case
index eeb24bab..11d1d090 100644
--- a/tests/cases/format_default_check_path.case
+++ b/tests/cases/format_default_check_path.case
@@ -1,7 +1,10 @@
 -- git-fixture
 {
   "config": {"core.autocrlf": "false"},
-  "files": {"docs/input.md": "#   Title\n"}
+  "files": {
+    ".gitignore": "!/docs/\n!/docs/input.md\n",
+    "docs/input.md": "#   Title\n"
+  }
 }
 -- args
 format --check
diff --git a/tests/cases/format_default_diff_path.case b/tests/cases/format_default_diff_path.case
index 5faa5b5c..5db153a9 100644
--- a/tests/cases/format_default_diff_path.case
+++ b/tests/cases/format_default_diff_path.case
@@ -1,13 +1,25 @@
 -- git-fixture
 {
   "config": {"core.autocrlf": "false"},
-  "files": {"docs/input.md": "# Title\n"}
+  "files": {
+    ".gitignore": "!/docs/\n!/docs/input.md\n",
+    "docs/input.md": "#   Title\n"
+  }
 }
 -- args
 format --diff
 -- stdin
--- stdout
+-- stdout-template
+[
+  "--- .{{sep}}docs{{sep}}input.md",
+  "+++ .{{sep}}docs{{sep}}input.md",
+  "@@ -1 +1 @@",
+  "-#   Title",
+  "+# Title"
+]
 -- stderr
-1 files scanned, 0 formatted, 1 unchanged, 0 skipped, 0 failed
+1 files scanned, 1 formatted, 0 unchanged, 0 skipped, 0 failed
+-- git-worktree
+{"docs/input.md": "#   Title\n"}
 -- status
-0
+1
diff --git a/tests/cases/format_missing_path_with_config.case b/tests/cases/format_missing_path_with_config.case
index 16d74a61..44ee27e8 100644
--- a/tests/cases/format_missing_path_with_config.case
+++ b/tests/cases/format_missing_path_with_config.case
@@ -2,6 +2,7 @@
 {
   "config": {"core.autocrlf": "false"},
   "files": {
+    ".gitignore": "!/docs/\n!/docs/input.md\n!/yamark.toml\n",
     "yamark.toml": "[format]\nwrap = \"none\"\n",
     "docs/input.md": "#   Title\n"
   }
@@ -11,13 +12,15 @@ format --wrap 40
 -- stdin
 #   Piped
 -- stdout
--- stderr
-error: the following required arguments were not provided:
-  ...
-
-Usage: {{exe}} format --wrap  ...
-
-For more information, try '--help'.
+-- stderr-template
+[
+  "error: the following required arguments were not provided:",
+  "  ...",
+  "",
+  "Usage: {{exe}} format --wrap  ...",
+  "",
+  "For more information, try '--help'."
+]
 -- git-worktree
 {"docs/input.md": "#   Title\n"}
 -- status
diff --git a/tests/cli_cases.rs b/tests/cli_cases.rs
index dba3b8cb..7c9769b0 100644
--- a/tests/cli_cases.rs
+++ b/tests/cli_cases.rs
@@ -256,12 +256,6 @@ fn parse_case(input: &str) -> Case {
             flush(&mut case, §ion, &body);
             section = name.trim().to_owned();
             body.clear();
-        } else if section == "stderr"
-            && let Some(args) = line.strip_prefix("Usage: {{exe}} ")
-        {
-            let binary = assert_cmd::cargo::cargo_bin("yamark");
-            let name = binary.file_name().unwrap().to_str().unwrap();
-            writeln!(body, "Usage: {name} {args}").unwrap();
         } else {
             body.push_str(line);
             body.push('\n');
@@ -279,16 +273,8 @@ fn flush(case: &mut Case, section: &str, body: &str) {
         "stdout" => case.stdout = body.to_owned(),
         "stderr" => case.stderr = body.to_owned(),
         "status" => case.status = value.trim().parse().unwrap(),
-        "stdout-from-help" => {
-            let help = Command::cargo_bin("yamark")
-                .unwrap()
-                .args([value, "--help"])
-                .env("NO_COLOR", "1")
-                .assert()
-                .success()
-                .stderr("");
-            case.stdout = String::from_utf8(help.get_output().stdout.clone()).unwrap();
-        }
+        "stdout-template" => case.stdout = render_output_template(value),
+        "stderr-template" => case.stderr = render_output_template(value),
         "git-fixture" => case.git_fixture = Some(serde_json::from_str(value).unwrap()),
         "git-status" => case.git_status = Some(body.to_owned()),
         "git-index" => case.git_index = Some(serde_json::from_str(value).unwrap()),
@@ -298,6 +284,24 @@ fn flush(case: &mut Case, section: &str, body: &str) {
     }
 }
 
+fn render_output_template(json: &str) -> String {
+    let binary = assert_cmd::cargo::cargo_bin("yamark");
+    let name = binary.file_name().unwrap().to_str().unwrap();
+    let mut output = String::new();
+    for line in serde_json::from_str::>(json).unwrap() {
+        let line = match line.strip_prefix("{{debug-only}}") {
+            Some(_) if !cfg!(debug_assertions) => continue,
+            Some(line) => line,
+            None => &line,
+        };
+        let line = line
+            .replace("{{exe}}", name)
+            .replace("{{sep}}", std::path::MAIN_SEPARATOR_STR);
+        writeln!(output, "{line}").unwrap();
+    }
+    output
+}
+
 fn split_args(input: &str) -> Vec {
     input.split_whitespace().map(ToOwned::to_owned).collect()
 }

From f9fc46c51c656216f9a0437fd38060192a855e39 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 18:31:40 -0500
Subject: [PATCH 62/64] Isolate format transcripts from hooks and ancestor
 settings

---
 tests/cases/format_bare_help.case                |  2 +-
 tests/cases/format_default_check_path.case       | 11 +++++++----
 tests/cases/format_default_diff_path.case        | 11 +++++++----
 tests/cases/format_missing_path_with_config.case |  2 +-
 4 files changed, 16 insertions(+), 10 deletions(-)

diff --git a/tests/cases/format_bare_help.case b/tests/cases/format_bare_help.case
index 674ad77f..62b18461 100644
--- a/tests/cases/format_bare_help.case
+++ b/tests/cases/format_bare_help.case
@@ -1,6 +1,6 @@
 -- git-fixture
 {
-  "config": {"core.autocrlf": "false"},
+  "config": {"core.autocrlf": "false", "core.hooksPath": ".git/no-hooks"},
   "files": {
     ".gitignore": "!/docs/\n!/docs/input.md\n",
     "docs/input.md": "#   Title\n"
diff --git a/tests/cases/format_default_check_path.case b/tests/cases/format_default_check_path.case
index 11d1d090..d63c066f 100644
--- a/tests/cases/format_default_check_path.case
+++ b/tests/cases/format_default_check_path.case
@@ -1,9 +1,12 @@
 -- git-fixture
 {
-  "config": {"core.autocrlf": "false"},
+  "config": {"core.autocrlf": "false", "core.hooksPath": ".git/no-hooks"},
+  "cwd": "work",
   "files": {
-    ".gitignore": "!/docs/\n!/docs/input.md\n",
-    "docs/input.md": "#   Title\n"
+    ".gitignore": "!/work/\n!/work/docs/\n!/work/docs/input.md\n",
+    "yamark.toml": "",
+    "work/.ignore": "!/docs/\n!/docs/input.md\n",
+    "work/docs/input.md": "#   Title\n"
   }
 }
 -- args
@@ -13,6 +16,6 @@ format --check
 -- stderr
 1 files scanned, 1 formatted, 0 unchanged, 0 skipped, 0 failed
 -- git-worktree
-{"docs/input.md": "#   Title\n"}
+{"work/docs/input.md": "#   Title\n"}
 -- status
 1
diff --git a/tests/cases/format_default_diff_path.case b/tests/cases/format_default_diff_path.case
index 5db153a9..48c629fd 100644
--- a/tests/cases/format_default_diff_path.case
+++ b/tests/cases/format_default_diff_path.case
@@ -1,9 +1,12 @@
 -- git-fixture
 {
-  "config": {"core.autocrlf": "false"},
+  "config": {"core.autocrlf": "false", "core.hooksPath": ".git/no-hooks"},
+  "cwd": "work",
   "files": {
-    ".gitignore": "!/docs/\n!/docs/input.md\n",
-    "docs/input.md": "#   Title\n"
+    ".gitignore": "!/work/\n!/work/docs/\n!/work/docs/input.md\n",
+    "yamark.toml": "",
+    "work/.ignore": "!/docs/\n!/docs/input.md\n",
+    "work/docs/input.md": "#   Title\n"
   }
 }
 -- args
@@ -20,6 +23,6 @@ format --diff
 -- stderr
 1 files scanned, 1 formatted, 0 unchanged, 0 skipped, 0 failed
 -- git-worktree
-{"docs/input.md": "#   Title\n"}
+{"work/docs/input.md": "#   Title\n"}
 -- status
 1
diff --git a/tests/cases/format_missing_path_with_config.case b/tests/cases/format_missing_path_with_config.case
index 44ee27e8..aaedb977 100644
--- a/tests/cases/format_missing_path_with_config.case
+++ b/tests/cases/format_missing_path_with_config.case
@@ -1,6 +1,6 @@
 -- git-fixture
 {
-  "config": {"core.autocrlf": "false"},
+  "config": {"core.autocrlf": "false", "core.hooksPath": ".git/no-hooks"},
   "files": {
     ".gitignore": "!/docs/\n!/docs/input.md\n!/yamark.toml\n",
     "yamark.toml": "[format]\nwrap = \"none\"\n",

From 091b55948b1e260e6a5ab4db0bf5448597e25ee3 Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 19:01:15 -0500
Subject: [PATCH 63/64] Exclude fixture ignore files from default-path scans

---
 tests/cases/format_default_check_path.case | 2 +-
 tests/cases/format_default_diff_path.case  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/tests/cases/format_default_check_path.case b/tests/cases/format_default_check_path.case
index d63c066f..20037cb5 100644
--- a/tests/cases/format_default_check_path.case
+++ b/tests/cases/format_default_check_path.case
@@ -5,7 +5,7 @@
   "files": {
     ".gitignore": "!/work/\n!/work/docs/\n!/work/docs/input.md\n",
     "yamark.toml": "",
-    "work/.ignore": "!/docs/\n!/docs/input.md\n",
+    "work/.ignore": "/.ignore\n!/docs/\n!/docs/input.md\n",
     "work/docs/input.md": "#   Title\n"
   }
 }
diff --git a/tests/cases/format_default_diff_path.case b/tests/cases/format_default_diff_path.case
index 48c629fd..71be04ff 100644
--- a/tests/cases/format_default_diff_path.case
+++ b/tests/cases/format_default_diff_path.case
@@ -5,7 +5,7 @@
   "files": {
     ".gitignore": "!/work/\n!/work/docs/\n!/work/docs/input.md\n",
     "yamark.toml": "",
-    "work/.ignore": "!/docs/\n!/docs/input.md\n",
+    "work/.ignore": "/.ignore\n!/docs/\n!/docs/input.md\n",
     "work/docs/input.md": "#   Title\n"
   }
 }

From 4f8abb29b69754d7b802c0c1cb123c9ef898f11e Mon Sep 17 00:00:00 2001
From: Tomasz Kalinowski 
Date: Fri, 4 Dec 2026 19:15:30 -0500
Subject: [PATCH 64/64] Warn that bare format rewrites files in Yamark 0.6.1

---
 tests/website.rs         | 2 ++
 website/cli-help.html.md | 5 ++++-
 website/cli-help.qmd     | 5 ++++-
 3 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/tests/website.rs b/tests/website.rs
index 47175202..abdfb73c 100644
--- a/tests/website.rs
+++ b/tests/website.rs
@@ -1379,6 +1379,8 @@ fn website_documents_command_line_reference() {
             "`yamark format --diff PATHS`",
             "`yamark format --stdin-file-path PATH`",
             "`yamark to-yaml --stdin-file-path PATH`",
+            "For help, run `yamark format --help`.",
+            "In Yamark 0.6.1, bare `yamark format` rewrites files in the current directory and its subdirectories.",
             "Use `yamark format .` to format the current directory and its subdirectories.",
             "`yamark format --check .`",
             "`yamark format --diff .`",
diff --git a/website/cli-help.html.md b/website/cli-help.html.md
index 4a86c2f9..07ca0b38 100644
--- a/website/cli-help.html.md
+++ b/website/cli-help.html.md
@@ -29,7 +29,10 @@ generated from the current Yamark binary.
 exits `1` when formatting fails and `0` on success otherwise. Invalid command
 syntax exits `2`.
 
-Running `yamark format` by itself shows the same help as `yamark format --help`.
+For help, run `yamark format --help`. In Yamark 0.6.1, bare `yamark format`
+rewrites files in the current directory and its subdirectories.
+
+In the development version documented here, bare `yamark format` shows help.
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 Use `yamark format --check .` to check those files or `yamark format --diff .`
diff --git a/website/cli-help.qmd b/website/cli-help.qmd
index a7885446..1c8de84d 100644
--- a/website/cli-help.qmd
+++ b/website/cli-help.qmd
@@ -62,7 +62,10 @@ generated from the current Yamark binary.
 exits `1` when formatting fails and `0` on success otherwise. Invalid command
 syntax exits `2`.
 
-Running `yamark format` by itself shows the same help as `yamark format --help`.
+For help, run `yamark format --help`. In Yamark 0.6.1, bare `yamark format`
+rewrites files in the current directory and its subdirectories.
+
+In the development version documented here, bare `yamark format` shows help.
 In-place formatting requires a path, even in a directory with a `yamark.toml`.
 Use `yamark format .` to format the current directory and its subdirectories.
 Use `yamark format --check .` to check those files or `yamark format --diff .`