From f3ade02d4b60375150b7f55ce0ef9f15f14b6faf Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 10:22:05 -0800 Subject: [PATCH 1/7] Scope the Husky prose gate to staged paths and skip generated trees by flag The Husky pre-commit hooks name the paths the commit stages, filtered to regular files, instead of scanning `.`, so an untracked scratch file no longer refuses every commit. The gate gains `--skip-generated`, which drops a named file inside a generated tree as a directory scan does, so the pre-commit snippet drops its hand-kept copy of `generated_trees`. `repo_root` drops git's location variables, since a hook in a linked worktree inherits `GIT_DIR` and git then reports each named file's directory as its own top level. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose-gate.json | 4 ++ .github/actions/prose-gate/prose_lint.py | 26 +++++++-- .husky/pre-commit | 13 ++++- catalog/snippets/husky/pre-commit | 14 ++++- .../pre-commit/.pre-commit-config.yaml | 3 +- catalog/snippets/pre-commit/README.md | 5 +- scripts/README.md | 4 +- tests/test_prose_lint.py | 56 +++++++++++++++++++ 8 files changed, 106 insertions(+), 19 deletions(-) diff --git a/.github/actions/prose-gate/prose-gate.json b/.github/actions/prose-gate/prose-gate.json index 26c7e34b3..7efd39230 100644 --- a/.github/actions/prose-gate/prose-gate.json +++ b/.github/actions/prose-gate/prose-gate.json @@ -53,6 +53,10 @@ "--exclude": { "action": "append", "default": [] }, "--summary": { "action": "store_true" }, "--list-files": { "action": "store_true", "help": "print the discovered file set and exit, for auditing the sweep scope" }, + "--skip-generated": { + "action": "store_true", + "help": "drop a named file inside a generated tree, as a directory scan does, for a hook naming a commit's paths" + }, "--diff": { "metavar": "BASE", "help": "only report violations on lines changed vs BASE (matches the repo policy: fix as each file is next edited, not swept)" diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index 657fb5bb6..fdf8f5823 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -494,9 +494,14 @@ def printable(line: str) -> str: def repo_root(path: Path) -> str: - """The repository top level containing `path`, or '' when git cannot say.""" + """The repository top level containing `path`, or '' when git cannot say. + + A hook in a linked worktree inherits `GIT_DIR`, under which git reports whatever directory it + starts in as the top level. So the lookup drops the location variables, as provenance does. + """ start = path if path.is_dir() else path.parent - return (git_text("-C", str(start), "rev-parse", "--show-toplevel") or "").strip() + env = {k: v for k, v in os.environ.items() if k not in GIT_LOCATION} + return (git_text("-C", str(start), "rev-parse", "--show-toplevel", env=env) or "").strip() def tracked_paths(root: Path) -> list[Path] | None: @@ -532,9 +537,16 @@ def shallow_checkout(root: Path) -> bool: def discover( - paths: list[str], excludes: tuple[str, ...] = (), root: Path | None = None + paths: list[str], + excludes: tuple[str, ...] = (), + root: Path | None = None, + skip_generated: bool = False, ) -> list[Path]: - """Every authored text file under the paths, scoped by git where git can describe the tree.""" + """Every authored text file under the paths, scoped by git where git can describe the tree. + + A named file is read even inside a generated tree, unless `skip_generated` drops it there as a + wider scan does. A hook naming a commit's paths sets it, so it keeps no copy of the tree list. + """ found: list[tuple[Path, str]] = [] for raw in paths: p = Path(raw) @@ -542,7 +554,9 @@ def discover( anchor = root if root is not None else Path(repo_root(base) or base) trees = config_for(str(anchor)).exempt["generated_trees"] if p.is_file(): - found.append((p, repo_key(p, anchor))) + key = repo_key(p, anchor) + if not skip_generated or trees.isdisjoint(Path(key).parts): + found.append((p, key)) continue candidates = tracked_paths(base) # Whether git can describe a tree is settled by asking git, never by its answer's size. @@ -2043,7 +2057,7 @@ def main(argv: list[str] | None = None) -> int: return refuse("error-override", path=scan_root / OVERRIDE_NAME, why=exc) stand_downs(rules, a, scan_root, in_git) - files = discover(scan_paths, tuple(a.exclude), scan_root) + files = discover(scan_paths, tuple(a.exclude), scan_root, a.skip_generated) keys = {f: repo_key(f, scan_root) for f in files} if a.list_files: for f in files: diff --git a/.husky/pre-commit b/.husky/pre-commit index f4203ee0c..739f92fb3 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -42,14 +42,21 @@ fi # The base is HEAD, or MERGE_HEAD on a merge commit, so the lines a merged-in parent brought are not read as added. # A rule is applied as a file is next edited rather than swept across the tree. # Whole-tree costs about 2.2 seconds where the diff-scoped run costs about 0.15. -# The scope is the working tree rather than the index. -# A partially staged file is therefore judged on all of its edits, not only the staged ones. +# The gate reads the paths this commit stages, so an unrelated untracked file cannot refuse it. +# It reads their working-tree content, so a partially staged file is judged on all of its edits. +# A path that is no longer a file is dropped, since the gate refuses a submodule or a deleted path. +# An empty list skips the gate, which given no path would scan the whole tree. +# `--skip-generated` passes over a staged file in a generated tree, as a whole-tree scan does. # The pull request gate reads every line the branch changes against its base. base=HEAD if git rev-parse -q --verify MERGE_HEAD >/dev/null; then base=MERGE_HEAD fi -uv run --no-project --script .github/actions/prose-gate/prose_lint.py . --diff "$base" +# shellcheck disable=SC2016 # Each expansion belongs to the inner sh. +git diff --cached --name-only --diff-filter=ACMR -z | + xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | + xargs -0 -r uv run --no-project --script .github/actions/prose-gate/prose_lint.py \ + --skip-generated --diff "$base" -- # The eol check is repo-wide rather than diff-scoped, and it is here because it is already fast. # It reads `.gitattributes` against `.editorconfig` for the whole repository and takes no file list. diff --git a/catalog/snippets/husky/pre-commit b/catalog/snippets/husky/pre-commit index d116172c0..91557d403 100644 --- a/catalog/snippets/husky/pre-commit +++ b/catalog/snippets/husky/pre-commit @@ -40,8 +40,16 @@ else exit 1 fi -# The prose gate scopes to the working tree against HEAD, not only the staged index. -# A partially staged file is judged on all of its edits, not only the staged ones. +# The prose gate reads the paths this commit stages, so an unrelated untracked file cannot refuse it. +# It reads their working-tree content, so a partially staged file is judged on all of its edits. +# A path that is no longer a file is dropped, since the gate refuses a submodule or a deleted path. +# An empty list skips the gate, which given no path would scan the whole tree. +# `--skip-generated` passes over a staged file in a generated tree, as a whole-tree scan does. +# The run_py function is out of reach of xargs, so uv chooses the interpreter, which hub_fetch_run.py needs anyway. # The pull request gate reads every line the branch changes against its base. -run_py "$hub_fetch_run" .github/actions/prose-gate/prose_lint.py . --diff HEAD || exit 1 +# shellcheck disable=SC2016 # Each expansion belongs to the inner sh. +git diff --cached --name-only --diff-filter=ACMR -z | + xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | + xargs -0 -r uv run --no-project python "$hub_fetch_run" .github/actions/prose-gate/prose_lint.py \ + --skip-generated --diff HEAD -- || exit 1 run_py "$hub_fetch_run" .github/actions/repo-gate/repo_gate.py --check eol || exit 1 diff --git a/catalog/snippets/pre-commit/.pre-commit-config.yaml b/catalog/snippets/pre-commit/.pre-commit-config.yaml index 497762caf..0499f79a5 100644 --- a/catalog/snippets/pre-commit/.pre-commit-config.yaml +++ b/catalog/snippets/pre-commit/.pre-commit-config.yaml @@ -33,9 +33,8 @@ repos: pass_filenames: false - id: prose-gate name: prose/comment-style gate (diff-scoped, fetched fresh from ProjectTemplate@main) - entry: uv run --no-project python hub_fetch_run.py .github/actions/prose-gate/prose_lint.py --diff HEAD -- + entry: uv run --no-project python hub_fetch_run.py .github/actions/prose-gate/prose_lint.py --skip-generated --diff HEAD -- language: system - exclude: (^|/)reports/ require_serial: true - id: eol-gate name: line-ending consistency gate (fetched fresh from ProjectTemplate@main) diff --git a/catalog/snippets/pre-commit/README.md b/catalog/snippets/pre-commit/README.md index fea110abd..8a4e9c7f1 100644 --- a/catalog/snippets/pre-commit/README.md +++ b/catalog/snippets/pre-commit/README.md @@ -20,9 +20,8 @@ the Husky.Net shape judges all of them. That set-aside covers tracked files only reads the paths `pre-commit` passes it rather than scanning `.`, which keeps an untracked file out of the check. Those are the staged paths, or the conflicted ones while a merge is in progress. `require_serial` keeps `pre-commit` from running the gate in parallel batches, each of which would -fetch it again. A path named that way is judged even inside a generated tree. So the -hook's `exclude` mirrors the gate's default `generated_trees`, and a repo adding to that list adds -the same names there. The pull request gate reads every line the branch changes against its base. A repo with no Python drops the `ruff-format`, +fetch it again. `--skip-generated` passes over a named path inside a generated tree, as a whole-tree +scan does. So the hook reads the gate's `generated_trees` rather than keeping a copy of it. The pull request gate reads every line the branch changes against its base. A repo with no Python drops the `ruff-format`, `ruff-check` and `type-check` hooks and keeps the doc gates. That is what a Docker, config, or docs repo wires. diff --git a/scripts/README.md b/scripts/README.md index 46af33e5c..23d00c0d1 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,6 +1,6 @@ # Repo Scripts -The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches. `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `uv run --no-project --script .github/actions/prose-gate/prose_lint.py . --diff HEAD` is diff-scoped, at about 0.15 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode. What reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, whose shell half needs Docker and either PyYAML or `uvx`, and whose schema half needs `uvx` or `pipx`. `uvx` alone is not enough for the shell half on a host that sets `UV_NO_CACHE` or uv's `no-cache = true`. There uv deletes the environment it resolved before the reader launches. Make PyYAML importable there or turn the setting off. The hook reads the working tree rather than the index, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added. +The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches. `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `uv run --no-project --script .github/actions/prose-gate/prose_lint.py --skip-generated --diff HEAD -- ` is diff-scoped, at about 0.15 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode. What reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, whose shell half needs Docker and either PyYAML or `uvx`, and whose schema half needs `uvx` or `pipx`. `uvx` alone is not enough for the shell half on a host that sets `UV_NO_CACHE` or uv's `no-cache = true`. There uv deletes the environment it resolved before the reader launches. Make PyYAML importable there or turn the setting off. The hook names the paths the commit stages, so an untracked file it does not commit cannot refuse it. It reads their working-tree content, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added. **Hosted here and reached, never carried.** These are not declared in [`spec/files.json`][files], so the audit does not expect a downstream repo to ship them, the same footing as `spec/audit.py`. That is the fleet model rather than an omission: a gate holding no per-repo content has one canonical implementation for the fleet. The prose and repository gate implementations live beside their composite actions under `.github/actions/`. That placement lets reusable workflows reach the implementation at their pinned hub commit through `$/.github/actions/` without checking out the hub. The same-named files in `scripts/` are thin local entry points that call those action-owned implementations. They let maintainers and hooks retain the established commands from a hub checkout without creating a second copy of either gate. A repository that cannot reach the hub reports a local check as not run rather than reconstructing it. That repository does so because a rebuilt gate encodes its author's reading of the rule and agrees with no other repository. @@ -68,7 +68,7 @@ The default set also carries `issue-ref`. It reports an issue or pull request re The default set also carries `sentence-length`. It reports a sentence over the word cap that `sentence_word_cap` in `prose-gate.json` sets, in Markdown prose, a comment, or a docstring. The tree reads zero over-cap sentences, so the rule gates like any other. -A wide scan skips the trees this repo generates rather than authors, currently `reports/`, which [`spec/audit.py`][audit] writes. A finding there is the audit engine's phrasing rather than an author's, so no edit to that tree can fix it. Leaving them in made the repo's own number mostly generated output. Naming such a path directly still reads it (`prose_lint.py reports`), so nothing becomes uncheckable. +A wide scan skips the trees this repo generates rather than authors, currently `reports/`, which [`spec/audit.py`][audit] writes. A finding there is the audit engine's phrasing rather than an author's, so no edit to that tree can fix it. Leaving them in made the repo's own number mostly generated output. Naming such a path directly still reads it (`prose_lint.py reports`), so nothing becomes uncheckable. `--skip-generated` drops a named file there instead, which is what a hook naming a commit's paths passes. The reusable prose gate reads optional exclusions from `.github/prose-gate-excludes` in the repository it scans. Each non-empty line that does not start with `#` is one repository-relative path fragment passed to `--exclude`. Use the contract only for vendored paths whose upstream body the repository preserves. Repository-authored provenance files and patches stay outside the excluded path so the gate continues to read them. diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 42f249935..933f97162 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -6938,6 +6938,62 @@ def test_a_generated_tree_stays_out_when_the_file_in_it_is_untracked(self) -> No (root / "reports" / "audit.md").write_text(self.BAIT, encoding="utf-8") self.assertEqual(0, self.run_in(root, ".")) + def test_a_hook_naming_a_staged_file_in_a_generated_tree_passes(self) -> None: + """A commit staging a report names it, and the hook must not read what a sweep skips. + + Read as named, the file reports its bait. The same file under `--skip-generated` is dropped, + so a hook keeps no copy of `generated_trees` to stay out of that tree. + """ + root = self.repo() + (root / "reports" / "run").mkdir(parents=True) + (root / "reports" / "run" / "audit.md").write_text(self.BAIT, encoding="utf-8") + self.git(root, "add", "-A") + named = ("--diff", "HEAD", "--", "reports/run/audit.md") + self.assertEqual(1, self.run_in(root, *named)) + self.assertEqual(0, self.run_in(root, "--skip-generated", *named)) + + def test_skip_generated_reads_the_trees_the_repository_declares(self) -> None: + """The repository's own `generated_trees` entry is honored, and an authored file is read.""" + root = self.repo() + (root / ".prose-gate.json").write_text('{"generated_trees": ["out"]}\n', encoding="utf-8") + (root / "out").mkdir() + (root / "out" / "page.md").write_text(self.BAIT, encoding="utf-8") + (root / "NEW.md").write_text(self.BAIT, encoding="utf-8") + self.git(root, "add", "-A") + argv = ("--skip-generated", "--diff", "HEAD", "--") + self.assertEqual(0, self.run_in(root, *argv, "out/page.md")) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(1, self.run_in(root, *argv, "out/page.md", "NEW.md")) + self.assertIn("NEW.md:3: dupword", out.getvalue()) + self.assertNotIn("out/page.md", out.getvalue()) + + def test_a_hook_naming_its_staged_paths_leaves_an_untracked_file_unread(self) -> None: + """An untracked scratch file refused every commit while the hook scanned the whole tree.""" + root = self.repo() + (root / "note.md").write_text(self.BAIT, encoding="utf-8") + (root / "DOC.md").write_text("# Doc\n\nA clean line, edited.\n", encoding="utf-8") + self.git(root, "add", "DOC.md") + self.assertEqual(1, self.run_in(root, ".", "--diff", "HEAD")) + self.assertEqual(0, self.run_in(root, "--skip-generated", "--diff", "HEAD", "--", "DOC.md")) + + def test_a_hook_in_a_linked_worktree_names_paths_from_several_directories(self) -> None: + """Git hands such a hook `GIT_DIR`, and under it each named directory read as its own top. + + So two staged files in two directories were refused as spanning two repositories. + """ + root = self.repo() + (root / "a").mkdir() + (root / "b").mkdir() + (root / "a" / "one.md").write_text(self.BAIT, encoding="utf-8") + (root / "b" / "two.md").write_text("# Two\n\nA clean line.\n", encoding="utf-8") + self.git(root, "add", "-A") + with mock.patch.dict(os.environ, {"GIT_DIR": str(root / ".git")}): + self.assertEqual(str(root.resolve()), prose_lint.repo_root(root / "a" / "one.md")) + code = self.run_in(root, "--diff", "HEAD", "--", "a/one.md", "b/two.md") + self.assertEqual(1, code) + self.assertNotIn("more than one repository", self.err.getvalue()) + def test_a_binary_file_is_not_read_because_it_is_untracked(self) -> None: """The text test decides what the rules can read, and it is applied to both sources.""" root = self.repo() From d73fbc27139371472ed8449e7b791fb869d3aa18 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 10:30:50 -0800 Subject: [PATCH 2/7] Keep a typechange in the staged list and look up each directory once The staged list keeps a typechange, which a symlink replaced by a regular file is, so its content reaches the gate. The gate resolves the repository once per distinct directory rather than once per named path, and both environment filters share one `git_env` helper. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose_lint.py | 13 +++++++++---- .husky/pre-commit | 2 +- catalog/snippets/husky/README.md | 4 ++-- catalog/snippets/husky/pre-commit | 2 +- tests/test_prose_lint.py | 13 +++++++++++++ 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index fdf8f5823..cfbb2afa8 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -442,9 +442,14 @@ def gate_provenance(explicit: str | None = None) -> str: ) +def git_env() -> dict[str, str]: + """This process's environment without the variables that tell git which repository to use.""" + return {k: v for k, v in os.environ.items() if k not in GIT_LOCATION} + + def checkout_provenance(script: Path) -> str: """The commit describing this file, `-dirty` where edited, unknown where git tracks it not.""" - env = {k: v for k, v in os.environ.items() if k not in GIT_LOCATION} + env = git_env() where = ("-C", str(script.parent)) if git_text(*where, "ls-files", "--error-unmatch", "--", str(script), env=env) is None: return "unknown" @@ -500,8 +505,7 @@ def repo_root(path: Path) -> str: starts in as the top level. So the lookup drops the location variables, as provenance does. """ start = path if path.is_dir() else path.parent - env = {k: v for k, v in os.environ.items() if k not in GIT_LOCATION} - return (git_text("-C", str(start), "rev-parse", "--show-toplevel", env=env) or "").strip() + return (git_text("-C", str(start), "rev-parse", "--show-toplevel", env=git_env()) or "").strip() def tracked_paths(root: Path) -> list[Path] | None: @@ -2046,7 +2050,8 @@ def main(argv: list[str] | None = None) -> int: # Anything that is not a file or a directory, a FIFO or a socket included, is refused. if unusable := [p for p in scan_paths if not (Path(p).is_file() or Path(p).is_dir())]: return refuse("error-not-a-path", paths=quoted(unusable)) - git_roots = {found for found in (repo_root(Path(p)) for p in scan_paths) if found} + starts = {Path(p) if Path(p).is_dir() else Path(p).parent for p in scan_paths} + git_roots = {found for found in map(repo_root, starts) if found} if len(git_roots) > 1: return refuse("error-many-repositories", roots=quoted(git_roots)) first, in_git = Path(scan_paths[0]), bool(git_roots) diff --git a/.husky/pre-commit b/.husky/pre-commit index 739f92fb3..d081c9917 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -53,7 +53,7 @@ if git rev-parse -q --verify MERGE_HEAD >/dev/null; then base=MERGE_HEAD fi # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. -git diff --cached --name-only --diff-filter=ACMR -z | +git diff --cached --name-only --diff-filter=ACMRT -z | xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | xargs -0 -r uv run --no-project --script .github/actions/prose-gate/prose_lint.py \ --skip-generated --diff "$base" -- diff --git a/catalog/snippets/husky/README.md b/catalog/snippets/husky/README.md index 07b153672..53470783d 100644 --- a/catalog/snippets/husky/README.md +++ b/catalog/snippets/husky/README.md @@ -5,7 +5,7 @@ runs **language formatting/lint and the fleet's shared doc gates**. For .NET it `dotnet format` style via `dotnet husky run`. For a Python repo it runs `ruff format --check` / `ruff check` / the repo's type checker (native tooling, no Docker, the same checks the `../pre-commit/.pre-commit-config.yaml` snippet runs). It also runs the diff-scoped -prose/comment-style gate and the whole-tree line-ending check. Copy `../hub_fetch_run.py` +prose/comment-style gate over the paths the commit stages, and the whole-tree line-ending check. Copy `../hub_fetch_run.py` alongside `pre-commit` for the doc gates to run. The script fetches those two checks fresh from `ptr727/ProjectTemplate`'s `main` branch and runs them, rather than vendoring or pinning a copy. A pin that nothing keeps current goes stale by construction. CI (this repo's own, and the hub's) is @@ -28,7 +28,7 @@ runs in CI as pinned action wrappers, and on demand via the VS Code **Lint** tas prose gate in whole-repo mode, for on-demand full-tree validation beyond the diff-scoped commit-time run. Its `Lint: EOL` task runs the same whole-tree EOL check the hook runs. Keeping the Docker-dependent doc linters out of the hook is what keeps it fast. Docker is the -dependency it stays free of, though the hook still needs network for the two +dependency it stays free of, though the hook still needs network for the `hub_fetch_run.py` calls above. A fully offline clone therefore fails the commit loudly on the fetch rather than silently skipping the doc gates. diff --git a/catalog/snippets/husky/pre-commit b/catalog/snippets/husky/pre-commit index 91557d403..4513822cf 100644 --- a/catalog/snippets/husky/pre-commit +++ b/catalog/snippets/husky/pre-commit @@ -48,7 +48,7 @@ fi # The run_py function is out of reach of xargs, so uv chooses the interpreter, which hub_fetch_run.py needs anyway. # The pull request gate reads every line the branch changes against its base. # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. -git diff --cached --name-only --diff-filter=ACMR -z | +git diff --cached --name-only --diff-filter=ACMRT -z | xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | xargs -0 -r uv run --no-project python "$hub_fetch_run" .github/actions/prose-gate/prose_lint.py \ --skip-generated --diff HEAD -- || exit 1 diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 933f97162..2133c2c5f 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -6994,6 +6994,19 @@ def test_a_hook_in_a_linked_worktree_names_paths_from_several_directories(self) self.assertEqual(1, code) self.assertNotIn("more than one repository", self.err.getvalue()) + def test_a_hook_naming_many_files_looks_up_each_directory_once(self) -> None: + """A commit staging hundreds of files names each, and each lookup starts a git process.""" + root = self.repo() + (root / "a").mkdir() + for name in ("one.md", "two.md", "three.md"): + (root / "a" / name).write_text("# Doc\n\nA clean line.\n", encoding="utf-8") + self.git(root, "add", "-A") + with mock.patch.object(prose_lint, "repo_root", wraps=prose_lint.repo_root) as lookup: + self.assertEqual( + 0, self.run_in(root, "--diff", "HEAD", "--", "a/one.md", "a/two.md", "a/three.md") + ) + self.assertEqual(1, lookup.call_count) + def test_a_binary_file_is_not_read_because_it_is_untracked(self) -> None: """The text test decides what the rules can read, and it is applied to both sources.""" root = self.repo() From c963e3c4d64ea8a9ecb5984282b114fef4b21c72 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 10:32:55 -0800 Subject: [PATCH 3/7] Drive the hub hook through commits beside an untracked finding Three cases on a shared fixture: a deletion-only commit skips the gate, an edit plus a staged report under `reports/` passes, and a staged finding is refused without naming the untracked file. Each fails against the hook that scanned `.`. Co-Authored-By: Claude Opus 5.5 --- tests/test_pre_commit_hook.py | 84 +++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 19 deletions(-) diff --git a/tests/test_pre_commit_hook.py b/tests/test_pre_commit_hook.py index 046f9c31d..17a462999 100755 --- a/tests/test_pre_commit_hook.py +++ b/tests/test_pre_commit_hook.py @@ -31,12 +31,8 @@ @unittest.skipUnless(sys.platform == "linux", "runs a POSIX shell hook with executable stubs") @unittest.skipUnless(shutil.which("uv"), "the hook runs the prose gate through uv") -class TestTheHookDiffsAMergeAgainstItsMergedInParent(unittest.TestCase): - """A merge of develop brings in lines the branch never wrote, and the hook must not read them. - - Measured against `HEAD`, every line develop gained since the fork reads as added. So a comment - another pull request already landed trips `comment-added` on a merge that adds none. - """ +class HookCase(unittest.TestCase): + """A throwaway repository carrying the hook and the gate, with one base commit.""" def setUp(self) -> None: self.root = Path(self.enterContext(tempfile.TemporaryDirectory())).resolve() @@ -76,20 +72,8 @@ def setUp(self) -> None: self.git("add", "-A") self.git("commit", "-q", "--no-verify", "-m", "base") - self.git("checkout", "-q", "-b", "feature") - self.write("conflict.py", "VALUE = 'feature'\n") - self.git("commit", "-q", "--no-verify", "-am", "feature side") - - self.git("checkout", "-q", "develop") - self.write("tool.py", COMMENT + "value = 1\n") - self.write("conflict.py", "VALUE = 'develop'\n") - self.git("commit", "-q", "--no-verify", "-am", "develop side, comment landed by its own PR") - - self.git("checkout", "-q", "feature") - merge = self.run_git("merge", "develop") - self.assertNotEqual(0, merge.returncode, "the fixture needs a conflicted merge") - def write(self, name: str, text: str) -> None: + (self.root / name).parent.mkdir(parents=True, exist_ok=True) (self.root / name).write_text(text, encoding="utf-8") def run_git(self, *args: str) -> subprocess.CompletedProcess[str]: @@ -109,6 +93,29 @@ def git(self, *args: str) -> None: if result.returncode != 0: raise AssertionError(f"git {' '.join(args)} failed: {result.stderr.strip()}") + +class TestTheHookDiffsAMergeAgainstItsMergedInParent(HookCase): + """A merge of develop brings in lines the branch never wrote, and the hook must not read them. + + Measured against `HEAD`, every line develop gained since the fork reads as added. So a comment + another pull request already landed trips `comment-added` on a merge that adds none. + """ + + def setUp(self) -> None: + super().setUp() + self.git("checkout", "-q", "-b", "feature") + self.write("conflict.py", "VALUE = 'feature'\n") + self.git("commit", "-q", "--no-verify", "-am", "feature side") + + self.git("checkout", "-q", "develop") + self.write("tool.py", COMMENT + "value = 1\n") + self.write("conflict.py", "VALUE = 'develop'\n") + self.git("commit", "-q", "--no-verify", "-am", "develop side, comment landed by its own PR") + + self.git("checkout", "-q", "feature") + merge = self.run_git("merge", "develop") + self.assertNotEqual(0, merge.returncode, "the fixture needs a conflicted merge") + def commit_resolution(self, resolved: str) -> subprocess.CompletedProcess[str]: self.write("conflict.py", resolved) self.git("add", "conflict.py") @@ -148,5 +155,44 @@ def test_a_commit_that_is_not_a_merge_still_diffs_against_head(self) -> None: self.assertIn("feature.py:1: comment-added", result.stdout + result.stderr) +class TestTheHookReadsOnlyWhatTheCommitStages(HookCase): + """An untracked scratch file is no part of a commit, so it cannot refuse one. + + The hook once scanned the whole working tree, untracked files in full. So a stray note with a + comment refused every commit in the clone, whatever the commit touched. + """ + + def setUp(self) -> None: + super().setUp() + self.write("note.py", COMMENT + "scratch = 1\n") + + def commit(self) -> subprocess.CompletedProcess[str]: + return self.run_git("commit", "-m", "change") + + def test_a_deletion_beside_an_untracked_finding_passes(self) -> None: + """A commit staging no file it can read skips the gate rather than scanning the tree.""" + self.git("rm", "-q", "conflict.py") + result = self.commit() + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + def test_an_edit_beside_an_untracked_finding_passes_and_a_staged_report_is_skipped( + self, + ) -> None: + """The edit is read, the report under the generated tree is not, and the note is not.""" + self.write("tool.py", "value = 2\n") + self.write("reports/run/audit.md", "# Audit\n\nA line with " + "the " + "the word.\n") + self.git("add", "tool.py", "reports/run/audit.md") + result = self.commit() + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + def test_a_staged_finding_is_still_refused_and_the_untracked_one_is_not_named(self) -> None: + self.write("feature.py", COMMENT + "value = 2\n") + self.git("add", "feature.py") + result = self.commit() + self.assertEqual(1, result.returncode, result.stdout + result.stderr) + self.assertIn("feature.py:1: comment-added", result.stdout + result.stderr) + self.assertNotIn("note.py", result.stdout + result.stderr) + + if __name__ == "__main__": unittest.main() From 96deead83ecdd4d10e527b6d2dd88bc9359820d8 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 10:41:12 -0800 Subject: [PATCH 4/7] Test the hook's file filter and typechange, and share the lookup start A staged-then-removed path and a symlink replaced by a file each get a hook case, failing when the `[ -f ]` filter or the `T` filter is dropped. `lookup_start` holds where a git lookup for a path starts, for `repo_root` and the per-directory lookup in `main`. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose_lint.py | 9 +++++++-- tests/test_pre_commit_hook.py | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index cfbb2afa8..bb3fa5caa 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -498,13 +498,18 @@ def printable(line: str) -> str: return escaped.encode("utf-8", "backslashreplace").decode("utf-8") +def lookup_start(path: Path) -> Path: + """The directory a git lookup for `path` starts in, the path itself or the file's directory.""" + return path if path.is_dir() else path.parent + + def repo_root(path: Path) -> str: """The repository top level containing `path`, or '' when git cannot say. A hook in a linked worktree inherits `GIT_DIR`, under which git reports whatever directory it starts in as the top level. So the lookup drops the location variables, as provenance does. """ - start = path if path.is_dir() else path.parent + start = lookup_start(path) return (git_text("-C", str(start), "rev-parse", "--show-toplevel", env=git_env()) or "").strip() @@ -2050,7 +2055,7 @@ def main(argv: list[str] | None = None) -> int: # Anything that is not a file or a directory, a FIFO or a socket included, is refused. if unusable := [p for p in scan_paths if not (Path(p).is_file() or Path(p).is_dir())]: return refuse("error-not-a-path", paths=quoted(unusable)) - starts = {Path(p) if Path(p).is_dir() else Path(p).parent for p in scan_paths} + starts = {lookup_start(Path(p)) for p in scan_paths} git_roots = {found for found in map(repo_root, starts) if found} if len(git_roots) > 1: return refuse("error-many-repositories", roots=quoted(git_roots)) diff --git a/tests/test_pre_commit_hook.py b/tests/test_pre_commit_hook.py index 17a462999..0dab0b8b5 100755 --- a/tests/test_pre_commit_hook.py +++ b/tests/test_pre_commit_hook.py @@ -185,6 +185,28 @@ def test_an_edit_beside_an_untracked_finding_passes_and_a_staged_report_is_skipp result = self.commit() self.assertEqual(0, result.returncode, result.stdout + result.stderr) + def test_a_path_staged_and_then_removed_is_left_out_of_the_list(self) -> None: + """The gate refuses a path that is not a file, so the hook drops it rather than failing.""" + self.write("gone.py", "value = 3\n") + self.git("add", "gone.py") + (self.root / "gone.py").unlink() + self.write("tool.py", "value = 2\n") + self.git("add", "tool.py") + result = self.commit() + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + def test_a_symlink_replaced_by_a_file_is_read(self) -> None: + """A typechange is staged content too, so a finding in it is refused.""" + (self.root / "link.py").symlink_to("tool.py") + self.git("add", "link.py") + self.git("commit", "-q", "--no-verify", "-m", "link") + (self.root / "link.py").unlink() + self.write("link.py", COMMENT + "value = 2\n") + self.git("add", "link.py") + result = self.commit() + self.assertEqual(1, result.returncode, result.stdout + result.stderr) + self.assertIn("link.py:1: comment-added", result.stdout + result.stderr) + def test_a_staged_finding_is_still_refused_and_the_untracked_one_is_not_named(self) -> None: self.write("feature.py", COMMENT + "value = 2\n") self.git("add", "feature.py") From 20533b56a573090398a196b2d12284745cafdc86 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 10:57:42 -0800 Subject: [PATCH 5/7] Skip an empty staged list without xargs -r and stop on a failed read The inner sh filters the list and skips the gate when nothing is left, since GNU xargs runs once on empty input and BSD xargs does not. The staged list is read once on its own first, so a failing `git diff` stops the hook rather than reading as an empty list. Co-Authored-By: Claude Opus 5.5 --- .husky/pre-commit | 9 ++++++--- catalog/snippets/husky/pre-commit | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.husky/pre-commit b/.husky/pre-commit index d081c9917..5debbe262 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -46,17 +46,20 @@ fi # It reads their working-tree content, so a partially staged file is judged on all of its edits. # A path that is no longer a file is dropped, since the gate refuses a submodule or a deleted path. # An empty list skips the gate, which given no path would scan the whole tree. +# The inner sh checks for that itself, since GNU xargs runs once on empty input and BSD xargs does not. +# The list is read once on its own first, because a pipeline hides a failure of its first command. # `--skip-generated` passes over a staged file in a generated tree, as a whole-tree scan does. # The pull request gate reads every line the branch changes against its base. base=HEAD if git rev-parse -q --verify MERGE_HEAD >/dev/null; then base=MERGE_HEAD fi +git diff --cached --name-only --diff-filter=ACMRT -z >/dev/null # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. git diff --cached --name-only --diff-filter=ACMRT -z | - xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | - xargs -0 -r uv run --no-project --script .github/actions/prose-gate/prose_lint.py \ - --skip-generated --diff "$base" -- + xargs -0 sh -c 'for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done + [ "$#" -eq 0 ] || exec uv run --no-project --script .github/actions/prose-gate/prose_lint.py \ + --skip-generated --diff "$0" -- "$@"' "$base" # The eol check is repo-wide rather than diff-scoped, and it is here because it is already fast. # It reads `.gitattributes` against `.editorconfig` for the whole repository and takes no file list. diff --git a/catalog/snippets/husky/pre-commit b/catalog/snippets/husky/pre-commit index 4513822cf..e5c1c8232 100644 --- a/catalog/snippets/husky/pre-commit +++ b/catalog/snippets/husky/pre-commit @@ -44,12 +44,15 @@ fi # It reads their working-tree content, so a partially staged file is judged on all of its edits. # A path that is no longer a file is dropped, since the gate refuses a submodule or a deleted path. # An empty list skips the gate, which given no path would scan the whole tree. +# The inner sh checks for that itself, since GNU xargs runs once on empty input and BSD xargs does not. +# The list is read once on its own first, because a pipeline hides a failure of its first command. # `--skip-generated` passes over a staged file in a generated tree, as a whole-tree scan does. # The run_py function is out of reach of xargs, so uv chooses the interpreter, which hub_fetch_run.py needs anyway. # The pull request gate reads every line the branch changes against its base. +git diff --cached --name-only --diff-filter=ACMRT -z >/dev/null || exit 1 # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. git diff --cached --name-only --diff-filter=ACMRT -z | - xargs -0 sh -c 'for p do if [ -f "$p" ]; then printf "%s\0" "$p"; fi; done' sh | - xargs -0 -r uv run --no-project python "$hub_fetch_run" .github/actions/prose-gate/prose_lint.py \ - --skip-generated --diff HEAD -- || exit 1 + xargs -0 sh -c 'for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done + [ "$#" -eq 0 ] || exec uv run --no-project python "$0" .github/actions/prose-gate/prose_lint.py \ + --skip-generated --diff HEAD -- "$@"' "$hub_fetch_run" || exit 1 run_py "$hub_fetch_run" .github/actions/repo-gate/repo_gate.py --check eol || exit 1 From 02ed8f1b79420c5aa54ee32326ff5945e58f0a01 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 11:05:56 -0800 Subject: [PATCH 6/7] Name the hooks' inner shell and reuse lookup_start for the scan root The inner sh takes a literal `sh` as its name and reads the base or the fetcher path from its first argument, so an error names the shell. The scan root's fallback calls `lookup_start` rather than restating it. Co-Authored-By: Claude Opus 5.5 --- .github/actions/prose-gate/prose_lint.py | 2 +- .husky/pre-commit | 4 ++-- catalog/snippets/husky/pre-commit | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/actions/prose-gate/prose_lint.py b/.github/actions/prose-gate/prose_lint.py index bb3fa5caa..997aecc52 100755 --- a/.github/actions/prose-gate/prose_lint.py +++ b/.github/actions/prose-gate/prose_lint.py @@ -2060,7 +2060,7 @@ def main(argv: list[str] | None = None) -> int: if len(git_roots) > 1: return refuse("error-many-repositories", roots=quoted(git_roots)) first, in_git = Path(scan_paths[0]), bool(git_roots) - scan_root = Path(git_roots.pop()) if git_roots else first if first.is_dir() else first.parent + scan_root = Path(git_roots.pop()) if git_roots else lookup_start(first) try: config_for(str(scan_root)) except OverrideError as exc: diff --git a/.husky/pre-commit b/.husky/pre-commit index 5debbe262..851101c21 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -57,9 +57,9 @@ fi git diff --cached --name-only --diff-filter=ACMRT -z >/dev/null # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. git diff --cached --name-only --diff-filter=ACMRT -z | - xargs -0 sh -c 'for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done + xargs -0 sh -c 'base=$1; shift; for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done [ "$#" -eq 0 ] || exec uv run --no-project --script .github/actions/prose-gate/prose_lint.py \ - --skip-generated --diff "$0" -- "$@"' "$base" + --skip-generated --diff "$base" -- "$@"' sh "$base" # The eol check is repo-wide rather than diff-scoped, and it is here because it is already fast. # It reads `.gitattributes` against `.editorconfig` for the whole repository and takes no file list. diff --git a/catalog/snippets/husky/pre-commit b/catalog/snippets/husky/pre-commit index e5c1c8232..19b5ec124 100644 --- a/catalog/snippets/husky/pre-commit +++ b/catalog/snippets/husky/pre-commit @@ -52,7 +52,7 @@ fi git diff --cached --name-only --diff-filter=ACMRT -z >/dev/null || exit 1 # shellcheck disable=SC2016 # Each expansion belongs to the inner sh. git diff --cached --name-only --diff-filter=ACMRT -z | - xargs -0 sh -c 'for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done - [ "$#" -eq 0 ] || exec uv run --no-project python "$0" .github/actions/prose-gate/prose_lint.py \ - --skip-generated --diff HEAD -- "$@"' "$hub_fetch_run" || exit 1 + xargs -0 sh -c 'fetch=$1; shift; for p do shift; if [ -f "$p" ]; then set -- "$@" "$p"; fi; done + [ "$#" -eq 0 ] || exec uv run --no-project python "$fetch" .github/actions/prose-gate/prose_lint.py \ + --skip-generated --diff HEAD -- "$@"' sh "$hub_fetch_run" || exit 1 run_py "$hub_fetch_run" .github/actions/repo-gate/repo_gate.py --check eol || exit 1 From dfc5093cb836d17e2e1f668ec7599fa107f0b436 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 2 Nov 2026 11:27:15 -0800 Subject: [PATCH 7/7] Compare the repository root as a path in the linked-worktree test Git prints a Windows top level with forward slashes, so the test compares resolved paths rather than strings. Co-Authored-By: Claude Opus 5.5 --- tests/test_prose_lint.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 2133c2c5f..8614aa680 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -6989,7 +6989,8 @@ def test_a_hook_in_a_linked_worktree_names_paths_from_several_directories(self) (root / "b" / "two.md").write_text("# Two\n\nA clean line.\n", encoding="utf-8") self.git(root, "add", "-A") with mock.patch.dict(os.environ, {"GIT_DIR": str(root / ".git")}): - self.assertEqual(str(root.resolve()), prose_lint.repo_root(root / "a" / "one.md")) + found = prose_lint.repo_root(root / "a" / "one.md") + self.assertEqual(root.resolve(), Path(found).resolve()) code = self.run_in(root, "--diff", "HEAD", "--", "a/one.md", "b/two.md") self.assertEqual(1, code) self.assertNotIn("more than one repository", self.err.getvalue())