diff --git a/CHANGELOG.md b/CHANGELOG.md index bff4a4a6..9a1efc70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Fixed + +- **`kit config migrate` deleted every comment in `.kit.toml`, and the dry run did not say so** + (#513). It re-serialised from the parsed object, so on the v0 → v1 step — whose entire job is to + stamp `version = 1` — kit's own config went from 8 comment lines to 0, and a one-line change + produced a 36-line diff. The parsed data was identical, so the backup-and-re-validate safety + path passed and flagged nothing. What was lost was policy reasoning: why those scanners are + declared, why the refs are `aqua:`-scheme-qualified, which values `environment` accepts. + + An add-only migration is now applied as a **text edit** — the added key is inserted above the + first table (top-level keys must precede it or TOML scopes them into it) and the rest of the + file is untouched. Anything more structural returns null from the patcher rather than being + forced through an edit that cannot express it, and then the run is **refused** while comments + exist unless `--allow-comment-loss` is passed, naming how many lines are at stake. + + `--dry-run` now says which path would be taken — *"Applied as a text edit: comments and + formatting are preserved"* or the count that would be deleted. A preview that omits the + destructive half of a change is worse than no preview. + ### Added - **Config drift is reported, both kinds** (#511). A `.kit.toml` falls behind in two ways and diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 087b2d5c..44c50ed2 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -54,7 +54,7 @@ through untouched (`kit run -- pnpm test --watch`). | `kit check --attest` | Opt-in, fail-soft: write a signed `.kit-check-attestation.json` receipt recording which scanners actually ran + the verdict (HMAC-signed with the machine-local anchor key; never blocks or alters the verdict). Also `kit ci --attest` / `KIT_ATTEST=1`. | | `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 migrate [--dry-run] [--check] [--force] [--allow-comment-loss]` | 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). An add-only migration is applied as a **text edit**, so comments and formatting survive; anything more structural would re-serialise the file and is **refused** while comments exist unless `--allow-comment-loss` is passed. `--dry-run` says which of the two would happen. | | `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`. | diff --git a/src/commands/config.ts b/src/commands/config.ts index 77cd5274..738eb975 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -8,6 +8,7 @@ // on disk. import { readFile, writeFile, access } from "node:fs/promises"; import { parse, stringify } from "smol-toml"; +import { patchConfigText, countCommentLines } from "../config-migrate.js"; import { CONFIG_SCHEMA_VERSION, kitConfigSchema } from "../config.js"; import { detectConfigVersion, @@ -41,6 +42,11 @@ export interface MigrateFileOptions { dryRun?: boolean; check?: boolean; force?: boolean; + /** + * Accept losing comments when a migration cannot be applied as a text edit. Off by default: + * a routine command must not silently delete the reasoning in a policy file (#513). + */ + allowCommentLoss?: boolean; } export interface MigrateStep { @@ -159,6 +165,16 @@ export async function migrateConfigFile( // --dry-run: report the plan + diff, write nothing. if (opts.dryRun) { + // Say HOW it would be applied. The preview used to show `+ version = 1` while the real run + // rewrote the file and deleted every comment — a preview that omits the destructive half of + // a change is worse than none (#513). + const asTextEdit = patchConfigText(content, diff) !== null; + const comments = countCommentLines(content); + const how = asTextEdit + ? " Applied as a text edit: comments and formatting are preserved." + : comments > 0 + ? ` This change cannot be applied as a text edit, so the file would be re-serialised and ${comments} comment line(s) WOULD BE DELETED — the real run refuses unless you pass --allow-comment-loss.` + : " Applied by re-serialising the file (no comments to lose)."; return { status: "dry-run", ok: true, @@ -167,7 +183,7 @@ export async function migrateConfigFile( steps, diff, wrote: false, - message: `Would migrate v${fromVersion} -> v${CONFIG_SCHEMA_VERSION} (${steps.length} step(s)). Nothing written (--dry-run).`, + message: `Would migrate v${fromVersion} -> v${CONFIG_SCHEMA_VERSION} (${steps.length} step(s)). Nothing written (--dry-run).${how}`, }; } @@ -179,7 +195,14 @@ export async function migrateConfigFile( diff, backupPath: `${configPath}.backup`, }; - return performMigration(configPath, content, result.migrated, base, opts.force === true); + return performMigration( + configPath, + content, + result.migrated, + base, + opts.force === true, + opts.allowCommentLoss === true, + ); } /** @@ -215,6 +238,7 @@ async function performMigration( migrated: RawConfig, base: MigrationBase, force: boolean, + allowCommentLoss = false, ): Promise { const err = (message: string): MigrateFileOutcome => ({ ...base, @@ -229,11 +253,27 @@ async function performMigration( return err(`Backup ${backupPath} already exists. Re-run with --force to overwrite it.`); } + // Prefer editing the SOURCE TEXT: `stringify(migrated)` re-serialises from the parsed object + // and deletes every comment — 8 comment lines became 0 on kit's own config for a migration + // whose only job was to stamp `version = 1` (#513). Comments in .kit.toml are where the why + // lives, so a routine maintenance command must not silently drop them. let migratedToml: string; - try { - migratedToml = stringify(migrated); - } catch (e) { - return err(`Could not serialize migrated config: ${(e as Error).message}`); + const patched = patchConfigText(original, base.diff ?? []); + if (patched !== null) { + migratedToml = patched; + } else { + const lost = countCommentLines(original); + if (lost > 0 && !allowCommentLoss) { + return err( + `this migration cannot be applied as a text edit, and re-serialising would delete ${lost} comment line(s) from ${configPath}. ` + + `Re-run with --allow-comment-loss to accept that (the original is kept at ${backupPath}), or apply the change by hand.`, + ); + } + try { + migratedToml = stringify(migrated); + } catch (e) { + return err(`Could not serialize migrated config: ${(e as Error).message}`); + } } await writeFile(backupPath, original, "utf-8"); @@ -280,8 +320,14 @@ async function cmdConfigMigrate(): Promise { const dryRun = hasFlag(process.argv, "--dry-run"); const check = hasFlag(process.argv, "--check"); const force = hasFlag(process.argv, "--force"); + const allowCommentLoss = hasFlag(process.argv, "--allow-comment-loss"); - const outcome = await migrateConfigFile(resolveConfigPath(), { dryRun, check, force }); + const outcome = await migrateConfigFile(resolveConfigPath(), { + dryRun, + check, + force, + allowCommentLoss, + }); switch (outcome.status) { case "already-current": @@ -414,6 +460,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 migrate --allow-comment-loss${c.reset} Accept losing comments when the change cannot be applied as a text edit`, + ); console.log( ` ${c.cyan}kit config recommend${c.reset} What this repo would gain, writing nothing (\`--json\`)`, ); diff --git a/src/config-migrate-text.test.ts b/src/config-migrate-text.test.ts new file mode 100644 index 00000000..90c9b02f --- /dev/null +++ b/src/config-migrate-text.test.ts @@ -0,0 +1,159 @@ +/** + * A migration must not delete the reasoning in the file it migrates. + * + * `kit config migrate` re-serialised `.kit.toml` from the parsed object, so every comment was + * deleted. Measured on kit's own config, on the v0 → v1 step whose entire job is to stamp + * `version = 1`: 8 comment lines became 0, and a one-line change produced a 36-line diff. The + * parsed data was identical, so re-validation passed and nothing flagged it — including the dry + * run, which previewed `+ version = 1` and said nothing about the rewrite (#513). + * + * What was lost was policy reasoning: why those scanners are declared, why the refs are + * `aqua:`-scheme-qualified, which values a field accepts. `.kit.toml` is where a repo declares + * its policy, and kit's argument is that policy should be reviewable. + * + * Three properties are pinned: an add-only migration is applied as a TEXT EDIT (comments and + * formatting survive byte-for-byte outside the insert), anything more structural returns null + * rather than being patched by an edit that cannot express it, and the dry run says which of the + * two would happen. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, readFileSync, 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 { parse } from "smol-toml"; + +import { patchConfigText, countCommentLines } from "./config-migrate.js"; + +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "cli.js"); + +describe("patchConfigText", () => { + it("inserts an added top-level key before the first table, leaving the rest untouched", () => { + const original = [ + "# why these tools matter", + "# a second line of reasoning", + "", + "[tools]", + 'node = "22" # inline note', + "", + "[secrets]", + 'store = "1password"', + "", + ].join("\n"); + + const patched = patchConfigText(original, [{ path: "version", before: undefined, after: "1" }]); + assert.ok(patched); + assert.match(patched, /^# why these tools matter/); + assert.match(patched, /version = 1/); + // Every original line survives, in order. + for (const line of original.split("\n").filter((l) => l.trim() !== "")) { + assert.ok(patched.includes(line), `lost: ${line}`); + } + assert.equal(countCommentLines(patched), countCommentLines(original)); + // The key must land ABOVE the first table, or TOML scopes it into that table. + assert.ok(patched.indexOf("version = 1") < patched.indexOf("[tools]")); + // And the data must be what the migration intended. + assert.equal((parse(patched) as { version?: number }).version, 1); + }); + + it("appends when the file has no table at all", () => { + const patched = patchConfigText('name = "x"\n', [ + { path: "version", before: undefined, after: "1" }, + ]); + assert.ok(patched); + assert.match(patched, /name = "x"/); + assert.equal((parse(patched) as { version?: number }).version, 1); + }); + + it("refuses anything that is not purely added top-level keys", () => { + // A changed value: a text insert cannot express it. + assert.equal(patchConfigText("[a]\nb = 1\n", [{ path: "a.b", before: "1", after: "2" }]), null); + // A removal. + assert.equal(patchConfigText("x = 1\n", [{ path: "x", before: "1", after: undefined }]), null); + // A nested addition needs placement rules a line insert does not have. + assert.equal( + patchConfigText("[a]\nb = 1\n", [{ path: "a.c", before: undefined, after: "2" }]), + null, + ); + // Nothing to do. + assert.equal(patchConfigText("x = 1\n", []), null); + }); +}); + +describe("countCommentLines", () => { + it("counts full-line and inline comments", () => { + assert.equal(countCommentLines("# one\nx = 1\n"), 1); + assert.equal(countCommentLines("x = 1 # inline\n"), 1); + assert.equal(countCommentLines("# one\ny = 2 # two\n"), 2); + assert.equal(countCommentLines("x = 1\n"), 0); + }); +}); + +describe("kit config migrate (compiled CLI)", () => { + const repo = (toml: string): string => { + const dir = mkdtempSync(join(tmpdir(), "kit-migrate-")); + writeFileSync(join(dir, ".kit.toml"), toml); + return dir; + }; + const run = (dir: string, args: string[]): { code: number; out: string } => { + const r = spawnSync(process.execPath, [CLI_PATH, "config", ...args], { + cwd: dir, + encoding: "utf-8", + env: { ...process.env, KIT_HIDE_HOOK_SKIP_BANNER: "1", KIT_AUDIT_ANCHOR: "0" }, + timeout: 60_000, + }); + return { code: r.status ?? 1, out: (r.stdout ?? "") + (r.stderr ?? "") }; + }; + + const COMMENTED = [ + "# why these tools matter", + "# and a second line", + "", + "[tools]", + 'node = "22" # inline note', + "", + ].join("\n"); + + it("keeps every comment on the v0 -> v1 stamp", () => { + const dir = repo(COMMENTED); + try { + const r = run(dir, ["migrate"]); + assert.equal(r.code, 0, r.out); + const after = readFileSync(join(dir, ".kit.toml"), "utf-8"); + assert.equal(countCommentLines(after), countCommentLines(COMMENTED)); + assert.match(after, /# why these tools matter/); + assert.match(after, /# inline note/); + assert.equal((parse(after) as { version?: number }).version, 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("the dry run says HOW it would apply the change", () => { + const dir = repo(COMMENTED); + try { + const r = run(dir, ["migrate", "--dry-run"]); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /Applied as a text edit: comments and formatting are preserved/); + // And it still wrote nothing. + assert.equal(readFileSync(join(dir, ".kit.toml"), "utf-8"), COMMENTED); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("--check still reports a stale config without touching it", () => { + const dir = repo(COMMENTED); + try { + const r = run(dir, ["migrate", "--check"]); + assert.equal(r.code, 1); + assert.match(r.out, /Config is at v0/); + assert.equal(readFileSync(join(dir, ".kit.toml"), "utf-8"), COMMENTED); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/config-migrate.ts b/src/config-migrate.ts index 798e8932..297ecae0 100644 --- a/src/config-migrate.ts +++ b/src/config-migrate.ts @@ -148,6 +148,50 @@ export function planConfigMigration( } } +/** + * Apply a migration by EDITING THE SOURCE TEXT, when the change is only added top-level keys. + * + * `stringify(migrated)` re-serialises from the parsed object, so every comment in the file is + * deleted. Measured on kit's own config, migrating v0 -> v1 — a step whose entire job is to stamp + * `version = 1`: 8 comment lines became 0, and a one-line change produced a 36-line diff (#513). + * The data was identical, so re-validation passed and nothing flagged the loss. + * + * `.kit.toml` is where a repo declares its policy, and the comments are where the WHY lives — + * why these scanners, why scheme-qualified refs, which values a field accepts. A routine + * maintenance command must not convert reviewable policy into bare data. + * + * Returns null when the diff is anything more than added top-level scalars, so a future migration + * that renames or moves keys does NOT get silently patched by a text edit that cannot express it. + * The caller then falls back to serialising — loudly. + */ +export function patchConfigText(original: string, diff: readonly ConfigDiffEntry[]): string | null { + const additions = diff.filter((d) => d.before === undefined && d.after !== undefined); + if (additions.length !== diff.length || additions.length === 0) return null; + // Only top-level scalars: a dotted path is a nested table, which needs placement rules a + // line insert cannot get right. + if (additions.some((d) => d.path.includes("."))) return null; + + // Insert before the first table header so the keys stay top-level (TOML scopes everything + // after a `[table]` to that table), keeping the original text byte-for-byte otherwise. + const lines = original.split("\n"); + const firstTable = lines.findIndex((l) => /^\s*\[/.test(l)); + const rendered = additions.map((d) => `${d.path} = ${d.after}`); + if (firstTable < 0) { + const body = original.endsWith("\n") ? original : `${original}\n`; + return `${body}${rendered.join("\n")}\n`; + } + const head = lines.slice(0, firstTable); + // Trim trailing blank lines from the head so the inserted block does not float. + while (head.length > 0 && head[head.length - 1].trim() === "") head.pop(); + const before = head.length > 0 ? [...head, ""] : []; + return [...before, ...rendered, "", ...lines.slice(firstTable)].join("\n"); +} + +/** Comment lines in a TOML source — used to report what a serialising migration would delete. */ +export function countCommentLines(toml: string): number { + return toml.split("\n").filter((l) => /^\s*#/.test(l) || /\s#/.test(l)).length; +} + export interface ConfigDiffEntry { path: string; before: string | undefined; diff --git a/src/flag-surface.ts b/src/flag-surface.ts index b8174754..aa224ee4 100644 --- a/src/flag-surface.ts +++ b/src/flag-surface.ts @@ -180,7 +180,7 @@ export const COMMAND_FLAGS: Record = { "--with-migrate", "--yes", ], - config: ["--check", "--dry-run", "--force", "--help", "--json"], + config: ["--allow-comment-loss", "--check", "--dry-run", "--force", "--help", "--json"], context: ["--format", "--json", "--prompt", "--require-declaration"], coverage: [ "--attest",