diff --git a/CHANGELOG.md b/CHANGELOG.md index 314aee0b..bff4a4a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Added + +- **Config drift is reported, both kinds** (#511). A `.kit.toml` falls behind in two ways and + neither reached the operator. + + **Schema drift had a detector and no caller.** `kit config migrate --check` has answered + *"Config is at v0; current is v1"* since versioning landed, and `kit status` said only + `✓ .kit.toml present` — "present" is not "current". Measured on kit's own repo: the config was + v0 while the schema was v1, and nothing said so. `kit status` now carries a `config schema` row + (`○ config schema v0, current is v1 → run kit config migrate`) via a new read-only + `planConfigMigration()` that answers without a write path. + + **Feature drift had no detector at all.** A long-lived config does not know about the sections + kit has learned since — `[context]`, `[policy.agent_writes]`, `[deploy]`, + `[governance.audit] require_anchor`. `applyRecommendedHardening()` knew the recommended posture + but was reachable only from `kit setup`, which APPLIES it (touching `~/.claude`, `~/.codex` and + the repo's git hooks), so asking "what would I get?" meant letting it happen. New + `kit config recommend [--json]` reports it and writes nothing. + + Each row says what the piece **buys**, not merely that it is absent — a checklist of missing + features is how a report gets ignored. And the pre-push context gate points at declaring + `[context]` first rather than at installing a gate that cannot fail, matching the refusal added + in #497. + + Deliberately **not** a new `kit rebase` verb: `rebase` means something specific and different to + every git user, and both halves of this were a missing reader rather than a missing command. + Auto-migrating on load is also out — a config that changes shape underneath a session is worse + than one that is behind, and the schema version exists so the change is explicit and reviewable. + ### Fixed - **The machine-wide wrapper pointed at whichever kit wrote it** (#509). `~/.kit/bin/kit` is what diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 072b22bc..087b2d5c 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -55,6 +55,7 @@ through untouched (`kit run -- pnpm test --watch`). | `kit check verify-attestation [--key ] [--pin]` | Verify a check receipt. HMAC against the local anchor key is authoritative; an Ed25519 receipt's embedded key is untrusted and reports `unverified-authenticity` unless the key is pinned (TOFU in `~/.kit`) or passed via `--key`. | | `kit check compare [--json] [--fail-on-worse]` | Diff two `kit check --json` runs. **Lost coverage ranks above a regression** — a check that stopped running makes its finding *unknown*, not fixed, so `fail → skip` is never read as an improvement. Pure function of the two files; no scan is run. Reports by default; `--fail-on-worse` exits non-zero on lost coverage, a disappeared check, or a regression. | | `kit config migrate [--dry-run] [--check] [--force]` | Migrate `.kit.toml` to the current schema `version` (`CONFIG_SCHEMA_VERSION`). `--dry-run` (default) prints the plan + value diff and writes nothing; a real run backs up to `.kit.toml.backup`, re-validates, and restores on any failure; `--check` exits non-zero on a stale config (CI). v0→v1 only stamps the version (baseline no-op). | +| `kit config recommend [--json]` | The recommended posture as a **report** — what this repo would gain, writing nothing. Each row says what the piece BUYS, not merely that it is absent: memory capture, the pre-commit secret scan, the post-merge audit, `[context]`, the pre-push context check, `[policy.agent_writes]`, `[deploy]`, `[governance.audit] require_anchor`. `kit setup` applies the hook/memory pieces; the `[section]` ones are yours to declare. | | `kit coverage [--standard=\|all] [--list-standards] [--json]` | **Evidence maps** that bucket kit's checks/rules per control as auto-verified / gap / manual / n-a, across 8 pinned standards: ASVS 4.0.3 L2 (default), OWASP LLM/Agentic/MCP Top 10, NIST SSDF 800-218A, NIST 800-53 Rev. 5 (control-family level), AIUC-1, GCP WAF Security. Evidence, **not** a compliance attestation (never claims "compliant"); `--json` for GRC tools. `experimental`. | | `kit browser doctor [--json]` | Diagnose browser-verification readiness from `[browser]`, selecting project Playwright, system Chrome, CDP, or a blocker with one human action. `experimental`. | | `kit browser status [--json]` | Short status/strategy summary for browser verification. | diff --git a/src/commands/config.ts b/src/commands/config.ts index 57e5a2af..77cd5274 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -325,11 +325,67 @@ function cmdConfigKnobs(): boolean { return true; } +/** + * `kit config recommend` — the recommended posture as a report, writing nothing. + * + * The knowledge lived in `applyRecommendedHardening()`, reachable only from `kit setup`, which + * APPLIES it — touching `~/.claude`, `~/.codex` and the repo's git hooks. So the only way to ask + * "what would this give me?" was to let it happen (#511). A repo that already exists needs the + * read-only half: a long-lived config keeps whatever posture it was set up with, and nothing said + * which sections kit has learned since. + */ +async function cmdConfigRecommend(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + let config; + try { + const { loadConfig } = await import("../config.js"); + config = await loadConfig(resolveConfigPath()); + } catch { + console.error(`${c.red}No readable ${KIT_FILE} — run \`kit init\` first.${c.reset}`); + return false; + } + + const { recommendPosture } = await import("../recommended.js"); + const { allMemoryHooksLiveness } = await import("../memory/install.js"); + const { describeHookFloor } = await import("../hook-floor.js"); + + const live = allMemoryHooksLiveness(); + const rows = recommendPosture(config, { + memoryHooks: live.everInstalled && live.missing.length === 0, + gitHooks: describeHookFloor(process.cwd(), config).installed, + }); + + if (jsonMode) { + console.log(JSON.stringify({ recommendations: rows }, null, 2)); + return true; + } + + console.log( + `${c.bold}${c.cyan}kit config recommend${c.reset} ${c.dim}(nothing is written)${c.reset}`, + ); + console.log(`${c.dim}${"─".repeat(60)}${c.reset}`); + const width = Math.max(...rows.map((r) => r.label.length)) + 2; + for (const r of rows) { + const icon = r.adopted ? `${c.green}✓${c.reset}` : `${c.yellow}○${c.reset}`; + console.log(` ${icon} ${r.label.padEnd(width)}${c.dim}${r.buys}${c.reset}`); + if (!r.adopted && r.how) console.log(` ${c.dim}→ ${r.how}${c.reset}`); + } + const missing = rows.filter((r) => !r.adopted).length; + console.log(); + console.log( + missing === 0 + ? `${c.green}✓ every recommended piece is in place.${c.reset}` + : `${c.dim}${missing} of ${rows.length} not adopted. \`kit setup\` applies the hook/memory pieces; the [section] ones are yours to declare.${c.reset}`, + ); + return true; +} + export async function cmdConfig(): Promise { const sub = process.argv[3]; if (sub === "migrate") return cmdConfigMigrate(); if (sub === "knobs") return cmdConfigKnobs(); + if (sub === "recommend") return cmdConfigRecommend(); // Default / help: show the current config version + available subcommands. if (!sub || sub === "--help" || sub === "-h") { @@ -358,6 +414,9 @@ export async function cmdConfig(): Promise { console.log( ` ${c.cyan}kit config migrate --force${c.reset} Overwrite an existing ${KIT_FILE}.backup`, ); + console.log( + ` ${c.cyan}kit config recommend${c.reset} What this repo would gain, writing nothing (\`--json\`)`, + ); console.log( ` ${c.cyan}kit config knobs${c.reset} List power-user env vars + ${KIT_FILE} fields (--json)`, ); diff --git a/src/config-drift.test.ts b/src/config-drift.test.ts new file mode 100644 index 00000000..b046715a --- /dev/null +++ b/src/config-drift.test.ts @@ -0,0 +1,168 @@ +/** + * The two ways a `.kit.toml` falls behind, and the readers that were missing. + * + * Schema drift had a working detector — `kit config migrate --check` answers it — and no caller, + * so `kit status` said `✓ .kit.toml present` and never that "present" is not "current". Measured + * on kit's own repo: v0 while the schema was v1, unreported (#511). + * + * Feature drift had no detector at all. `applyRecommendedHardening()` knew the recommended + * posture and was reachable only from `kit setup`, which APPLIES it — touching `~/.claude`, + * `~/.codex` and the repo's git hooks — so asking "what would I get?" meant letting it happen. + * + * Both readers are asserted here on the property that makes them worth having: a row that states + * what the piece BUYS rather than that it is missing, and a planner that answers without writing. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { planConfigMigration } from "./config-migrate.js"; +import { recommendPosture } from "./recommended.js"; +import { CONFIG_SCHEMA_VERSION } from "./config.js"; + +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "cli.js"); + +function repoWith(toml: string): string { + const dir = mkdtempSync(join(tmpdir(), "kit-drift-")); + writeFileSync(join(dir, ".kit.toml"), toml); + return dir; +} + +describe("planConfigMigration — the detector, without a write path", () => { + it("reports a legacy config as behind, naming both versions", () => { + const dir = repoWith('[tools]\nnode = "22"\n'); + try { + const plan = planConfigMigration(dir); + assert.ok(plan); + assert.equal(plan.fromVersion, 0, "no version stamp is legacy v0"); + assert.equal(plan.toVersion, CONFIG_SCHEMA_VERSION); + assert.equal(plan.current, false); + assert.ok(plan.steps > 0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("reports a stamped config as current", () => { + const dir = repoWith(`version = ${CONFIG_SCHEMA_VERSION}\n[tools]\nnode = "22"\n`); + try { + const plan = planConfigMigration(dir); + assert.equal(plan?.current, true); + assert.equal(plan?.steps, 0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("returns null rather than guessing when there is no readable config", () => { + const empty = mkdtempSync(join(tmpdir(), "kit-drift-empty-")); + const broken = repoWith("this is not toml = = =\n"); + try { + assert.equal(planConfigMigration(empty), null); + assert.equal(planConfigMigration(broken), null); + } finally { + rmSync(empty, { recursive: true, force: true }); + rmSync(broken, { recursive: true, force: true }); + } + }); + + it("writes nothing — the file is byte-identical afterwards", () => { + const dir = repoWith('[tools]\nnode = "22"\n'); + try { + const before = spawnSync("cat", [join(dir, ".kit.toml")], { encoding: "utf-8" }).stdout; + planConfigMigration(dir); + const after = spawnSync("cat", [join(dir, ".kit.toml")], { encoding: "utf-8" }).stdout; + assert.equal(after, before); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("recommendPosture — states what each piece buys", () => { + const probes = { memoryHooks: false, gitHooks: [] as string[] }; + + it("marks nothing adopted for a bare config, and every row says what it buys", () => { + const rows = recommendPosture({}, probes); + assert.ok(rows.length >= 8); + for (const r of rows) { + assert.equal(r.adopted, false, r.key); + assert.ok(r.buys.length > 30, `${r.key}: a row that only says "missing" gets ignored`); + assert.ok(r.how, `${r.key}: an unadopted row must say how`); + } + }); + + it("marks a declared section as adopted and drops its how", () => { + const rows = recommendPosture( + { context: { github: { org: "acme" } }, deploy: { required: ["A"] } } as never, + probes, + ); + const ctx = rows.find((r) => r.key === "context"); + const deploy = rows.find((r) => r.key === "deploy-env"); + assert.equal(ctx?.adopted, true); + assert.equal(ctx?.how, undefined); + assert.equal(deploy?.adopted, true); + }); + + it("tells you to declare [context] before the pre-push gate, not to install a gate that cannot fail", () => { + const without = recommendPosture({}, probes).find((r) => r.key === "context-check-hook"); + assert.match(without?.how ?? "", /declare \[context\] first/); + + const with_ = recommendPosture({ context: { git: { email: "a@b.c" } } } as never, probes).find( + (r) => r.key === "context-check-hook", + ); + assert.match(with_?.how ?? "", /kit hooks add context-check/); + }); + + it("reads installed git hooks and memory hooks as adopted", () => { + const rows = recommendPosture({}, { memoryHooks: true, gitHooks: ["secret-scan"] }); + assert.equal(rows.find((r) => r.key === "memory-hooks")?.adopted, true); + assert.equal(rows.find((r) => r.key === "secret-scan")?.adopted, true); + assert.equal(rows.find((r) => r.key === "post-pull-audit")?.adopted, false); + }); +}); + +describe("the readers, through the compiled CLI", () => { + const run = (args: string[], cwd: string): { code: number; out: string; err: string } => { + const r = spawnSync(process.execPath, [CLI_PATH, ...args], { + cwd, + encoding: "utf-8", + env: { ...process.env, KIT_HIDE_HOOK_SKIP_BANNER: "1", KIT_AUDIT_ANCHOR: "0" }, + timeout: 120_000, + }); + return { code: r.status ?? 1, out: r.stdout ?? "", err: r.stderr ?? "" }; + }; + + it("kit status names the schema gap instead of only saying the file is present", () => { + const dir = repoWith('[tools]\nnode = "22"\n'); + try { + const r = run(["status"], dir); + assert.match(r.out, /config schema/); + assert.match(r.out, /current is v/); + assert.match(r.out, /kit config migrate/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("kit config recommend reports without writing", () => { + const dir = repoWith('[tools]\nnode = "22"\n'); + try { + const before = spawnSync("ls", ["-a", dir], { encoding: "utf-8" }).stdout; + const r = run(["config", "recommend", "--json"], dir); + assert.equal(r.code, 0, r.err); + const parsed = JSON.parse(r.out) as { recommendations: Array<{ key: string; buys: string }> }; + assert.ok(parsed.recommendations.length >= 8); + assert.ok(parsed.recommendations.every((x) => x.buys.length > 0)); + // Nothing created, nothing removed. + assert.equal(spawnSync("ls", ["-a", dir], { encoding: "utf-8" }).stdout, before); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/config-migrate.ts b/src/config-migrate.ts index fd4d9c15..798e8932 100644 --- a/src/config-migrate.ts +++ b/src/config-migrate.ts @@ -11,6 +11,9 @@ // v0->v1 migration stamps version=1 and changes no other field. The point is the // FRAMEWORK, which is real and extensible — a future field rename is one row. import { CONFIG_SCHEMA_VERSION } from "./config.js"; +import { readFileSync } from "node:fs"; +import { join as joinPath } from "node:path"; +import { parse as parseToml } from "smol-toml"; /** A parsed-but-untyped config object (smol-toml output / Zod input). */ export type RawConfig = Record; @@ -119,6 +122,32 @@ export function migrateConfig( }; } +/** + * Read-only: is the config file on disk behind the current schema? + * + * `kit config migrate --check` answered this and nothing called it, so `kit status` said + * `✓ .kit.toml present` and never that "present" is not "current" (#511). This is the same + * detection with no write path at all, so a status row can ask cheaply. Returns null when there + * is no readable config — an absent or malformed config is reported by other rows. + */ +export function planConfigMigration( + cwd: string = process.cwd(), +): { fromVersion: number; toVersion: number; current: boolean; steps: number } | null { + try { + const raw = parseToml(readFileSync(joinPath(cwd, ".kit.toml"), "utf-8")) as RawConfig; + const fromVersion = detectConfigVersion(raw); + const steps = planMigrations(fromVersion, CONFIG_SCHEMA_VERSION); + return { + fromVersion, + toVersion: CONFIG_SCHEMA_VERSION, + current: steps.length === 0, + steps: steps.length, + }; + } catch { + return null; + } +} + export interface ConfigDiffEntry { path: string; before: string | undefined; diff --git a/src/recommended.ts b/src/recommended.ts index 57b9198f..ad451b97 100644 --- a/src/recommended.ts +++ b/src/recommended.ts @@ -39,6 +39,120 @@ function kitInvocation(): string { * touches GLOBAL `~/.claude` / `~/.codex` (memory hooks) and the repo's git hooks, so the * caller must surface that to the user first. */ +/** + * The recommended posture as a REPORT — what a repo would gain, with nothing written. + * + * `applyRecommendedHardening` knew this and was reachable only from `kit setup`, so the only way + * to ask "what would I get?" was to let it write to `~/.claude`, `~/.codex` and the repo's git + * hooks (#511). A repo that already exists needs the read-only half: a long-lived `.kit.toml` + * silently keeps whatever posture it was set up with, and nothing said which sections kit has + * learned since. + * + * Each row states what it BUYS, not just that it is missing — a checklist of absent features is + * how a report gets ignored. Pure given (config, probes), so the tests do not need a machine in + * any particular state. + */ +export interface RecommendationRow { + key: string; + /** Present already, or worth adopting. */ + adopted: boolean; + label: string; + /** One line: what declaring/installing this buys. */ + buys: string; + /** The command that adopts it, when it is not adopted. */ + how?: string; +} + +export interface RecommendProbes { + /** Memory capture hooks wired in the agent lifecycle configs. */ + memoryHooks: boolean; + /** kit-managed git hooks present in the resolved hooks dir. */ + gitHooks: string[]; +} + +export function recommendPosture(config: kitConfig, probes: RecommendProbes): RecommendationRow[] { + const rows: RecommendationRow[] = []; + + rows.push({ + key: "memory-hooks", + adopted: probes.memoryHooks, + label: "cross-harness memory capture", + buys: "transcripts from every agent land in one local store, so a later session can recall what was decided instead of re-deriving it", + how: probes.memoryHooks ? undefined : "kit memory install", + }); + + rows.push({ + key: "secret-scan", + adopted: probes.gitHooks.includes("secret-scan"), + label: "pre-commit secret scan", + buys: "a staged credential is refused before it becomes git history, which is immutable", + how: probes.gitHooks.includes("secret-scan") ? undefined : "kit hooks add secret-scan", + }); + + rows.push({ + key: "post-pull-audit", + adopted: probes.gitHooks.includes("post-pull-audit"), + label: "post-merge audit", + buys: "after a pull, new dependencies, dropped gitignore rules and introduced secrets are surfaced rather than inherited silently", + how: probes.gitHooks.includes("post-pull-audit") ? undefined : "kit hooks add post-pull-audit", + }); + + const hasContext = config.context !== undefined; + rows.push({ + key: "context", + adopted: hasContext, + label: "[context] CLI lock", + buys: "each CLI is pinned to the account + project this repo must use, so a tool answering as the wrong identity is a red row instead of a filtered result set that looks complete", + how: hasContext ? undefined : "kit context check (prints a ready-to-paste block)", + }); + + rows.push({ + key: "context-check-hook", + // Only meaningful once [context] exists — the gate has nothing to compare against otherwise, + // which is why `kit hooks add context-check` now refuses without it. + adopted: probes.gitHooks.includes("context-check"), + label: "pre-push context check", + buys: "a push to the wrong org/project is blocked before it leaves the machine", + how: hasContext + ? probes.gitHooks.includes("context-check") + ? undefined + : "kit hooks add context-check" + : "declare [context] first — the gate has nothing to compare against without it", + }); + + rows.push({ + key: "policy-agent-writes", + adopted: config.policy?.agent_writes !== undefined, + label: "[policy.agent_writes]", + buys: "vendor writes an agent may perform are declared and narrowed at kit's choke points and inside the plugins; an empty list is a lock, not a wildcard", + how: + config.policy?.agent_writes !== undefined + ? undefined + : "add [policy.agent_writes] to .kit.toml (see docs/POLICY.md)", + }); + + rows.push({ + key: "deploy-env", + adopted: config.deploy !== undefined, + label: "[deploy] env key names", + buys: "`kit check --category deploy` diffs the env key NAMES your platform has against the ones this repo declares — never reading a value", + how: config.deploy !== undefined ? undefined : "add [deploy] to .kit.toml", + }); + + rows.push({ + key: "audit-anchor", + adopted: config.governance?.audit?.require_anchor === true, + label: "[governance.audit] require_anchor", + buys: "an unanchored or rewritten audit log fails the gate instead of reading as verified — tamper-evidence you can prove rather than assume", + how: + config.governance?.audit?.require_anchor === true + ? undefined + : "set [governance.audit] require_anchor = true", + }); + + return rows; +} + export async function applyRecommendedHardening( config: kitConfig, gitDir = ".git", diff --git a/src/status.test.ts b/src/status.test.ts index 9efe39d4..d70f714d 100644 --- a/src/status.test.ts +++ b/src/status.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { gatherStatus } from "./status.js"; import { openMemoryDb, insertMessage } from "./memory/db.js"; +import { CONFIG_SCHEMA_VERSION } from "./config.js"; import { KIT_BLOCK_BEGIN } from "./agent-config.js"; describe("kit status", () => { @@ -54,7 +55,10 @@ describe("kit status", () => { mkdirSync(proj, { recursive: true }); writeFileSync( join(proj, ".kit.toml"), - `[tools]\nnode = "22"\n\n[secrets]\nstore = "1password"\n`, + // The version stamp is part of being configured: the new `config schema` row reports a + // config that predates the current schema, and this fixture is meant to be a repo with + // nothing outstanding. Written from the constant so the fixture cannot rot behind it. + `version = ${CONFIG_SCHEMA_VERSION}\n\n[tools]\nnode = "22"\n\n[secrets]\nstore = "1password"\n`, ); writeFileSync(join(proj, "CLAUDE.md"), `# Project\n\n${KIT_BLOCK_BEGIN}\nuse kit\n`); writeFileSync( diff --git a/src/status.ts b/src/status.ts index 05a16117..470691e6 100644 --- a/src/status.ts +++ b/src/status.ts @@ -90,6 +90,28 @@ export async function gatherStatus(cwd: string = process.cwd()): Promise