config-audit/tests/scanners/cli-unknown-flag-rejection.test.mjs
Kjell Tore Guttormsen 44b222859e feat(scanners): the recovery path is code you can run, not prose you can read
R1+R2 as one chunk — both KRITISK rows of the Q3 severity table sit on the
restore path, and neither closes alone.

R1: rollback-engine.mjs verified every checksum before AND after each write,
resolved the legacy backup root and reported createdNotRemoved — and none of it
was reachable. Measured: 16 files under scanners/ carry a process.argv entry;
the engine was not one of them. commands/rollback.md drove the restore as model
prose: an ESM import block a template cannot execute, ad-hoc `cp` offered
underneath as the runnable path, and "(checksum verified)" pre-rendered three
times in the success output. `cp` establishes no checksum, so the verification
was a property of the template rather than of the run — on the one surface that
runs when the user is already in trouble.

R2: implement.md Step 3 hand-built its backup (mkdir, cp, a date-derived id, a
manifest typed out in the template) while parseManifest knew one frozen sample
of that format, pinned by a HAND-WRITTEN fixture instead of by the template's
own text. Rename a key and parseManifest returns zero files while rollback
reports success.

Fixing only R1 leaves the new CLI parsing a prose format; fixing only R2 leaves
a clean format with no runnable entry.

- scanners/rollback-cli.mjs — --list / --create / --restore / --delete over the
  existing engine, on the shared requireValidArgs gate. Exit 0 done, 1
  outstanding (gate refusal with nothing written, or a backup that covered fewer
  targets than given), 2 a file failed, 3 could not do the job. A gated restore
  is 1, not 3: "this write leaves your project" is a verdict about a write that
  WAS examined, and it rides in the payload where a command under 2>/dev/null
  can act on it.
- createBackup gains `created` (recorded, never copied — no backup can hold a
  file that does not exist) and `skipped`, so a backup covering fewer files than
  asked is no longer indistinguishable from a clean one.
- implement.md Step 3 and rollback.md now call the CLI. parseManifest's
  implement-format branch stays: nothing writes that shape now, but every backup
  made before this chunk is on disk in it.
- backup-restore-contract.test.mjs checks every field rollback.md renders
  against a payload produced by RUNNING the CLI. That is what replaced
  "(checksum verified)".

20 guards seen red against the original state before any production code, then
each against its own defect. Two holes that surfaced there were mine: the
implement assertion matched `--create` as a substring of `--created` and stayed
green when the call was removed; and mutating the argv gate showed
requireValidArgs sets exit 3 by itself, so a CLI can report that it could not
parse its arguments and still run the restore underneath — that case is now
asserted on the bytes.

Suite 1752 -> 1777, 0 fail. Frozen tests/snapshots/v5.0.0 untouched. Dogfooded
through the templates' own command lines against a sandboxed HOME, including the
machine-wide arm: refused with the file unchanged, then restored under
--approve-scope.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Logq8GGWKhtyDem63FTEnG
2026-08-18 21:28:15 +02:00

201 lines
9 KiB
JavaScript

