From 4160810953f9c9445087ce92ba358f2866a065d6 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:57:26 -0500 Subject: [PATCH 1/7] feat(git-hooks): inspect what runs at each hook stage, and detect Husky.Net The shared git-hook installer gains a read-only `inspect` action. For each git hook stage it lists every item that runs under the repository's hook manager (plain dispatcher markers and chained hooks, .husky/ lines, lefthook jobs from `lefthook dump`, git config hooks, any other hook file), names stamped entry copies by plugin and entry, and times only the calling plugin's own installed entries that rewrite nothing and whose tools are present. Every other item is reported not run, with the reason. Each carrier's setup exposes it as `check inspect`. `detect` recognizes Husky.Net's .husky/task-runner.json as husky with variant "husky.net": Husky.Net runs .husky/ as husky does, so the husky adapter drives it unchanged, and inspect lists the tasks a `husky run --group` or `--name` line selects. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- .../feat-git-hooks-inspect-9e83d8f9.md | 8 + .../feat-git-hooks-inspect-e17b94e7.md | 8 + .../feat-git-hooks-inspect-534a268d.md | 8 + .../feat-git-hooks-inspect-e28a44d8.md | 8 + .../feat-git-hooks-inspect-e670076f.md | 8 + .../feat-git-hooks-inspect-9a856722.md | 8 + .../feat-git-hooks-inspect-d8c496e6.md | 8 + .../feat-git-hooks-inspect-46218c3e.md | 8 + .../feat-git-hooks-inspect-7c0c691f.md | 8 + .../feat-git-hooks-inspect-a8b1b962.md | 8 + .../feat-git-hooks-inspect-f6f6d253.md | 8 + docs/contracts/check-placement/README.md | 20 +- .../check-placement/adopting-git-hooks.md | 9 + lib/git-hooks/install.mjs | 342 +++++++++++++++++- lib/git-hooks/install.test.mjs | 227 ++++++++++++ plugins/actionlint/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/actionlint/skills/setup/SKILL.md | 19 +- plugins/bash-format/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/bash-format/skills/setup/SKILL.md | 19 +- .../code-tidying/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/code-tidying/skills/setup/SKILL.md | 17 +- plugins/go-format/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/go-format/skills/setup/SKILL.md | 19 +- plugins/guardrails/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/guardrails/skills/setup/SKILL.md | 19 +- .../lib/git-hooks/install.mjs | 342 +++++++++++++++++- .../skills/setup/SKILL.md | 19 +- .../lib/git-hooks/install.mjs | 342 +++++++++++++++++- .../javascript-format/skills/setup/SKILL.md | 19 +- .../markdown-format/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/markdown-format/skills/setup/SKILL.md | 19 +- .../lib/git-hooks/install.mjs | 342 +++++++++++++++++- .../powershell-format/skills/setup/SKILL.md | 19 +- .../python-format/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/python-format/skills/setup/SKILL.md | 19 +- plugins/spelling/lib/git-hooks/install.mjs | 342 +++++++++++++++++- plugins/spelling/skills/setup/SKILL.md | 19 +- 37 files changed, 4570 insertions(+), 85 deletions(-) create mode 100644 .changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md create mode 100644 .changes/bash-format/feat-git-hooks-inspect-e17b94e7.md create mode 100644 .changes/code-tidying/feat-git-hooks-inspect-534a268d.md create mode 100644 .changes/go-format/feat-git-hooks-inspect-e28a44d8.md create mode 100644 .changes/guardrails/feat-git-hooks-inspect-e670076f.md create mode 100644 .changes/instruction-placement/feat-git-hooks-inspect-9a856722.md create mode 100644 .changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md create mode 100644 .changes/markdown-format/feat-git-hooks-inspect-46218c3e.md create mode 100644 .changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md create mode 100644 .changes/python-format/feat-git-hooks-inspect-a8b1b962.md create mode 100644 .changes/spelling/feat-git-hooks-inspect-f6f6d253.md diff --git a/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/guardrails/feat-git-hooks-inspect-e670076f.md b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md new file mode 100644 index 00000000000..c07adc998ff --- /dev/null +++ b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. diff --git a/docs/contracts/check-placement/README.md b/docs/contracts/check-placement/README.md index 31858473f09..af06c0f5e65 100644 --- a/docs/contracts/check-placement/README.md +++ b/docs/contracts/check-placement/README.md @@ -219,8 +219,9 @@ the consumer git floor moves. ### HookManager port ```text -detect(repo) -> { manager: "lefthook"|"husky"|"plain"|"conflict", evidence[] } +detect(repo) -> { manager: "lefthook"|"husky"|"plain"|"conflict", evidence[], variant? } list(repo) -> [{ entryId, event, scope, stamp }] +inspect(repo, runs?) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } # read-only plan(repo, entries, scope) -> { actions[], decisions[] } copy(repo, entry, scope) -> "installed" | "refreshed" | "unchanged" | "blocked" | "unsafe-path" | "stage-failed" # plugin-owned files only decline(repo, entryId) -> sets the git config --local key (--global: the global one) @@ -230,7 +231,22 @@ decline(repo, entryId) -> sets the git config --local key (--global: the (D1). Entry names, events and scopes are manager-neutral; each manager's file format stays inside its adapter. `detect` also recognizes other hook managers (the pre-commit framework, simple-git-hooks, overcommit, husky v4) and returns them as conflict decisions. A set `core.hooksPath` is treated as -husky or foreign, never as plain. +husky or foreign, never as plain. A `.husky/task-runner.json` marks Husky.Net: `detect` returns +`husky` with `variant: "husky.net"`, since Husky.Net runs `.husky/` as husky does and the +husky adapter drives it unchanged. + +**`inspect`.** For each git hook stage, `inspect` lists every item that runs, under whichever +manager the repository uses: plain dispatcher markers and a chained `.pre-checks`, each +command line of `.husky/` (and the Husky.Net tasks a `husky run --group` or `--name` line +selects), the lefthook jobs `lefthook dump` reports, git config hooks, and any other hook file. +`installed` says whether git finds an executable hook file for the stage. An item that is a stamped +entry copy names its plugin and entry. Only the calling plugin's own entries that rewrite nothing +and whose tools are present are run, from their installed copies, on the staged set (`pre-commit`), +a message file outside the repository (`commit-msg`) or the branch against its upstream +(`pre-push`), and get `measured: { medianMs, minMs, maxMs, runs, input, exitCodes }`; every other +item gets `notMeasured` with the reason. `inspect` itself writes nothing in the repository; a +timed entry does only what it does in a real hook run. Its numbers feed +the [duration budgets](#duration-budgets) for placing a check. **`hooks-path-owned`.** When `core.hooksPath` hands the local hooks directory to another tool (any value except the plain shared `.githooks`), `plan` returns only one decision, diff --git a/docs/contracts/check-placement/adopting-git-hooks.md b/docs/contracts/check-placement/adopting-git-hooks.md index 41744fb9596..f6d785b7574 100644 --- a/docs/contracts/check-placement/adopting-git-hooks.md +++ b/docs/contracts/check-placement/adopting-git-hooks.md @@ -49,6 +49,8 @@ Committed config does not install itself: every clone runs the manager's install - lefthook: `lefthook install`. - husky: the project's package install, which runs husky's setup. +- Husky.Net: `dotnet tool restore`, then `dotnet husky install` + ([getting started](https://alirezanet.github.io/Husky.Net/guide/getting-started.html#setup-husky-for-your-project)). - plain git hooks: `git config core.hooksPath .githooks`. A clone that skips this step gets no hooks, so for a team with authors outside Claude Code prefer @@ -59,6 +61,13 @@ or pushing on a branch you do not trust, read its diff to `lefthook.yml`, `lefth `.lefthook/`, `.lefthook-local/`, `.husky/` and `.githooks/` ([details](README.md#where-installed-copies-live)). +## See what runs at each stage + +`/:setup check inspect` lists every hook each stage runs, under whichever manager the +repository uses, with the plugin's own entries timed and every other hook marked not run with the +reason. Compare the times with the [duration budgets](README.md#duration-budgets) before placing a +new check ([`inspect`](README.md#hookmanager-port)). + ## Decline A decline is a git config key, never committed. It silences the session-start drift line for that diff --git a/lib/git-hooks/install.mjs b/lib/git-hooks/install.mjs index 1d620e1a231..40700aa8162 100755 --- a/lib/git-hooks/install.mjs +++ b/lib/git-hooks/install.mjs @@ -1,10 +1,12 @@ #!/usr/bin/env node // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -49,6 +51,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -58,7 +61,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -75,6 +78,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -412,6 +416,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -419,14 +425,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1398,8 +1406,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1413,9 +1734,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1435,6 +1757,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1489,6 +1815,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1513,6 +1842,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/lib/git-hooks/install.test.mjs b/lib/git-hooks/install.test.mjs index 5d897215136..3f534fc6578 100644 --- a/lib/git-hooks/install.test.mjs +++ b/lib/git-hooks/install.test.mjs @@ -1765,3 +1765,230 @@ test("installed scripts are executable", { skip: !posixHost }, () => { assert.ok(statSync(path.join(dir, ".git", "hooks", "pre-commit")).mode & 0o100); assert.ok(statSync(path.join(dir, ".git", "hooks", "demo-checks", "word-check.sh")).mode & 0o100); }); + +describe("inspect", () => { + // inspect(root, dir, ctx, ...args) -> the parsed report and exit code. + function inspectRun(root, dir, ctx = {}, ...args) { + const out = []; + const code = main(["inspect", ...args, "--repo", dir, "--plugin-root", root], ctx, { stdout: (s) => out.push(s), stderr: () => {} }); + return { code, report: code === 0 ? JSON.parse(out.join("\n")) : null }; + } + const stage = (report, event) => report.stages.find((s) => s.event === event); + const named = (s, name) => s.items.find((i) => i.name === name); + const RAN = "inspect-ran-this"; + const touches = `#!/bin/sh\ntouch "${RAN}"\n`; + + function otherPlugin() { + const root = plugin(); + writeFileSync(path.join(root, ".claude-plugin", "plugin.json"), JSON.stringify({ name: "other-checks" })); + return root; + } + + test("plain: times this plugin's report-only entry on the staged set, and runs nothing else", () => { + const root = plugin(); + const dir = repo(); + run(root, dir, "copy", "--scope", "local"); + run(otherPlugin(), dir, "copy", "--scope", "local"); + writeFileSync(path.join(dir, ".git", "hooks", "pre-commit.pre-checks"), touches); + chmodSync(path.join(dir, ".git", "hooks", "pre-commit.pre-checks"), 0o755); + stageBad(dir); + const before = tree(dir); + const { code, report } = inspectRun(root, dir, {}, "--runs", "2"); + assert.equal(code, 0); + assert.deepEqual(tree(dir), before, "inspect writes nothing in the repository"); + assert.equal(existsSync(path.join(dir, RAN)), false, "the chained hook did not run"); + assert.equal(report.manager, "plain"); + const pre = stage(report, "pre-commit"); + assert.equal(pre.installed, true); + assert.deepEqual(pre.items.map((i) => i.kind), ["chained", "entry", "entry"]); + assert.match(named(pre, "pre-commit.pre-checks").notMeasured, /^a pre-existing hook/); + const own = named(pre, "demo-checks/word-check"); + assert.equal(own.measured.runs, 2); + assert.equal(own.measured.input, "1 staged file"); + assert.deepEqual(own.measured.exitCodes, [1, 1], "the timed run found the staged BADWORD"); + assert.ok(own.measured.minMs <= own.measured.medianMs && own.measured.medianMs <= own.measured.maxMs); + assert.equal(named(pre, "other-checks/word-check").notMeasured, "an entry of other-checks: time it with /other-checks:setup check inspect"); + }); + + test("plain: an entry is not timed with nothing staged, when it rewrites, or when its tool is missing", () => { + const dir = repo(); + const nothing = plugin(); + run(nothing, dir, "copy", "--scope", "local"); + const item = (root) => stage(inspectRun(root, dir).report, "pre-commit").items[0].notMeasured; + assert.equal(item(nothing), "nothing staged: stage the files to time it on, then rerun"); + stageBad(dir); + const rewrites = plugin([{ name: "word-check", event: "pre-commit", script: "word-check.sh", tools: ["grep"], rewrites: true }]); + assert.equal(item(rewrites), "rewrites staged files"); + const absent = plugin([{ name: "word-check", event: "pre-commit", script: "word-check.sh", tools: ["no-such-tool-for-inspect"], rewrites: false }]); + assert.equal(item(absent), "tool missing: no-such-tool-for-inspect"); + }); + + test("plain: a commit-msg entry is timed on a message file outside the repository; a pre-push one needs an upstream", () => { + const entries = [ + { name: "msg-check", event: "commit-msg", script: "msg-check.sh", tools: ["grep"], rewrites: false }, + { name: "push-check", event: "pre-push", script: "push-check.sh", tools: ["grep"], rewrites: false }, + ]; + const root = plugin(entries); + writeFileSync(path.join(root, "git-hooks", "msg-check.sh"), '#!/bin/sh\ngrep -q "^chore: " "$1"\n'); + writeFileSync(path.join(root, "git-hooks", "push-check.sh"), "#!/bin/sh\nexit 0\n"); + const dir = repo(); + run(root, dir, "copy", "--scope", "local"); + const report = inspectRun(root, dir).report; + const msg = stage(report, "commit-msg").items[0]; + assert.equal(msg.measured.input, "a one-line message"); + assert.deepEqual(msg.measured.exitCodes, [0, 0, 0]); + assert.equal(stage(report, "pre-push").items[0].notMeasured, "no upstream: with no refs on stdin the entry checks nothing"); + git(dir, ["remote", "add", "origin", path.join(work, "no-such-remote")]); + git(dir, ["update-ref", "refs/remotes/origin/main", "HEAD"]); + assert.equal(git(dir, ["branch", "--set-upstream-to=origin/main"]).status, 0); + const push = stage(inspectRun(root, dir).report, "pre-push").items[0]; + assert.equal(push.measured.runs, 1, "pre-push is timed once by default"); + assert.equal(push.measured.input, "no refs on stdin, so HEAD against origin/main"); + }); + + test("--runs takes 1 to 20, and only with inspect", () => { + const root = plugin(); + const dir = repo(); + assert.equal(inspectRun(root, dir, {}, "--runs", "0").code, 2); + assert.equal(inspectRun(root, dir, {}, "--runs", "21").code, 2); + assert.equal(run(root, dir, "list", "--runs", "2").code, 2); + }); + + test("a hook file no manager owns is listed, not run", () => { + const dir = repo(); + writeFileSync(path.join(dir, ".git", "hooks", "pre-commit"), touches); + chmodSync(path.join(dir, ".git", "hooks", "pre-commit"), 0o755); + writeFileSync(path.join(dir, ".pre-commit-config.yaml"), "repos: []\n"); + const report = inspectRun(plugin(), dir).report; + assert.equal(report.manager, "conflict"); + assert.deepEqual(stage(report, "pre-commit").items, [ + { kind: "hook", name: "pre-commit", source: ".git/hooks/pre-commit", notMeasured: "a repository hook: running it could change files, the index or a remote" }, + ]); + assert.equal(existsSync(path.join(dir, RAN)), false); + }); + + test("husky 9: each line of .husky/ is listed, and the plugin's own line is its entry", () => { + const root = plugin(); + const dir = repo(); + mkdirSync(path.join(dir, ".husky", "_"), { recursive: true }); + writeFileSync(path.join(dir, ".husky", "_", "pre-commit"), '#!/bin/sh\n. "$(dirname "$0")/h"\n'); + chmodSync(path.join(dir, ".husky", "_", "pre-commit"), 0o755); + git(dir, ["config", "core.hooksPath", ".husky/_"]); + run(root, dir, "copy", "--scope", "shared"); + writeFileSync(path.join(dir, ".husky", "pre-commit"), `# lint first\nnpm test\nsh .githooks/demo-checks/word-check.sh\n`); + const report = inspectRun(root, dir).report; + assert.equal(report.manager, "husky"); + assert.equal(report.variant, undefined); + const pre = stage(report, "pre-commit"); + assert.equal(pre.hookFile, ".husky/_/pre-commit"); + assert.deepEqual(pre.items.map((i) => [i.kind, i.name]), [["hook", "npm test"], ["entry", "demo-checks/word-check"]]); + assert.equal(pre.items[1].via, "husky"); + assert.match(pre.items[1].measured.input, /staged file/, "shared copy staged files to time it on"); + }); + + // Husky.Net (https://alirezanet.github.io/Husky.Net/guide/getting-started.html) sets + // core.hooksPath to .husky and keeps its tasks in .husky/task-runner.json. + function huskyNetRepo(hookLine) { + const dir = repo(); + mkdirSync(path.join(dir, ".husky", "_"), { recursive: true }); + writeFileSync(path.join(dir, ".husky", "_", "husky.sh"), "#!/bin/sh\n"); + const tasks = [ + { name: "format", group: "pre-commit", command: "dotnet", args: ["format", "--include", "${staged}"] }, + { name: "build", group: "pre-push", command: "dotnet", args: ["build"] }, + ]; + writeFileSync(path.join(dir, ".husky", "task-runner.json"), JSON.stringify({ tasks })); + writeFileSync(path.join(dir, ".husky", "pre-commit"), `#!/bin/sh\n. "$(dirname "$0")/_/husky.sh"\n${hookLine}\n`); + chmodSync(path.join(dir, ".husky", "pre-commit"), 0o755); + git(dir, ["config", "core.hooksPath", ".husky"]); + return dir; + } + + test("Husky.Net is detected as husky, variant husky.net, and plans as husky does", () => { + const root = plugin(); + const dir = huskyNetRepo("dotnet husky run --group pre-commit"); + const detected = run(root, dir, "detect").json(); + assert.equal(detected.manager, "husky"); + assert.equal(detected.variant, "husky.net"); + assert.ok(detected.evidence.some((e) => e.evidence === ".husky/task-runner.json")); + assert.deepEqual(kinds(run(root, dir, "plan", "--scope", "local").json()), ["husky-shared-only"]); + const config = run(root, dir, "plan", "--scope", "shared").json().decisions.find((d) => d.kind === "husky-config"); + assert.equal(config.file, ".husky/pre-commit"); + }); + + test("Husky.Net: `husky run --group` lists that group's tasks; with no group or name the line stays one item", () => { + const root = plugin(); + const grouped = inspectRun(root, huskyNetRepo("dotnet husky run --group pre-commit")).report; + const pre = stage(grouped, "pre-commit"); + assert.equal(pre.hookFile, ".husky/pre-commit"); + assert.deepEqual(pre.items, [ + { + kind: "task", + name: "format", + source: ".husky/task-runner.json", + command: "dotnet format --include ${staged}", + notMeasured: "a Husky.Net task: running it could change files, the index or a remote", + }, + ]); + const bare = stage(inspectRun(root, huskyNetRepo("dotnet husky run")).report, "pre-commit"); + assert.deepEqual(bare.items.map((i) => [i.kind, i.name]), [["hook", "dotnet husky run"]]); + }); + + test("lefthook: jobs come from lefthook dump, groups flattened; a job running the plugin's copy is its entry", () => { + const root = plugin(); + const dir = repo(); + writeFileSync(path.join(dir, "lefthook.yml"), "pre-commit:\n jobs: []\n"); + run(root, dir, "copy", "--scope", "shared"); + writeFileSync(path.join(dir, ".git", "hooks", "pre-commit"), "#!/bin/sh\nlefthook run pre-commit\n"); + chmodSync(path.join(dir, ".git", "hooks", "pre-commit"), 0o755); + const config = { + "pre-commit": { + jobs: [ + { name: "demo-checks-word-check", run: "sh .githooks/demo-checks/word-check.sh" }, + { name: "linters", group: { jobs: [{ name: "eslint", run: "npx eslint {staged_files}" }] } }, + ], + commands: { typecheck: { run: "tsc --noEmit" } }, + }, + }; + const report = inspectRun(root, dir, { lefthookDump: () => ({ config }) }).report; + assert.equal(report.manager, "lefthook"); + const pre = stage(report, "pre-commit"); + assert.deepEqual(pre.items.map((i) => [i.kind, i.name]), [["entry", "demo-checks/word-check"], ["job", "eslint"], ["job", "typecheck"]]); + assert.equal(pre.items[0].job, "demo-checks-word-check"); + assert.ok(pre.items[0].measured); + assert.equal(pre.items[1].notMeasured, "a lefthook job: running it could change files, the index or a remote"); + }); + + test("lefthook: without the lefthook binary the installed hook is one item naming why its jobs are not listed", () => { + const dir = repo(); + writeFileSync(path.join(dir, "lefthook.yml"), "pre-commit:\n jobs: []\n"); + writeFileSync(path.join(dir, ".git", "hooks", "pre-commit"), "#!/bin/sh\nlefthook run pre-commit\n"); + chmodSync(path.join(dir, ".git", "hooks", "pre-commit"), 0o755); + const report = inspectRun(plugin(), dir, { lefthookDump: () => ({ error: "lefthook not on PATH" }) }).report; + assert.deepEqual(stage(report, "pre-commit").items, [ + { kind: "hook", name: "lefthook", source: ".git/hooks/pre-commit", notMeasured: "lefthook not on PATH: its jobs are not listed" }, + ]); + }); + + test("a git config hook is listed, and named as not running before git 2.54", () => { + const dir = repo(); + git(dir, ["config", "hook.lint.event", "pre-commit"]); + git(dir, ["config", "hook.lint.command", "make lint"]); + const [major, minor] = /(\d+)\.(\d+)/.exec(git(dir, ["--version"]).stdout).slice(1).map(Number); + const modern = major > 2 || (major === 2 && minor >= 54); + const items = stage(inspectRun(plugin(), dir).report, "pre-commit").items; + assert.deepEqual(items, [ + { + kind: "config-hook", + name: "lint", + source: "git config", + command: "make lint", + notMeasured: modern ? "a git config hook: running it could change files, the index or a remote" : "git before 2.54 ignores config hooks, so it does not run here", + }, + ]); + }); + + test("a repository with no hooks has no stages", () => { + const report = inspectRun(plugin(), repo()).report; + assert.deepEqual(report.stages, []); + }); +}); diff --git a/plugins/actionlint/lib/git-hooks/install.mjs b/plugins/actionlint/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/actionlint/lib/git-hooks/install.mjs +++ b/plugins/actionlint/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/actionlint/skills/setup/SKILL.md b/plugins/actionlint/skills/setup/SKILL.md index b1839d915fc..585b92eb8d7 100644 --- a/plugins/actionlint/skills/setup/SKILL.md +++ b/plugins/actionlint/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify actionlint's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up actionlint', 'configure actionlint', 'is actionlint working', workflow lint silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-git-hooks [scope=local|shared]]. Re-runnable and safe." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -8,6 +8,8 @@ allowed-tools: - "Bash(command -v actionlint*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -94,6 +96,21 @@ entry): the entry runs at commit outside Claude Code and reads no toggle. `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` **Run this section only when the user typed `/actionlint:setup apply install-git-hooks` as a diff --git a/plugins/bash-format/lib/git-hooks/install.mjs b/plugins/bash-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/bash-format/lib/git-hooks/install.mjs +++ b/plugins/bash-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/bash-format/skills/setup/SKILL.md b/plugins/bash-format/skills/setup/SKILL.md index 2004be25851..0fa0a587a62 100644 --- a/plugins/bash-format/skills/setup/SKILL.md +++ b/plugins/bash-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify bash-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up bash-format', 'configure bash-format', 'is bash-format working', shell lint or formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only verification, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -10,6 +10,8 @@ allowed-tools: - "Bash(command -v shfmt*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -142,6 +144,21 @@ When every probe passes, report the result **with the scope caveats** (items 10 Never an unqualified "fully operational", which would imply out-of-project shell edits are covered when they are deliberately skipped. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/code-tidying/lib/git-hooks/install.mjs b/plugins/code-tidying/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/code-tidying/lib/git-hooks/install.mjs +++ b/plugins/code-tidying/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/code-tidying/skills/setup/SKILL.md b/plugins/code-tidying/skills/setup/SKILL.md index 5783882112a..79ad7c8eb73 100644 --- a/plugins/code-tidying/skills/setup/SKILL.md +++ b/plugins/code-tidying/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Checks or scaffolds this repository's code-tidying configuration: tracked project tidy lanes, the optional HARD-exclusion overrides file, and the comment-lint git pre-commit entry. Use when 'set up code-tidying' is asked, the tidy skill reports no project lanes, or a session-start line says the comment-lint git hook is missing or stale. Actions: check (read-only, default), apply (one named lane or all), apply install-git-hooks (scope local or shared)." -argument-hint: "[check|apply [|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true --- @@ -164,6 +164,21 @@ answer unambiguous; ask only where a lane's scope genuinely needs the user's cal Re-running `apply` after everything passes changes nothing and reports "already configured". +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entry (`git-hooks/entries.json`, `comment-lint` at `pre-commit`) diff --git a/plugins/go-format/lib/git-hooks/install.mjs b/plugins/go-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/go-format/lib/git-hooks/install.mjs +++ b/plugins/go-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/go-format/skills/setup/SKILL.md b/plugins/go-format/skills/setup/SKILL.md index 40d4aef1e78..e3f17883d92 100644 --- a/plugins/go-format/skills/setup/SKILL.md +++ b/plugins/go-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify go-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up go-format', 'configure go-format', 'is go-format working', Go import/formatting fixes silently aren't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -9,6 +9,8 @@ allowed-tools: - "Bash(command -v goimports*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -106,6 +108,21 @@ commit outside Claude Code and reads no toggle. There is no consumer-config probe (unlike `spelling`'s config-walk check). This hook has no consumer-config gate by design; report that plainly as INFO, not as a gap. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/guardrails/lib/git-hooks/install.mjs b/plugins/guardrails/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/guardrails/lib/git-hooks/install.mjs +++ b/plugins/guardrails/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/guardrails/skills/setup/SKILL.md b/plugins/guardrails/skills/setup/SKILL.md index ed5effef867..544892f0657 100644 --- a/plugins/guardrails/skills/setup/SKILL.md +++ b/plugins/guardrails/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify the guardrails hooks' runtime prerequisites, per-guard toggle state and git-hook entries for this machine, and register those entries. Use when: 'set up guardrails', 'configure guardrails', 'is guardrails working', 'which guards are on', a guard failed open with a jq notice, after tuning guard toggles, a hook reported a drifted git hook, or 'install the guardrails git hooks' / 'enforce the commit convention for every committer' / 'check secrets and hardcoded paths on every commit'. Actions: check (read-only verification, default) | apply (resolve what check found) | apply install-git-hooks [scope=local|shared|user] (register the commit-msg convention, pre-commit and pre-push content and reference-verify entries with the repository's hook manager; user: the commit-msg entry as a git config hook under an includeIf) | apply read-deny (opt-in: print Read() deny rules for .env, with user also ~/.ssh and ~/.aws, and add or remove them in the chosen settings file). Re-runnable and safe." -argument-hint: "[check|apply] [install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" +argument-hint: "[check [inspect]|apply] [install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -8,6 +8,8 @@ allowed-tools: - "Bash(command -v node*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/prerequisites.mjs\" check \"${CLAUDE_PLUGIN_ROOT}\" --for hook:run-guards.sh)" @@ -151,6 +153,21 @@ file. Re-running `apply` after everything passes changes nothing and reports "already configured". +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared|user]` (explicit argument only) Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/instruction-placement/lib/git-hooks/install.mjs b/plugins/instruction-placement/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/instruction-placement/lib/git-hooks/install.mjs +++ b/plugins/instruction-placement/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/instruction-placement/skills/setup/SKILL.md b/plugins/instruction-placement/skills/setup/SKILL.md index a9e457028bd..64f79a42ab4 100644 --- a/plugins/instruction-placement/skills/setup/SKILL.md +++ b/plugins/instruction-placement/skills/setup/SKILL.md @@ -1,11 +1,13 @@ --- description: "Verify instruction-placement's prerequisites, resolve its effective configuration for this repository, and register its rules-index git pre-commit entry. Confirm that the index target exists AND that nothing in the repository stops Claude Code loading it (a root CLAUDE.md is read instead of the AGENTS.md beside it, so an unimported AGENTS.md index is inert while every other gate reports green), that `git` backs tracked-file discovery, and that the Claude Code CLI plus `jq` are present for the optional empirical load probe. Reports the resolved index target, breadth ceiling, and index row cap, naming which came from configuration and which from a default. Use when: 'set up instruction-placement', 'configure instruction-placement', 'where will the index go', 'why is my index not loading', 'is instruction-placement working', or before a first audit on a new repository. Actions: check (read-only, default) | apply (point at each remediation) | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -110,6 +112,21 @@ one write path is `apply install-git-hooks`, which writes only files this plugin After an accepted change, re-run the reachability check and report the new verdict. An `apply` that does not re-verify has not finished. +## Action: check inspect (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## Action: apply install-git-hooks [scope=local|shared] Registers the plugin's git-hook entry (`git-hooks/entries.json`) with the repository's hook manager. diff --git a/plugins/javascript-format/lib/git-hooks/install.mjs b/plugins/javascript-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/javascript-format/lib/git-hooks/install.mjs +++ b/plugins/javascript-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/javascript-format/skills/setup/SKILL.md b/plugins/javascript-format/skills/setup/SKILL.md index c4a7ed6f7fa..78647883595 100644 --- a/plugins/javascript-format/skills/setup/SKILL.md +++ b/plugins/javascript-format/skills/setup/SKILL.md @@ -1,12 +1,14 @@ --- description: "Verify javascript-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up javascript-format', 'configure javascript-format', 'is javascript-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-biome] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-biome|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-biome|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(command -v jq*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -110,6 +112,21 @@ entry runs at commit outside Claude Code and reads no toggle. `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/markdown-format/lib/git-hooks/install.mjs b/plugins/markdown-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/markdown-format/lib/git-hooks/install.mjs +++ b/plugins/markdown-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/markdown-format/skills/setup/SKILL.md b/plugins/markdown-format/skills/setup/SKILL.md index b88de2f959f..f916a8030eb 100644 --- a/plugins/markdown-format/skills/setup/SKILL.md +++ b/plugins/markdown-format/skills/setup/SKILL.md @@ -1,12 +1,14 @@ --- description: "Verify markdown-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up markdown-format', 'configure markdown-format', 'is markdown-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-lint] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-lint|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-lint|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(command -v jq*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -134,6 +136,21 @@ Report the probes informationally and note that re-enabling restores the FAIL se `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/powershell-format/lib/git-hooks/install.mjs b/plugins/powershell-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/powershell-format/lib/git-hooks/install.mjs +++ b/plugins/powershell-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/powershell-format/skills/setup/SKILL.md b/plugins/powershell-format/skills/setup/SKILL.md index 2cf55f8bfcd..4426e3054c3 100644 --- a/plugins/powershell-format/skills/setup/SKILL.md +++ b/plugins/powershell-format/skills/setup/SKILL.md @@ -1,11 +1,13 @@ --- description: "Verify powershell-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up powershell-format', 'configure powershell-format', 'is powershell-format working', PowerShell formatting or linting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -97,6 +99,21 @@ restores the FAIL semantics. A missing `node` stays FAIL in either state: every `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/python-format/lib/git-hooks/install.mjs b/plugins/python-format/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/python-format/lib/git-hooks/install.mjs +++ b/plugins/python-format/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/python-format/skills/setup/SKILL.md b/plugins/python-format/skills/setup/SKILL.md index e5f0167fbd1..82d99a29972 100644 --- a/plugins/python-format/skills/setup/SKILL.md +++ b/plugins/python-format/skills/setup/SKILL.md @@ -1,12 +1,14 @@ --- description: "Verify python-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up python-format', 'configure python-format', 'is python-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-ruff] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-ruff|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-ruff|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(command -v jq*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -103,6 +105,21 @@ or `modified` entry): the entry runs at commit outside Claude Code and reads no `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook diff --git a/plugins/spelling/lib/git-hooks/install.mjs b/plugins/spelling/lib/git-hooks/install.mjs index abb112d48ac..451984dd704 100755 --- a/plugins/spelling/lib/git-hooks/install.mjs +++ b/plugins/spelling/lib/git-hooks/install.mjs @@ -3,10 +3,12 @@ // edit the canonical source, then rerun the script. // Register a plugin's git-hook entries with the repository's hook manager. // The contract is the check-placement convention: the entry manifest, the -// HookManager port (detect, list, plan, copy, decline) and verify's drift states. +// HookManager port (detect, list, plan, copy, decline), verify's drift states +// and the read-only inspect of what runs at each hook stage. // // install.mjs detect [common] // install.mjs list [common] +// install.mjs inspect [--runs <1-20>] [common] // install.mjs plan --scope local|shared|remote [--manager ] [common] // install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force] [common] // install.mjs decline --entry [--undo|--opt-in] [--global] [common] @@ -51,6 +53,7 @@ import { fstatSync, lstatSync, mkdirSync, + mkdtempSync, openSync, readdirSync, readFileSync, @@ -60,7 +63,7 @@ import { statSync, writeFileSync, } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; @@ -77,6 +80,7 @@ const SENTINEL = "# checks-dispatcher v1"; const SHARED_DIR = ".githooks"; const ATTRIBUTES_LINE = ".githooks/** text eol=lf"; const LIB_NAME = "check-lib.sh"; +const HUSKY_NET_TASKS = ".husky/task-runner.json"; const LEFTHOOK_NAMES = ["yml", "yaml", "toml", "json", "jsonc"].flatMap((ext) => [ `lefthook.${ext}`, @@ -414,6 +418,8 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); + // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,16 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } +// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; const managers = new Set(evidence.map((e) => e.manager)); const only = [...managers][0]; - if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence }; - return { manager: "conflict", evidence }; + const variant = evidence.some((e) => e.evidence === HUSKY_NET_TASKS) ? { variant: "husky.net" } : {}; + if (managers.size === 1 && MANAGERS.includes(only)) return { manager: only, evidence, ...variant }; + return { manager: "conflict", evidence, ...variant }; } // The directory a scope's copies live in, and the dispatcher directory for plain. @@ -1400,8 +1408,321 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// inspect: what git runs at each hook stage, under whichever manager the +// repository uses. Read-only: it writes nothing in the repository, and the only +// code it runs is this plugin's own installed entries that rewrite nothing, +// each timed from its installed copy. Every other hook is listed with the reason +// it was not run. Stage names are git's client-side hooks (githooks(5)). +const GIT_HOOKS = [ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "pre-merge-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-auto-gc", + "post-rewrite", + "sendemail-validate", + "fsmonitor-watchman", + "post-index-change", + "reference-transaction", +]; +const RUN_TIMEOUT_MS = 120_000; +const SCRIPT_TOKEN_RE = /[^\s"'`;|&()<>]+\.sh\b/g; +const MAY_CHANGE = "running it could change files, the index or a remote"; +const NOT_RUN = { + hook: `a repository hook: ${MAY_CHANGE}`, + chained: `a pre-existing hook the dispatcher runs first: ${MAY_CHANGE}`, + job: `a lefthook job: ${MAY_CHANGE}`, + task: `a Husky.Net task: ${MAY_CHANGE}`, + config: `a git config hook: ${MAY_CHANGE}`, +}; + +function executable(file) { + try { + const st = statSync(file); + return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0); + } catch { + return false; + } +} + +// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. +function stampOf(file) { + const text = readText(file); + const stamp = text === null ? null : readStamp(text); + return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; +} + +// The first script a command names that is a stamped entry copy. +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + if (found) return found; + } + return null; +} + +const median = (sorted) => { + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +// The input an entry is timed on: the staged set, a message file, or the +// branch against its upstream; skip names why there is nothing to time. +function timingInput(info, event) { + if (event === "pre-commit") { + const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; + if (!staged) return { skip: "nothing staged: stage the files to time it on, then rerun" }; + return { args: [], label: `${staged} staged file${staged === 1 ? "" : "s"}` }; + } + if (event === "commit-msg") { + const dir = mkdtempSync(path.join(tmpdir(), "git-hooks-inspect-")); + const file = path.join(dir, "COMMIT_EDITMSG"); + writeFileSync(file, "chore: time the commit-msg hook\n"); + return { args: [file], label: "a one-line message", cleanup: () => rmSync(dir, { recursive: true, force: true }) }; + } + if (event === "pre-push") { + const up = git(info.top, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + if (!up.ok || !up.out) return { skip: "no upstream: with no refs on stdin the entry checks nothing" }; + return { args: [], label: `no refs on stdin, so HEAD against ${up.out}` }; + } + return { skip: `${event} is not an event entries run on` }; +} + +// timing -> { measured } or { notMeasured }: only this plugin's own entry, +// one that rewrites nothing and whose tools are on PATH, is run. +function timing(info, plugin, event, found, opts) { + if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; + const entry = plugin.entries.find((e) => e.name === found.entry); + if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + const missing = entry.tools.filter((t) => !whichTool(t)); + if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; + const input = timingInput(info, event); + if (input.skip) return { notMeasured: input.skip }; + const runs = opts.runs ?? (event === "pre-push" ? 1 : 3); + const ms = []; + const exitCodes = []; + try { + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + const r = spawnSync("sh", [found.file, ...input.args], { + cwd: info.top, + input: "", + stdio: ["pipe", "ignore", "ignore"], + timeout: RUN_TIMEOUT_MS, + }); + if (r.error) { + const timedOut = r.error.code === "ETIMEDOUT"; + return { notMeasured: timedOut ? `timed out after ${RUN_TIMEOUT_MS / 1000} s` : `could not run: ${r.error.message}` }; + } + ms.push(Number(process.hrtime.bigint() - start) / 1e6); + exitCodes.push(r.status); + } + } finally { + input.cleanup?.(); + } + const sorted = ms.sort((a, b) => a - b); + const round = (n) => Math.round(n); + return { + measured: { medianMs: round(median(sorted)), minMs: round(sorted[0]), maxMs: round(sorted.at(-1)), runs, input: input.label, exitCodes }, + }; +} + +function entryItem(ctx, event, found, extra = {}) { + const { info, plugin, opts } = ctx; + return { + kind: "entry", + name: `${found.plugin}/${found.entry}`, + source: configPath(info, found.file), + plugin: found.plugin, + entry: found.entry, + ...extra, + ...timing(info, plugin, event, found, opts), + }; +} + +// The plain dispatcher runs .pre-checks, then each marker in .d/ +// and local/.d/, in glob order. +function dispatcherItems(ctx, event) { + const { info } = ctx; + const items = []; + const pre = path.join(info.hooksDir, `${event}.pre-checks`); + if (readText(pre) !== null) items.push({ kind: "chained", name: `${event}.pre-checks`, source: configPath(info, pre), notMeasured: NOT_RUN.chained }); + for (const base of [info.hooksDir, path.join(info.hooksDir, "local")]) { + const dir = path.join(base, `${event}.d`); + for (const { name, isDir } of dirNames(dir).sort((a, b) => (a.name < b.name ? -1 : 1))) { + if (isDir) continue; + const marker = path.join(dir, name); + const rel = lf(readText(marker) ?? "").split("\n")[0]; + const file = path.join(base, rel); + if (!rel || readText(file) === null) { + items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); + continue; + } + const found = stampOf(file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the +// config merged from the main and local files, extends and already-fetched +// remotes; it runs no job. +function lefthookDump(info) { + const r = spawnSync("lefthook", ["dump", "--format", "json"], { + cwd: info.top, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }); + if (r.error) return { error: r.error.code === "ENOENT" ? "lefthook not on PATH" : `lefthook dump failed: ${r.error.message}` }; + if (r.status !== 0) return { error: `lefthook dump exited ${r.status}` }; + try { + return { config: JSON.parse(r.stdout) }; + } catch { + return { error: "lefthook dump printed no JSON" }; + } +} + +// A lefthook hook's jobs (groups flattened), commands and scripts. +function lefthookJobs(hook) { + const out = []; + const walk = (jobs) => { + for (const job of Array.isArray(jobs) ? jobs : []) { + if (job?.group) walk(job.group.jobs); + else if (job && typeof job === "object") out.push({ name: job.name, run: job.run, script: job.script, runner: job.runner }); + } + }; + walk(hook?.jobs); + for (const [name, c] of Object.entries(hook?.commands ?? {})) out.push({ name, run: c?.run }); + for (const [script, s] of Object.entries(hook?.scripts ?? {})) out.push({ name: script, script, runner: s?.runner }); + return out; +} + +function lefthookItems(ctx, event, dump) { + const { info } = ctx; + if (dump.error) return [{ kind: "hook", name: "lefthook", source: configPath(info, path.join(info.hooksDir, event)), notMeasured: `${dump.error}: its jobs are not listed` }]; + const remotes = Array.isArray(dump.config?.remotes) && dump.config.remotes.length > 0; + return lefthookJobs(dump.config?.[event]).map((job) => { + const run = typeof job.run === "string" ? job.run : ""; + const command = (run || [job.runner, job.script].filter(Boolean).join(" ")).split("\n")[0]; + const name = String(job.name || command); + const base = { kind: "job", name, source: "lefthook config", command }; + let found = run ? entryInCommand(info, run) : null; + if (!found && typeof job.script === "string") { + const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); + const file = local.find((f) => readText(f) !== null); + if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; + found = stampOf(file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// Husky.Net's `husky run` with --group or --name runs those tasks from +// task-runner.json; null when the line names neither or the file will not parse. +function huskyNetTasks(info, line) { + const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; + const [group, name] = [flag("group"), flag("name")]; + if (!group && !name) return null; + let tasks; + try { + tasks = JSON.parse(readText(path.join(info.top, HUSKY_NET_TASKS)) ?? "").tasks; + } catch { + return null; + } + if (!Array.isArray(tasks)) return null; + return tasks + .filter((t) => (!group || t?.group === group) && (!name || t?.name === name)) + .map((t) => ({ + kind: "task", + name: String(t.name ?? ""), + source: HUSKY_NET_TASKS, + command: [t.command, ...(Array.isArray(t.args) ? t.args : [])].join(" "), + notMeasured: NOT_RUN.task, + })); +} + +// Each command line of .husky/; the line sourcing husky's own helper is skipped. +function huskyItems(ctx, event, variant) { + const { info } = ctx; + const source = `.husky/${event}`; + const text = readText(path.join(info.top, source)); + if (text === null) return []; + const lines = lf(text) + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#") && !/^\.\s.*_\/husky\.sh/.test(l)); + return lines.flatMap((line) => { + const found = entryInCommand(info, line); + if (found) return [entryItem(ctx, event, found, { via: "husky" })]; + const tasks = variant === "husky.net" && /\bhusky\s+run\b/.test(line) ? huskyNetTasks(info, line) : null; + if (tasks) return tasks; + return [{ kind: "hook", name: line, source, notMeasured: NOT_RUN.hook }]; + }); +} + +// git config hooks: hook..event lines, run from git 2.54. +function configHookItems(info) { + const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + return r.out + .split("\n") + .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) + .filter(([key, event]) => key && event) + .map(([key, event]) => { + const name = key.slice("hook.".length, -".event".length); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; + return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; + }); +} + +// inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } +// installed: git finds an executable hook file for the stage. opts.runs times +// each measured entry that many times (default 3; 1 for pre-push). +export function inspect(info, plugin, opts = {}) { + const found = detect(info); + const ctx = { info, plugin, opts }; + const hasLefthook = LEFTHOOK_NAMES.some((n) => existsSync(path.join(info.top, n))); + const dump = hasLefthook ? (opts.lefthookDump ?? lefthookDump)(info) : null; + const config = configHookItems(info); + const stages = []; + for (const event of GIT_HOOKS) { + const hookFile = path.join(info.hooksDir, event); + const text = readText(hookFile); + const items = []; + if (["ours", "prior"].includes(dispatcherState(hookFile))) items.push(...dispatcherItems(ctx, event)); + else if (dump && (text?.includes("lefthook") || (text === null && dump.config?.[event]))) items.push(...lefthookItems(ctx, event, dump)); + else if (found.evidence.some((e) => e.manager === "husky") && readText(path.join(info.top, ".husky", event)) !== null) { + items.push(...huskyItems(ctx, event, found.variant)); + } else if (text !== null) items.push({ kind: "hook", name: event, source: configPath(info, hookFile), notMeasured: NOT_RUN.hook }); + items.push(...config.filter((c) => c.event === event).map((c) => c.item)); + const installed = executable(hookFile); + if (items.length || installed) stages.push({ event, installed, hookFile: configPath(info, hookFile), items }); + } + return { + manager: found.manager, + ...(found.variant ? { variant: found.variant } : {}), + evidence: found.evidence, + hooksDir: configPath(info, info.hooksDir), + stages, + }; +} + const USAGE = [ "usage: install.mjs detect|list [--repo ] [--plugin-root ]", + " install.mjs inspect [--runs <1-20>]", " install.mjs plan --scope local|shared|remote [--manager lefthook|husky|plain]", " install.mjs copy --scope local|shared [--entry ]... [--manager ] [--force]", " install.mjs decline --entry [--undo|--opt-in] [--global]", @@ -1415,9 +1736,10 @@ const VALUE_FLAGS = { "--scope": "scope", "--manager": "manager", "--include-if": "includeIf", + "--runs": "runs", }; const BOOL_FLAGS = { "--force": "force", "--quiet": "quiet", "--undo": "undo", "--global": "global", "--opt-in": "optIn" }; -const ACTIONS = ["detect", "list", "plan", "copy", "decline", "verify", "config-hook"]; +const ACTIONS = ["detect", "list", "inspect", "plan", "copy", "decline", "verify", "config-hook"]; function parseArgs(argv, defaults) { const [action, ...rest] = argv; @@ -1437,6 +1759,10 @@ function parseArgs(argv, defaults) { throw new UsageError("copy needs --scope local or --scope shared; a remote install writes nothing, so apply plan's decisions"); } if (opts.manager && !MANAGERS.includes(opts.manager)) throw new UsageError(`unknown manager: ${opts.manager}`); + if (opts.runs !== undefined) { + if (action !== "inspect" || !/^([1-9]|1[0-9]|20)$/.test(opts.runs)) throw new UsageError("--runs takes 1 to 20, with inspect"); + opts.runs = Number(opts.runs); + } if (action === "decline" && opts.entries.length !== 1) throw new UsageError("decline needs one --entry"); if (action === "config-hook" && !INCLUDE_IF_RE.test(opts.includeIf ?? "")) { throw new UsageError("config-hook needs --include-if , such as gitdir:~/work/"); @@ -1491,6 +1817,9 @@ function dispatch(info, plugin, opts, io) { case "list": io.stdout(JSON.stringify(list(info, plugin))); return 0; + case "inspect": + io.stdout(JSON.stringify(inspect(info, plugin, { runs: opts.runs, lefthookDump: opts.lefthookDump }))); + return 0; case "plan": io.stdout(JSON.stringify(plan(info, plugin, opts.scope, opts.manager))); return 0; @@ -1515,6 +1844,7 @@ export function main(argv, ctx = {}, out = {}) { let opts; try { opts = parseArgs(argv, { repo: ctx.cwd ?? process.cwd(), pluginRoot: path.resolve(here, "..", "..") }); + opts.lefthookDump = ctx.lefthookDump; const info = repoInfo(opts.repo); if (!info) { if (opts.quiet) return 0; diff --git a/plugins/spelling/skills/setup/SKILL.md b/plugins/spelling/skills/setup/SKILL.md index 7cbf3957295..cf9862e5df8 100644 --- a/plugins/spelling/skills/setup/SKILL.md +++ b/plugins/spelling/skills/setup/SKILL.md @@ -1,12 +1,14 @@ --- description: "Verify spelling's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up spelling', 'configure spelling', 'is spelling working', spelling findings never show up, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: - "Bash(command -v typos*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" verify:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs verify:*)" + - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" inspect:*)" + - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs inspect:*)" - "Bash(node \"${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs\" plan:*)" - "Bash(node ${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs plan:*)" shell: bash @@ -100,6 +102,21 @@ without Claude Code. Node.js (step 5) is a FAIL either way too. `${CLAUDE_PLUGIN_ROOT}/prerequisites.json` (Read that path), so a lane or cloud setup script can provision it before an auto-mode session commits. Outside a git repository, report INFO and skip the step. +## `check inspect` (read-only) + +Lists what runs at each git hook stage in this repository, under whichever hook manager it uses, +and times this plugin's own entries. Run +`node "${CLAUDE_PLUGIN_ROOT}/lib/git-hooks/install.mjs" inspect` from the repository (add +`--runs ` to time each entry more often) and render its JSON as one table per stage: each item's +kind, name and source, then its `measured` median and range with the input it ran on and its exit +codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no +hook file git runs: say the manager's install step has not run in this clone. The script runs only +this plugin's installed entries that change no files; it never runs a repository's own hook, +another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the +numbers with the duration budgets in the check-placement contract +(`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). +Modify nothing. Outside a git repository, report INFO and stop. + ## `apply install-git-hooks [scope=local|shared]` Registers the plugin's git-hook entries (`git-hooks/entries.json`) with the repository's hook From c5f6eeefdf4b7901f9b68d7f72cafeb0faa4626a Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:58:05 -0500 Subject: [PATCH 2/7] refactor(git-hooks): keep only inspect comments that link an outside source Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- lib/git-hooks/install.mjs | 29 ++++--------------- lib/git-hooks/install.test.mjs | 1 - plugins/actionlint/lib/git-hooks/install.mjs | 29 ++++--------------- plugins/bash-format/lib/git-hooks/install.mjs | 29 ++++--------------- .../code-tidying/lib/git-hooks/install.mjs | 29 ++++--------------- plugins/go-format/lib/git-hooks/install.mjs | 29 ++++--------------- plugins/guardrails/lib/git-hooks/install.mjs | 29 ++++--------------- .../lib/git-hooks/install.mjs | 29 ++++--------------- .../lib/git-hooks/install.mjs | 29 ++++--------------- .../markdown-format/lib/git-hooks/install.mjs | 29 ++++--------------- .../lib/git-hooks/install.mjs | 29 ++++--------------- .../python-format/lib/git-hooks/install.mjs | 29 ++++--------------- plugins/spelling/lib/git-hooks/install.mjs | 29 ++++--------------- 13 files changed, 72 insertions(+), 277 deletions(-) diff --git a/lib/git-hooks/install.mjs b/lib/git-hooks/install.mjs index 40700aa8162..0badb6d2d8c 100755 --- a/lib/git-hooks/install.mjs +++ b/lib/git-hooks/install.mjs @@ -416,7 +416,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -426,7 +426,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1406,11 +1405,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1451,14 +1446,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1472,8 +1465,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1494,8 +1485,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1547,8 +1537,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1572,9 +1560,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1591,7 +1578,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1626,8 +1612,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1650,7 +1635,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1669,7 +1653,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/lib/git-hooks/install.test.mjs b/lib/git-hooks/install.test.mjs index 3f534fc6578..858a498fc4b 100644 --- a/lib/git-hooks/install.test.mjs +++ b/lib/git-hooks/install.test.mjs @@ -1767,7 +1767,6 @@ test("installed scripts are executable", { skip: !posixHost }, () => { }); describe("inspect", () => { - // inspect(root, dir, ctx, ...args) -> the parsed report and exit code. function inspectRun(root, dir, ctx = {}, ...args) { const out = []; const code = main(["inspect", ...args, "--repo", dir, "--plugin-root", root], ctx, { stdout: (s) => out.push(s), stderr: () => {} }); diff --git a/plugins/actionlint/lib/git-hooks/install.mjs b/plugins/actionlint/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/actionlint/lib/git-hooks/install.mjs +++ b/plugins/actionlint/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/bash-format/lib/git-hooks/install.mjs b/plugins/bash-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/bash-format/lib/git-hooks/install.mjs +++ b/plugins/bash-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/code-tidying/lib/git-hooks/install.mjs b/plugins/code-tidying/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/code-tidying/lib/git-hooks/install.mjs +++ b/plugins/code-tidying/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/go-format/lib/git-hooks/install.mjs b/plugins/go-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/go-format/lib/git-hooks/install.mjs +++ b/plugins/go-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/guardrails/lib/git-hooks/install.mjs b/plugins/guardrails/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/guardrails/lib/git-hooks/install.mjs +++ b/plugins/guardrails/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/instruction-placement/lib/git-hooks/install.mjs b/plugins/instruction-placement/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/instruction-placement/lib/git-hooks/install.mjs +++ b/plugins/instruction-placement/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/javascript-format/lib/git-hooks/install.mjs b/plugins/javascript-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/javascript-format/lib/git-hooks/install.mjs +++ b/plugins/javascript-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/markdown-format/lib/git-hooks/install.mjs b/plugins/markdown-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/markdown-format/lib/git-hooks/install.mjs +++ b/plugins/markdown-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/powershell-format/lib/git-hooks/install.mjs b/plugins/powershell-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/powershell-format/lib/git-hooks/install.mjs +++ b/plugins/powershell-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/python-format/lib/git-hooks/install.mjs b/plugins/python-format/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/python-format/lib/git-hooks/install.mjs +++ b/plugins/python-format/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; diff --git a/plugins/spelling/lib/git-hooks/install.mjs b/plugins/spelling/lib/git-hooks/install.mjs index 451984dd704..04c8fbca271 100755 --- a/plugins/spelling/lib/git-hooks/install.mjs +++ b/plugins/spelling/lib/git-hooks/install.mjs @@ -418,7 +418,7 @@ function managerEvidence(info) { if (config) found.push({ manager: "lefthook", evidence: config }); if (isHuskyPath(info.hooksPath)) found.push({ manager: "husky", evidence: `core.hooksPath=${info.hooksPath}` }); else if (existsSync(path.join(info.top, ".husky"))) found.push({ manager: "husky", evidence: ".husky/" }); - // Husky.Net keeps its tasks here and runs .husky/ as husky does, so the husky adapter drives it. + // Husky.Net runs .husky/ as husky does: https://alirezanet.github.io/Husky.Net/guide/getting-started.html if (existsSync(path.join(info.top, HUSKY_NET_TASKS))) found.push({ manager: "husky", evidence: HUSKY_NET_TASKS }); if (info.hooksPath === SHARED_DIR) found.push({ manager: "plain", evidence: `core.hooksPath=${SHARED_DIR}` }); else if (info.hooksPath && !isHuskyPath(info.hooksPath)) { @@ -428,7 +428,6 @@ function managerEvidence(info) { } // detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } -// variant "husky.net" when .husky/task-runner.json is present. export function detect(info) { const evidence = [...managerEvidence(info), ...foreignEvidence(info.top)]; if (evidence.length === 0) return { manager: "plain", evidence }; @@ -1408,11 +1407,7 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } -// inspect: what git runs at each hook stage, under whichever manager the -// repository uses. Read-only: it writes nothing in the repository, and the only -// code it runs is this plugin's own installed entries that rewrite nothing, -// each timed from its installed copy. Every other hook is listed with the reason -// it was not run. Stage names are git's client-side hooks (githooks(5)). +// https://git-scm.com/docs/githooks const GIT_HOOKS = [ "applypatch-msg", "pre-applypatch", @@ -1453,14 +1448,12 @@ function executable(file) { } } -// stampOf(file) -> { file, plugin, entry } for a stamped entry copy, else null. function stampOf(file) { const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; } -// The first script a command names that is a stamped entry copy. function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); @@ -1474,8 +1467,6 @@ const median = (sorted) => { return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }; -// The input an entry is timed on: the staged set, a message file, or the -// branch against its upstream; skip names why there is nothing to time. function timingInput(info, event) { if (event === "pre-commit") { const staged = git(info.top, ["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).out.split("\0").filter(Boolean).length; @@ -1496,8 +1487,7 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// timing -> { measured } or { notMeasured }: only this plugin's own entry, -// one that rewrites nothing and whose tools are on PATH, is run. +// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); @@ -1549,8 +1539,6 @@ function entryItem(ctx, event, found, extra = {}) { }; } -// The plain dispatcher runs .pre-checks, then each marker in .d/ -// and local/.d/, in glob order. function dispatcherItems(ctx, event) { const { info } = ctx; const items = []; @@ -1574,9 +1562,8 @@ function dispatcherItems(ctx, event) { return items; } -// lefthookDump(info) -> { config } or { error }. `lefthook dump` prints the -// config merged from the main and local files, extends and already-fetched -// remotes; it runs no job. +// Reads already-fetched remotes, fetches none and runs no job: +// https://github.com/evilmartians/lefthook/blob/v2.2.2/internal/config/loader.go function lefthookDump(info) { const r = spawnSync("lefthook", ["dump", "--format", "json"], { cwd: info.top, @@ -1593,7 +1580,6 @@ function lefthookDump(info) { } } -// A lefthook hook's jobs (groups flattened), commands and scripts. function lefthookJobs(hook) { const out = []; const walk = (jobs) => { @@ -1628,8 +1614,7 @@ function lefthookItems(ctx, event, dump) { }); } -// Husky.Net's `husky run` with --group or --name runs those tasks from -// task-runner.json; null when the line names neither or the file will not parse. +// https://alirezanet.github.io/Husky.Net/guide/task-runner.html function huskyNetTasks(info, line) { const flag = (f) => new RegExp(`--${f}(?:=|\\s+)("?)([^\\s"]+)\\1`).exec(line)?.[2]; const [group, name] = [flag("group"), flag("name")]; @@ -1652,7 +1637,6 @@ function huskyNetTasks(info, line) { })); } -// Each command line of .husky/; the line sourcing husky's own helper is skipped. function huskyItems(ctx, event, variant) { const { info } = ctx; const source = `.husky/${event}`; @@ -1671,7 +1655,6 @@ function huskyItems(ctx, event, variant) { }); } -// git config hooks: hook..event lines, run from git 2.54. function configHookItems(info) { const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; From 1a8828ff52b6c4bdd41fdc83faa315b951f375a5 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:00:37 -0500 Subject: [PATCH 3/7] docs(git-hooks): make a new Husky.Net event file executable Husky.Net points core.hooksPath at .husky, so git runs .husky/ directly and skips it unless it is executable. The husky-config decision now says so, and the adopting guide links Husky.Net's install steps for contributors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- .changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md | 1 + .changes/bash-format/feat-git-hooks-inspect-e17b94e7.md | 1 + .changes/code-tidying/feat-git-hooks-inspect-534a268d.md | 1 + .changes/go-format/feat-git-hooks-inspect-e28a44d8.md | 1 + .changes/guardrails/feat-git-hooks-inspect-e670076f.md | 1 + .../instruction-placement/feat-git-hooks-inspect-9a856722.md | 1 + .changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md | 1 + .changes/markdown-format/feat-git-hooks-inspect-46218c3e.md | 1 + .changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md | 1 + .changes/python-format/feat-git-hooks-inspect-a8b1b962.md | 1 + .changes/spelling/feat-git-hooks-inspect-f6f6d253.md | 1 + docs/contracts/check-placement/README.md | 3 ++- docs/contracts/check-placement/adopting-git-hooks.md | 2 +- lib/git-hooks/git-hook-decisions.md | 2 +- .../actionlint/skills/setup/reference/git-hook-decisions.md | 2 +- .../bash-format/skills/setup/reference/git-hook-decisions.md | 2 +- .../code-tidying/skills/setup/reference/git-hook-decisions.md | 2 +- plugins/go-format/skills/setup/reference/git-hook-decisions.md | 2 +- .../guardrails/skills/setup/reference/git-hook-decisions.md | 2 +- .../skills/setup/reference/git-hook-decisions.md | 2 +- .../skills/setup/reference/git-hook-decisions.md | 2 +- .../skills/setup/reference/git-hook-decisions.md | 2 +- .../skills/setup/reference/git-hook-decisions.md | 2 +- .../python-format/skills/setup/reference/git-hook-decisions.md | 2 +- plugins/spelling/skills/setup/reference/git-hook-decisions.md | 2 +- 25 files changed, 26 insertions(+), 14 deletions(-) diff --git a/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md +++ b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md +++ b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md +++ b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md +++ b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/guardrails/feat-git-hooks-inspect-e670076f.md b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/guardrails/feat-git-hooks-inspect-e670076f.md +++ b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md +++ b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md +++ b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md +++ b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md +++ b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md +++ b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md index c07adc998ff..77077a8eb89 100644 --- a/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md +++ b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md @@ -6,3 +6,4 @@ bump: minor - `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. +- Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/docs/contracts/check-placement/README.md b/docs/contracts/check-placement/README.md index af06c0f5e65..e87c19c5185 100644 --- a/docs/contracts/check-placement/README.md +++ b/docs/contracts/check-placement/README.md @@ -233,7 +233,8 @@ its adapter. `detect` also recognizes other hook managers (the pre-commit framew overcommit, husky v4) and returns them as conflict decisions. A set `core.hooksPath` is treated as husky or foreign, never as plain. A `.husky/task-runner.json` marks Husky.Net: `detect` returns `husky` with `variant: "husky.net"`, since Husky.Net runs `.husky/` as husky does and the -husky adapter drives it unchanged. +husky adapter drives it. One difference: Husky.Net points `core.hooksPath` at `.husky` itself, so +git runs `.husky/` directly and skips it unless it is executable. **`inspect`.** For each git hook stage, `inspect` lists every item that runs, under whichever manager the repository uses: plain dispatcher markers and a chained `.pre-checks`, each diff --git a/docs/contracts/check-placement/adopting-git-hooks.md b/docs/contracts/check-placement/adopting-git-hooks.md index f6d785b7574..9e53ec424e5 100644 --- a/docs/contracts/check-placement/adopting-git-hooks.md +++ b/docs/contracts/check-placement/adopting-git-hooks.md @@ -50,7 +50,7 @@ Committed config does not install itself: every clone runs the manager's install - lefthook: `lefthook install`. - husky: the project's package install, which runs husky's setup. - Husky.Net: `dotnet tool restore`, then `dotnet husky install` - ([getting started](https://alirezanet.github.io/Husky.Net/guide/getting-started.html#setup-husky-for-your-project)). + ([automate installation](https://alirezanet.github.io/Husky.Net/guide/automate.html#manual-attach)). - plain git hooks: `git config core.hooksPath .githooks`. A clone that skips this step gets no hooks, so for a team with authors outside Claude Code prefer diff --git a/lib/git-hooks/git-hook-decisions.md b/lib/git-hooks/git-hook-decisions.md index 8c59f174cbc..4db3c8ebf2f 100644 --- a/lib/git-hooks/git-hook-decisions.md +++ b/lib/git-hooks/git-hook-decisions.md @@ -6,7 +6,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/actionlint/skills/setup/reference/git-hook-decisions.md b/plugins/actionlint/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/actionlint/skills/setup/reference/git-hook-decisions.md +++ b/plugins/actionlint/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/bash-format/skills/setup/reference/git-hook-decisions.md b/plugins/bash-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/bash-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/bash-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/code-tidying/skills/setup/reference/git-hook-decisions.md b/plugins/code-tidying/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/code-tidying/skills/setup/reference/git-hook-decisions.md +++ b/plugins/code-tidying/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/go-format/skills/setup/reference/git-hook-decisions.md b/plugins/go-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/go-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/go-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/guardrails/skills/setup/reference/git-hook-decisions.md b/plugins/guardrails/skills/setup/reference/git-hook-decisions.md index e4b2899b09e..01a9b41db29 100644 --- a/plugins/guardrails/skills/setup/reference/git-hook-decisions.md +++ b/plugins/guardrails/skills/setup/reference/git-hook-decisions.md @@ -6,7 +6,7 @@ a file or a choice the user owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file` (a remote plan's snippet is one `remotes:` entry: add it to an existing `remotes:` list; with `foundRef`, the entry exists on that other ref, so set its `ref` to the snippet's), keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. The `reference-verify` and `pre-push-content` jobs are `pre-push`, and each snippet sets `use_stdin: true`: keep it. When the consumer's `lefthook version` is not 2.2.2, whatever `parallel` is set to, tell the user that `pre-push-content` may not receive the pushed refs. A job that receives none checks only the branch against its upstream, and nothing on a branch with no upstream, so a push it never checked can pass, a secret included. Pointer: lefthook's [`use_stdin`](https://lefthook.dev/configuration/use_stdin/#usestdin), whose note says only one job receives stdin. Probe: on lefthook 2.2.2 both pre-push jobs receive the refs, with `parallel` off and on (a manual run on 2026-11-11). `git-hooks/lefthook-remote.test.sh` checks that both jobs block from the refs on stdin under the pinned lefthook. Other versions are untested. As of: 2026-11-11. Recheck trigger: a lefthook version bump, or that test's second-job case failing. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file` (a remote plan's snippet is one `remotes:` entry: add it to an existing `remotes:` list; with `foundRef`, the entry exists on that other ref, so set its `ref` to the snippet's), keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. The `reference-verify` and `pre-push-content` jobs are `pre-push`, and each snippet sets `use_stdin: true`: keep it. When the consumer's `lefthook version` is not 2.2.2, whatever `parallel` is set to, tell the user that `pre-push-content` may not receive the pushed refs. A job that receives none checks only the branch against its upstream, and nothing on a branch with no upstream, so a push it never checked can pass, a secret included. Pointer: lefthook's [`use_stdin`](https://lefthook.dev/configuration/use_stdin/#usestdin), whose note says only one job receives stdin. Probe: on lefthook 2.2.2 both pre-push jobs receive the refs, with `parallel` off and on (a manual run on 2026-11-11). `git-hooks/lefthook-remote.test.sh` checks that both jobs block from the refs on stdin under the pinned lefthook. Other versions are untested. As of: 2026-11-11. Recheck trigger: a lefthook version bump, or that test's second-job case failing. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone; for a remote plan it also fetches the remote, so rerun it when it reported that it could not sync. | | `remote-source-dir` | The lefthook config sets `source_dir` (`sourceDir`) to a directory other than `.lefthook/`, the only place the guardrails remote holds its scripts, so the remote's jobs would not find them. Pointer: lefthook's [`remotes`](https://lefthook.dev/configuration/remotes/#remotes) on a remote's script `source_dir`. Tell the user and run `plan --scope shared` instead, unless they move their scripts to the default `.lefthook/`. | | `remote-needs-lefthook` | The repository uses husky or plain hooks, which have no remotes: run `plan --scope shared` instead. | diff --git a/plugins/instruction-placement/skills/setup/reference/git-hook-decisions.md b/plugins/instruction-placement/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/instruction-placement/skills/setup/reference/git-hook-decisions.md +++ b/plugins/instruction-placement/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/javascript-format/skills/setup/reference/git-hook-decisions.md b/plugins/javascript-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/javascript-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/javascript-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/markdown-format/skills/setup/reference/git-hook-decisions.md b/plugins/markdown-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/markdown-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/markdown-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/powershell-format/skills/setup/reference/git-hook-decisions.md b/plugins/powershell-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/powershell-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/powershell-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/python-format/skills/setup/reference/git-hook-decisions.md b/plugins/python-format/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/python-format/skills/setup/reference/git-hook-decisions.md +++ b/plugins/python-format/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | diff --git a/plugins/spelling/skills/setup/reference/git-hook-decisions.md b/plugins/spelling/skills/setup/reference/git-hook-decisions.md index d5a41b34f6d..e6ea2630f48 100644 --- a/plugins/spelling/skills/setup/reference/git-hook-decisions.md +++ b/plugins/spelling/skills/setup/reference/git-hook-decisions.md @@ -9,7 +9,7 @@ owns. | Kind | What you do | |---|---| -| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. | +| `lefthook-config`, `husky-config` | Merge `snippet` into `file`, keeping the user's own jobs, comments and order; create the file when absent. For a TOML or JSON lefthook config, write the same job in that format. When `detect` reports `variant: "husky.net"` and you create `.husky/`, start it with `#!/bin/sh`, make it executable and stage it at mode 100755: Husky.Net points `core.hooksPath` at `.husky`, so git runs the file directly and skips one that is not executable. | | `lefthook-install` | Run `lefthook install` so the manager's hooks exist in this clone. | | `husky-install` | Tell the user to run the project's install so husky's hooks exist in this clone. | | `husky-shared-only` | Say husky has no per-clone hooks and offer `scope=shared`. | From 395e9f27e4d9f71bd879b6a695dc6aa515566158 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:02:19 -0500 Subject: [PATCH 4/7] fix(git-hooks): keep check as the setup skills' leading argument-hint action The argument-hint contract requires setup skills to lead with "[check|apply]"; `check inspect` stays documented in each body's own section. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- plugins/actionlint/skills/setup/SKILL.md | 2 +- plugins/bash-format/skills/setup/SKILL.md | 2 +- plugins/code-tidying/skills/setup/SKILL.md | 2 +- plugins/go-format/skills/setup/SKILL.md | 2 +- plugins/guardrails/skills/setup/SKILL.md | 2 +- plugins/instruction-placement/skills/setup/SKILL.md | 2 +- plugins/javascript-format/skills/setup/SKILL.md | 2 +- plugins/markdown-format/skills/setup/SKILL.md | 2 +- plugins/powershell-format/skills/setup/SKILL.md | 2 +- plugins/python-format/skills/setup/SKILL.md | 2 +- plugins/spelling/skills/setup/SKILL.md | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/plugins/actionlint/skills/setup/SKILL.md b/plugins/actionlint/skills/setup/SKILL.md index 585b92eb8d7..4f3519c1d70 100644 --- a/plugins/actionlint/skills/setup/SKILL.md +++ b/plugins/actionlint/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify actionlint's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up actionlint', 'configure actionlint', 'is actionlint working', workflow lint silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-git-hooks [scope=local|shared]]. Re-runnable and safe." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/bash-format/skills/setup/SKILL.md b/plugins/bash-format/skills/setup/SKILL.md index 0fa0a587a62..fc30e0a94ef 100644 --- a/plugins/bash-format/skills/setup/SKILL.md +++ b/plugins/bash-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify bash-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up bash-format', 'configure bash-format', 'is bash-format working', shell lint or formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only verification, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/code-tidying/skills/setup/SKILL.md b/plugins/code-tidying/skills/setup/SKILL.md index 79ad7c8eb73..b17780b75df 100644 --- a/plugins/code-tidying/skills/setup/SKILL.md +++ b/plugins/code-tidying/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Checks or scaffolds this repository's code-tidying configuration: tracked project tidy lanes, the optional HARD-exclusion overrides file, and the comment-lint git pre-commit entry. Use when 'set up code-tidying' is asked, the tidy skill reports no project lanes, or a session-start line says the comment-lint git hook is missing or stale. Actions: check (read-only, default), apply (one named lane or all), apply install-git-hooks (scope local or shared)." -argument-hint: "[check [inspect]|apply [|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true --- diff --git a/plugins/go-format/skills/setup/SKILL.md b/plugins/go-format/skills/setup/SKILL.md index e3f17883d92..3282dbfabb4 100644 --- a/plugins/go-format/skills/setup/SKILL.md +++ b/plugins/go-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify go-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up go-format', 'configure go-format', 'is go-format working', Go import/formatting fixes silently aren't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/guardrails/skills/setup/SKILL.md b/plugins/guardrails/skills/setup/SKILL.md index 544892f0657..62504868cb5 100644 --- a/plugins/guardrails/skills/setup/SKILL.md +++ b/plugins/guardrails/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify the guardrails hooks' runtime prerequisites, per-guard toggle state and git-hook entries for this machine, and register those entries. Use when: 'set up guardrails', 'configure guardrails', 'is guardrails working', 'which guards are on', a guard failed open with a jq notice, after tuning guard toggles, a hook reported a drifted git hook, or 'install the guardrails git hooks' / 'enforce the commit convention for every committer' / 'check secrets and hardcoded paths on every commit'. Actions: check (read-only verification, default) | apply (resolve what check found) | apply install-git-hooks [scope=local|shared|user] (register the commit-msg convention, pre-commit and pre-push content and reference-verify entries with the repository's hook manager; user: the commit-msg entry as a git config hook under an includeIf) | apply read-deny (opt-in: print Read() deny rules for .env, with user also ~/.ssh and ~/.aws, and add or remove them in the chosen settings file). Re-runnable and safe." -argument-hint: "[check [inspect]|apply] [install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" +argument-hint: "[check|apply] [install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/instruction-placement/skills/setup/SKILL.md b/plugins/instruction-placement/skills/setup/SKILL.md index 64f79a42ab4..e4b97f45ebc 100644 --- a/plugins/instruction-placement/skills/setup/SKILL.md +++ b/plugins/instruction-placement/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify instruction-placement's prerequisites, resolve its effective configuration for this repository, and register its rules-index git pre-commit entry. Confirm that the index target exists AND that nothing in the repository stops Claude Code loading it (a root CLAUDE.md is read instead of the AGENTS.md beside it, so an unimported AGENTS.md index is inert while every other gate reports green), that `git` backs tracked-file discovery, and that the Claude Code CLI plus `jq` are present for the optional empirical load probe. Reports the resolved index target, breadth ceiling, and index row cap, naming which came from configuration and which from a default. Use when: 'set up instruction-placement', 'configure instruction-placement', 'where will the index go', 'why is my index not loading', 'is instruction-placement working', or before a first audit on a new repository. Actions: check (read-only, default) | apply (point at each remediation) | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/javascript-format/skills/setup/SKILL.md b/plugins/javascript-format/skills/setup/SKILL.md index 78647883595..f55cca66634 100644 --- a/plugins/javascript-format/skills/setup/SKILL.md +++ b/plugins/javascript-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify javascript-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up javascript-format', 'configure javascript-format', 'is javascript-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-biome] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-biome|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-biome|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/markdown-format/skills/setup/SKILL.md b/plugins/markdown-format/skills/setup/SKILL.md index f916a8030eb..11cf79b7b54 100644 --- a/plugins/markdown-format/skills/setup/SKILL.md +++ b/plugins/markdown-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify markdown-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up markdown-format', 'configure markdown-format', 'is markdown-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-lint] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-lint|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-lint|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/powershell-format/skills/setup/SKILL.md b/plugins/powershell-format/skills/setup/SKILL.md index 4426e3054c3..7916600ff2b 100644 --- a/plugins/powershell-format/skills/setup/SKILL.md +++ b/plugins/powershell-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify powershell-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up powershell-format', 'configure powershell-format', 'is powershell-format working', PowerShell formatting or linting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/python-format/skills/setup/SKILL.md b/plugins/python-format/skills/setup/SKILL.md index 82d99a29972..aa3f1d71311 100644 --- a/plugins/python-format/skills/setup/SKILL.md +++ b/plugins/python-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify python-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up python-format', 'configure python-format', 'is python-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-ruff] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-ruff|install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-ruff|install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: diff --git a/plugins/spelling/skills/setup/SKILL.md b/plugins/spelling/skills/setup/SKILL.md index cf9862e5df8..ae17994fdc6 100644 --- a/plugins/spelling/skills/setup/SKILL.md +++ b/plugins/spelling/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- description: "Verify spelling's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up spelling', 'configure spelling', 'is spelling working', spelling findings never show up, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check [inspect]|apply [install-git-hooks [scope=local|shared]]]" +argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" user-invocable: true disable-model-invocation: true allowed-tools: From 5144b382c57eace1369c8bfd077e2a7fe8e59401 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:09:39 -0500 Subject: [PATCH 5/7] fix(git-hooks): do not time an older non-sh entry copy under sh The plain dispatcher runs an installed copy whose first line is not #!/bin/sh by its own shebang, so timing it under sh measured a shell failure, not the check. inspect now reports such a copy as not measured, naming the refresh that makes it timeable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- docs/contracts/check-placement/README.md | 3 ++- lib/git-hooks/install.mjs | 3 +++ lib/git-hooks/install.test.mjs | 18 ++++++++++++++++++ plugins/actionlint/lib/git-hooks/install.mjs | 3 +++ plugins/bash-format/lib/git-hooks/install.mjs | 3 +++ plugins/code-tidying/lib/git-hooks/install.mjs | 3 +++ plugins/go-format/lib/git-hooks/install.mjs | 3 +++ plugins/guardrails/lib/git-hooks/install.mjs | 3 +++ .../lib/git-hooks/install.mjs | 3 +++ .../lib/git-hooks/install.mjs | 3 +++ .../markdown-format/lib/git-hooks/install.mjs | 3 +++ .../lib/git-hooks/install.mjs | 3 +++ .../python-format/lib/git-hooks/install.mjs | 3 +++ plugins/spelling/lib/git-hooks/install.mjs | 3 +++ 14 files changed, 56 insertions(+), 1 deletion(-) diff --git a/docs/contracts/check-placement/README.md b/docs/contracts/check-placement/README.md index e87c19c5185..0b18194f7af 100644 --- a/docs/contracts/check-placement/README.md +++ b/docs/contracts/check-placement/README.md @@ -242,7 +242,8 @@ command line of `.husky/` (and the Husky.Net tasks a `husky run --group` selects), the lefthook jobs `lefthook dump` reports, git config hooks, and any other hook file. `installed` says whether git finds an executable hook file for the stage. An item that is a stamped entry copy names its plugin and entry. Only the calling plugin's own entries that rewrite nothing -and whose tools are present are run, from their installed copies, on the staged set (`pre-commit`), +and whose tools are present are run, from installed copies that start `#!/bin/sh` (an older copy +the dispatcher runs by its own first line is reported not measured), on the staged set (`pre-commit`), a message file outside the repository (`commit-msg`) or the branch against its upstream (`pre-push`), and get `measured: { medianMs, minMs, maxMs, runs, input, exitCodes }`; every other item gets `notMeasured` with the reason. `inspect` itself writes nothing in the repository; a diff --git a/lib/git-hooks/install.mjs b/lib/git-hooks/install.mjs index 0badb6d2d8c..44522234d7a 100755 --- a/lib/git-hooks/install.mjs +++ b/lib/git-hooks/install.mjs @@ -1491,6 +1491,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/lib/git-hooks/install.test.mjs b/lib/git-hooks/install.test.mjs index 858a498fc4b..398f3076388 100644 --- a/lib/git-hooks/install.test.mjs +++ b/lib/git-hooks/install.test.mjs @@ -1822,6 +1822,24 @@ describe("inspect", () => { assert.equal(item(absent), "tool missing: no-such-tool-for-inspect"); }); + test("plain: an older stamped copy with a bash shebang, which the dispatcher runs by its first line, is not timed under sh", () => { + const root = plugin(); + const dir = repo(); + run(root, dir, "copy", "--scope", "local"); + const copy = path.join(dir, ".git", "hooks", "demo-checks", "word-check.sh"); + const lines = readFileSync(copy, "utf8").split("\n"); + writeFileSync(copy, ["#!/usr/bin/env bash", ...lines.slice(1)].join("\n")); + assert.ok(readStamp(readFileSync(copy, "utf8")), "the copy still carries its stamp"); + stageBad(dir); + const item = stage(inspectRun(root, dir).report, "pre-commit").items[0]; + assert.equal(item.name, "demo-checks/word-check"); + assert.equal(item.measured, undefined); + assert.equal( + item.notMeasured, + "an older installed copy that runs by its own first line: refresh it with /demo-checks:setup apply install-git-hooks, then time it", + ); + }); + test("plain: a commit-msg entry is timed on a message file outside the repository; a pre-push one needs an upstream", () => { const entries = [ { name: "msg-check", event: "commit-msg", script: "msg-check.sh", tools: ["grep"], rewrites: false }, diff --git a/plugins/actionlint/lib/git-hooks/install.mjs b/plugins/actionlint/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/actionlint/lib/git-hooks/install.mjs +++ b/plugins/actionlint/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/bash-format/lib/git-hooks/install.mjs b/plugins/bash-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/bash-format/lib/git-hooks/install.mjs +++ b/plugins/bash-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/code-tidying/lib/git-hooks/install.mjs b/plugins/code-tidying/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/code-tidying/lib/git-hooks/install.mjs +++ b/plugins/code-tidying/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/go-format/lib/git-hooks/install.mjs b/plugins/go-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/go-format/lib/git-hooks/install.mjs +++ b/plugins/go-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/guardrails/lib/git-hooks/install.mjs b/plugins/guardrails/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/guardrails/lib/git-hooks/install.mjs +++ b/plugins/guardrails/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/instruction-placement/lib/git-hooks/install.mjs b/plugins/instruction-placement/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/instruction-placement/lib/git-hooks/install.mjs +++ b/plugins/instruction-placement/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/javascript-format/lib/git-hooks/install.mjs b/plugins/javascript-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/javascript-format/lib/git-hooks/install.mjs +++ b/plugins/javascript-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/markdown-format/lib/git-hooks/install.mjs b/plugins/markdown-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/markdown-format/lib/git-hooks/install.mjs +++ b/plugins/markdown-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/powershell-format/lib/git-hooks/install.mjs b/plugins/powershell-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/powershell-format/lib/git-hooks/install.mjs +++ b/plugins/powershell-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/python-format/lib/git-hooks/install.mjs b/plugins/python-format/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/python-format/lib/git-hooks/install.mjs +++ b/plugins/python-format/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); diff --git a/plugins/spelling/lib/git-hooks/install.mjs b/plugins/spelling/lib/git-hooks/install.mjs index 04c8fbca271..f6669963024 100755 --- a/plugins/spelling/lib/git-hooks/install.mjs +++ b/plugins/spelling/lib/git-hooks/install.mjs @@ -1493,6 +1493,9 @@ function timing(info, plugin, event, found, opts) { const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; if (entry.rewrites) return { notMeasured: "rewrites staged files" }; + if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { + return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + } const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); From 29f7c52a3dc1ae2fdbb0f82d57b06b34627d951c Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:19:18 -0500 Subject: [PATCH 6/7] docs(git-hooks): drop the Husky.Net docs link from the adopting guide Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MWmASPFjTu4anSp6BowqVC --- docs/contracts/check-placement/adopting-git-hooks.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/contracts/check-placement/adopting-git-hooks.md b/docs/contracts/check-placement/adopting-git-hooks.md index 9e53ec424e5..c6d7c0ea3c5 100644 --- a/docs/contracts/check-placement/adopting-git-hooks.md +++ b/docs/contracts/check-placement/adopting-git-hooks.md @@ -49,8 +49,7 @@ Committed config does not install itself: every clone runs the manager's install - lefthook: `lefthook install`. - husky: the project's package install, which runs husky's setup. -- Husky.Net: `dotnet tool restore`, then `dotnet husky install` - ([automate installation](https://alirezanet.github.io/Husky.Net/guide/automate.html#manual-attach)). +- Husky.Net: `dotnet tool restore`, then `dotnet husky install`. - plain git hooks: `git config core.hooksPath .githooks`. A clone that skips this step gets no hooks, so for a team with authors outside Claude Code prefer From 210a14f828aed2f2d4c3b5d7fa353ab6918a39ee Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:43:44 -0500 Subject: [PATCH 7/7] fix(git-hooks): run only shipped copies in inspect and route check inspect inspect timed any file whose second line parsed as this plugin's stamp, so a repository's .husky or lefthook line naming a forged script ran it. It now times a copy only when its script, lib and assets hash to what the plugin ships now (copyState is ok) and the entry's own event matches the stage; an edited or forged copy is reported not run, an older one gets a refresh hint. A script path from a husky or lefthook command, a dispatcher marker or a lefthook script is followed only inside the work tree or the hooks directory, which holds a linked worktree's local copies. Config hooks honor an empty hook..event value's reset and report hook..enabled=false as disabled. Each setup skill that carries the inspect section routes `check inspect` to it: the routing sentence, the description's action list and an argument-hint of `[check|apply] [inspect|...]`, the setup shape the argument-hint contract and validator accept. Co-Authored-By: Claude Opus 5.5 --- .../feat-git-hooks-inspect-9e83d8f9.md | 2 +- .../feat-git-hooks-inspect-e17b94e7.md | 2 +- .../feat-git-hooks-inspect-534a268d.md | 2 +- .../feat-git-hooks-inspect-e28a44d8.md | 2 +- .../feat-git-hooks-inspect-e670076f.md | 2 +- .../feat-git-hooks-inspect-9a856722.md | 2 +- .../feat-git-hooks-inspect-d8c496e6.md | 2 +- .../feat-git-hooks-inspect-46218c3e.md | 2 +- .../feat-git-hooks-inspect-7c0c691f.md | 2 +- .../feat-git-hooks-inspect-a8b1b962.md | 2 +- .../feat-git-hooks-inspect-f6f6d253.md | 2 +- docs/contracts/check-placement/README.md | 13 ++- lib/git-hooks/install.mjs | 49 +++++---- lib/git-hooks/install.test.mjs | 100 ++++++++++++++++-- plugins/actionlint/lib/git-hooks/install.mjs | 49 +++++---- plugins/actionlint/skills/setup/SKILL.md | 9 +- plugins/bash-format/lib/git-hooks/install.mjs | 49 +++++---- plugins/bash-format/skills/setup/SKILL.md | 9 +- .../code-tidying/lib/git-hooks/install.mjs | 49 +++++---- plugins/code-tidying/skills/setup/SKILL.md | 8 +- plugins/go-format/lib/git-hooks/install.mjs | 49 +++++---- plugins/go-format/skills/setup/SKILL.md | 9 +- plugins/guardrails/lib/git-hooks/install.mjs | 49 +++++---- plugins/guardrails/skills/setup/SKILL.md | 9 +- .../lib/git-hooks/install.mjs | 49 +++++---- .../skills/setup/SKILL.md | 9 +- .../lib/git-hooks/install.mjs | 49 +++++---- .../javascript-format/skills/setup/SKILL.md | 9 +- .../markdown-format/lib/git-hooks/install.mjs | 49 +++++---- plugins/markdown-format/skills/setup/SKILL.md | 9 +- .../lib/git-hooks/install.mjs | 49 +++++---- .../powershell-format/skills/setup/SKILL.md | 9 +- .../python-format/lib/git-hooks/install.mjs | 49 +++++---- plugins/python-format/skills/setup/SKILL.md | 9 +- plugins/spelling/lib/git-hooks/install.mjs | 49 +++++---- plugins/spelling/skills/setup/SKILL.md | 9 +- 36 files changed, 525 insertions(+), 296 deletions(-) diff --git a/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md +++ b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md +++ b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md +++ b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md +++ b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/guardrails/feat-git-hooks-inspect-e670076f.md b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/guardrails/feat-git-hooks-inspect-e670076f.md +++ b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md +++ b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md +++ b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md +++ b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md +++ b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md +++ b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md index 77077a8eb89..38b1ec0ea40 100644 --- a/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md +++ b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md @@ -4,6 +4,6 @@ bump: minor ### Added -- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from their installed copies, on the staged set, a message file or the branch against its upstream. Every other hook is listed as not run, with the reason. The installer's new `inspect` action is read-only. +- `setup check inspect` lists what runs at each git hook stage in the repository, under whichever hook manager it uses (plain hooks, husky, Husky.Net, lefthook, git config hooks, or a hook no manager owns), and times this plugin's own entries that change no files, from installed copies that still match what the plugin ships, on the staged set, a message file or the branch against its upstream. Every other hook, an edited, forged or older copy, and a git config hook the repository disables is listed as not run, with the reason; a script path outside the work tree and the hooks directory is never followed. The installer's new `inspect` action is read-only. - The git-hook installer detects Husky.Net (`.husky/task-runner.json`) as husky with `variant: "husky.net"`, so it installs as husky does, and `inspect` lists the Husky.Net tasks a `husky run --group` or `--name` line selects. - Setup's `husky-config` decision says how to create a new `.husky/` under Husky.Net: with `#!/bin/sh`, executable and staged at mode 100755, since git runs that file directly there and skips one that is not executable. diff --git a/docs/contracts/check-placement/README.md b/docs/contracts/check-placement/README.md index 0b18194f7af..8cf24a0e270 100644 --- a/docs/contracts/check-placement/README.md +++ b/docs/contracts/check-placement/README.md @@ -239,11 +239,14 @@ git runs `.husky/` directly and skips it unless it is executable. **`inspect`.** For each git hook stage, `inspect` lists every item that runs, under whichever manager the repository uses: plain dispatcher markers and a chained `.pre-checks`, each command line of `.husky/` (and the Husky.Net tasks a `husky run --group` or `--name` line -selects), the lefthook jobs `lefthook dump` reports, git config hooks, and any other hook file. -`installed` says whether git finds an executable hook file for the stage. An item that is a stamped -entry copy names its plugin and entry. Only the calling plugin's own entries that rewrite nothing -and whose tools are present are run, from installed copies that start `#!/bin/sh` (an older copy -the dispatcher runs by its own first line is reported not measured), on the staged set (`pre-commit`), +selects), the lefthook jobs `lefthook dump` reports, git config hooks (the events left after an +empty-value reset; one with `hook..enabled=false` is reported disabled), and any other hook +file. `installed` says whether git finds an executable hook file for the stage. An item that is a +stamped entry copy names its plugin and entry; a script path from a command, marker or lefthook +job is followed only inside the work tree or the hooks directory. Only the calling plugin's own entries, on their own event, that +rewrite nothing and whose tools are present are run, and only from an installed copy whose script, +lib and assets hash to what the plugin ships now: a stamp alone proves nothing, so an edited or +forged copy is never run and an older one gets a refresh hint. They run on the staged set (`pre-commit`), a message file outside the repository (`commit-msg`) or the branch against its upstream (`pre-push`), and get `measured: { medianMs, minMs, maxMs, runs, input, exitCodes }`; every other item gets `notMeasured` with the reason. `inspect` itself writes nothing in the repository; a diff --git a/lib/git-hooks/install.mjs b/lib/git-hooks/install.mjs index 44522234d7a..618a1525dd5 100755 --- a/lib/git-hooks/install.mjs +++ b/lib/git-hooks/install.mjs @@ -1446,7 +1446,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1454,7 +1460,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1485,15 +1491,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1556,7 +1564,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1609,7 +1617,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1657,19 +1665,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/lib/git-hooks/install.test.mjs b/lib/git-hooks/install.test.mjs index 398f3076388..040514ee69d 100644 --- a/lib/git-hooks/install.test.mjs +++ b/lib/git-hooks/install.test.mjs @@ -1822,21 +1822,69 @@ describe("inspect", () => { assert.equal(item(absent), "tool missing: no-such-tool-for-inspect"); }); - test("plain: an older stamped copy with a bash shebang, which the dispatcher runs by its first line, is not timed under sh", () => { + test("plain: an older installed copy is not timed, and gets a refresh hint", () => { const root = plugin(); const dir = repo(); run(root, dir, "copy", "--scope", "local"); - const copy = path.join(dir, ".git", "hooks", "demo-checks", "word-check.sh"); - const lines = readFileSync(copy, "utf8").split("\n"); - writeFileSync(copy, ["#!/usr/bin/env bash", ...lines.slice(1)].join("\n")); - assert.ok(readStamp(readFileSync(copy, "utf8")), "the copy still carries its stamp"); + writeFileSync(path.join(root, "git-hooks", "word-check.sh"), `${WORD_CHECK}# a newer release\n`); stageBad(dir); const item = stage(inspectRun(root, dir).report, "pre-commit").items[0]; assert.equal(item.name, "demo-checks/word-check"); assert.equal(item.measured, undefined); - assert.equal( - item.notMeasured, - "an older installed copy that runs by its own first line: refresh it with /demo-checks:setup apply install-git-hooks, then time it", + assert.equal(item.notMeasured, "an older installed copy: refresh it with /demo-checks:setup apply install-git-hooks, then time it"); + }); + + test("an edited copy, or a repository file with a forged stamp, is never run", () => { + const root = plugin(); + const dir = repo(); + mkdirSync(path.join(dir, ".husky", "_"), { recursive: true }); + git(dir, ["config", "core.hooksPath", ".husky/_"]); + run(root, dir, "copy", "--scope", "shared"); + const copy = path.join(dir, ".githooks", "demo-checks", "word-check.sh"); + writeFileSync(copy, `${readFileSync(copy, "utf8")}touch "${RAN}"\n`); + mkdirSync(path.join(dir, "scripts")); + const zeros = `#!/bin/sh\n# demo-checks word-check sha256:${"0".repeat(64)}\ntouch "${RAN}"\n`; + writeFileSync(path.join(dir, "scripts", "zeros.sh"), zeros); + const lib = readFileSync(path.join(root, "lib", "git-hooks", "check-lib.sh"), "utf8"); + const body = `#!/bin/sh\ntouch "${RAN}"\n`; + writeFileSync(path.join(dir, "scripts", "check-lib.sh"), lib); + writeFileSync(path.join(dir, "scripts", "self.sh"), `#!/bin/sh\n# demo-checks word-check sha256:${stampHash(body, lib)}\ntouch "${RAN}"\n`); + const lines = ["sh .githooks/demo-checks/word-check.sh", "sh scripts/zeros.sh", "sh scripts/self.sh"]; + writeFileSync(path.join(dir, ".husky", "pre-commit"), `${lines.join("\n")}\n`); + stageBad(dir); + const items = stage(inspectRun(root, dir).report, "pre-commit").items; + assert.equal(existsSync(path.join(dir, RAN)), false, "no forged or edited script ran"); + assert.deepEqual( + items.map((i) => [i.name, i.measured, i.notMeasured]), + [ + ["demo-checks/word-check", undefined, "not what demo-checks ships (edited, or not its copy), so not run"], + ["demo-checks/word-check", undefined, "not what demo-checks ships (edited, or not its copy), so not run"], + ["demo-checks/word-check", undefined, "an older installed copy: refresh it with /demo-checks:setup apply install-git-hooks, then time it"], + ], + ); + }); + + test("husky: an entry on another event, or a script path outside the work tree, is not run", () => { + const root = plugin(); + const dir = repo(); + mkdirSync(path.join(dir, ".husky", "_"), { recursive: true }); + git(dir, ["config", "core.hooksPath", ".husky/_"]); + run(root, dir, "copy", "--scope", "shared"); + writeFileSync(path.join(dir, ".husky", "commit-msg"), "sh .githooks/demo-checks/word-check.sh\n"); + const outside = path.join(work, `outside${++counter}`); + mkdirSync(outside); + cpSync(path.join(dir, ".githooks", "demo-checks"), outside, { recursive: true }); + const rel = path.relative(dir, path.join(outside, "word-check.sh")); + writeFileSync(path.join(dir, ".husky", "pre-commit"), `sh ${path.join(outside, "word-check.sh")}\nsh ${rel}\n`); + stageBad(dir); + const report = inspectRun(root, dir).report; + assert.deepEqual(stage(report, "commit-msg").items.map((i) => i.notMeasured), ["word-check is a pre-commit entry, not commit-msg"]); + assert.deepEqual( + stage(report, "pre-commit").items.map((i) => [i.kind, i.notMeasured]), + [ + ["hook", "a repository hook: running it could change files, the index or a remote"], + ["hook", "a repository hook: running it could change files, the index or a remote"], + ], ); }); @@ -1975,6 +2023,22 @@ describe("inspect", () => { assert.equal(pre.items[1].notMeasured, "a lefthook job: running it could change files, the index or a remote"); }); + test("lefthook in a linked worktree: a local job naming the copy in the common hooks dir by absolute path is timed", () => { + const root = plugin(); + const dir = repo(); + const linked = path.join(work, `linked${++counter}`); + git(dir, ["worktree", "add", "-q", "-b", "side", linked]); + run(root, linked, "copy", "--scope", "local"); + const copy = path.join(dir, ".git", "hooks", "demo-checks", "word-check.sh"); + writeFileSync(path.join(dir, ".git", "hooks", "pre-commit"), "#!/bin/sh\nlefthook run pre-commit\n"); + writeFileSync(path.join(linked, "lefthook.yml"), "pre-commit:\n jobs: []\n"); + stageBad(linked); + const config = { "pre-commit": { jobs: [{ name: "demo-checks-word-check", run: `sh "${copy}"` }] } }; + const item = stage(inspectRun(root, linked, { lefthookDump: () => ({ config }) }).report, "pre-commit").items[0]; + assert.equal(item.name, "demo-checks/word-check"); + assert.deepEqual(item.measured.exitCodes, [1, 1, 1]); + }); + test("lefthook: without the lefthook binary the installed hook is one item naming why its jobs are not listed", () => { const dir = repo(); writeFileSync(path.join(dir, "lefthook.yml"), "pre-commit:\n jobs: []\n"); @@ -2004,6 +2068,26 @@ describe("inspect", () => { ]); }); + test("a config hook's events honor an empty-value reset, and a disabled one is named so", () => { + const dir = repo(); + git(dir, ["config", "--add", "hook.lint.event", "pre-push"]); + git(dir, ["config", "--add", "hook.lint.event", ""]); + git(dir, ["config", "--add", "hook.lint.event", "pre-commit"]); + git(dir, ["config", "hook.lint.command", "make lint"]); + git(dir, ["config", "hook.off.event", "pre-commit"]); + git(dir, ["config", "hook.off.command", "make off"]); + git(dir, ["config", "hook.off.enabled", "false"]); + const report = inspectRun(plugin(), dir).report; + assert.equal(stage(report, "pre-push"), undefined, "the empty value cleared pre-push"); + assert.deepEqual( + stage(report, "pre-commit").items.map((i) => [i.name, i.notMeasured]), + [ + ["lint", configHooks ? "a git config hook: running it could change files, the index or a remote" : "git before 2.54 ignores config hooks, so it does not run here"], + ["off", "disabled (hook.off.enabled=false)"], + ], + ); + }); + test("a repository with no hooks has no stages", () => { const report = inspectRun(plugin(), repo()).report; assert.deepEqual(report.stages, []); diff --git a/plugins/actionlint/lib/git-hooks/install.mjs b/plugins/actionlint/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/actionlint/lib/git-hooks/install.mjs +++ b/plugins/actionlint/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/actionlint/skills/setup/SKILL.md b/plugins/actionlint/skills/setup/SKILL.md index 4f3519c1d70..1b9e61fa86e 100644 --- a/plugins/actionlint/skills/setup/SKILL.md +++ b/plugins/actionlint/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify actionlint's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up actionlint', 'configure actionlint', 'is actionlint working', workflow lint silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-git-hooks [scope=local|shared]]. Re-runnable and safe." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify actionlint's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up actionlint', 'configure actionlint', 'is actionlint working', workflow lint silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply [install-git-hooks [scope=local|shared]]. Re-runnable and safe." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -44,7 +44,8 @@ plugin never bundles, and the plugin never installs system packages, so `apply` guidance-and-verify with that one write path. It never modifies user settings or the plugin cache. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then offers remediation guidance; `apply install-git-hooks` registers the git-hook entry. All are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -105,7 +106,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/bash-format/lib/git-hooks/install.mjs b/plugins/bash-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/bash-format/lib/git-hooks/install.mjs +++ b/plugins/bash-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/bash-format/skills/setup/SKILL.md b/plugins/bash-format/skills/setup/SKILL.md index fc30e0a94ef..e15ce71b047 100644 --- a/plugins/bash-format/skills/setup/SKILL.md +++ b/plugins/bash-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify bash-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up bash-format', 'configure bash-format', 'is bash-format working', shell lint or formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only verification, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify bash-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up bash-format', 'configure bash-format', 'is bash-format working', shell lint or formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only verification, default) | check inspect (read-only) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -48,7 +48,8 @@ Every prerequisite is a `PATH` binary the plugin never bundles, and the plugin n system packages, so the rest of `apply` is guidance-only. It never modifies user settings or the plugin cache. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then offers remediation guidance. Both are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -153,7 +154,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/code-tidying/lib/git-hooks/install.mjs b/plugins/code-tidying/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/code-tidying/lib/git-hooks/install.mjs +++ b/plugins/code-tidying/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/code-tidying/skills/setup/SKILL.md b/plugins/code-tidying/skills/setup/SKILL.md index b17780b75df..a2ee3962dec 100644 --- a/plugins/code-tidying/skills/setup/SKILL.md +++ b/plugins/code-tidying/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Checks or scaffolds this repository's code-tidying configuration: tracked project tidy lanes, the optional HARD-exclusion overrides file, and the comment-lint git pre-commit entry. Use when 'set up code-tidying' is asked, the tidy skill reports no project lanes, or a session-start line says the comment-lint git hook is missing or stale. Actions: check (read-only, default), apply (one named lane or all), apply install-git-hooks (scope local or shared)." -argument-hint: "[check|apply [|install-git-hooks [scope=local|shared]]]" +description: "Checks or scaffolds this repository's code-tidying configuration: tracked project tidy lanes, the optional HARD-exclusion overrides file, and the comment-lint git pre-commit entry. Use when 'set up code-tidying' is asked, the tidy skill reports no project lanes, or a session-start line says the comment-lint git hook is missing or stale. Actions: check (read-only, default), check inspect (read-only), apply (one named lane or all), apply install-git-hooks (scope local or shared)." +argument-hint: "[check|apply] [inspect||install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true --- @@ -16,7 +16,7 @@ the bundled lane, one without it resolves project-only (the `tidy` skill's Lane Project lanes are optional: with none, tidy uses the bundled lanes, so their absence is an INFO, never a FAIL. The skill follows the uniform setup contract (`docs/plugin-philosophy.md` "Setup is explicit and repeatable" in the marketplace repository): no argument or `check` inspects -read-only; `apply` runs the check, scaffolds or retunes lanes, then re-runs `check`; `apply ` +read-only; `check inspect` runs only the `check inspect` section; `apply` runs the check, scaffolds or retunes lanes, then re-runs `check`; `apply ` targets one lane. Re-running reads the existing lane files and proposes changes against them rather than overwriting a consumer lane blind. @@ -173,7 +173,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/go-format/lib/git-hooks/install.mjs b/plugins/go-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/go-format/lib/git-hooks/install.mjs +++ b/plugins/go-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/go-format/skills/setup/SKILL.md b/plugins/go-format/skills/setup/SKILL.md index 3282dbfabb4..ab37e6a0d31 100644 --- a/plugins/go-format/skills/setup/SKILL.md +++ b/plugins/go-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify go-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up go-format', 'configure go-format', 'is go-format working', Go import/formatting fixes silently aren't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify go-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up go-format', 'configure go-format', 'is go-format working', Go import/formatting fixes silently aren't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -48,7 +48,8 @@ a project dependency. `apply` is therefore guidance-only for tools: it never ins matching the hook's own PATH-only resolution and the plugin philosophy's never-download-silently rule. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then prints remediation guidance for each FAIL. Both are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -117,7 +118,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/guardrails/lib/git-hooks/install.mjs b/plugins/guardrails/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/guardrails/lib/git-hooks/install.mjs +++ b/plugins/guardrails/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/guardrails/skills/setup/SKILL.md b/plugins/guardrails/skills/setup/SKILL.md index 62504868cb5..df1a1791a06 100644 --- a/plugins/guardrails/skills/setup/SKILL.md +++ b/plugins/guardrails/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify the guardrails hooks' runtime prerequisites, per-guard toggle state and git-hook entries for this machine, and register those entries. Use when: 'set up guardrails', 'configure guardrails', 'is guardrails working', 'which guards are on', a guard failed open with a jq notice, after tuning guard toggles, a hook reported a drifted git hook, or 'install the guardrails git hooks' / 'enforce the commit convention for every committer' / 'check secrets and hardcoded paths on every commit'. Actions: check (read-only verification, default) | apply (resolve what check found) | apply install-git-hooks [scope=local|shared|user] (register the commit-msg convention, pre-commit and pre-push content and reference-verify entries with the repository's hook manager; user: the commit-msg entry as a git config hook under an includeIf) | apply read-deny (opt-in: print Read() deny rules for .env, with user also ~/.ssh and ~/.aws, and add or remove them in the chosen settings file). Re-runnable and safe." -argument-hint: "[check|apply] [install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" +description: "Verify the guardrails hooks' runtime prerequisites, per-guard toggle state and git-hook entries for this machine, and register those entries. Use when: 'set up guardrails', 'configure guardrails', 'is guardrails working', 'which guards are on', a guard failed open with a jq notice, after tuning guard toggles, a hook reported a drifted git hook, or 'install the guardrails git hooks' / 'enforce the commit convention for every committer' / 'check secrets and hardcoded paths on every commit'. Actions: check (read-only, default) | check inspect (read-only) | apply (resolve what check found) | apply install-git-hooks [scope=local|shared|user] (register the commit-msg convention, pre-commit and pre-push content and reference-verify entries with the repository's hook manager; user: the commit-msg entry as a git config hook under an includeIf) | apply read-deny (opt-in: print Read() deny rules for .env, with user also ~/.ssh and ~/.aws, and add or remove them in the chosen settings file). Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope]|read-deny [scope user remove]|identity-domains]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -45,7 +45,8 @@ the only other writes, each as its section states: `install-git-hooks` writes th git-hook entry copies, `read-deny` touches settings through your edit tools, and `identity-domains` writes the `block-cross-domain` map into the plugin data directory. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then points at each remediation. Both are non-interactive: never prompt when the action is given, except for the confirmation bare `apply` asks before each retired-hook cleanup. The other actions ask only where their sections say to, and only in an attended run: `install-git-hooks` for scope, @@ -162,7 +163,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/instruction-placement/lib/git-hooks/install.mjs b/plugins/instruction-placement/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/instruction-placement/lib/git-hooks/install.mjs +++ b/plugins/instruction-placement/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/instruction-placement/skills/setup/SKILL.md b/plugins/instruction-placement/skills/setup/SKILL.md index e4b97f45ebc..52ae4f83725 100644 --- a/plugins/instruction-placement/skills/setup/SKILL.md +++ b/plugins/instruction-placement/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify instruction-placement's prerequisites, resolve its effective configuration for this repository, and register its rules-index git pre-commit entry. Confirm that the index target exists AND that nothing in the repository stops Claude Code loading it (a root CLAUDE.md is read instead of the AGENTS.md beside it, so an unimported AGENTS.md index is inert while every other gate reports green), that `git` backs tracked-file discovery, and that the Claude Code CLI plus `jq` are present for the optional empirical load probe. Reports the resolved index target, breadth ceiling, and index row cap, naming which came from configuration and which from a default. Use when: 'set up instruction-placement', 'configure instruction-placement', 'where will the index go', 'why is my index not loading', 'is instruction-placement working', or before a first audit on a new repository. Actions: check (read-only, default) | apply (point at each remediation) | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify instruction-placement's prerequisites, resolve its effective configuration for this repository, and register its rules-index git pre-commit entry. Confirm that the index target exists AND that nothing in the repository stops Claude Code loading it (a root CLAUDE.md is read instead of the AGENTS.md beside it, so an unimported AGENTS.md index is inert while every other gate reports green), that `git` backs tracked-file discovery, and that the Claude Code CLI plus `jq` are present for the optional empirical load probe. Reports the resolved index target, breadth ceiling, and index row cap, naming which came from configuration and which from a default. Use when: 'set up instruction-placement', 'configure instruction-placement', 'where will the index go', 'why is my index not loading', 'is instruction-placement working', or before a first audit on a new repository. Actions: check (read-only, default) | check inspect (read-only) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -20,7 +20,8 @@ shell: bash ## Purpose Thin check-centric setup per the uniform setup contract (`docs/plugin-philosophy.md`, "Setup is -explicit and repeatable"): `check` inspects and reports, `apply` points at what it found. +explicit and repeatable"): `check` inspects and reports, `check inspect` runs only the `check inspect` section, `apply` +points at what it found. The warrant is all three criteria, but one carries the weight. **The index target is an external referent whose validity cannot be established by a configuration prompt.** A prompt stores the path @@ -121,7 +122,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/javascript-format/lib/git-hooks/install.mjs b/plugins/javascript-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/javascript-format/lib/git-hooks/install.mjs +++ b/plugins/javascript-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/javascript-format/skills/setup/SKILL.md b/plugins/javascript-format/skills/setup/SKILL.md index f55cca66634..b7f7f877a4d 100644 --- a/plugins/javascript-format/skills/setup/SKILL.md +++ b/plugins/javascript-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify javascript-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up javascript-format', 'configure javascript-format', 'is javascript-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-biome] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-biome|install-git-hooks [scope=local|shared]]]" +description: "Verify javascript-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up javascript-format', 'configure javascript-format', 'is javascript-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply [install-biome] | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-biome|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -41,7 +41,8 @@ gitignored-file switch and the end-of-turn check). `apply` is otherwise guidance with one more write path: the explicitly invoked `apply install-biome` dependency install described below. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then remediation; `apply install-biome` additionally authorizes the consumer-repo dependency install described below. All are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -121,7 +122,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/markdown-format/lib/git-hooks/install.mjs b/plugins/markdown-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/markdown-format/lib/git-hooks/install.mjs +++ b/plugins/markdown-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/markdown-format/skills/setup/SKILL.md b/plugins/markdown-format/skills/setup/SKILL.md index 11cf79b7b54..ad54009b09c 100644 --- a/plugins/markdown-format/skills/setup/SKILL.md +++ b/plugins/markdown-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify markdown-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up markdown-format', 'configure markdown-format', 'is markdown-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-lint] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-lint|install-git-hooks [scope=local|shared]]]" +description: "Verify markdown-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up markdown-format', 'configure markdown-format', 'is markdown-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply [install-lint] | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-lint|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -41,7 +41,8 @@ the gitignored-file switch and the end-of-turn check). `apply` is otherwise guid with one more write path: the explicitly invoked `apply install-lint` dependency install described below. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then remediation; `apply install-lint` additionally authorizes the consumer-repo dependency install described below. All are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -145,7 +146,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/powershell-format/lib/git-hooks/install.mjs b/plugins/powershell-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/powershell-format/lib/git-hooks/install.mjs +++ b/plugins/powershell-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/powershell-format/skills/setup/SKILL.md b/plugins/powershell-format/skills/setup/SKILL.md index 7916600ff2b..6ca2dd99112 100644 --- a/plugins/powershell-format/skills/setup/SKILL.md +++ b/plugins/powershell-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify powershell-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up powershell-format', 'configure powershell-format', 'is powershell-format working', PowerShell formatting or linting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify powershell-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up powershell-format', 'configure powershell-format', 'is powershell-format working', PowerShell formatting or linting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -31,7 +31,8 @@ module, or a repo without a settings file, is INFO in `check`, never FAIL: the h quiet by design. A machine without PowerShell still gets the `SessionStart` probe's notice once per session while the plugin is enabled. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then offers remediation guidance. Both are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -108,7 +109,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/python-format/lib/git-hooks/install.mjs b/plugins/python-format/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/python-format/lib/git-hooks/install.mjs +++ b/plugins/python-format/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/python-format/skills/setup/SKILL.md b/plugins/python-format/skills/setup/SKILL.md index aa3f1d71311..027dc12a51f 100644 --- a/plugins/python-format/skills/setup/SKILL.md +++ b/plugins/python-format/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify python-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up python-format', 'configure python-format', 'is python-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply [install-ruff] | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-ruff|install-git-hooks [scope=local|shared]]]" +description: "Verify python-format's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up python-format', 'configure python-format', 'is python-format working', formatting silently isn't happening, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply [install-ruff] | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-ruff|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -41,7 +41,8 @@ gitignored-file switch and the end-of-turn check). `apply` is otherwise guidance with one more write path: the explicitly invoked `apply install-ruff` install into the repo's existing managed environment described below. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then remediation; `apply install-ruff` additionally authorizes the consumer-repo install described below. All are non-interactive. Never prompt when the action is given. `apply install-git-hooks` asks only where its section says to. @@ -114,7 +115,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository). diff --git a/plugins/spelling/lib/git-hooks/install.mjs b/plugins/spelling/lib/git-hooks/install.mjs index f6669963024..7046a743c4a 100755 --- a/plugins/spelling/lib/git-hooks/install.mjs +++ b/plugins/spelling/lib/git-hooks/install.mjs @@ -1448,7 +1448,13 @@ function executable(file) { } } -function stampOf(file) { +const within = (dir, file) => { + const rel = path.relative(realOr(dir), realOr(file)); + return Boolean(rel) && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); +}; + +function stampOf(info, file) { + if (!within(info.top, file) && !within(info.hooksDir, file)) return null; const text = readText(file); const stamp = text === null ? null : readStamp(text); return stamp ? { file, plugin: stamp.plugin, entry: stamp.name } : null; @@ -1456,7 +1462,7 @@ function stampOf(file) { function entryInCommand(info, command) { for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { - const found = stampOf(path.isAbsolute(token) ? token : path.join(info.top, token)); + const found = stampOf(info, path.resolve(info.top, token)); if (found) return found; } return null; @@ -1487,15 +1493,17 @@ function timingInput(info, event) { return { skip: `${event} is not an event entries run on` }; } -// Runs only this plugin's own entry that rewrites nothing and has its tools. function timing(info, plugin, event, found, opts) { if (found.plugin !== plugin.name) return { notMeasured: `an entry of ${found.plugin}: time it with /${found.plugin}:setup check inspect` }; const entry = plugin.entries.find((e) => e.name === found.entry); if (!entry) return { notMeasured: `${plugin.name} ships no entry named ${found.entry}` }; - if (entry.rewrites) return { notMeasured: "rewrites staged files" }; - if (!lf(readText(found.file) ?? "").startsWith("#!/bin/sh")) { - return { notMeasured: `an older installed copy that runs by its own first line: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; + if (entry.event !== event) return { notMeasured: `${entry.name} is a ${entry.event} entry, not ${event}` }; + const state = copyState(found.file, entry, sourceHash(plugin, entry)); + if (state === "stale") { + return { notMeasured: `an older installed copy: refresh it with /${plugin.name}:setup apply install-git-hooks, then time it` }; } + if (state !== "ok") return { notMeasured: `not what ${plugin.name} ships (edited, or not its copy), so not run` }; + if (entry.rewrites) return { notMeasured: "rewrites staged files" }; const missing = entry.tools.filter((t) => !whichTool(t)); if (missing.length) return { notMeasured: `tool missing: ${missing.join(", ")}` }; const input = timingInput(info, event); @@ -1558,7 +1566,7 @@ function dispatcherItems(ctx, event) { items.push({ kind: "hook", name, source: configPath(info, marker), notMeasured: "registered, but the script it names is missing" }); continue; } - const found = stampOf(file); + const found = stampOf(info, file); items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); } } @@ -1611,7 +1619,7 @@ function lefthookItems(ctx, event, dump) { const local = [".lefthook", ".lefthook-local"].map((d) => path.join(info.top, d, event, job.script)); const file = local.find((f) => readText(f) !== null); if (!file) return { ...base, notMeasured: remotes ? "runs from lefthook's fetched remote copy, not a file in this clone" : NOT_RUN.job }; - found = stampOf(file); + found = stampOf(info, file); } return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; }); @@ -1659,19 +1667,22 @@ function huskyItems(ctx, event, variant) { } function configHookItems(info) { - const r = git(info.top, ["config", "--get-regexp", "^hook\\..*\\.event$"]); + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); if (!r.ok) return []; const runs = hasConfigHooks(info); - return r.out - .split("\n") - .map((line) => [line.slice(0, line.indexOf(" ")), line.slice(line.indexOf(" ") + 1)]) - .filter(([key, event]) => key && event) - .map(([key, event]) => { - const name = key.slice("hook.".length, -".event".length); - const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; - const notMeasured = runs ? NOT_RUN.config : "git before 2.54 ignores config hooks, so it does not run here"; - return { event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } }; - }); + const names = new Set(r.out.split("\0").filter(Boolean).map((key) => key.slice("hook.".length, -".event".length))); + return [...names].flatMap((name) => { + const values = git(info.top, ["config", "--null", "--get-all", `hook.${name}.event`]).out.split("\0").slice(0, -1); + const events = new Set(values.slice(values.lastIndexOf("") + 1)); + const command = git(info.top, ["config", "--get", `hook.${name}.command`]).out; + const notMeasured = + configBool(info, `hook.${name}.enabled`) === "false" + ? `disabled (hook.${name}.enabled=false)` + : runs + ? NOT_RUN.config + : "git before 2.54 ignores config hooks, so it does not run here"; + return [...events].map((event) => ({ event, item: { kind: "config-hook", name, source: "git config", command, notMeasured } })); + }); } // inspect(info, plugin, opts) -> { manager, variant?, evidence[], hooksDir, stages[{ event, installed, hookFile, items[] }] } diff --git a/plugins/spelling/skills/setup/SKILL.md b/plugins/spelling/skills/setup/SKILL.md index ae17994fdc6..7cd56c30d5a 100644 --- a/plugins/spelling/skills/setup/SKILL.md +++ b/plugins/spelling/skills/setup/SKILL.md @@ -1,6 +1,6 @@ --- -description: "Verify spelling's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up spelling', 'configure spelling', 'is spelling working', spelling findings never show up, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." -argument-hint: "[check|apply [install-git-hooks [scope=local|shared]]]" +description: "Verify spelling's prerequisites and configuration here, and register its git pre-commit entry. Use when: 'set up spelling', 'configure spelling', 'is spelling working', spelling findings never show up, or a hook reported a missing prerequisite or drifted git hook. Actions: check (read-only, default) | check inspect (read-only) | apply | apply install-git-hooks [scope=local|shared]. Re-runnable." +argument-hint: "[check|apply] [inspect|install-git-hooks [scope=local|shared]]" user-invocable: true disable-model-invocation: true allowed-tools: @@ -44,7 +44,8 @@ a pre-built binary), never as a project dependency. `apply` is therefore guidanc never installs anything, matching the check's own PATH-only resolution and the plugin philosophy's never-download-silently rule. -Action routing: no argument or `check` runs the check; `apply` runs the check first, then +Action routing: no argument or `check` runs the check; `check inspect` runs only the +`check inspect` section; `apply` runs the check first, then prints remediation guidance for each FAIL. Both are non-interactive. Never prompt when the action is given. `apply install-git-hooks` is the one write path, and it asks only where its section says to. @@ -111,7 +112,7 @@ and times this plugin's own entries. Run kind, name and source, then its `measured` median and range with the input it ran on and its exit codes, or `not measured` with the `notMeasured` reason. A stage whose `installed` is false has no hook file git runs: say the manager's install step has not run in this clone. The script runs only -this plugin's installed entries that change no files; it never runs a repository's own hook, +this plugin's installed entries that change no files and still match what the plugin ships; it never runs a repository's own hook, another plugin's entry, a lefthook job or a Husky.Net task. To place a new check, compare the numbers with the duration budgets in the check-placement contract (`docs/contracts/check-placement/README.md#duration-budgets` in the marketplace repository).