From 94197189ca72c24ceac756655a4bbff66bedfb90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= Date: Thu, 20 Aug 2026 12:22:56 +0200 Subject: [PATCH 1/2] feat(hooks): report where the git-hook floor is and whether it can fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit README calls git hooks the agent-agnostic enforcement floor, and nothing reported on them: kit check had a row for memory hooks and one for the PreToolUse gates, none for these. Two measured states were invisible. #496 — the floor can live OUTSIDE the repo. resolveHooksDir() honors core.hooksPath, which is right (installing into .git/hooks while git reads elsewhere is a silent no-op), but only the WRITER used it: check-hooks.ts and `kit hooks add`'s own already-installed pre-check hardcoded /hooks, so kit installed to one directory and reported on another. Writer and readers now share the resolver. Measured consequence of the silence: a checkout copied from another inherits its absolute core.hooksPath, so its hooks live in the other clone's tree — deleting that unrelated directory let a staged fake credential commit cleanly, exit 0, with every report green. #497 — `kit hooks add context-check` installed a gate that could not fail. With no [context] block there is nothing to compare the live CLI state against, so the pre-push hook passed every push under a ✓ installed. It now refuses (with --force for someone about to declare the block), the installed hook runs `kit context check --require-declaration` so a block that disappears later fails the push, and each built-in prints how to exercise ITSELF instead of secret-scan's stage-a-credential recipe. New `git hook floor` row in the security gate: fail for a gone hooksPath directory (every hook is off) or an unarmed gate, warn when the floor resolves outside the repo, pass naming what is wired, skip when the repo has no kit-managed hooks — kit does not claim a floor nobody asked for. Also corrects fix.ts's claim that git-hook installs "land inside the repo, which the repo-rooted [scope].fs covers": true only while core.hooksPath is unset or repo-relative. Closes #496 Closes #497 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 39 +++++- docs/COMMANDS.md | 3 +- src/check-hooks.ts | 6 +- src/check-security.ts | 32 +++++ src/commands/context.ts | 13 ++ src/commands/hooks.ts | 62 ++++++++- src/fix.ts | 7 +- src/flag-surface.ts | 8 +- src/hook-floor.test.ts | 297 ++++++++++++++++++++++++++++++++++++++++ src/hook-floor.ts | 184 +++++++++++++++++++++++++ 10 files changed, 638 insertions(+), 13 deletions(-) create mode 100644 src/hook-floor.test.ts create mode 100644 src/hook-floor.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 281ad94e..5d5debb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **`kit check` now reports the git-hook floor: where it is, and whether it can fail.** README + calls git hooks the agent-agnostic enforcement floor, and nothing reported on them — there was + a row for memory hooks and one for the PreToolUse gates, none for these. Two measured states + were therefore invisible (#496, #497): + + - **The floor can live outside the repo.** `resolveHooksDir()` honors `core.hooksPath`, which + is correct (installing into `.git/hooks` while git reads elsewhere is a silent no-op) — but + only the WRITER used it. `check-hooks.ts` and `kit hooks add`'s own already-installed + pre-check hardcoded `/hooks`, so with an external `core.hooksPath` kit installed to + one directory and reported on another. Both readers now use the same resolver, so writer and + reader can no longer disagree. Measured consequence of the silence: a checkout copied from + another inherits its absolute `core.hooksPath`, so its hooks live in the other clone's tree + — deleting that unrelated directory let a staged fake credential commit cleanly, exit 0. + - **A dangling `core.hooksPath` means every hook is OFF**, and now fails the gate instead of + reading like a repo that never wired hooks. + + New `git hook floor` row: `fail` for a gone directory or an unarmed gate, `warn` when the floor + resolves outside the repo, `pass` naming the hooks actually wired, and `skip` when the repo has + no kit-managed hooks — kit does not claim a floor nobody asked for. `kit hooks add` also prints + the resolved directory when it is external, instead of a bare `✓ installed`. + - **`kit audit verify --all` — the union view over every audit log this machine sealed.** `kit audit verify` answers for one working tree, correctly: a git worktree IS a distinct working tree, so it gets its own chain. On a machine running several — the normal case @@ -82,6 +103,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Fixed +- **`kit hooks add context-check` installed a gate that could not fail.** With no `[context]` + block there is nothing to compare the live CLI state against, so the pre-push hook passed every + push while reporting `✓ installed` — the false green kit exists to refuse (#497). It now + refuses, points at `kit context check` (which prints a ready-to-paste block from the live CLI + state), and takes `--force` for someone about to declare the block. The installed hook runs + `kit context check --require-declaration`, so a `[context]` block that disappears later fails + the push instead of passing it; the bare command still exits 0, since a repo may legitimately + have no lock and a read-only report should not invent one. + +- **Every hook printed secret-scan's test recipe.** `kit hooks add post-pull-audit` and + `context-check` both told you to stage a fake credential and commit — advice that exercises + nothing for a post-merge or pre-push gate. Each built-in now prints how to exercise itself. + - **`triage`'s pip score is no longer higher than npm's for running fewer probes.** The score is a flat penalty count (`100 - 45*critical - 12*warning`), so it fell out of how many probes an ecosystem HAS: `pip opensandbox-server` printed 100/100 next to @@ -112,7 +146,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). `ensureMiseActivation` — the appender — has no production caller at all (it sits in self-audit's unwired-code advisory). `kit doctor` reports the gap and prints the line. The claim is corrected rather than the feature quietly invented: writing to a user's shell - profile needs its own consent design. + profile needs its own consent design. `fix.ts` carried the same shape of false claim — + git-hook installs "land inside the repo, which the repo-rooted `[scope].fs` covers" — which + holds only while `core.hooksPath` is unset or repo-relative; an absolute one puts the write + outside the repo. Both are now corrected. - **`self-audit`'s flag-validation row now measures verbs, not file text.** It grepped `src/commands/*.ts` for the string `unknownFlags(`, which measured the shape of the fix: diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 5e1a7bea..5bd0d43c 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -188,7 +188,7 @@ required = ["NEXT_PUBLIC_SENTRY_DSN", "NEXT_PUBLIC_SENTRY_ENVIRONMENT"] | Command | Purpose | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `kit hooks install` | Install hooks declared in `[hooks]`. If no `[hooks]` section exists, it explains that nothing was installed and points to `kit hooks add `. | -| `kit hooks add ` | Add a built-in hook (`secret-scan`, `post-pull-audit`, `context-check`) without requiring `[hooks]`. | +| `kit hooks add [--force]` | Add a built-in hook (`secret-scan`, `post-pull-audit`, `context-check`) without requiring `[hooks]`. Installs into the directory git will actually use — `core.hooksPath` is honored, and the path is printed when it resolves OUTSIDE the repo, since deleting that directory then removes the gate silently. `context-check` is **refused** when `.kit.toml` has no `[context]` block: the hook would pass every push and report a gate you do not have. `--force` installs it anyway. | | `kit hooks sync` | Reconcile installed hooks with config. | | `kit hooks uninstall` | Remove the configured git hooks. **Enforcement is off until re-installed** — git hooks are the agent-agnostic floor, so this disables the gate that fires in any agent or none. | @@ -343,6 +343,7 @@ scope/RoE, so a profile can move to a fresh host without trusting the transport. | `kit escalate` | Collect failures + format for manual handoff. | | `kit ci [--strict] [--attest]` | One-shot CI gate (check + design + tests). Scanner-health gate: a crashed / missing / token-less scanner can no longer exit 0 (default warns); `--strict` / `KIT_CI_STRICT=1` (or `[governance.scan].required_scanners`) hard-fails any non-running scanner. | | `kit context [--format json]` | Print kit context for agent introspection. | +| `kit context check [--json] [--require-declaration]` | Verify the live CLI state against `[context]` — each tool's declared (account, project) pair, never inferred from whatever is logged in. With no `[context]` block it prints a ready-to-paste one from the detected state and exits 0; `--require-declaration` makes that absence a **failure** instead, which is what the `context-check` pre-push hook runs — a gate with nothing to compare against is a check that could not run, not a pass. | | `kit create-plugin ` | Scaffold a new adapter. | | `kit add ` · `kit add --list` | Add service to `.kit.toml`; `--list` prints every available adapter (so does bare `kit add`, which exits 1 as a usage error). | | `kit version` | Print kit version + exit. | diff --git a/src/check-hooks.ts b/src/check-hooks.ts index 36f90440..fb984856 100644 --- a/src/check-hooks.ts +++ b/src/check-hooks.ts @@ -19,7 +19,11 @@ export async function checkHooks( cwd = process.cwd(), ): Promise { const results: HookCheckResult[] = []; - const hooksDir = resolve(cwd, gitDir, "hooks"); + // The SAME resolver the writer uses. Hardcoding `/hooks` here meant that with an + // external `core.hooksPath`, kit installed to one directory and reported on another: the + // declared hooks read as "not installed" while they were installed and firing (#496). + const { resolveHooksDir } = await import("./hooks.js"); + const hooksDir = resolveHooksDir(gitDir, cwd); for (const [hookName, commands] of Object.entries(config)) { if (!commands || commands.length === 0) { diff --git a/src/check-security.ts b/src/check-security.ts index 5c922218..fa5fa13b 100644 --- a/src/check-security.ts +++ b/src/check-security.ts @@ -181,6 +181,36 @@ export async function checkMemoryHooksLiveness(): Promise { }; } +/** + * Git-hook floor — WHERE it is and whether it can fail. + * + * README calls git hooks the agent-agnostic enforcement floor, and nothing reported on them: + * `kit check` had a row for memory hooks and for the PreToolUse gates, none for these. Two + * measured states were therefore invisible (#496, #497): a floor resolved OUTSIDE the repo + * through an absolute `core.hooksPath` (deleting that unrelated directory removed the gate, + * exit 0, no warning), and `context-check` installed with no `[context]` block, which passes + * every push. Skips when the repo has no kit-managed hooks — kit does not claim a floor nobody + * asked for. + */ +export async function checkGitHookFloor(cwd?: string): Promise { + const name = "git hook floor"; + const category = "exposure" as const; + const root = cwd ?? process.cwd(); + const { describeHookFloor, judgeHookFloor } = await import("./hook-floor.js"); + let config; + try { + const { loadConfig } = await import("./config.js"); + const { resolve } = await import("node:path"); + config = await loadConfig(resolve(root, ".kit.toml")); + } catch { + config = undefined; + } + const verdict = judgeHookFloor(describeHookFloor(root, config)); + return verdict.severity + ? { category, name, status: verdict.status, severity: verdict.severity, detail: verdict.detail } + : { category, name, status: verdict.status, detail: verdict.detail }; +} + /** * Gate liveness — the enforcement floor must prove it exists. If kit installed the * PreToolUse gates on THIS machine (machine-local marker present) but a gate has @@ -2588,6 +2618,8 @@ export async function checkSecurity(cwd?: string): Promise { return findings.every((f) => f.status !== "mismatch"); } if (!config.context) { + // The hook path passes --require-declaration: for a gate someone installed on purpose, + // "nothing declared" is not a pass, it is a check that could not run (#497). The bare + // command keeps exiting 0 — it is a read-only report, and a repo may legitimately have no + // lock — so only the caller that asked for enforcement gets the strict answer. + if (hasFlag(process.argv, "--require-declaration")) { + console.error( + `${c.red}✗ no [context] block in .kit.toml, so there is nothing to verify — refusing to report a context lock that does not exist.${c.reset}`, + ); + console.error( + `${c.dim}Run 'kit context check' without --require-declaration for a ready-to-paste block, or remove the context-check hook.${c.reset}`, + ); + return false; + } console.log( `${c.dim}No [context] declared in .kit.toml — each CLI is unlocked from its account + project.${c.reset}`, ); diff --git a/src/commands/hooks.ts b/src/commands/hooks.ts index a4888f0a..f3f7ae5b 100644 --- a/src/commands/hooks.ts +++ b/src/commands/hooks.ts @@ -22,7 +22,9 @@ const BUILTIN_HOOKS: Record { return false; } + // A gate that cannot fail must not be installed silently. `kit context check` with no + // [context] block has nothing to compare the live CLI state against, so the pre-push hook + // passed unconditionally while reporting `✓ installed` (#497) — the false green kit exists + // to refuse. --force installs anyway, for someone who is about to add the block. + if (name === "context-check") { + const { hasFlag } = await import("../utils/flags.js"); + const cfg = await loadConfig(resolveConfigPath()).catch(() => null); + if (!cfg?.context && !hasFlag(process.argv, "--force")) { + console.error( + `${c.red}✗ refusing to install context-check: no [context] block in ${KIT_FILE}.${c.reset}`, + ); + console.error( + `${c.dim}The hook runs \`kit context check\`, which has nothing to compare against without one — it would pass every push and report a gate you do not have.${c.reset}`, + ); + console.error( + `${c.dim}Run ${c.bold}kit context check${c.reset}${c.dim} first: it prints a ready-to-paste [context] block from the live CLI state. Then re-run this. Or ${c.bold}--force${c.reset}${c.dim} to install it now and declare the block after.${c.reset}`, + ); + return false; + } + } + console.log( `${c.bold}${c.cyan}kit hooks add ${name}${c.reset} ${c.dim}(git ${builtin.hookName})${c.reset}`, ); @@ -238,13 +261,40 @@ async function cmdHooksAdd(): Promise { console.log( ` ${c.green}✓${c.reset} ${builtin.hookName} ${c.green}${r.action}${c.reset} ${c.dim}${r.detail}${c.reset}`, ); - console.log( - `\n${c.dim}Test by staging a file with a fake credential (e.g. ${c.bold}sk_${"test"}_${"A".repeat(20)}${c.reset}${c.dim}) and running ${c.bold}git commit${c.reset}${c.dim} — the commit should be blocked.${c.reset}\n`, - ); + // Where it landed, when that is not inside the repo. `✓ installed` with no path is what let a + // floor live in another clone's tree unnoticed (#496). + const { describeHookFloor } = await import("../hook-floor.js"); + const floor = describeHookFloor(process.cwd()); + if (floor.external) { + console.log( + `\n ${c.yellow}!${c.reset} written to ${c.bold}${floor.dir}${c.reset} ${c.dim}— OUTSIDE this repo (core.hooksPath).` + + ` Hooks fire, but deleting that directory silently removes the gate.${c.reset}` + + `\n ${c.dim}keep the floor in the repo with:${c.reset} git config --unset core.hooksPath`, + ); + } + + // Per-hook test recipe. Every hook used to print secret-scan's, which tells you to stage a + // credential and commit — advice that exercises nothing for a pre-push or post-merge gate. + console.log(`\n${c.dim}${TEST_HINTS[name]}${c.reset}\n`); return true; } +/** How to actually exercise each built-in hook, so the hint matches the hook. */ +const TEST_HINTS: Record = { + "secret-scan": `Test: stage a file containing sk_${"test"}_${"A".repeat(20)} and run git commit — the commit should be blocked.`, + "post-pull-audit": + "Test: merge or pull a branch that adds a dependency — the audit runs after the merge and reports new deps, gitignore drops and introduced secrets.", + "context-check": + "Test: temporarily change one value in [context] (e.g. github.org) and run `kit context check` — it must exit 1 naming the mismatch. Restore it afterwards.", +}; + +/** + * The directory the install will actually write to — `resolveHooksDir()`, not + * `/.git/hooks`. The already-installed pre-check below reads this; when it hardcoded + * `.git/hooks` and `core.hooksPath` pointed elsewhere, the check looked at an empty directory + * and every run reported a fresh "installed" for a hook that was already there (#496). + */ async function ensureHooksDir(): Promise<{ hooksDir: string }> { - const { resolve } = await import("node:path"); - return { hooksDir: resolve(process.cwd(), ".git", "hooks") }; + const { resolveHooksDir } = await import("../hooks.js"); + return { hooksDir: resolveHooksDir(".git", process.cwd()) }; } diff --git a/src/fix.ts b/src/fix.ts index 4e38a98d..41e57637 100644 --- a/src/fix.ts +++ b/src/fix.ts @@ -208,8 +208,11 @@ export async function cmdFix(cwd: string = process.cwd()): Promise { // Tool installs go through mise into $HOME — infrastructure provisioning the // project [scope] RoE does not govern (mirrors the MCP kit_fix site's // `infrastructure: true`). Git-hook installs resolve their target via - // `core.hooksPath` at runtime; they land inside the repo, which the - // repo-rooted [scope].fs covers. + // `core.hooksPath` at runtime. They land inside the repo ONLY when hooksPath is unset or + // repo-relative: an absolute hooksPath pointing at another checkout puts the write + // outside the repo, i.e. outside what a repo-rooted [scope].fs covers (measured in #496). + // `kit check`'s "git hook floor" row reports that case; declaring the resolved directory + // here would need a dynamic scopeNeeds, which this static declaration cannot express. scopeNeeds: { fsWrites: ["skills-lock.json", "cli-lock.json", ".env.template", ".gitignore"], }, diff --git a/src/flag-surface.ts b/src/flag-surface.ts index 28e3304c..ee3d6e9e 100644 --- a/src/flag-surface.ts +++ b/src/flag-surface.ts @@ -44,6 +44,7 @@ export const COMMAND_FLAGS: Record = { "--fail-on-worse", "--fix", "--fly-app", + "--force", "--force-history", "--from", "--github-repo", @@ -180,7 +181,7 @@ export const COMMAND_FLAGS: Record = { "--yes", ], config: ["--check", "--dry-run", "--force", "--help", "--json"], - context: ["--format", "--json", "--prompt"], + context: ["--format", "--json", "--prompt", "--require-declaration"], coverage: [ "--attest", "--claude", @@ -224,6 +225,7 @@ export const COMMAND_FLAGS: Record = { "--fail-on-worse", "--fix", "--fly-app", + "--force", "--force-history", "--from", "--github-repo", @@ -279,7 +281,7 @@ export const COMMAND_FLAGS: Record = { "guard-observe": ["--all", "--allow-scripts-pending", "--call", "--dry-run", "--help", "--with"], heal: ["--agent", "--dry-run", "--help"], health: ["--attest", "--json", "--mode", "--no-auto-install", "--non-interactive"], - hooks: ["--non-interactive"], + hooks: ["--force", "--non-interactive"], identity: ["--public"], ingest: ["--attest", "--json", "--mode", "--no-auto-install", "--non-interactive"], init: [ @@ -293,6 +295,7 @@ export const COMMAND_FLAGS: Record = { "--fail-on-worse", "--fix", "--fly-app", + "--force", "--force-history", "--from", "--github-repo", @@ -526,6 +529,7 @@ export const COMMAND_FLAGS: Record = { "--fail-on-worse", "--fix", "--fly-app", + "--force", "--force-history", "--from", "--github-repo", diff --git a/src/hook-floor.test.ts b/src/hook-floor.test.ts new file mode 100644 index 00000000..343cb829 --- /dev/null +++ b/src/hook-floor.test.ts @@ -0,0 +1,297 @@ +/** + * The git-hook floor has to report where it is and whether it can fail. + * + * Both properties were measured missing (#496, #497), and both failure modes are silent, so the + * tests drive the real thing: temp repos with a real `core.hooksPath`, real generated hooks, and + * the compiled CLI for the paths an operator actually types. + * + * The measurement that produced #496: a second checkout copied from the first inherits the + * first's ABSOLUTE `core.hooksPath`, so its hooks live in the other clone's tree. Deleting that + * unrelated directory removed the gate — a staged fake credential that had been blocked + * committed cleanly afterwards, exit 0, with every kit report silent. #497: `kit hooks add + * context-check` installed a pre-push gate that, with no `[context]` block, passes every push. + */ + +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, mkdirSync, writeFileSync, realpathSync } from "node:fs"; +import { execFile, execFileSync } from "node:child_process"; +import { promisify } from "node:util"; +import { tmpdir } from "node:os"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describeHookFloor, judgeHookFloor, type HookFloorReport } from "./hook-floor.js"; + +const exec = promisify(execFile); +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "cli.js"); + +/** A generated-looking kit hook body, matching what installHooks writes. */ +const kitHook = (command: string): string => + ["#!/bin/sh", "# Generated by kit", "# Hook: test", `"$HOME/.kit/bin/kit" ${command}`, ""].join( + "\n", + ); + +function git(cwd: string, ...args: string[]): void { + execFileSync("git", ["-C", cwd, ...args], { stdio: "ignore" }); +} + +describe("hook floor — describeHookFloor", () => { + let dirs: string[] = []; + const repo = (): string => { + const d = realpathSync(mkdtempSync(join(tmpdir(), "kit-floor-"))); + dirs.push(d); + execFileSync("git", ["init", "-q", d], { stdio: "ignore" }); + return d; + }; + + beforeEach(() => { + dirs = []; + }); + afterEach(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); + }); + + it("reports the repo-local floor and the kit hooks in it", () => { + const r = repo(); + writeFileSync(join(r, ".git", "hooks", "pre-commit"), kitHook("security scan-staged")); + const f = describeHookFloor(r); + assert.equal(f.external, false); + assert.equal(f.exists, true); + assert.equal(f.hooksPath, undefined); + assert.deepEqual(f.installed, ["secret-scan"]); + assert.deepEqual(f.unarmed, []); + }); + + it("does not claim a hand-written hook as kit's floor", () => { + const r = repo(); + writeFileSync(join(r, ".git", "hooks", "pre-commit"), "#!/bin/sh\nnpm test\n"); + assert.deepEqual(describeHookFloor(r).installed, []); + }); + + it("reports a floor that resolves OUTSIDE the repo", () => { + const r = repo(); + const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), "kit-floor-other-"))); + dirs.push(elsewhere); + mkdirSync(join(elsewhere, "hooks")); + writeFileSync(join(elsewhere, "hooks", "pre-commit"), kitHook("security scan-staged")); + git(r, "config", "core.hooksPath", join(elsewhere, "hooks")); + + const f = describeHookFloor(r); + assert.equal(f.external, true, "a hooks dir in another tree is external"); + assert.equal(f.dir, join(elsewhere, "hooks")); + assert.equal(f.hooksPath, join(elsewhere, "hooks")); + assert.deepEqual(f.installed, ["secret-scan"]); + + const v = judgeHookFloor(f); + assert.equal(v.status, "warn"); + assert.match(v.detail, /OUTSIDE/); + assert.match(v.detail, /silently removes the gate/); + }); + + it("a repo-relative hooksPath inside the repo is NOT external (the husky/.githooks case)", () => { + const r = repo(); + mkdirSync(join(r, ".githooks")); + writeFileSync(join(r, ".githooks", "pre-commit"), kitHook("security scan-staged")); + git(r, "config", "core.hooksPath", ".githooks"); + + const f = describeHookFloor(r); + assert.equal(f.external, false); + assert.equal(f.exists, true); + assert.equal(judgeHookFloor(f).status, "pass"); + }); + + it("a hooksPath pointing at a deleted directory means every hook is OFF", () => { + const r = repo(); + const gone = join(tmpdir(), "kit-floor-deleted-does-not-exist", "hooks"); + git(r, "config", "core.hooksPath", gone); + + const f = describeHookFloor(r); + assert.equal(f.exists, false); + assert.deepEqual(f.installed, [], "nothing can be installed in a directory that is gone"); + + const v = judgeHookFloor(f); + assert.equal(v.status, "fail"); + assert.equal(v.severity, "high"); + assert.match(v.detail, /does not exist — every git hook is OFF/); + }); + + it("context-check with no [context] block is reported as unarmed", () => { + const r = repo(); + writeFileSync(join(r, ".git", "hooks", "pre-push"), kitHook("context check")); + const f = describeHookFloor(r, undefined); + assert.deepEqual(f.installed, ["context-check"]); + assert.deepEqual(f.unarmed, ["context-check"]); + + const v = judgeHookFloor(f); + assert.equal(v.status, "fail"); + assert.match(v.detail, /cannot fail/); + }); + + it("context-check with a [context] block is armed", () => { + const r = repo(); + writeFileSync(join(r, ".git", "hooks", "pre-push"), kitHook("context check")); + const f = describeHookFloor(r, { context: { github: { org: "acme" } } }); + assert.deepEqual(f.unarmed, []); + assert.equal(judgeHookFloor(f).status, "pass"); + }); +}); + +describe("hook floor — judgeHookFloor policy", () => { + const base: HookFloorReport = { + dir: "/repo/.git/hooks", + external: false, + exists: true, + installed: [], + unarmed: [], + }; + + it("skips when the repo has no kit-managed hooks — no floor is claimed", () => { + const v = judgeHookFloor(base); + assert.equal(v.status, "skip"); + assert.equal(v.severity, undefined); + }); + + it("ranks a dangling hooksPath above everything else", () => { + const v = judgeHookFloor({ + ...base, + hooksPath: "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/gone/hooks", + dir: "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/gone/hooks", + exists: false, + external: true, + installed: ["secret-scan"], + unarmed: ["context-check"], + }); + assert.equal(v.status, "fail"); + assert.match(v.detail, /does not exist/); + }); + + it("ranks an unarmed gate above an external location", () => { + const v = judgeHookFloor({ + ...base, + external: true, + hooksPath: "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/other/hooks", + installed: ["context-check"], + unarmed: ["context-check"], + }); + assert.equal(v.status, "fail"); + assert.match(v.detail, /cannot fail/); + }); + + it("passes with the hooks named, so the report says what is actually wired", () => { + const v = judgeHookFloor({ ...base, installed: ["secret-scan", "post-pull-audit"] }); + assert.equal(v.status, "pass"); + assert.match(v.detail, /secret-scan, post-pull-audit/); + }); +}); + +describe("hook floor — compiled CLI", () => { + let repoDir = ""; + let extras: string[] = []; + + const runCli = async ( + args: string[], + cwd: string, + ): Promise<{ exitCode: number; stdout: string; stderr: string }> => { + try { + const { stdout, stderr } = await exec(process.execPath, [CLI_PATH, ...args], { + cwd, + env: { ...process.env, KIT_HIDE_HOOK_SKIP_BANNER: "1", KIT_AUDIT_ANCHOR: "0" }, + timeout: 60_000, + }); + return { exitCode: 0, stdout: stdout ?? "", stderr: stderr ?? "" }; + } catch (err: unknown) { + const e = err as { code?: number; stdout?: string; stderr?: string }; + return { + exitCode: typeof e.code === "number" ? e.code : 1, + stdout: e.stdout ?? "", + stderr: e.stderr ?? "", + }; + } + }; + + beforeEach(() => { + repoDir = realpathSync(mkdtempSync(join(tmpdir(), "kit-floor-cli-"))); + extras = []; + execFileSync("git", ["init", "-q", repoDir], { stdio: "ignore" }); + writeFileSync(join(repoDir, ".kit.toml"), '[tools]\nnode = "22"\n'); + }); + afterEach(() => { + rmSync(repoDir, { recursive: true, force: true }); + for (const d of extras) rmSync(d, { recursive: true, force: true }); + }); + + it("refuses to install context-check with no [context] — a gate that cannot fail", async () => { + const r = await runCli(["hooks", "add", "context-check", "--non-interactive"], repoDir); + assert.equal(r.exitCode, 1); + assert.match(r.stderr, /refusing to install context-check/); + assert.match(r.stderr, /kit context check/); + assert.equal(describeHookFloor(repoDir).installed.length, 0, "nothing was installed"); + }); + + it("--force installs it anyway, for someone about to declare the block", async () => { + const r = await runCli( + ["hooks", "add", "context-check", "--force", "--non-interactive"], + repoDir, + ); + assert.equal(r.exitCode, 0, r.stderr); + assert.deepEqual(describeHookFloor(repoDir).installed, ["context-check"]); + }); + + it("prints a test hint for the hook it installed, not secret-scan's for everything", async () => { + const secret = await runCli(["hooks", "add", "secret-scan", "--non-interactive"], repoDir); + assert.match(secret.stdout, /stage a file containing sk_test/); + + const merge = await runCli(["hooks", "add", "post-pull-audit", "--non-interactive"], repoDir); + assert.match(merge.stdout, /merge or pull a branch/); + assert.doesNotMatch(merge.stdout, /stage a file containing sk_test/); + }); + + it("names the directory when the floor lands outside the repo", async () => { + const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), "kit-floor-ext-"))); + extras.push(elsewhere); + mkdirSync(join(elsewhere, "hooks")); + execFileSync("git", ["-C", repoDir, "config", "core.hooksPath", join(elsewhere, "hooks")], { + stdio: "ignore", + }); + + const r = await runCli(["hooks", "add", "secret-scan", "--non-interactive"], repoDir); + assert.equal(r.exitCode, 0, r.stderr); + assert.match(r.stdout, /OUTSIDE this repo/); + assert.match(r.stdout, new RegExp(elsewhere.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(r.stdout, /git config --unset core\.hooksPath/); + }); + + it("the security gate reports the floor instead of staying silent", async () => { + writeFileSync(join(repoDir, ".git", "hooks", "pre-push"), kitHook("context check")); + const r = await runCli(["check", "--category", "security", "--json"], repoDir); + const rows = JSON.parse(r.stdout) as { + checks?: Array<{ name: string; status: string; detail: string }>; + }; + const row = (rows.checks ?? []).find((x) => x.name === "git hook floor"); + assert.ok(row, "kit check must have a git hook floor row"); + assert.equal(row.status, "fail"); + assert.match(row.detail, /cannot fail/); + }); + + it("an installed hook in an external dir is not reported as missing (reader/writer agree)", async () => { + const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), "kit-floor-agree-"))); + extras.push(elsewhere); + mkdirSync(join(elsewhere, "hooks")); + execFileSync("git", ["-C", repoDir, "config", "core.hooksPath", join(elsewhere, "hooks")], { + stdio: "ignore", + }); + writeFileSync( + join(repoDir, ".kit.toml"), + '[tools]\nnode = "22"\n\n[hooks]\npre-commit = ["kit security scan-staged"]\n', + ); + + const install = await runCli(["hooks", "install", "--non-interactive"], repoDir); + assert.equal(install.exitCode, 0, install.stderr); + + // Before the fix the status reader looked at /.git/hooks — empty — and called an + // installed, firing hook missing. + const status = await runCli(["hooks"], repoDir); + assert.doesNotMatch(status.stdout + status.stderr, /missing/i); + }); +}); diff --git a/src/hook-floor.ts b/src/hook-floor.ts new file mode 100644 index 00000000..9ada2947 --- /dev/null +++ b/src/hook-floor.ts @@ -0,0 +1,184 @@ +/** + * Where kit's git-hook enforcement floor actually is, and whether it can fail. + * + * README calls git hooks "the agent-agnostic enforcement floor" — the one that fires in any + * agent or none. Two properties of that floor were unreported, and both were measured (#496, + * #497): + * + * 1. **Location.** `resolveHooksDir()` honors `core.hooksPath`, which is right: installing into + * `.git/hooks` while git reads elsewhere is a silent no-op. But only the WRITER used it. Two + * readers — `check-hooks.ts:checkHooks` and `commands/hooks.ts`'s own already-installed + * pre-check — hardcoded `/hooks`, so with an external `core.hooksPath` kit installed + * to one directory and reported on another. That disagreement is the root defect; this module + * plus those two call-site fixes close it. + * + * Measured consequence: a second checkout made by copying the first inherits the first's + * ABSOLUTE `core.hooksPath`, so its hooks live in the other clone's tree. Deleting that + * unrelated directory removed the gate — the same staged fake credential that was blocked + * before committed cleanly afterwards, exit 0, with every kit report still silent. + * + * 2. **Armed or not.** `kit hooks add context-check` installed a pre-push hook that, with no + * `[context]` block to compare against, passed unconditionally. `✓ installed` for a gate that + * cannot fail is the false green kit exists to refuse. + * + * The rule this module applies is kit's own: coverage that could not run is UNKNOWN, never + * clean. A floor that is external is fragile, a floor whose directory is gone is off, and an + * installed gate with nothing to check is not a gate. + */ + +import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { resolve, sep } from "node:path"; +import { resolveHooksDir } from "./hooks.js"; +import type { kitConfig } from "./config.js"; + +/** The kit-managed built-in hooks, keyed by the git hook file they install into. */ +export const BUILTIN_HOOK_FILES: Record = { + "pre-commit": { name: "secret-scan", command: "security scan-staged" }, + "post-merge": { name: "post-pull-audit", command: "security verify-pull" }, + "pre-push": { name: "context-check", command: "context check" }, +}; + +export interface HookFloorReport { + /** The directory git will actually run hooks from. */ + dir: string; + /** `core.hooksPath` when set — the reason `dir` may not be `/.git/hooks`. */ + hooksPath?: string; + /** True when `dir` is not inside the repo root: the floor lives outside the repo. */ + external: boolean; + /** False when `dir` does not exist. Every hook is then off, whatever is declared. */ + exists: boolean; + /** Built-in hooks found installed in `dir` (by kit-managed marker), e.g. ["secret-scan"]. */ + installed: string[]; + /** + * Installed hooks that cannot fail as configured. Today: `context-check` with no `[context]` + * block — nothing to compare the live CLI state against, so the push gate always passes. + */ + unarmed: string[]; +} + +/** Is `child` inside `parent`? Realpath-free: callers pass already-resolved paths. */ +function isInside(parent: string, child: string): boolean { + const p = parent.endsWith(sep) ? parent : parent + sep; + return child === parent || child.startsWith(p); +} + +/** + * Describe the floor for one repo. Pure w.r.t. its inputs (`cwd`, config) apart from reading + * the filesystem and git config, so every branch is reachable in a test with a temp repo. + */ +export function describeHookFloor(cwd = process.cwd(), config?: kitConfig): HookFloorReport { + const repoRoot = resolve(cwd); + const dir = resolve(resolveHooksDir(".git", repoRoot)); + let hooksPath: string | undefined; + try { + // Read it directly rather than inferring from `dir`: "hooksPath set to the default" and + // "hooksPath unset" resolve identically but are different states to report. + const raw = execFileSync("git", ["-C", repoRoot, "config", "--get", "core.hooksPath"], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + if (raw) hooksPath = raw; + } catch { + /* not a repo, unset, or git absent — leave undefined */ + } + + const exists = existsSync(dir); + const installed: string[] = []; + if (exists) { + let entries: string[] = []; + try { + entries = readdirSync(dir); + } catch { + entries = []; + } + for (const [file, builtin] of Object.entries(BUILTIN_HOOK_FILES)) { + if (!entries.includes(file)) continue; + let body = ""; + try { + body = readFileSync(resolve(dir, file), "utf-8"); + } catch { + continue; + } + // "kit-managed" = the generated marker plus the command it was installed for. A + // hand-written pre-commit that happens to exist is not kit's floor and is not claimed. + if (body.includes("Generated by kit") && body.includes(builtin.command)) { + installed.push(builtin.name); + } + } + } + + const unarmed: string[] = []; + if (installed.includes("context-check") && !config?.context) unarmed.push("context-check"); + + return { + dir, + hooksPath, + external: !isInside(repoRoot, dir), + exists, + installed: installed.sort(), + unarmed, + }; +} + +export interface HookFloorVerdict { + status: "pass" | "warn" | "fail" | "skip"; + severity?: "low" | "medium" | "high"; + detail: string; +} + +/** + * Turn a floor report into a verdict. Exported separately so the policy is one testable + * decision rather than prose spread across two commands. + * + * Ordering is by what an operator must do about it: a gone directory means the floor is OFF, an + * unarmed gate means it cannot fail, an external floor means it can be removed from outside the + * repo. Nothing installed and nothing configured is a skip, not a pass — kit does not claim a + * floor a repo never asked for. + */ +export function judgeHookFloor(report: HookFloorReport): HookFloorVerdict { + const where = report.hooksPath ? `${report.dir} (core.hooksPath)` : report.dir; + + if (report.hooksPath && !report.exists) { + return { + status: "fail", + severity: "high", + detail: + `core.hooksPath points at ${report.dir}, which does not exist — every git hook is OFF, ` + + `including any kit installed. Unset it (git config --unset core.hooksPath) and re-run ` + + `'kit hooks add ', or recreate the directory.`, + }; + } + if (report.installed.length === 0) { + return { + status: "skip", + detail: report.hooksPath + ? `no kit-managed git hooks in ${where}` + : "no kit-managed git hooks installed here", + }; + } + if (report.unarmed.length > 0) { + return { + status: "fail", + severity: "high", + detail: + `${report.unarmed.join(", ")} is installed but cannot fail: no [context] block in .kit.toml, ` + + `so the pre-push check has nothing to compare the live CLI state against. Declare one ` + + `('kit context check' prints a starting point) or remove the hook.`, + }; + } + if (report.external) { + return { + status: "warn", + severity: "medium", + detail: + `the git-hook floor for this repo lives OUTSIDE it, in ${report.dir} (core.hooksPath). ` + + `Hooks fire, but deleting or moving that directory silently removes the gate. ` + + `Unset core.hooksPath to keep the floor inside the repo.`, + }; + } + return { + status: "pass", + detail: `${report.installed.length} kit hook(s) wired in ${where}: ${report.installed.join(", ")}`, + }; +} From 77f1cc731d10fcfa455c8692ae19f45c30baca9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= Date: Thu, 20 Aug 2026 12:26:06 +0200 Subject: [PATCH 2/2] fix(lint): drop the redundant initializers eslint's no-useless-assignment flags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's Lint step (inside build-and-test) tolerates warnings but not errors, and these two were errors. `npm run lint` locally reported them too — I had checked before the file existed. --- src/hook-floor.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/hook-floor.ts b/src/hook-floor.ts index 9ada2947..7321bb16 100644 --- a/src/hook-floor.ts +++ b/src/hook-floor.ts @@ -86,15 +86,16 @@ export function describeHookFloor(cwd = process.cwd(), config?: kitConfig): Hook const exists = existsSync(dir); const installed: string[] = []; if (exists) { - let entries: string[] = []; + let entries: string[]; try { entries = readdirSync(dir); } catch { + // Unreadable hooks dir: report nothing installed rather than guessing. entries = []; } for (const [file, builtin] of Object.entries(BUILTIN_HOOK_FILES)) { if (!entries.includes(file)) continue; - let body = ""; + let body: string; try { body = readFileSync(resolve(dir, file), "utf-8"); } catch {