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
This commit is contained in:
Kjell Tore Guttormsen 2026-08-09 21:42:00 +02:00
commit 182a37c1af
14 changed files with 337 additions and 45 deletions

View file

@ -24,6 +24,7 @@
import { resolve } from 'node:path';
import { writeOutputFile } from './lib/write-output.mjs';
import { findArgError } from './lib/cli-args.mjs';
import {
loadLedger,
validateLedger,
@ -43,20 +44,21 @@ 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 = { value: ['--ledger-file', '--output-file'] };
async function main() {
const args = process.argv.slice(2);
const argError = findArgError(args, ARG_SPEC);
if (argError) fail(argError);
let ledgerFile = null;
let outputFile = null;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--ledger-file' && args[i + 1]) ledgerFile = args[++i];
else if (a === '--output-file' && args[i + 1]) outputFile = args[++i];
// A flag we do not understand must fail loudly. Silently dropping it lets a
// caller-side mistake — a typo'd `--ledger-file`, or a shell that did not
// word-split "--flag value" into two argv entries — produce a confident
// report about the wrong ledger.
else if (a.startsWith('--')) fail(`unknown flag "${a}"`);
if (a === '--ledger-file') ledgerFile = args[++i];
else if (a === '--output-file') outputFile = args[++i];
}
const ledgerPath = resolve(ledgerFile || defaultLedgerPath());

View file

@ -58,6 +58,7 @@ import {
} from './lib/campaign-ledger.mjs';
import { readActiveConfig } from './lib/active-config-reader.mjs';
import { buildManifest, splitManifestByOwnership } from './manifest.mjs';
import { findArgError } from './lib/cli-args.mjs';
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
@ -72,19 +73,26 @@ 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 = {
value: ['--ledger-file', '--reference-date', '--output-file', '--name', '--findings', '--session'],
};
/** Parse argv into a subcommand, positional args, and the flag map. */
function parseArgs(argv) {
const argError = findArgError(argv, ARG_SPEC);
if (argError) fail(argError);
const positionals = [];
const flags = { ledgerFile: null, referenceDate: null, outputFile: null, name: null, findings: null, session: null };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === '--ledger-file' && argv[i + 1] !== undefined) flags.ledgerFile = argv[++i];
else if (a === '--reference-date' && argv[i + 1] !== undefined) flags.referenceDate = argv[++i];
else if (a === '--output-file' && argv[i + 1] !== undefined) flags.outputFile = argv[++i];
else if (a === '--name' && argv[i + 1] !== undefined) flags.name = argv[++i];
else if (a === '--findings' && argv[i + 1] !== undefined) flags.findings = argv[++i];
else if (a === '--session' && argv[i + 1] !== undefined) flags.session = argv[++i];
else if (a.startsWith('--')) fail(`unknown flag "${a}"`);
if (a === '--ledger-file') flags.ledgerFile = argv[++i];
else if (a === '--reference-date') flags.referenceDate = argv[++i];
else if (a === '--output-file') flags.outputFile = argv[++i];
else if (a === '--name') flags.name = argv[++i];
else if (a === '--findings') flags.findings = argv[++i];
else if (a === '--session') flags.session = argv[++i];
else positionals.push(a);
}
return { subcommand: positionals[0], rest: positionals.slice(1), flags };

View file

@ -27,6 +27,7 @@ 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}$/;
@ -41,8 +42,14 @@ 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
@ -51,20 +58,15 @@ async function main() {
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--dry-run') dryRun = true;
else if (a === '--output-file' && args[i + 1]) outputFile = args[++i];
else if (a === '--stale-after' && args[i + 1] !== undefined) {
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' && args[i + 1]) {
} else if (a === '--reference-date') {
referenceDate = args[++i];
if (!DATE_RE.test(referenceDate)) fail('--reference-date must be YYYY-MM-DD');
}
// A flag we do not understand must fail loudly. Silently dropping it is how
// `--stale-after 30` — arriving as ONE argv entry from a shell that does not
// word-split — became "all 14 entries are fresh within 90 days": a confident
// answer to a question the caller did not ask.
else if (a.startsWith('--')) fail(`unknown flag "${a}"`);
}
// The clock is read here ONLY — the core takes an injected date and stays pure.

