diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a43c072..d2f780d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,52 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Added + +- **`self-audit` now checks documentation in both directions.** The existing docs-claims + rules prove no doc names something kit lacks; they are structurally incapable of catching + the reverse, because an undocumented command has no doc reference to check. The new + `undocumented commands` rule closes that half: every human-facing command must appear in + at least one non-exempt doc, in invocable form. It found 13 — `kit broker` and its two + subcommands, all seven `kit profile` subcommands, `kit insight`, `kit memory context`, + and `kit hooks uninstall`, the off-switch for the git-hook enforcement floor, whose + installers were documented while it was not. + + The oracle is the **union** of two sources, because each alone hides a real gap: the + committed contract lists top-level verbs and no subcommands (so it cannot see + `kit hooks uninstall`), while `COMMAND_HELP` lists subcommands but omits some top-level + verbs (so it cannot see `kit insight`). Measured: contract-only reported 1 gap, + help-only reported 9, neither a superset of the other. `x-kit-audience: "harness"` verbs + — the `gate-*` commands invoked by hook wiring, never typed by a human — are excluded, + and that exclusion is read from the contract rather than hardcoded, so a new gate verb + inherits it. Brace form counts, so `kit hooks {install,add,sync}` documents each member. + + **Known limit:** the same inverse check is not possible for flags. No machine-readable + inventory of the flags kit *accepts* exists — `contracts/kit.opencli.json` carries + `x-kit-args-modeled: false` on all 71 commands, and the flag oracle used by the forward + rule is a scrape of source literals that also contains flags kit passes to subprocesses + (`--severity` for trivy, `--name-only` for git). Answering "which flags are + undocumented" needs argument modeling in the contract first. + +### Fixed + +- **A third test that reported a verdict its environment could not support.** The + `writeCheckDetail` failed-write test forced its precondition with `chmod 0o500` without + checking whether the mode denied *this* process — root mkdirs straight through it, so the + failure path was never exercised and the test reported a working write path as broken. It + now probes with a real `mkdir` and skips loudly when the mode does not deny, the same + guard applied to the WAL-sidecar test in 6.6.3. Verified pre-existing on a clean tree + before touching it. + +### Documentation + +- **The 13 commands above are now in `docs/COMMANDS.md`**, with two new sections — + exec-broker runtime posture (`broker enforce-readiness` / `enforce`) and the traveling + profile (`profile show/freeze/check/sign/verify/export/import`) — plus `kit hooks + uninstall`, `kit memory context` and `kit insight` in the tables they belong to. Text is + taken from each command's own help string rather than written from the outside. + + ## [6.6.5] - 2026-08-19 ### Changed diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index e1343366..63be6be4 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -176,6 +176,7 @@ required = ["NEXT_PUBLIC_SENTRY_DSN", "NEXT_PUBLIC_SENTRY_ENVIRONMENT"] | `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 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. | ## Agent Config User Rules @@ -292,12 +293,38 @@ fixture credentials at run time) so nothing new accumulates. | `kit team member remove ` | Remove a team member. | | `kit team audit log [--limit=]` | View team audit logs. | +## Exec-broker runtime posture + +Graduating the exec-broker from observe to enforce is evidence-driven: the readiness verdict is +computed from the recorded observe window, and the flip refuses unless that verdict says `ready`. + +| Command | Purpose | +| ------- | ------- | +| `kit broker enforce-readiness [--gate]` | Read the recorded observe window (`.kit-audit.jsonl`) and report whether flipping to enforce is safe: `ready` \| `would-block` (+ exactly what breaks) \| `untested`. `--gate` fails CI on any not-ready verdict. | +| `kit broker enforce [--force]` | Guided observe→enforce flip: readiness pre-flight (refuses unless `ready`; `--force` overrides), sets `[scope].enforce_runtime = true`, re-signs the profile scope, and audits the transition. | + +## Traveling profile + +The declared project profile (`.kit-profile.toml`) plus an offline-verifiable signature over its +scope/RoE, so a profile can move to a fresh host without trusting the transport. + +| Command | Purpose | +| ------- | ------- | +| `kit profile show` | Render the declared profile with per-line reconciliation marks. | +| `kit profile freeze` | Snapshot the discovered toolchain into `.kit-profile.toml` (preserves operator-authored workflows/plugins/scope/gates). | +| `kit profile check [--gate]` | Report declared-vs-discovered drift. `--gate` fails CI on any drift; honest skip when no profile is declared. | +| `kit profile sign` | Sign the profile (scope/RoE) into `.kit-profile.sig` via your identity/keystore — offline-verifiable. | +| `kit profile verify [--key ]` | Verify `.kit-profile.sig` offline: `--key` pin → local identity → org `.kit-policy.signers`. | +| `kit profile export [--out ]` | Export a portable signed bundle (profile + signature + signer key) to `--out` or stdout. | +| `kit profile import ` | Import a bundle on a fresh host — integrity-verified offline, fail-closed on tamper/revoked. Authoritative only once the signer is anchored. | + ## Misc | Command | Purpose | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `kit open ` | Open service dashboard in browser (stripe, vercel, etc.). | | `kit run ` | Arbitrary command runner (audit-logged). | +| `kit insight [--json]` | Deterministic lifecycle insight — what is loaded but never called (e.g. MCP servers), from the transcript index. Experimental. | | `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. | @@ -339,6 +366,7 @@ Local-first second brain — SQLite + FTS5, deterministic, zero model calls. Ful | `kit memory pal [list\|add\|done\|snooze\|verify\|import]` | Pending-action ledger; auto-closes on verify. Project-scoped (`--global` for all). | | `kit memory save ` / `threads` / `resume ` / `forget ` | Named copilots — bookmark + resume sessions; `resume` prints the Claude or Codex command for the saved harness. | | `kit memory share …` / `areas` / `area ` | Shared, area-organized team memory (committed, secret-scanned, reviewed like code). | +| `kit memory context` | Push-surface the active decisions for the area(s) whose files you are touching (deterministic, path→cluster). | ## Exit codes diff --git a/src/check-detail-store.test.ts b/src/check-detail-store.test.ts index 8319b648..673e7a98 100644 --- a/src/check-detail-store.test.ts +++ b/src/check-detail-store.test.ts @@ -27,12 +27,29 @@ describe("writeCheckDetail", () => { assert.equal(ref.path, join(cwd, RUNS_DIR, "check-1000.json")); }); - it("returns null instead of a dangling reference when the write fails", () => { + it("returns null instead of a dangling reference when the write fails", (t) => { const cwd = tmpProject(); // A .kit that cannot be written into: mkdir of .kit/runs fails, so there is no file. mkdirSync(join(cwd, ".kit")); chmodSync(join(cwd, ".kit"), 0o500); try { + // The mode bits are the INTENT; whether they deny THIS process is a separate fact. + // root carries CAP_DAC_OVERRIDE and mkdirs straight through 0500, so without this + // probe the precondition silently does not exist and the test reports a working + // write path as a broken one. Same guard, same reason, as the WAL-sidecar test in + // check-security.test.ts: a check that could not run must not report a verdict. + let denied = false; + try { + mkdirSync(join(cwd, ".kit", ".write-probe")); + } catch { + denied = true; + } + if (!denied) { + t.skip( + "0500 does not deny writes to this process (running as root?) — the failed-write path is NOT verified in this run", + ); + return; + } assert.equal(writeCheckDetail(cwd, { ok: true }, 1000), null); } finally { chmodSync(join(cwd, ".kit"), 0o700); diff --git a/src/self-audit-docs.test.ts b/src/self-audit-docs.test.ts index f8dd46d0..7f4c20dc 100644 --- a/src/self-audit-docs.test.ts +++ b/src/self-audit-docs.test.ts @@ -15,6 +15,8 @@ import { docExemption, loadContractVerbs, runDocsClaimsAudit, + undocumentedCommands, + loadCommandSurface, PRE_DISPATCH_VERBS, } from "./self-audit-docs.js"; import { COMMANDS, COMMAND_HELP } from "./cli.js"; @@ -171,6 +173,7 @@ describe("self-audit-docs — runDocsClaimsAudit", () => { "documented flags", "documented config sections", "documented env vars", + "undocumented commands", ], ); // The synthetic repo has no src/commands, so coverage reports a single pass. @@ -253,7 +256,12 @@ describe("self-audit-docs — runDocsClaimsAudit", () => { }); try { const res = runDocsClaimsAudit(root); - assert.equal(res[0].status, "pass", res[0].detail); + // By name, not by position: this test is about node_modules being skipped, and a + // positional assertion made it fail when an unrelated row was added first. + const flags = res.find((r) => r.category === "self-audit/flag-validation")!; + assert.equal(flags.status, "pass", flags.detail); + const cmds = res.find((r) => r.name === "documented commands")!; + assert.equal(cmds.status, "pass", cmds.detail); } finally { rmSync(root, { recursive: true, force: true }); } @@ -576,3 +584,134 @@ describe("self-audit-docs — loadKnownEnvVars", () => { assert.ok(known.has("KIT_REQUIRE_HARDWARE_IDENTITY")); }); }); + +/** + * The INVERSE gate. Its siblings prove no doc names something kit lacks; these prove kit + * ships nothing a reader cannot find. The distinction matters because the forward gate is + * structurally incapable of catching this class: an undocumented command has, by + * definition, no doc reference to check. + */ +describe("self-audit-docs — undocumentedCommands (the inverse gate)", () => { + const CONTRACT_WITH_HARNESS = JSON.stringify({ + opencliVersion: "0.1", + commands: { + check: { kind: "command", "x-kit-audience": "all" }, + "gate-fs": { kind: "command", "x-kit-audience": "harness" }, + }, + }); + + it("passes when every human-facing command appears in a doc", () => { + const root = makeRepo({ + "contracts/kit.opencli.json": CONTRACT, + "README.md": "Run `kit check` then `kit fix`.", + }); + try { + const r = undocumentedCommands(root); + assert.equal(r.status, "pass"); + assert.match(r.detail, /all 2 human-facing command\(s\)/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("FAILS naming a command that exists but no doc mentions", () => { + const root = makeRepo({ + "contracts/kit.opencli.json": CONTRACT, + "README.md": "Run `kit check`.", // `kit fix` deliberately absent + }); + try { + const r = undocumentedCommands(root); + assert.equal(r.status, "fail"); + assert.match(r.detail, /kit fix/); + assert.match(r.detail, /1 of 2/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("counts the brace form, so the repo's own house style is not 40 false gaps", () => { + // `kit hooks {install,add,sync}` is how README documents a subcommand family. A + // literal-only matcher would report every one of them as undocumented. + const root = makeRepo({ + "contracts/kit.opencli.json": JSON.stringify({ + opencliVersion: "0.1", + commands: { hooks: { kind: "command", "x-kit-audience": "human" } }, + }), + "src/cli.ts": + 'const COMMAND_HELP = {\n "hooks install": "x",\n "hooks uninstall": "y",\n};', + "README.md": "Use `kit hooks {install,uninstall}` to manage them.", + }); + try { + assert.equal(undocumentedCommands(root).status, "pass"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("excludes harness-audience commands, read from the contract not a hardcoded list", () => { + // `gate-fs` is invoked by hook wiring, never typed by a human. Requiring it in human + // docs would manufacture busywork; the exclusion has to come from the contract so a + // newly added gate verb inherits it without editing this rule. + const root = makeRepo({ + "contracts/kit.opencli.json": CONTRACT_WITH_HARNESS, + "README.md": "Run `kit check`.", // gate-fs deliberately undocumented + }); + try { + const r = undocumentedCommands(root); + assert.equal(r.status, "pass"); + assert.match(r.detail, /1 harness-audience excluded/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("sees a SUBCOMMAND the contract cannot express — the union oracle's whole point", () => { + // Measured on the real tree: the contract lists top-level verbs only, so a + // contract-only oracle reported 1 gap while the help-map oracle reported 9, and + // neither was a superset. `kit hooks uninstall` — an enforcement off-switch — is + // invisible to the contract alone. + const root = makeRepo({ + "contracts/kit.opencli.json": JSON.stringify({ + opencliVersion: "0.1", + commands: { hooks: { kind: "command", "x-kit-audience": "human" } }, + }), + "src/cli.ts": 'const COMMAND_HELP = {\n "hooks uninstall": "Remove the hooks",\n};', + "README.md": "Use `kit hooks` for git hooks.", + }); + try { + const r = undocumentedCommands(root); + assert.equal(r.status, "fail"); + assert.match(r.detail, /kit hooks uninstall/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("cannot verify => didNotRun, rather than a green with no oracle", () => { + const root = makeRepo({ "README.md": "no contract, no cli.ts" }); + try { + const r = undocumentedCommands(root); + assert.equal(r.status, "warn"); + assert.equal(r.didNotRun, true); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("loadCommandSurface unions both oracles and marks harness verbs", () => { + const root = makeRepo({ + "contracts/kit.opencli.json": CONTRACT_WITH_HARNESS, + "src/cli.ts": 'const COMMAND_HELP = {\n "check --json": "x",\n "memory context": "y",\n};', + }); + try { + const s = loadCommandSurface(root); + const verbs = s.map((c) => c.verb); + assert.ok(verbs.includes("check"), "contract verb present"); + assert.ok(verbs.includes("memory context"), "help-map subcommand present"); + assert.equal(s.find((c) => c.verb === "gate-fs")?.harness, true); + assert.equal(s.find((c) => c.verb === "check")?.harness, false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/self-audit-docs.ts b/src/self-audit-docs.ts index 6c090974..71ade494 100644 --- a/src/self-audit-docs.ts +++ b/src/self-audit-docs.ts @@ -455,6 +455,136 @@ const CLAIM_CLASSES: ClaimClass[] = [ * and counted, so a pass line states what was actually verified rather than implying * full coverage. */ +/** + * The complete set of commands kit CLAIMS TO HAVE — the union of two oracles, because + * each alone has a blind spot that hides a real gap: + * + * - `contracts/kit.opencli.json` lists 71 top-level verbs and NO subcommands, so on its + * own it cannot see that `kit hooks uninstall` is undocumented. + * - `COMMAND_HELP` in cli.ts lists subcommands but omits some top-level verbs, so on its + * own it cannot see that `kit insight` is undocumented. + * + * Measured: the contract-only view reported 1 gap, the help-only view reported 9, and + * neither was a superset of the other. A union is the only honest oracle here. + * + * `x-kit-audience: "harness"` verbs are EXCLUDED, and that exclusion is read from the + * contract rather than hardcoded: `gate-bash`, `gate-env`, `gate-fs` and `gate-egress` are + * invoked by hook wiring, never typed by a human, so requiring them in human documentation + * would manufacture busywork rather than catch anything. + */ +export function loadCommandSurface(repoRoot: string): { verb: string; harness: boolean }[] { + const out = new Map(); + let contract: Record = {}; + try { + const raw = readFileSync(join(repoRoot, CONTRACT_PATH), "utf-8"); + const parsed: unknown = JSON.parse(raw); + const commands = (parsed as { commands?: unknown })?.commands; + if (commands && typeof commands === "object") { + contract = commands as Record; + } + } catch { + contract = {}; + } + const isHarness = (verb: string): boolean => + contract[verb.split(" ")[0]]?.["x-kit-audience"] === "harness"; + + for (const verb of Object.keys(contract)) out.set(verb, isHarness(verb)); + + // COMMAND_HELP keys, read as text so this stays a static audit with no import cycle. + try { + const cli = readFileSync(join(repoRoot, "src/cli.ts"), "utf-8"); + const block = cli.slice(cli.indexOf("COMMAND_HELP")); + for (const m of block.matchAll(/^ {2}"([a-z][a-z0-9 :._-]*)":/gm)) { + out.set(m[1], isHarness(m[1])); + } + } catch { + /* contract alone still yields a usable, smaller surface */ + } + + return [...out].map(([verb, harness]) => ({ verb, harness })); +} + +/** + * Does any doc invoke `verb`? Brace form counts: `kit hooks {install,add,sync}` documents + * `hooks install`. Without that, the repo's own house style would read as 40+ false gaps. + */ +function docsMentionCommand(corpus: string, verb: string): boolean { + if (corpus.includes(`kit ${verb}`)) return true; + const parts = verb.split(" "); + if (parts.length < 2) return false; + const sub = parts + .slice(1) + .join(" ") + .replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`kit\\s+${parts[0]}\\s*\\{[^}]*\\b${sub}\\b`).test(corpus); +} + +/** + * THE INVERSE GATE. `documented commands` proves no doc names something kit lacks; this + * proves kit ships nothing a reader cannot find. Both directions are needed for "kit is + * what kit says it is" — the existing gate could not have caught an undocumented + * enforcement off-switch, because nothing in the docs pointed at it to be checked. + * + * Requiring the invocable form (`kit profile import`) rather than a prose mention is + * deliberate and symmetric with the sibling rule, which extracts `kit ` refs: a + * command a reader cannot see how to type is not documented. + */ +export function undocumentedCommands(repoRoot: string): SecurityCheckResult { + const surface = loadCommandSurface(repoRoot); + const inScope = surface.filter((c) => !c.harness); + if (inScope.length === 0) { + return { + category: DOCS_CATEGORY, + name: "undocumented commands", + status: "warn", + severity: "medium", + detail: "could not read the command surface — coverage NOT verified", + didNotRun: true, + suggestion: "regenerate the contract (npm run build) so the inverse audit can run", + }; + } + + const corpus = findMarkdownFiles(repoRoot) + .filter((f) => !docExemption(f)) + .map((f) => { + try { + return readFileSync(join(repoRoot, f), "utf-8"); + } catch { + return ""; + } + }) + .join("\n"); + + const missing = inScope.filter((c) => !docsMentionCommand(corpus, c.verb)).map((c) => c.verb); + const harnessCount = surface.length - inScope.length; + + if (missing.length === 0) { + return { + category: DOCS_CATEGORY, + name: "undocumented commands", + status: "pass", + detail: + `all ${inScope.length} human-facing command(s) appear in the docs ` + + `(${harnessCount} harness-audience excluded)`, + }; + } + + return { + category: DOCS_CATEGORY, + name: "undocumented commands", + status: "fail", + severity: "medium", + detail: + `${missing.length} of ${inScope.length} command(s) appear in no doc: ` + + missing + .slice(0, 10) + .map((v) => `kit ${v}`) + .join(", "), + suggestion: + "document it, or mark it harness-audience in the contract if no human should type it", + }; +} + export function runDocsClaimsAudit(repoRoot: string): SecurityCheckResult[] { const verbs = loadContractVerbs(repoRoot); if (!verbs) { @@ -567,5 +697,9 @@ export function runDocsClaimsAudit(repoRoot: string): SecurityCheckResult[] { suggestion: `fix the doc, or implement it — a doc naming something kit does not have misleads humans and agents alike`, }; }), + // Appended last on purpose: `flagValidation` occupies res[0] and a test pins that + // position. Prepending this row displaced it and failed a test about node_modules + // skipping — an unrelated rule broken by an ordering assumption. + [undocumentedCommands(repoRoot)], ); }