Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ through untouched (`kit run -- pnpm test --watch`).
| `kit check verify-attestation <file> [--key <k>] [--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 <before.json> <after.json> [--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=<key>\|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. |
Expand Down
59 changes: 59 additions & 0 deletions src/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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<boolean> {
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") {
Expand Down Expand Up @@ -358,6 +414,9 @@ export async function cmdConfig(): Promise<boolean> {
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)`,
);
Expand Down
168 changes: 168 additions & 0 deletions src/config-drift.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
});
});
29 changes: 29 additions & 0 deletions src/config-migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading