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..38b1ec0ea40 --- /dev/null +++ b/.changes/actionlint/feat-git-hooks-inspect-9e83d8f9.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/bash-format/feat-git-hooks-inspect-e17b94e7.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/code-tidying/feat-git-hooks-inspect-534a268d.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/go-format/feat-git-hooks-inspect-e28a44d8.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/guardrails/feat-git-hooks-inspect-e670076f.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/instruction-placement/feat-git-hooks-inspect-9a856722.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/javascript-format/feat-git-hooks-inspect-d8c496e6.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/markdown-format/feat-git-hooks-inspect-46218c3e.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/powershell-format/feat-git-hooks-inspect-7c0c691f.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/python-format/feat-git-hooks-inspect-a8b1b962.md @@ -0,0 +1,9 @@ +--- +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 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 new file mode 100644 index 00000000000..38b1ec0ea40 --- /dev/null +++ b/.changes/spelling/feat-git-hooks-inspect-f6f6d253.md @@ -0,0 +1,9 @@ +--- +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 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 31858473f09..8cf24a0e270 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,27 @@ 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. 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 +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 (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 +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..c6d7c0ea3c5 100644 --- a/docs/contracts/check-placement/adopting-git-hooks.md +++ b/docs/contracts/check-placement/adopting-git-hooks.md @@ -49,6 +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`. - 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 +60,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/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/lib/git-hooks/install.mjs b/lib/git-hooks/install.mjs index 1d620e1a231..618a1525dd5 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -419,14 +425,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1405,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1731,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 +1754,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 +1812,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 +1839,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..040514ee69d 100644 --- a/lib/git-hooks/install.test.mjs +++ b/lib/git-hooks/install.test.mjs @@ -1765,3 +1765,331 @@ 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", () => { + 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: an older installed copy is not timed, and gets a refresh hint", () => { + const root = plugin(); + const dir = repo(); + run(root, dir, "copy", "--scope", "local"); + 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: 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"], + ], + ); + }); + + 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 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"); + 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 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 abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..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: @@ -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 @@ -42,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. @@ -94,6 +97,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/bash-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..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: @@ -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 @@ -46,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. @@ -142,6 +145,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/code-tidying/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..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. @@ -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 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). +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/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/lib/git-hooks/install.mjs b/plugins/go-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..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: @@ -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 @@ -46,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. @@ -106,6 +109,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/guardrails/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..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: @@ -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)" @@ -43,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, @@ -151,6 +154,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/instruction-placement/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..52ae4f83725 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]]]" +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: - "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 @@ -18,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 @@ -110,6 +113,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/javascript-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..b7f7f877a4d 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]]]" +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: - "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 @@ -39,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. @@ -110,6 +113,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/markdown-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..ad54009b09c 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]]]" +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: - "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 @@ -39,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. @@ -134,6 +137,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/powershell-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..6ca2dd99112 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]]]" +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: - "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 @@ -29,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. @@ -97,6 +100,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/python-format/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..027dc12a51f 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]]]" +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: - "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 @@ -39,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. @@ -103,6 +106,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 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). +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/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/lib/git-hooks/install.mjs b/plugins/spelling/lib/git-hooks/install.mjs index abb112d48ac..7046a743c4a 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 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)) { found.push({ manager: "unknown", evidence: `core.hooksPath=${info.hooksPath}` }); @@ -421,14 +427,15 @@ function managerEvidence(info) { return found; } -// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[] } +// detect(info) -> { manager: lefthook|husky|plain|conflict, evidence[], variant? } 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 +1407,319 @@ export function driftLine(plugin, row) { return `${plugin.name}: git hook ${row.entry} ${row.state}; run /${plugin.name}:setup apply install-git-hooks`; } +// https://git-scm.com/docs/githooks +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; + } +} + +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; +} + +function entryInCommand(info, command) { + for (const token of command.match(SCRIPT_TOKEN_RE) ?? []) { + const found = stampOf(info, path.resolve(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; +}; + +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` }; +} + +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.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); + 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), + }; +} + +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(info, file); + items.push(found ? entryItem(ctx, event, found) : { kind: "hook", name, source: configPath(info, file), notMeasured: NOT_RUN.hook }); + } + } + return items; +} + +// 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, + 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" }; + } +} + +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(info, file); + } + return found ? entryItem(ctx, event, found, { via: "lefthook", job: name }) : { ...base, notMeasured: NOT_RUN.job }; + }); +} + +// 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")]; + 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, + })); +} + +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 }]; + }); +} + +function configHookItems(info) { + const r = git(info.top, ["config", "--null", "--name-only", "--get-regexp", "^hook\\..*\\.event$"]); + if (!r.ok) return []; + const runs = hasConfigHooks(info); + 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[] }] } +// 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 +1733,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 +1756,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 +1814,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 +1841,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..7cd56c30d5a 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]]]" +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: - "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 @@ -42,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. @@ -100,6 +103,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 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). +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/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`. |