85
scanners/lib/cli-args.mjs Normal file
View file

@ -0,0 +1,85 @@
/**
* Argv precondition shared by the CLIs the companion to `require-target-dir`.
*
* Every CLI here parses argv with a chain of `if (a === '--x') … else if …`.
* Two things fall through that chain silently:
*
* 1. **An unknown flag.** With no `else` branch, `--zzz` leaves no trace: the
* CLI exits 0 with a full payload a confident answer to a question the
* caller did not ask. Measured live (#51): `knowledge-refresh`'s only knob
* reached the CLI malformed, was ignored, and the command reported "all 14
* entries re-verified within the last 90 days" about a threshold the user
* had just overridden.
*
* 2. **A value-taking flag whose value is another flag.** The guard
* `a === '--output-file' && args[i + 1]` asks only whether a next token
* exists, never whether it is a *value*. Measured live (#57):
* `manifest --output-file --json` wrote a file literally named `--json`
* into the caller's working directory, exit 0, with `--json` mode silently
* dropped. A wrong answer is bad; an unintended file on disk is worse.
*
* This runs BEFORE the CLI's own loop and does not replace it. That is
* deliberate: valid argv reaches the existing parser byte-for-byte unchanged, so
* no frozen snapshot can move. Malformed argv never reaches it at all.
*
* By the exit-code contract, a malformed argument is exit **3** the scanner
* did not get to do its job never 0/1/2, which are verdicts about a
* configuration that WAS examined.
*/
/**
* Find the first thing wrong with `args`.
*
* @param {string[]} args - argv slice (no node/script entries).
* @param {{ boolean?: string[], value?: string[] }} spec - the CLI's flag surface.
* @returns {string|null} diagnostic, or null when argv is well-formed.
*/
export function findArgError(args, spec) {
const booleanFlags = new Set(spec.boolean || []);
const valueFlags = new Set(spec.value || []);
for (let i = 0; i < args.length; i++) {
const a = args[i];
// Positionals and subcommands are the CLI's own business.
if (!a.startsWith('-')) continue;
if (booleanFlags.has(a)) continue;
if (valueFlags.has(a)) {
const next = args[i + 1];
if (next === undefined) {
return `flag "${a}" needs a value, but nothing followed it`;
}
if (next.startsWith('-')) {
return `flag "${a}" needs a value, but the next argument was another flag: "${next}"`;
}
i++; // consume the value so it is never re-examined as a positional
continue;
}
return `unknown flag "${a}"`;
}
return null;
}
/**
* Gate a CLI on well-formed argv. Writes the diagnostic and sets the exit code
* itself, so callers stay a two-line guard:
*
* if (!requireValidArgs(args, ARG_SPEC)) return;
*
* Never throws, and never calls `process.exit()` an abrupt exit discards
* unflushed stdout when the CLI is on a pipe.
*
* @param {string[]} args - argv slice.
* @param {{ boolean?: string[], value?: string[] }} spec - the CLI's flag surface.
* @returns {boolean} true when the CLI may proceed.
*/
export function requireValidArgs(args, spec) {
const error = findArgError(args, spec);
if (error === null) return true;
process.stderr.write(`Error: ${error}\n`);
process.exitCode = 3;
return false;
}

View file