/**
* Session #51 — CLIs must reject an unknown flag, never ignore it.
*
* Third arm of the argument-handling class first measured in #44/#47/#50. The
* earlier arms were about a flag's VALUE being swallowed as the scan target
* (`else if (!args[i].startsWith('-')) targetPath = args[i]`). This arm is
* quieter and worse: several CLIs have no `else` branch at all, so an
* unrecognised flag falls out of the parse loop leaving no trace — exit 0, a
* full payload, and an answer to a question the caller did not ask.
*
* Measured cost, live, in the same session that wrote this test: the
* `knowledge-refresh` command's only user-facing knob (`--stale-after N`)
* reached the CLI as one malformed argv entry (see
* command-flag-value-portability.test.mjs). Because the CLI ignored it, the
* command reported "✓ All 14 register entries were re-verified within the last
* 90 days" — a true-sounding sentence about a threshold the user had just
* overridden. Had the CLI failed loudly, the shell bug would have been a
* one-line exit-3 message instead of a silent wrong answer.
*
* Scope of this guard: the CLIs whose commands were dogfooded in this chunk.
* `optimize-lens-cli.mjs` and `token-hotspots-cli.mjs` share the defect but
* also carry the still-open positional-swallow arm; both are fixed together in
* the v5.14 arg-handling chunk, where every call site's flags can be audited at
* once. They are listed in KNOWN_OPEN so the number stays visible rather than
* being quietly rounded down to zero.
*/
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { spawn } from 'node:child_process';
import { readFile, mkdtemp, readdir, rm } from 'node:fs/promises';
import { resolve, dirname, join } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const SCANNERS_DIR = resolve(__dirname, '..', '..', 'scanners');
/**
* Every CLI in `scanners/` that reads `process.argv`, with the argv it needs to
* get past required-arg checks and — where it has one — a value-taking flag.
*
* KNOWN_OPEN is gone. It named two CLIs; measuring all fourteen (#57) found
* **seven** open on the unknown-flag arm and **ten** on the value arm, including
* two CLIs that were already in GUARDED and passing. The deferral list was a
* prediction from the previous session's field of view, never a measurement.
*/
const GUARDED = [
{ cli: 'campaign-cli.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'knowledge-refresh-cli.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'campaign-write-cli.mjs', argv: ['init'], valueFlag: '--output-file' },
{ cli: 'campaign-export-cli.mjs', argv: ['--repo', '.'], valueFlag: '--output-file' },
{ cli: 'drift-cli.mjs', argv: [], valueFlag: '--baseline' },
{ cli: 'fix-cli.mjs', argv: ['--dry-run'], valueFlag: '--output-file' },
{ cli: 'plugin-health-scanner.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'manifest.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'optimize-lens-cli.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'posture.mjs', argv: [], valueFlag: '--context-window' },
{ cli: 'scan-orchestrator.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'token-hotspots-cli.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'whats-active.mjs', argv: [], valueFlag: '--output-file' },
{ cli: 'self-audit.mjs', argv: [], valueFlag: null }, // no value-taking flag
{ cli: 'write-scope-cli.mjs', argv: ['--target', 'x'], valueFlag: '--output-file' },
{ cli: 'subtraction-write-cli.mjs', argv: ['--approved', 'x'], valueFlag: '--output-file' },
// R1. All three probes below exit at `requireValidArgs`, before any mode runs,
// so none of them reaches the operator's real backup root.
{ cli: 'rollback-cli.mjs', argv: [], valueFlag: '--output-file' },
];
/**
* GUARDED was hand-maintained, and a hand-maintained list of what to sweep is a
* premise rather than a measurement — the shape that made `KNOWN_OPEN` wrong
* about its own breadth (#57). Measured when this guard was added: the list was
* complete at 14 of 14, so nothing was hiding. It is the NEXT CLI that is at
* risk, so the coverage is derived from the directory instead of asserted about
* a literal.
*/
test('every argv-reading CLI in scanners/ appears in GUARDED', async () => {
const entries = await readdir(SCANNERS_DIR);
const clis = [];
for (const name of entries) {
if (!name.endsWith('.mjs')) continue;
const src = await readFile(resolve(SCANNERS_DIR, name), 'utf-8');
if (src.includes('process.argv')) clis.push(name);
}
const guarded = new Set(GUARDED.map((g) => g.cli));
const missing = clis.filter((c) => !guarded.has(c)).sort();
assert.deepEqual(
missing,
[],
'A CLI that reads process.argv but is absent from GUARDED is swept by nothing: it can\n' +
'accept an unknown flag, or write a file named after one, and both arms of this test\n' +
'would still be green. Add it to GUARDED rather than relaxing this check.',
);
});
function run(cli, argv, cwd = resolve(__dirname, '..', '..')) {
return new Promise((res) => {
const child = spawn(process.execPath, [resolve(SCANNERS_DIR, cli), ...argv], { cwd });
let stderr = '';
child.stderr.on('data', (d) => { stderr += d; });
child.stdout.on('data', () => {});
child.on('close', (code) => res({ code, stderr }));
});
}
for (const { cli, argv } of GUARDED) {
test(`${cli} rejects an unknown flag with exit 3`, async () => {
const { code, stderr } = await run(cli, [...argv, '--zzz-not-a-real-flag']);
assert.equal(
code,
3,
`${cli} accepted an unknown flag (exit ${code}). A flag the CLI does not understand\n` +
'must fail loudly — silently ignoring it turns a caller-side bug into a confident\n' +
'wrong answer. stderr was: ' + JSON.stringify(stderr),
);
assert.match(
stderr,
/--zzz-not-a-real-flag/,
`${cli} must name the offending flag so the caller can find it.`,
);
});
}
/**
* Arm 2 — the value arm, and the sharper of the two.
*
* `else if (a === '--output-file' && args[i + 1])` only asks whether a next token
* EXISTS, never whether it is a value. So `--output-file --json` takes `--json`
* as the filename: measured live (#57), `manifest`, `campaign-cli` and
* `knowledge-refresh-cli` each wrote a file literally named `--json` into the
* caller's working directory, exit 0, with `--json` mode silently dropped. A
* wrong answer is bad; writing an unintended file is worse.
*
* Two of the CLIs this catches were already in GUARDED and green on arm 1 — the
* guard was passing on one arm while the other stood open a few lines away
* ([[guard-can-be-green-on-its-own-defect]]).
*/
for (const { cli, argv, valueFlag } of GUARDED) {
if (!valueFlag) continue;
test(`${cli} rejects ${valueFlag} followed by another flag instead of a value`, async () => {
const scratch = await mkdtemp(join(tmpdir(), 'config-audit-argsluk-'));
try {
const { code, stderr } = await run(cli, [...argv, valueFlag, '--json'], scratch);
assert.equal(
code,
3,
`${cli} treated "--json" as the value of ${valueFlag} (exit ${code}). The flag needs a\n` +
'value; the next flag is not one. stderr was: ' + JSON.stringify(stderr),
);
assert.deepEqual(
await readdir(scratch),
[],
`${cli} wrote a file into the caller's working directory named after a FLAG. A CLI that\n` +
'misreads its own argv must not leave anything on disk.',
);
} finally {
await rm(scratch, { recursive: true, force: true });
}
});
test(`${cli} rejects ${valueFlag} with no value at all`, async () => {
const { code } = await run(cli, [...argv, valueFlag]);
assert.equal(
code,
3,
`${cli} ignored a trailing ${valueFlag} (exit ${code}). Under the ux-rule every command\n` +
'invokes these CLIs as `--output-file <path> 2>/dev/null` — an empty <path> must fail\n' +
'loudly, not fall through to stdout the command has been told to discard.',
);
});
}
/**
* The caller arm. #45/#46/#47 all taught the same lesson: fixing a CLI does not fix the
* command that reads its payload. `addedUnverified` and the `skipped` reasons only reach the
* user if the command template is told to report them — otherwise the CLI is honest into a
* void, and the phantom repo is just as invisible as before.
*/
const CAMPAIGN_MD = resolve(__dirname, '..', '..', 'commands', 'campaign.md');
test('campaign.md reports the fields the write-CLI added for honest coverage', async () => {
const content = await readFile(CAMPAIGN_MD, 'utf-8');
assert.match(
content,
/addedUnverified/,
'campaign.md must report `addedUnverified` after an add — a tracked path the CLI could\n' +
'not read is exactly the row that silently pollutes the backlog and the token bill.',
);
assert.match(
content,
/skipped/,
'campaign.md must report `skipped[]` after a token sweep so the bill\'s coverage is honest.',
);
});