From 05894c01306410dc7feeb3c50d1f76ab7a85211b Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 07:05:18 -0700 Subject: [PATCH 1/3] Pin the Prose Gate and Its Data to One Commit via git ls-remote Where the API lookup of main's commit fails, hub_fetch_run.py resolves it through git ls-remote, so prose_lint.py and prose-gate.json are fetched at one commit and always pair. Where neither lookup resolves, the gate still runs against main, since a hook with no network cannot fetch the gate at all and the CI gate is the enforcement. --- GOVERNANCE.md | 2 +- catalog/snippets/hub_fetch_run.py | 36 +++++++++++++-- catalog/snippets/husky/README.md | 3 +- catalog/snippets/pre-commit/README.md | 3 +- tests/test_hub_fetch_run.py | 65 +++++++++++++++++++++++++++ 5 files changed, 103 insertions(+), 6 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 93558713d..f9c8d101d 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -290,7 +290,7 @@ CI runs the full lint set, but run the linters locally before pushing to catch i - **CI (authoritative)** runs **markdownlint-cli2**, **cspell**, and **actionlint** as pinned action wrappers, which Dependabot bumps. It runs **editorconfig-checker** via Docker `:latest`, since its action only installs the CLI and the Docker one-liner is what actually runs the check. **shellcheck** and **shfmt** run the same way for a repo that carries a shell script, and **PSScriptAnalyzer** does for a repo that carries `.ps1` files. None of shellcheck, shfmt, and PSScriptAnalyzer has an action. For a repo that carries an action under `.github/actions/`, the repo gate's `composite-actions` check runs **shellcheck** in Docker over each bash or sh `run:` body. It also runs **check-jsonschema** through `uvx`, because actionlint reads workflows only. The `composite-actions` check runs shellcheck at warning severity without SC2154, weaker than for a `.sh` file. markdownlint covers all `**/*.md`, and **cspell is scoped to `README.md` + `HISTORY.md`** (see [CODESTYLE.md](./CODESTYLE.md) "Markdown and Spelling" for why), matching the cspell one-liner below. A "shell script" here is a tracked `.sh` file, plus a tracked, extension-less file whose shebang names bash or sh, the shape a script meant to run as a bare command takes: a bare `*.sh` glob misses that second case, so both discovery paths run before either tool does. This whole block is the hub's `validate-task.yml` reusable workflow, so a fleet repo reaches it rather than carrying a copy of these steps. - **A working local hook is strongly suggested fleet-wide, and its absence is a measured audit finding, not an invisible gap.** `spec/project-types.json`'s `parity.hooks` check reads this section for its rationale, judged by hand during an `AUDIT.md` run like every sibling check in its dimension, never mechanized by `spec/audit.py`: a repo with no local hook mechanism wired at all is a `linter-parity` defect, the same severity a missing markdownlint config already gets, while a repo mid-convergence (below) stays operational. CI remains the authoritative run regardless. Catalog snippets carry the canonical shape, each with a copy of `catalog/snippets/hub_fetch_run.py` alongside it. `catalog/snippets/husky/` is Husky.Net, for a repo that already keeps a .NET tool manifest declaring it, since `dotnet tool restore` then `dotnet husky install` is what generates the `.husky/_/husky.sh` its hook sources, and the snippet ships no manifest of its own. `catalog/snippets/pre-commit/` is the `pre-commit` framework, for a repo without one and for any repo that prefers it. No snippet is scoped to a language by what it runs. Each carries the repo's own language checks plus the shared doc gates. A repo drops the block for a language it does not have. A Docker, config, or docs repo therefore wires the doc gates alone, which is a mechanism rather than the absence of one. Which snippet a repo starts from is bounded by the toolchain it already keeps, never by which languages its checks cover. A snippet is a starting point rather than the only shape: a repo may wire an equivalent hook of its own at `.husky/pre-commit`, enabled with `core.hooksPath` and sourcing nothing, which is what this repository does. That path matters, since `parity.hooks` reads the tracked file at `.husky/pre-commit` or `.pre-commit-config.yaml` rather than a per-clone hooks path it cannot observe. - **The hook** runs **language formatting** and the **diff-scoped doc gates**, never Docker, so it stays fast. The formatting half is whatever the repo's own language needs, CSharpier and `dotnet format` for .NET or ruff and the repo's type checker for Python, via native tooling. A repo adds each half once its tree passes that half, since a gate that fails on the corpus it guards blocks every commit from the moment it lands, so a hook running one half is a repo mid-convergence rather than a repo out of conformance. The doc half runs each gate at the scope that fits it. The prose gate is scoped to the working tree diff against `HEAD` rather than swept over the tree, which is the difference between about 2.2 seconds and about 0.13 and is what makes it affordable in a hook at all. That scope is the working tree rather than the staged index under a plain git hook, so a partially staged file is judged on all of its edits. Under the `pre-commit` framework it is the staged state instead, since that runner sets unstaged changes aside before running a hook, which is measured rather than assumed. The pull request gate re-checks every line the branch changes against its base, which is the scope a review is judged on. A whole-repo check belongs in the hook too when it is already fast and takes no file list, which the line-ending consistency check is, so scope is a property of the gate rather than a rule the hook applies to all of them. `repo_gate.py --check sha-pin` stays out of the hook regardless, since it resolves a same-owner pin against the GitHub API. -- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, and `uv` resolves the packages its script block declares on a cache miss, and those are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. +- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss, and those are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. - **The hub carries a second hook, `.husky/pre-push`, gating the local-review rule rather than lint.** It runs `scripts/local_review.py check`, refusing a branch push whose diff no recorded review pass covers, per "Verification Discipline" above. It fires only for a branch update, so a tag push and a branch delete pass through, and a branch holding no net content against its target has nothing for a review to cover. It refuses rather than guesses in every state it cannot speak for, since the engine reads the checkout it runs in while a push delivers a commit, and those describe the same content only sometimes. The order that keeps them describing the same content is to commit the change, then review the diff, record its receipt, and push, the receipt being untracked and so recorded after the last commit. A change that also carries the canonical ledger records those passes ahead of that commit instead, the ledger being tracked content the commit has to hold. It reads `develop` and accepts no override from the environment, since an environment variable is set inline on the very command being gated, by whoever is being gated, which is the same reason an authorization is never read from a channel the agent itself can set. The cost is that it measures a branch based on anything but `develop` against `develop` anyway, so its refusal there is not a verdict about that branch. Each refusal names its own case, and the `local-strict-review` Skill carries the fleet's one enumeration of them with what clears each, deliberately in one place rather than restated here. It folds the engine's three-valued exit honestly: a check that could not run blocks too, and says so in different words than a check that ran and found no pass, because a gate that waves a push through when it could not run is a gate that stopped gating. It is a backstop rather than a seal, and it is bypassable by construction: `--no-verify` is the documented route out of a pickle and is not the only one, since a git hook cannot police its own invocation. A Claude Code session meets a narrower surface, that flag being denied unconditionally by the agent-safety hook's explicit-bypass rule, and that denial is Claude Code's alone, since Codex and opencode carry no such hook yet. So the committed hook raises the cost of skipping the rule for one agent and lowers it for none, and the prose layer above stays the agent-agnostic one that actually binds. It is hub-only for now. `local_review.py` is hub-hosted per "Hub-Hosted Tooling", and a downstream repo reaches it as a hub checkout's copy run with its own worktree as the working directory, so a catalog snippet carrying this hook fleet-wide is a later step rather than part of this one. `canonical_review.py` is not run here at all, and nothing else gates a push or a pull request over a canonical unit either, that read being swept on a schedule instead, per "Verification Discipline" above. The hub's own `.github/actions/validate` composite action renders its coverage burn-down into every run's job summary and fails no pull request over what that shows, while still failing where the engine could not read the manifest or the ledger at all, that being a boundary rather than a verdict. - **The VS Code Lint tasks** run the full doc-lint set via Docker `:latest` on demand, the local surface for Markdown, spelling, workflow, and EditorConfig checks, plus `Lint: Prose` and `Lint: EOL`, the same hook gates in whole-repo mode rather than diff-scoped, for on-demand full-tree validation. diff --git a/catalog/snippets/hub_fetch_run.py b/catalog/snippets/hub_fetch_run.py index 7287ba982..68dbd3611 100644 --- a/catalog/snippets/hub_fetch_run.py +++ b/catalog/snippets/hub_fetch_run.py @@ -22,6 +22,7 @@ HUB_REPO = "ptr727/ProjectTemplate" HUB_RAW_BASE = f"https://raw.githubusercontent.com/{HUB_REPO}" HUB_MAIN_SHA_URL = f"https://api.github.com/repos/{HUB_REPO}/commits/main" +HUB_GIT_URL = f"https://github.com/{HUB_REPO}" PROVENANCE_VAR = "PROSE_GATE_PROVENANCE" PROSE_GATE_PATH = ".github/actions/prose-gate/prose_lint.py" # The files a script reads beside itself, fetched into the same directory before it runs. @@ -31,10 +32,35 @@ EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" +def lookup_via_git() -> tuple[str | None, str]: + """`main`'s commit from `git ls-remote`, which spends no API quota, else None and the cause.""" + try: + probe = subprocess.run( + ["git", "ls-remote", HUB_GIT_URL, "refs/heads/main"], + capture_output=True, + check=False, + encoding="utf-8", + errors="replace", + env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}, + timeout=LOOKUP_TIMEOUT, + ) + except subprocess.TimeoutExpired: + return None, "timed out" + except OSError as exc: + return None, type(exc).__name__ + if probe.returncode != 0: + return None, f"exit {probe.returncode}" + if m := re.fullmatch(r"([0-9a-f]{40})\trefs/heads/main\n?", probe.stdout): + return m.group(1), "" + return None, "unexpected output" + + def resolve_main_commit() -> str | None: - """Return the full commit hash `main` points at now, or None when it cannot be resolved. + """Return the full commit hash `main` points at now, from the API or else `git ls-remote`. - Any failure prints one line naming the cause and returns None, so the gate still runs. + Every file a run fetches comes from that one commit, so a script and its data always pair. + Where neither resolves, one line names both causes and the gate runs against `main` instead. + A hook with no network cannot fetch the gate at all, and the CI gate is the enforcement. """ token = (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") or "").strip() request = urllib.request.Request( @@ -53,8 +79,12 @@ def resolve_main_commit() -> str | None: if re.fullmatch(r"[0-9a-f]{40}", sha): return sha reason = "unexpected response body" + sha, git_reason = lookup_via_git() + if sha: + return sha print( - f"hub_fetch_run: could not resolve the main commit ({reason}), using main.", + f"hub_fetch_run: could not resolve the main commit (API {reason}, git ls-remote " + f"{git_reason}), using main.", file=sys.stderr, ) return None diff --git a/catalog/snippets/husky/README.md b/catalog/snippets/husky/README.md index 9c8db8151..7310de305 100644 --- a/catalog/snippets/husky/README.md +++ b/catalog/snippets/husky/README.md @@ -10,7 +10,8 @@ the doc gates to run: it fetches those two checks fresh from `ptr727/ProjectTemp branch and runs them, rather than vendoring or pinning a copy. A pin nothing keeps current goes stale by construction, and CI (this repo's own, and the hub's) is the backstop for a change that lands broken on `main` before it does real damage locally. The prose gate adds one -`api.github.com` commit lookup to its fetch, and an allow-list permitting only +`api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` +where that fails. An allow-list permitting only `raw.githubusercontent.com` gets an unresolved-commit fallback. These are network calls alongside the Docker pulls the Lint tasks below already do. A fetch failure fails the commit rather than silently skipping the gate. diff --git a/catalog/snippets/pre-commit/README.md b/catalog/snippets/pre-commit/README.md index 98e747dca..c104d25f2 100644 --- a/catalog/snippets/pre-commit/README.md +++ b/catalog/snippets/pre-commit/README.md @@ -24,7 +24,8 @@ to run: it fetches those two checks fresh from `ptr727/ProjectTemplate`'s `main` runs them, rather than vendoring or pinning a copy. A pin that no tool keeps current goes stale by construction, and CI (this repo's own, and the hub's) is the backstop for a change that lands broken on `main` before it does real damage locally. The prose gate adds one -`api.github.com` commit lookup to its fetch, and an allow-list permitting only +`api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` +where that fails. An allow-list permitting only `raw.githubusercontent.com` gets an unresolved-commit fallback. These are network calls alongside the Docker pulls the VS Code Lint tasks already do. A fetch failure fails the commit rather than silently skipping the gate. diff --git a/tests/test_hub_fetch_run.py b/tests/test_hub_fetch_run.py index b5b97ef74..bc4c7f300 100755 --- a/tests/test_hub_fetch_run.py +++ b/tests/test_hub_fetch_run.py @@ -29,6 +29,7 @@ SNIPPET = ROOT / "catalog" / "snippets" / "hub_fetch_run.py" TIMEOUT = 30 SHA = "0123456789abcdef0123456789abcdef01234567" +GIT_SHA = "fedcba9876543210fedcba9876543210fedcba98" def load_snippet() -> ModuleType: @@ -192,6 +193,8 @@ def read(self) -> bytes: b" out.write(os.environ.get('PROSE_GATE_PROVENANCE', ''))\n" ) RAISE = b"raise RuntimeError('gate crashed')\n" +DATA_PATH = ".github/actions/prose-gate/prose-gate.json" +RATE_LIMITED = urllib.error.HTTPError("u", 403, "rate limit", {}, None) # type: ignore[arg-type] ENV_KEYS = ("PROSE_GATE_PROVENANCE", "GH_TOKEN", "GITHUB_TOKEN") @@ -213,6 +216,10 @@ def setUp(self) -> None: self.requests: list[urllib.request.Request | str] = [] self.timeouts: list[float | None] = [] self.stderr = io.StringIO() + self.git = mock.Mock(return_value=(None, "exit 128")) + patcher = mock.patch.object(hub, "lookup_via_git", self.git) + patcher.start() + self.addCleanup(patcher.stop) def urls(self) -> list[str]: return [r if isinstance(r, str) else r.full_url for r in self.requests] @@ -275,6 +282,7 @@ def test_lookup_only_for_the_prose_gate(self) -> None: seen = self.run_main(path=".github/actions/repo-gate/repo_gate.py") self.assertEqual(seen, "") self.assertEqual(self.lookup_requests(), []) + self.git.assert_not_called() self.assertTrue(self.urls()[-1].endswith("/main/.github/actions/repo-gate/repo_gate.py")) def test_fallback_causes_print_a_line_and_the_gate_still_runs(self) -> None: @@ -297,9 +305,30 @@ def test_fallback_causes_print_a_line_and_the_gate_still_runs(self) -> None: self.assertEqual(self.run_main(lookup), UNRESOLVED) line = self.stderr.getvalue() self.assertIn(cause, line) + self.assertIn("git ls-remote exit 128", line) self.assertEqual(line.count("\n"), 1, line) + self.assertTrue(self.urls()[-2].endswith(f"/main/{DATA_PATH}"), self.urls()) self.assertTrue(self.urls()[-1].endswith(f"/main/{PROSE_PATH}"), self.urls()) + def test_git_fallback_pins_the_script_and_its_data_to_one_commit(self) -> None: + """A rate-limited API lookup still fetches both files at one commit, so they pair.""" + self.git.return_value = (GIT_SHA, "") + seen = self.run_main(RATE_LIMITED) + self.assertEqual(seen, f"ptr727/ProjectTemplate@{GIT_SHA} (hub-fetch-run main)") + fetched = [u for u in self.urls() if u != hub.HUB_MAIN_SHA_URL] + self.assertEqual( + fetched, + [ + f"{hub.HUB_RAW_BASE}/{GIT_SHA}/{DATA_PATH}", + f"{hub.HUB_RAW_BASE}/{GIT_SHA}/{PROSE_PATH}", + ], + ) + self.assertEqual(self.stderr.getvalue(), "") + + def test_git_fallback_is_not_run_when_the_api_resolves(self) -> None: + self.assertEqual(self.run_main(), RESOLVED) + self.git.assert_not_called() + def test_token_header_sent_only_when_set(self) -> None: self.run_main() self.assertIsNone(self.lookup_requests()[-1].get_header("Authorization")) @@ -378,5 +407,41 @@ def test_token_header_is_unredirected(self) -> None: self.assertEqual(request.unredirected_hdrs.get("Authorization"), "Bearer tok-one") +class GitLookupTests(unittest.TestCase): + """lookup_via_git reads one `git ls-remote` line, and every other shape is a named cause.""" + + def lookup(self, run: mock.Mock) -> tuple[str | None, str]: + with mock.patch.object(hub.subprocess, "run", run): + return hub.lookup_via_git() + + def test_one_main_line_is_its_commit(self) -> None: + done = subprocess.CompletedProcess([], 0, f"{GIT_SHA}\trefs/heads/main\n", "") + run = mock.Mock(return_value=done) + self.assertEqual(self.lookup(run), (GIT_SHA, "")) + args, kwargs = run.call_args + self.assertEqual(args[0], ["git", "ls-remote", hub.HUB_GIT_URL, "refs/heads/main"]) + self.assertEqual(kwargs["timeout"], hub.LOOKUP_TIMEOUT) + self.assertEqual(kwargs["env"]["GIT_TERMINAL_PROMPT"], "0") + + def test_every_other_shape_names_its_cause(self) -> None: + line = f"{GIT_SHA}\trefs/heads/main\n" + cases: list[tuple[str, mock.Mock]] = [ + ("exit 128", mock.Mock(return_value=subprocess.CompletedProcess([], 128, "", "x"))), + ("FileNotFoundError", mock.Mock(side_effect=FileNotFoundError("git"))), + ("timed out", mock.Mock(side_effect=subprocess.TimeoutExpired("git", 5))), + ] + for out in ( + "", + GIT_SHA[:8] + "\trefs/heads/main\n", + line + line, + GIT_SHA.upper() + line[40:], + ): + done = subprocess.CompletedProcess([], 0, out, "") + cases.append(("unexpected output", mock.Mock(return_value=done))) + for cause, run in cases: + with self.subTest(cause=cause, run=run): + self.assertEqual(self.lookup(run), (None, cause)) + + if __name__ == "__main__": unittest.main() From 03665d55d48336c61d060a35e4ba91148cc958cf Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 07:10:14 -0700 Subject: [PATCH 2/3] Discard ls-remote Stderr and Keep the API Hash Name Distinct --- GOVERNANCE.md | 2 +- catalog/snippets/hub_fetch_run.py | 15 ++++++++++----- tests/test_hub_fetch_run.py | 1 + 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index f9c8d101d..6523f7c69 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -290,7 +290,7 @@ CI runs the full lint set, but run the linters locally before pushing to catch i - **CI (authoritative)** runs **markdownlint-cli2**, **cspell**, and **actionlint** as pinned action wrappers, which Dependabot bumps. It runs **editorconfig-checker** via Docker `:latest`, since its action only installs the CLI and the Docker one-liner is what actually runs the check. **shellcheck** and **shfmt** run the same way for a repo that carries a shell script, and **PSScriptAnalyzer** does for a repo that carries `.ps1` files. None of shellcheck, shfmt, and PSScriptAnalyzer has an action. For a repo that carries an action under `.github/actions/`, the repo gate's `composite-actions` check runs **shellcheck** in Docker over each bash or sh `run:` body. It also runs **check-jsonschema** through `uvx`, because actionlint reads workflows only. The `composite-actions` check runs shellcheck at warning severity without SC2154, weaker than for a `.sh` file. markdownlint covers all `**/*.md`, and **cspell is scoped to `README.md` + `HISTORY.md`** (see [CODESTYLE.md](./CODESTYLE.md) "Markdown and Spelling" for why), matching the cspell one-liner below. A "shell script" here is a tracked `.sh` file, plus a tracked, extension-less file whose shebang names bash or sh, the shape a script meant to run as a bare command takes: a bare `*.sh` glob misses that second case, so both discovery paths run before either tool does. This whole block is the hub's `validate-task.yml` reusable workflow, so a fleet repo reaches it rather than carrying a copy of these steps. - **A working local hook is strongly suggested fleet-wide, and its absence is a measured audit finding, not an invisible gap.** `spec/project-types.json`'s `parity.hooks` check reads this section for its rationale, judged by hand during an `AUDIT.md` run like every sibling check in its dimension, never mechanized by `spec/audit.py`: a repo with no local hook mechanism wired at all is a `linter-parity` defect, the same severity a missing markdownlint config already gets, while a repo mid-convergence (below) stays operational. CI remains the authoritative run regardless. Catalog snippets carry the canonical shape, each with a copy of `catalog/snippets/hub_fetch_run.py` alongside it. `catalog/snippets/husky/` is Husky.Net, for a repo that already keeps a .NET tool manifest declaring it, since `dotnet tool restore` then `dotnet husky install` is what generates the `.husky/_/husky.sh` its hook sources, and the snippet ships no manifest of its own. `catalog/snippets/pre-commit/` is the `pre-commit` framework, for a repo without one and for any repo that prefers it. No snippet is scoped to a language by what it runs. Each carries the repo's own language checks plus the shared doc gates. A repo drops the block for a language it does not have. A Docker, config, or docs repo therefore wires the doc gates alone, which is a mechanism rather than the absence of one. Which snippet a repo starts from is bounded by the toolchain it already keeps, never by which languages its checks cover. A snippet is a starting point rather than the only shape: a repo may wire an equivalent hook of its own at `.husky/pre-commit`, enabled with `core.hooksPath` and sourcing nothing, which is what this repository does. That path matters, since `parity.hooks` reads the tracked file at `.husky/pre-commit` or `.pre-commit-config.yaml` rather than a per-clone hooks path it cannot observe. - **The hook** runs **language formatting** and the **diff-scoped doc gates**, never Docker, so it stays fast. The formatting half is whatever the repo's own language needs, CSharpier and `dotnet format` for .NET or ruff and the repo's type checker for Python, via native tooling. A repo adds each half once its tree passes that half, since a gate that fails on the corpus it guards blocks every commit from the moment it lands, so a hook running one half is a repo mid-convergence rather than a repo out of conformance. The doc half runs each gate at the scope that fits it. The prose gate is scoped to the working tree diff against `HEAD` rather than swept over the tree, which is the difference between about 2.2 seconds and about 0.13 and is what makes it affordable in a hook at all. That scope is the working tree rather than the staged index under a plain git hook, so a partially staged file is judged on all of its edits. Under the `pre-commit` framework it is the staged state instead, since that runner sets unstaged changes aside before running a hook, which is measured rather than assumed. The pull request gate re-checks every line the branch changes against its base, which is the scope a review is judged on. A whole-repo check belongs in the hook too when it is already fast and takes no file list, which the line-ending consistency check is, so scope is a property of the gate rather than a rule the hook applies to all of them. `repo_gate.py --check sha-pin` stays out of the hook regardless, since it resolves a same-owner pin against the GitHub API. -- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss, and those are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. +- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss. Those lookups and that resolution are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. - **The hub carries a second hook, `.husky/pre-push`, gating the local-review rule rather than lint.** It runs `scripts/local_review.py check`, refusing a branch push whose diff no recorded review pass covers, per "Verification Discipline" above. It fires only for a branch update, so a tag push and a branch delete pass through, and a branch holding no net content against its target has nothing for a review to cover. It refuses rather than guesses in every state it cannot speak for, since the engine reads the checkout it runs in while a push delivers a commit, and those describe the same content only sometimes. The order that keeps them describing the same content is to commit the change, then review the diff, record its receipt, and push, the receipt being untracked and so recorded after the last commit. A change that also carries the canonical ledger records those passes ahead of that commit instead, the ledger being tracked content the commit has to hold. It reads `develop` and accepts no override from the environment, since an environment variable is set inline on the very command being gated, by whoever is being gated, which is the same reason an authorization is never read from a channel the agent itself can set. The cost is that it measures a branch based on anything but `develop` against `develop` anyway, so its refusal there is not a verdict about that branch. Each refusal names its own case, and the `local-strict-review` Skill carries the fleet's one enumeration of them with what clears each, deliberately in one place rather than restated here. It folds the engine's three-valued exit honestly: a check that could not run blocks too, and says so in different words than a check that ran and found no pass, because a gate that waves a push through when it could not run is a gate that stopped gating. It is a backstop rather than a seal, and it is bypassable by construction: `--no-verify` is the documented route out of a pickle and is not the only one, since a git hook cannot police its own invocation. A Claude Code session meets a narrower surface, that flag being denied unconditionally by the agent-safety hook's explicit-bypass rule, and that denial is Claude Code's alone, since Codex and opencode carry no such hook yet. So the committed hook raises the cost of skipping the rule for one agent and lowers it for none, and the prose layer above stays the agent-agnostic one that actually binds. It is hub-only for now. `local_review.py` is hub-hosted per "Hub-Hosted Tooling", and a downstream repo reaches it as a hub checkout's copy run with its own worktree as the working directory, so a catalog snippet carrying this hook fleet-wide is a later step rather than part of this one. `canonical_review.py` is not run here at all, and nothing else gates a push or a pull request over a canonical unit either, that read being swept on a schedule instead, per "Verification Discipline" above. The hub's own `.github/actions/validate` composite action renders its coverage burn-down into every run's job summary and fails no pull request over what that shows, while still failing where the engine could not read the manifest or the ledger at all, that being a boundary rather than a verdict. - **The VS Code Lint tasks** run the full doc-lint set via Docker `:latest` on demand, the local surface for Markdown, spelling, workflow, and EditorConfig checks, plus `Lint: Prose` and `Lint: EOL`, the same hook gates in whole-repo mode rather than diff-scoped, for on-demand full-tree validation. diff --git a/catalog/snippets/hub_fetch_run.py b/catalog/snippets/hub_fetch_run.py index 68dbd3611..9c71eeb30 100644 --- a/catalog/snippets/hub_fetch_run.py +++ b/catalog/snippets/hub_fetch_run.py @@ -33,11 +33,16 @@ def lookup_via_git() -> tuple[str | None, str]: - """`main`'s commit from `git ls-remote`, which spends no API quota, else None and the cause.""" + """`main`'s commit from `git ls-remote`, which spends no API quota, else None and the cause. + + Stderr is discarded rather than captured, so a remote helper git leaves behind on a timeout holds + no pipe this process waits on. + """ try: probe = subprocess.run( ["git", "ls-remote", HUB_GIT_URL, "refs/heads/main"], - capture_output=True, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, encoding="utf-8", errors="replace", @@ -79,9 +84,9 @@ def resolve_main_commit() -> str | None: if re.fullmatch(r"[0-9a-f]{40}", sha): return sha reason = "unexpected response body" - sha, git_reason = lookup_via_git() - if sha: - return sha + git_sha, git_reason = lookup_via_git() + if git_sha: + return git_sha print( f"hub_fetch_run: could not resolve the main commit (API {reason}, git ls-remote " f"{git_reason}), using main.", diff --git a/tests/test_hub_fetch_run.py b/tests/test_hub_fetch_run.py index bc4c7f300..53f278571 100755 --- a/tests/test_hub_fetch_run.py +++ b/tests/test_hub_fetch_run.py @@ -422,6 +422,7 @@ def test_one_main_line_is_its_commit(self) -> None: self.assertEqual(args[0], ["git", "ls-remote", hub.HUB_GIT_URL, "refs/heads/main"]) self.assertEqual(kwargs["timeout"], hub.LOOKUP_TIMEOUT) self.assertEqual(kwargs["env"]["GIT_TERMINAL_PROMPT"], "0") + self.assertIs(kwargs["stderr"], subprocess.DEVNULL) def test_every_other_shape_names_its_cause(self) -> None: line = f"{GIT_SHA}\trefs/heads/main\n" From 9b4922901f2887e29cff3b9fcff368a9ef37d009 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 07:16:56 -0700 Subject: [PATCH 3/3] Scope the Doc Gates' Network Sentence and Rewrap a Docstring Line --- GOVERNANCE.md | 2 +- catalog/snippets/hub_fetch_run.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 6523f7c69..d7586e8fb 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -290,7 +290,7 @@ CI runs the full lint set, but run the linters locally before pushing to catch i - **CI (authoritative)** runs **markdownlint-cli2**, **cspell**, and **actionlint** as pinned action wrappers, which Dependabot bumps. It runs **editorconfig-checker** via Docker `:latest`, since its action only installs the CLI and the Docker one-liner is what actually runs the check. **shellcheck** and **shfmt** run the same way for a repo that carries a shell script, and **PSScriptAnalyzer** does for a repo that carries `.ps1` files. None of shellcheck, shfmt, and PSScriptAnalyzer has an action. For a repo that carries an action under `.github/actions/`, the repo gate's `composite-actions` check runs **shellcheck** in Docker over each bash or sh `run:` body. It also runs **check-jsonschema** through `uvx`, because actionlint reads workflows only. The `composite-actions` check runs shellcheck at warning severity without SC2154, weaker than for a `.sh` file. markdownlint covers all `**/*.md`, and **cspell is scoped to `README.md` + `HISTORY.md`** (see [CODESTYLE.md](./CODESTYLE.md) "Markdown and Spelling" for why), matching the cspell one-liner below. A "shell script" here is a tracked `.sh` file, plus a tracked, extension-less file whose shebang names bash or sh, the shape a script meant to run as a bare command takes: a bare `*.sh` glob misses that second case, so both discovery paths run before either tool does. This whole block is the hub's `validate-task.yml` reusable workflow, so a fleet repo reaches it rather than carrying a copy of these steps. - **A working local hook is strongly suggested fleet-wide, and its absence is a measured audit finding, not an invisible gap.** `spec/project-types.json`'s `parity.hooks` check reads this section for its rationale, judged by hand during an `AUDIT.md` run like every sibling check in its dimension, never mechanized by `spec/audit.py`: a repo with no local hook mechanism wired at all is a `linter-parity` defect, the same severity a missing markdownlint config already gets, while a repo mid-convergence (below) stays operational. CI remains the authoritative run regardless. Catalog snippets carry the canonical shape, each with a copy of `catalog/snippets/hub_fetch_run.py` alongside it. `catalog/snippets/husky/` is Husky.Net, for a repo that already keeps a .NET tool manifest declaring it, since `dotnet tool restore` then `dotnet husky install` is what generates the `.husky/_/husky.sh` its hook sources, and the snippet ships no manifest of its own. `catalog/snippets/pre-commit/` is the `pre-commit` framework, for a repo without one and for any repo that prefers it. No snippet is scoped to a language by what it runs. Each carries the repo's own language checks plus the shared doc gates. A repo drops the block for a language it does not have. A Docker, config, or docs repo therefore wires the doc gates alone, which is a mechanism rather than the absence of one. Which snippet a repo starts from is bounded by the toolchain it already keeps, never by which languages its checks cover. A snippet is a starting point rather than the only shape: a repo may wire an equivalent hook of its own at `.husky/pre-commit`, enabled with `core.hooksPath` and sourcing nothing, which is what this repository does. That path matters, since `parity.hooks` reads the tracked file at `.husky/pre-commit` or `.pre-commit-config.yaml` rather than a per-clone hooks path it cannot observe. - **The hook** runs **language formatting** and the **diff-scoped doc gates**, never Docker, so it stays fast. The formatting half is whatever the repo's own language needs, CSharpier and `dotnet format` for .NET or ruff and the repo's type checker for Python, via native tooling. A repo adds each half once its tree passes that half, since a gate that fails on the corpus it guards blocks every commit from the moment it lands, so a hook running one half is a repo mid-convergence rather than a repo out of conformance. The doc half runs each gate at the scope that fits it. The prose gate is scoped to the working tree diff against `HEAD` rather than swept over the tree, which is the difference between about 2.2 seconds and about 0.13 and is what makes it affordable in a hook at all. That scope is the working tree rather than the staged index under a plain git hook, so a partially staged file is judged on all of its edits. Under the `pre-commit` framework it is the staged state instead, since that runner sets unstaged changes aside before running a hook, which is measured rather than assumed. The pull request gate re-checks every line the branch changes against its base, which is the scope a review is judged on. A whole-repo check belongs in the hook too when it is already fast and takes no file list, which the line-ending consistency check is, so scope is a property of the gate rather than a rule the hook applies to all of them. `repo_gate.py --check sha-pin` stays out of the hook regardless, since it resolves a same-owner pin against the GitHub API. -- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss. Those lookups and that resolution are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. +- **The doc gates reach a downstream repo by fetching `.github/actions/prose-gate/prose_lint.py` with the `prose-gate.json` beside it and `.github/actions/repo-gate/repo_gate.py` fresh from `ptr727/ProjectTemplate`'s `main` branch, via `hub_fetch_run.py`, never vendored and never pinned.** Pinning anything Dependabot does not maintain goes stale by construction, and CI (this repo's own, and the hub's) is the backstop that catches a change landing broken on `main` before a locally fetched copy does real damage. The prose gate adds one `api.github.com` commit lookup to its fetch, with a `git ls-remote` against `github.com` where that fails. `uv` resolves the packages its script block declares on a cache miss. Beyond fetching the scripts, those lookups and that resolution are the only network calls the doc gates make. An allow-list permitting only `raw.githubusercontent.com` still runs the gate, with the commit reported as unresolved. A Python repo's `uvx`-run ruff and type checker can also reach the network, to resolve `@latest` on a cache miss or refresh, the same category of dependency as the Docker pulls the VS Code Lint tasks already do routinely, not a new one. A fetch failure fails the commit, and it never silently skips the gate. The **hub's own** `.husky/pre-commit` is the one exception, staying local and offline, since it carries both gates directly and has no hub to reach. A repo enables its hook per clone with `git config core.hooksPath .husky` or (`uv tool install pre-commit` once, then) `pre-commit install`. The Husky.Net snippet needs one more step per clone, `dotnet tool restore` then `dotnet husky install`, which generates `.husky/_/husky.sh`, the file the hook sources. CI remains the authoritative run either way. - **The hub carries a second hook, `.husky/pre-push`, gating the local-review rule rather than lint.** It runs `scripts/local_review.py check`, refusing a branch push whose diff no recorded review pass covers, per "Verification Discipline" above. It fires only for a branch update, so a tag push and a branch delete pass through, and a branch holding no net content against its target has nothing for a review to cover. It refuses rather than guesses in every state it cannot speak for, since the engine reads the checkout it runs in while a push delivers a commit, and those describe the same content only sometimes. The order that keeps them describing the same content is to commit the change, then review the diff, record its receipt, and push, the receipt being untracked and so recorded after the last commit. A change that also carries the canonical ledger records those passes ahead of that commit instead, the ledger being tracked content the commit has to hold. It reads `develop` and accepts no override from the environment, since an environment variable is set inline on the very command being gated, by whoever is being gated, which is the same reason an authorization is never read from a channel the agent itself can set. The cost is that it measures a branch based on anything but `develop` against `develop` anyway, so its refusal there is not a verdict about that branch. Each refusal names its own case, and the `local-strict-review` Skill carries the fleet's one enumeration of them with what clears each, deliberately in one place rather than restated here. It folds the engine's three-valued exit honestly: a check that could not run blocks too, and says so in different words than a check that ran and found no pass, because a gate that waves a push through when it could not run is a gate that stopped gating. It is a backstop rather than a seal, and it is bypassable by construction: `--no-verify` is the documented route out of a pickle and is not the only one, since a git hook cannot police its own invocation. A Claude Code session meets a narrower surface, that flag being denied unconditionally by the agent-safety hook's explicit-bypass rule, and that denial is Claude Code's alone, since Codex and opencode carry no such hook yet. So the committed hook raises the cost of skipping the rule for one agent and lowers it for none, and the prose layer above stays the agent-agnostic one that actually binds. It is hub-only for now. `local_review.py` is hub-hosted per "Hub-Hosted Tooling", and a downstream repo reaches it as a hub checkout's copy run with its own worktree as the working directory, so a catalog snippet carrying this hook fleet-wide is a later step rather than part of this one. `canonical_review.py` is not run here at all, and nothing else gates a push or a pull request over a canonical unit either, that read being swept on a schedule instead, per "Verification Discipline" above. The hub's own `.github/actions/validate` composite action renders its coverage burn-down into every run's job summary and fails no pull request over what that shows, while still failing where the engine could not read the manifest or the ledger at all, that being a boundary rather than a verdict. - **The VS Code Lint tasks** run the full doc-lint set via Docker `:latest` on demand, the local surface for Markdown, spelling, workflow, and EditorConfig checks, plus `Lint: Prose` and `Lint: EOL`, the same hook gates in whole-repo mode rather than diff-scoped, for on-demand full-tree validation. diff --git a/catalog/snippets/hub_fetch_run.py b/catalog/snippets/hub_fetch_run.py index 9c71eeb30..f9b44f50e 100644 --- a/catalog/snippets/hub_fetch_run.py +++ b/catalog/snippets/hub_fetch_run.py @@ -35,8 +35,8 @@ def lookup_via_git() -> tuple[str | None, str]: """`main`'s commit from `git ls-remote`, which spends no API quota, else None and the cause. - Stderr is discarded rather than captured, so a remote helper git leaves behind on a timeout holds - no pipe this process waits on. + Stderr is discarded rather than captured, so a remote helper git leaves behind on a timeout + holds no pipe this process waits on. """ try: probe = subprocess.run(