@ -43,6 +43,10 @@ import { resolve } from 'node:path';
import { stat } from 'node:fs/promises';
import { writeOutputFile } from './lib/write-output.mjs';
import { readActiveConfig, deriveLoadPattern } from './lib/active-config-reader.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = { boolean: ['--json', '--raw'], value: ['--output-file'] };
// CLAUDE.md cascade files are all discovered by walking UP from the repo, so
// each one is always-loaded; the scope only changes the derivation confidence.
@ -241,6 +245,7 @@ function estimateClaudeMdEntryTokens(file, activeConfig) {
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let jsonMode = false;

View file

@ -34,6 +34,10 @@ import { loadRegister, getEntry } from './lib/best-practices-register.mjs';
import { prefilterClaudeMd, LENS_DETECTORS } from './lib/lens-prefilter.mjs';
import { subtractionCandidates, SUBTRACT_DETECTORS } from './lib/subtraction-prefilter.mjs';
import { scan as optScan } from './optimization-lens-scanner.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = { boolean: ['--global', '--subtract'], value: ['--output-file'] };
// Files under `.claude/plugins/` are shipped by an installed plugin — vendored
// CLAUDE.md plus its bundled tests/fixtures and examples. They are not the user's
@ -52,6 +56,7 @@ function confirmedEntry(register, id) {
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let includeGlobal = false;

View file

@ -12,6 +12,7 @@ import { writeOutputFile } from './lib/write-output.mjs';
import { requireTargetDir } from './lib/require-target-dir.mjs';
import { runAllScanners } from './scan-orchestrator.mjs';
import { humanizeEnvelope } from './lib/humanizer.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
import {
calculateUtilization,
determineMaturityLevel,
@ -22,6 +23,12 @@ import {
generateHealthScorecard,
} from './lib/scoring.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = {
boolean: ['--json', '--raw', '--global', '--full-machine', '--include-fixtures'],
value: ['--output-file', '--context-window'],
};
/**
* Run posture assessment and return structured result.
* @param {string} targetPath
@ -59,6 +66,7 @@ export async function runPosture(targetPath, opts = {}) {
// --- CLI entry point ---
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let jsonMode = false;

View file

@ -36,6 +36,16 @@ import { scan as scanSkillListing } from './skill-listing-scanner.mjs';
import { scan as scanAgentListing } from './agent-listing-scanner.mjs';
import { scan as scanOutputStyle } from './output-style-scanner.mjs';
import { scan as scanOptimizationLens } from './optimization-lens-scanner.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = {
boolean: [
'--json', '--raw', '--global', '--full-machine', '--no-suppress',
'--include-fixtures', '--exclude-cache', '--no-exclude-cache', '--save-baseline',
],
value: ['--output-file', '--context-window', '--baseline'],
};
// Directory names that identify test fixture / example directories
const FIXTURE_DIR_NAMES = ['tests', 'examples', '__tests__', 'test-fixtures'];
@ -217,6 +227,7 @@ export async function runAllScanners(targetPath, opts = {}) {
// --- CLI entry point ---
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let saveBaseline = false;

View file

@ -20,6 +20,10 @@ import { gradeFromPassRate } from './lib/severity.mjs';
import { loadSuppressions, applySuppressions } from './lib/suppression.mjs';
import { parseJson } from './lib/yaml-parser.mjs';
import { humanizeEnvelope, humanizeFindings } from './lib/humanizer.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = { boolean: ['--json', '--fix', '--check-readme'] };
const execFileAsync = promisify(execFile);
@ -330,6 +334,7 @@ export function formatSelfAudit(result) {
// --- CLI entry point ---
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
const jsonMode = args.includes('--json');
const fixMode = args.includes('--fix');
const checkReadmeMode = args.includes('--check-readme');

View file

@ -21,6 +21,16 @@ import { resetCounter } from './lib/output.mjs';
import { scan } from './token-hotspots.mjs';
import * as tokenizerApi from './lib/tokenizer-api.mjs';
import { humanizeFindings } from './lib/humanizer.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = {
boolean: [
'--json', '--raw', '--global', '--with-telemetry-recipe',
'--accurate-tokens', '--exclude-cache', '--no-exclude-cache',
],
value: ['--output-file'],
};
const __dirname = dirname(fileURLToPath(import.meta.url));
const TELEMETRY_RECIPE_PATH = resolve(__dirname, '..', 'knowledge', 'cache-telemetry-recipe.md');
@ -50,6 +60,7 @@ async function calibrateAgainstApi(hotspots, apiKey) {
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let jsonMode = false;

View file

@ -16,9 +16,14 @@ import { resolve } from 'node:path';
import { stat } from 'node:fs/promises';
import { writeOutputFile } from './lib/write-output.mjs';
import { readActiveConfig } from './lib/active-config-reader.mjs';
import { requireValidArgs } from './lib/cli-args.mjs';
/** Flag surface, measured 2026-08-09. Anything else is exit 3. */
const ARG_SPEC = { boolean: ['--json', '--raw', '--verbose', '--suggest-disables'], value: ['--output-file'] };
async function main() {
const args = process.argv.slice(2);
if (!requireValidArgs(args, ARG_SPEC)) return;
let targetPath = '.';
let outputFile = null;
let jsonMode = false;