config-audit/scanners/knowledge-refresh-cli.mjs
Kjell Tore Guttormsen 182a37c1af fix(scanners): close the CLI argument class across all fourteen CLIs
`KNOWN_OPEN` in cli-unknown-flag-rejection.test.mjs named two CLIs as still
carrying the argument-swallow defect. That number was the previous session's
field of view, not a measurement. Measuring all fourteen found **7** open on
the unknown-flag arm and **10** on a second arm the deferral note never
described.

Arm 1 — unknown flag: with no `else` branch, `--zzz` leaves no trace. exit 0,
full payload, a confident answer to a question the caller did not ask.

Arm 2 — the sharper one: `a === '--output-file' && args[i + 1]` asks only
whether a next token EXISTS, never whether it is a value. `manifest`,
`campaign-cli` and `knowledge-refresh-cli` each wrote a file literally named
`--json` into the caller's working directory when handed `--output-file
--json`, exit 0, with `--json` mode silently dropped. A wrong answer is bad;
an unintended file on disk is worse.

Two of the CLIs this catches were already in GUARDED and green on arm 1 while
arm 2 stood open a few lines away — the guard asserted one relation instead of
the invariant.

Fixed with a shared gate (`lib/cli-args.mjs`) that runs BEFORE each CLI's own
parse loop rather than replacing it: valid argv reaches the existing parser
byte-for-byte unchanged, so the byte-stability argument is structural rather
than empirical. `drift-cli`, `fix-cli` and `plugin-health-scanner` were
already correct on both arms and were moved into GUARDED instead of rewritten.
The three CLIs with a bespoke unknown-flag branch had it removed once the gate
made it unreachable.

Suite 1488 → 1531. Frozen v5.0.0 snapshots untouched; `self-audit
--check-readme` passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014P6Rh59Mtj4uYrdYMCYZJE
2026-08-09 21:42:00 +02:00

117 lines
4.3 KiB
JavaScript

#!/usr/bin/env node
/**
* knowledge-refresh CLI — feeds the v5.7 `/config-audit knowledge-refresh` command
* (Chunk 3: the "living" half of the living knowledge base).
*
* This is the DETERMINISTIC half of the hybrid motor: it loads the best-practices
* register and classifies every entry as `fresh` or `stale` by the age of its
* `source.verified` stamp (via the pure `assessFreshness` core). It is READ-ONLY —
* it NEVER writes the register and NEVER touches the network. Candidate discovery
* (polling the CC changelog + Anthropic blog) and the human-approved writes live in
* the command layer (Verifiseringsplikt). `--dry-run` is implicit and the only mode;
* the flag is accepted for explicitness and echoed back.
*
* Naming: `-cli` suffix → NOT an orchestrated scanner (the scan-orchestrator only
* loads scanner modules), so the scanner count is unchanged and the snapshot suite
* stays byte-stable.
*
* Usage:
* node knowledge-refresh-cli.mjs [--output-file <path>] [--stale-after <N>]
* [--reference-date <YYYY-MM-DD>] [--dry-run]
*
* Exit codes: 0 = every entry fresh, 1 = one or more stale (advisory), 3 = error.
*/
import { resolve } from 'node:path';
import { writeOutputFile } from './lib/write-output.mjs';
import { loadRegister, REGISTER_PATH } from './lib/best-practices-register.mjs';
import { assessFreshness, STALE_AFTER_DAYS_DEFAULT } from './lib/knowledge-refresh.mjs';
import { findArgError } from './lib/cli-args.mjs';
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
/**
* Usage error. Throws rather than calling process.exit(): exit() discards
* unflushed stdout when stdout is a pipe. The top-level catch prints the same
* `Error: ` text and sets the same exit code 3, so callers see no difference.
*/
class CliUsageError extends Error {}
function fail(message) {
throw new CliUsageError(message);
}
/** Flag surface, measured 2026-08-09. The gate runs BEFORE the loop below, so the
* loop no longer needs to re-check that a value followed its flag. */
const ARG_SPEC = { boolean: ['--dry-run'], value: ['--output-file', '--stale-after', '--reference-date'] };
async function main() {
const args = process.argv.slice(2);
const argError = findArgError(args, ARG_SPEC);
if (argError) fail(argError);
let outputFile = null;
let staleAfterDays = STALE_AFTER_DAYS_DEFAULT;
let referenceDate = null; // null → today
let dryRun = false;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--dry-run') dryRun = true;
else if (a === '--output-file') outputFile = args[++i];
else if (a === '--stale-after') {
const n = Number.parseInt(args[++i], 10);
if (!Number.isInteger(n) || n < 0) fail('--stale-after must be a non-negative integer (days)');
staleAfterDays = n;
} else if (a === '--reference-date') {
referenceDate = args[++i];
if (!DATE_RE.test(referenceDate)) fail('--reference-date must be YYYY-MM-DD');
}
}
// The clock is read here ONLY — the core takes an injected date and stays pure.
const ref = referenceDate || new Date();
let register;
try {
register = loadRegister();
} catch (err) {
fail(`could not load register at ${REGISTER_PATH}: ${err.message}`);
}
let assessment;
try {
assessment = assessFreshness(register, { referenceDate: ref, staleAfterDays });
} catch (err) {
fail(err.message);
}
const payload = {
status: 'ok',
registerPath: REGISTER_PATH,
version: register.version,
dryRun: true, // this CLI never writes; the flag is informational
requestedDryRun: dryRun,
referenceDate: assessment.referenceDate,
staleAfterDays: assessment.staleAfterDays,
counts: assessment.counts,
stale: assessment.stale,
fresh: assessment.fresh,
};
const json = JSON.stringify(payload, null, 2);
if (outputFile) await writeOutputFile(outputFile, json, 'utf-8');
else process.stdout.write(json + '\n');
process.exitCode = assessment.counts.stale > 0 ? 1 : 0;
}
const isDirectRun =
process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname);
if (isDirectRun) {
main().catch((err) => {
const prefix = err instanceof CliUsageError ? 'Error' : 'Fatal';
process.stderr.write(`${prefix}: ${err.message}\n`);
process.exitCode = 3;
});
}