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:
parent
3d6ddb273c
commit
182a37c1af
14 changed files with 337 additions and 45 deletions
|
|
@ -44,6 +44,8 @@ Scanner CLI: `node scanners/scan-orchestrator.mjs <path> [--global] [--full-mach
|
||||||
| `active-config-reader.mjs` | Read-only inventory: readActiveConfig(), detectGitRoot(), walkClaudeMdCascade(), readClaudeJsonProjectSlice() (longest-prefix match), enumeratePlugins(), enumerateSkills(), readActiveHooks(), readActiveMcpServers() (with cache → package.json tool-count fallback), estimateTokens() (v5: `'mcp'` kind = 500 + toolCount × 200) |
|
| `active-config-reader.mjs` | Read-only inventory: readActiveConfig(), detectGitRoot(), walkClaudeMdCascade(), readClaudeJsonProjectSlice() (longest-prefix match), enumeratePlugins(), enumerateSkills(), readActiveHooks(), readActiveMcpServers() (with cache → package.json tool-count fallback), estimateTokens() (v5: `'mcp'` kind = 500 + toolCount × 200) |
|
||||||
| `tokenizer-api.mjs` | Anthropic `count_tokens` wrapper for `--accurate-tokens` (v5 N5); 5s AbortController timeout, exponential 429 backoff, key masking |
|
| `tokenizer-api.mjs` | Anthropic `count_tokens` wrapper for `--accurate-tokens` (v5 N5); 5s AbortController timeout, exponential 429 backoff, key masking |
|
||||||
| `humanizer.mjs` | Plain-language output translator (v5.1.0): `humanizeFinding`, `humanizeFindings`, `humanizeEnvelope`, `computeRelevanceContext`. Pure functions; never mutate inputs. Adds `userImpactCategory`, `userActionLanguage`, `relevanceContext` fields and replaces title/description/recommendation when a translation exists. Bypassed by `--raw` and `--json` paths. |
|
| `humanizer.mjs` | Plain-language output translator (v5.1.0): `humanizeFinding`, `humanizeFindings`, `humanizeEnvelope`, `computeRelevanceContext`. Pure functions; never mutate inputs. Adds `userImpactCategory`, `userActionLanguage`, `relevanceContext` fields and replaces title/description/recommendation when a translation exists. Bypassed by `--raw` and `--json` paths. |
|
||||||
|
| `cli-args.mjs` | Argv precondition shared by the CLIs: `findArgError(args, spec)` / `requireValidArgs(args, spec)`. Rejects an unknown flag, and a value-taking flag whose next token is missing or is itself a flag — exit 3, never a verdict. Runs BEFORE each CLI's own parse loop, so valid argv reaches the existing parser unchanged (see Implementation notes → arg-sluk) |
|
||||||
|
| `require-target-dir.mjs` | Target-path precondition: a scan root that does not exist, or is not a directory, is exit 3 rather than a graded verdict (#56) |
|
||||||
| `humanizer-data.mjs` | TRANSLATIONS table for 16 scanner prefixes (CML/SET/HKV/RUL/MCP/IMP/CNF/COL/TOK/CPS/DIS/GAP/PLH/SKL/OST/OPT). Three-step lookup: exact title → regex pattern → `_default` → fall through to original |
|
| `humanizer-data.mjs` | TRANSLATIONS table for 16 scanner prefixes (CML/SET/HKV/RUL/MCP/IMP/CNF/COL/TOK/CPS/DIS/GAP/PLH/SKL/OST/OPT). Three-step lookup: exact title → regex pattern → `_default` → fall through to original |
|
||||||
|
|
||||||
## Action Engines (`scanners/`)
|
## Action Engines (`scanners/`)
|
||||||
|
|
@ -727,3 +729,39 @@ The second half of Block 4. **Asymmetric:** plan export is the new testable code
|
||||||
commands **21** (export is a *mode*, not a new command), snapshot/backcompat suite untouched.
|
commands **21** (export is a *mode*, not a new command), snapshot/backcompat suite untouched.
|
||||||
suite 1150→1168 (lib +8, export-cli +10). **Block 4a (`migrateLedger`) still deferred** to the
|
suite 1150→1168 (lib +8, export-cli +10). **Block 4a (`migrateLedger`) still deferred** to the
|
||||||
first breaking schema change (export needs no schema bump).
|
first breaking schema change (export needs no schema bump).
|
||||||
|
|
||||||
|
### arg-sluk — the CLI argument class, measured across all fourteen CLIs (v5.14, #57)
|
||||||
|
|
||||||
|
`scanners/lib/cli-args.mjs`. Every CLI in `scanners/` parses argv with a chain of
|
||||||
|
`if (a === '--x') … else if …`, and two things fell through that chain in silence.
|
||||||
|
|
||||||
|
**Arm 1 — the unknown flag.** With no `else` branch, `--zzz` left no trace: exit 0, full
|
||||||
|
payload, a confident answer to a question the caller did not ask. First costed in #51, when
|
||||||
|
`knowledge-refresh`'s only knob reached the CLI malformed and the command reported "all 14
|
||||||
|
register entries were re-verified within the last 90 days" — about a threshold the user had
|
||||||
|
just overridden.
|
||||||
|
|
||||||
|
**Arm 2 — the value that was really a flag.** `a === '--output-file' && args[i + 1]` asks
|
||||||
|
only whether a next token *exists*, never whether it is a value. So `--output-file --json`
|
||||||
|
took `--json` as the filename. Measured: `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; an
|
||||||
|
unintended file on disk is worse.
|
||||||
|
|
||||||
|
**Width — the deferral list was a prediction, not a measurement.** `KNOWN_OPEN` in
|
||||||
|
`tests/scanners/cli-unknown-flag-rejection.test.mjs` named **two** CLIs. Measuring all
|
||||||
|
fourteen found **7** open on arm 1 and **10** on arm 2 — including `campaign-cli` and
|
||||||
|
`knowledge-refresh-cli`, which were already in `GUARDED` and *passing* the arm-1 test while
|
||||||
|
arm 2 stood open a few lines away. Three CLIs (`drift-cli`, `fix-cli`,
|
||||||
|
`plugin-health-scanner`) were already correct on both arms because they use a different
|
||||||
|
parse form; they were moved into `GUARDED` rather than left unguarded.
|
||||||
|
|
||||||
|
**Why a gate and not a rewrite.** The module runs *before* each CLI's existing loop and does
|
||||||
|
not replace it. Valid argv therefore reaches the existing parser byte-for-byte unchanged, so
|
||||||
|
no frozen snapshot can move — the byte-stability argument is structural, not empirical. The
|
||||||
|
three CLIs that carried a bespoke `else if (a.startsWith('--')) fail(…)` branch had it removed
|
||||||
|
once the gate made it unreachable, along with the now-redundant `&& args[i + 1]` guards.
|
||||||
|
|
||||||
|
Exit code is **3** by the exit-code contract: a malformed argument means the scanner never got
|
||||||
|
to do its job, which is categorically different from 0/1/2 — verdicts about a configuration
|
||||||
|
that *was* examined.
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@
|
||||||
|
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { writeOutputFile } from './lib/write-output.mjs';
|
import { writeOutputFile } from './lib/write-output.mjs';
|
||||||
|
import { findArgError } from './lib/cli-args.mjs';
|
||||||
import {
|
import {
|
||||||
loadLedger,
|
loadLedger,
|
||||||
validateLedger,
|
validateLedger,
|
||||||
|
|
@ -43,20 +44,21 @@ function fail(message) {
|
||||||
throw new CliUsageError(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() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
const argError = findArgError(args, ARG_SPEC);
|
||||||
|
if (argError) fail(argError);
|
||||||
let ledgerFile = null;
|
let ledgerFile = null;
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
const a = args[i];
|
const a = args[i];
|
||||||
if (a === '--ledger-file' && args[i + 1]) ledgerFile = args[++i];
|
if (a === '--ledger-file') ledgerFile = args[++i];
|
||||||
else if (a === '--output-file' && args[i + 1]) outputFile = args[++i];
|
else if (a === '--output-file') 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}"`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ledgerPath = resolve(ledgerFile || defaultLedgerPath());
|
const ledgerPath = resolve(ledgerFile || defaultLedgerPath());
|
||||||
|
|
|
||||||
|
|
@ -58,6 +58,7 @@ import {
|
||||||
} from './lib/campaign-ledger.mjs';
|
} from './lib/campaign-ledger.mjs';
|
||||||
import { readActiveConfig } from './lib/active-config-reader.mjs';
|
import { readActiveConfig } from './lib/active-config-reader.mjs';
|
||||||
import { buildManifest, splitManifestByOwnership } from './manifest.mjs';
|
import { buildManifest, splitManifestByOwnership } from './manifest.mjs';
|
||||||
|
import { findArgError } from './lib/cli-args.mjs';
|
||||||
|
|
||||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
|
|
@ -72,19 +73,26 @@ function fail(message) {
|
||||||
throw new CliUsageError(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. */
|
/** Parse argv into a subcommand, positional args, and the flag map. */
|
||||||
function parseArgs(argv) {
|
function parseArgs(argv) {
|
||||||
|
const argError = findArgError(argv, ARG_SPEC);
|
||||||
|
if (argError) fail(argError);
|
||||||
const positionals = [];
|
const positionals = [];
|
||||||
const flags = { ledgerFile: null, referenceDate: null, outputFile: null, name: null, findings: null, session: null };
|
const flags = { ledgerFile: null, referenceDate: null, outputFile: null, name: null, findings: null, session: null };
|
||||||
for (let i = 0; i < argv.length; i++) {
|
for (let i = 0; i < argv.length; i++) {
|
||||||
const a = argv[i];
|
const a = argv[i];
|
||||||
if (a === '--ledger-file' && argv[i + 1] !== undefined) flags.ledgerFile = argv[++i];
|
if (a === '--ledger-file') flags.ledgerFile = argv[++i];
|
||||||
else if (a === '--reference-date' && argv[i + 1] !== undefined) flags.referenceDate = argv[++i];
|
else if (a === '--reference-date') flags.referenceDate = argv[++i];
|
||||||
else if (a === '--output-file' && argv[i + 1] !== undefined) flags.outputFile = argv[++i];
|
else if (a === '--output-file') flags.outputFile = argv[++i];
|
||||||
else if (a === '--name' && argv[i + 1] !== undefined) flags.name = argv[++i];
|
else if (a === '--name') flags.name = argv[++i];
|
||||||
else if (a === '--findings' && argv[i + 1] !== undefined) flags.findings = argv[++i];
|
else if (a === '--findings') flags.findings = argv[++i];
|
||||||
else if (a === '--session' && argv[i + 1] !== undefined) flags.session = argv[++i];
|
else if (a === '--session') flags.session = argv[++i];
|
||||||
else if (a.startsWith('--')) fail(`unknown flag "${a}"`);
|
|
||||||
else positionals.push(a);
|
else positionals.push(a);
|
||||||
}
|
}
|
||||||
return { subcommand: positionals[0], rest: positionals.slice(1), flags };
|
return { subcommand: positionals[0], rest: positionals.slice(1), flags };
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import { resolve } from 'node:path';
|
||||||
import { writeOutputFile } from './lib/write-output.mjs';
|
import { writeOutputFile } from './lib/write-output.mjs';
|
||||||
import { loadRegister, REGISTER_PATH } from './lib/best-practices-register.mjs';
|
import { loadRegister, REGISTER_PATH } from './lib/best-practices-register.mjs';
|
||||||
import { assessFreshness, STALE_AFTER_DAYS_DEFAULT } from './lib/knowledge-refresh.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}$/;
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
|
||||||
|
|
@ -41,8 +42,14 @@ function fail(message) {
|
||||||
throw new CliUsageError(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() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
const argError = findArgError(args, ARG_SPEC);
|
||||||
|
if (argError) fail(argError);
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let staleAfterDays = STALE_AFTER_DAYS_DEFAULT;
|
let staleAfterDays = STALE_AFTER_DAYS_DEFAULT;
|
||||||
let referenceDate = null; // null → today
|
let referenceDate = null; // null → today
|
||||||
|
|
@ -51,20 +58,15 @@ async function main() {
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
const a = args[i];
|
const a = args[i];
|
||||||
if (a === '--dry-run') dryRun = true;
|
if (a === '--dry-run') dryRun = true;
|
||||||
else if (a === '--output-file' && args[i + 1]) outputFile = args[++i];
|
else if (a === '--output-file') outputFile = args[++i];
|
||||||
else if (a === '--stale-after' && args[i + 1] !== undefined) {
|
else if (a === '--stale-after') {
|
||||||
const n = Number.parseInt(args[++i], 10);
|
const n = Number.parseInt(args[++i], 10);
|
||||||
if (!Number.isInteger(n) || n < 0) fail('--stale-after must be a non-negative integer (days)');
|
if (!Number.isInteger(n) || n < 0) fail('--stale-after must be a non-negative integer (days)');
|
||||||
staleAfterDays = n;
|
staleAfterDays = n;
|
||||||
} else if (a === '--reference-date' && args[i + 1]) {
|
} else if (a === '--reference-date') {
|
||||||
referenceDate = args[++i];
|
referenceDate = args[++i];
|
||||||
if (!DATE_RE.test(referenceDate)) fail('--reference-date must be YYYY-MM-DD');
|
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.
|
// The clock is read here ONLY — the core takes an injected date and stays pure.
|
||||||
|
|
|
||||||
85
scanners/lib/cli-args.mjs
Normal file
85
scanners/lib/cli-args.mjs
Normal 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;
|
||||||
|
}
|
||||||
|
|
@ -43,6 +43,10 @@ import { resolve } from 'node:path';
|
||||||
import { stat } from 'node:fs/promises';
|
import { stat } from 'node:fs/promises';
|
||||||
import { writeOutputFile } from './lib/write-output.mjs';
|
import { writeOutputFile } from './lib/write-output.mjs';
|
||||||
import { readActiveConfig, deriveLoadPattern } from './lib/active-config-reader.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
|
// 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.
|
// each one is always-loaded; the scope only changes the derivation confidence.
|
||||||
|
|
@ -241,6 +245,7 @@ function estimateClaudeMdEntryTokens(file, activeConfig) {
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let jsonMode = false;
|
let jsonMode = false;
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,10 @@ import { loadRegister, getEntry } from './lib/best-practices-register.mjs';
|
||||||
import { prefilterClaudeMd, LENS_DETECTORS } from './lib/lens-prefilter.mjs';
|
import { prefilterClaudeMd, LENS_DETECTORS } from './lib/lens-prefilter.mjs';
|
||||||
import { subtractionCandidates, SUBTRACT_DETECTORS } from './lib/subtraction-prefilter.mjs';
|
import { subtractionCandidates, SUBTRACT_DETECTORS } from './lib/subtraction-prefilter.mjs';
|
||||||
import { scan as optScan } from './optimization-lens-scanner.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
|
// 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
|
// 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() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let includeGlobal = false;
|
let includeGlobal = false;
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import { writeOutputFile } from './lib/write-output.mjs';
|
||||||
import { requireTargetDir } from './lib/require-target-dir.mjs';
|
import { requireTargetDir } from './lib/require-target-dir.mjs';
|
||||||
import { runAllScanners } from './scan-orchestrator.mjs';
|
import { runAllScanners } from './scan-orchestrator.mjs';
|
||||||
import { humanizeEnvelope } from './lib/humanizer.mjs';
|
import { humanizeEnvelope } from './lib/humanizer.mjs';
|
||||||
|
import { requireValidArgs } from './lib/cli-args.mjs';
|
||||||
import {
|
import {
|
||||||
calculateUtilization,
|
calculateUtilization,
|
||||||
determineMaturityLevel,
|
determineMaturityLevel,
|
||||||
|
|
@ -22,6 +23,12 @@ import {
|
||||||
generateHealthScorecard,
|
generateHealthScorecard,
|
||||||
} from './lib/scoring.mjs';
|
} 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.
|
* Run posture assessment and return structured result.
|
||||||
* @param {string} targetPath
|
* @param {string} targetPath
|
||||||
|
|
@ -59,6 +66,7 @@ export async function runPosture(targetPath, opts = {}) {
|
||||||
// --- CLI entry point ---
|
// --- CLI entry point ---
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let jsonMode = false;
|
let jsonMode = false;
|
||||||
|
|
|
||||||
|
|
@ -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 scanAgentListing } from './agent-listing-scanner.mjs';
|
||||||
import { scan as scanOutputStyle } from './output-style-scanner.mjs';
|
import { scan as scanOutputStyle } from './output-style-scanner.mjs';
|
||||||
import { scan as scanOptimizationLens } from './optimization-lens-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
|
// Directory names that identify test fixture / example directories
|
||||||
const FIXTURE_DIR_NAMES = ['tests', 'examples', '__tests__', 'test-fixtures'];
|
const FIXTURE_DIR_NAMES = ['tests', 'examples', '__tests__', 'test-fixtures'];
|
||||||
|
|
@ -217,6 +227,7 @@ export async function runAllScanners(targetPath, opts = {}) {
|
||||||
// --- CLI entry point ---
|
// --- CLI entry point ---
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let saveBaseline = false;
|
let saveBaseline = false;
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,10 @@ import { gradeFromPassRate } from './lib/severity.mjs';
|
||||||
import { loadSuppressions, applySuppressions } from './lib/suppression.mjs';
|
import { loadSuppressions, applySuppressions } from './lib/suppression.mjs';
|
||||||
import { parseJson } from './lib/yaml-parser.mjs';
|
import { parseJson } from './lib/yaml-parser.mjs';
|
||||||
import { humanizeEnvelope, humanizeFindings } from './lib/humanizer.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);
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
|
@ -330,6 +334,7 @@ export function formatSelfAudit(result) {
|
||||||
// --- CLI entry point ---
|
// --- CLI entry point ---
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
const jsonMode = args.includes('--json');
|
const jsonMode = args.includes('--json');
|
||||||
const fixMode = args.includes('--fix');
|
const fixMode = args.includes('--fix');
|
||||||
const checkReadmeMode = args.includes('--check-readme');
|
const checkReadmeMode = args.includes('--check-readme');
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,16 @@ import { resetCounter } from './lib/output.mjs';
|
||||||
import { scan } from './token-hotspots.mjs';
|
import { scan } from './token-hotspots.mjs';
|
||||||
import * as tokenizerApi from './lib/tokenizer-api.mjs';
|
import * as tokenizerApi from './lib/tokenizer-api.mjs';
|
||||||
import { humanizeFindings } from './lib/humanizer.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 __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const TELEMETRY_RECIPE_PATH = resolve(__dirname, '..', 'knowledge', 'cache-telemetry-recipe.md');
|
const TELEMETRY_RECIPE_PATH = resolve(__dirname, '..', 'knowledge', 'cache-telemetry-recipe.md');
|
||||||
|
|
@ -50,6 +60,7 @@ async function calibrateAgainstApi(hotspots, apiKey) {
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let jsonMode = false;
|
let jsonMode = false;
|
||||||
|
|
|
||||||
|
|
@ -16,9 +16,14 @@ import { resolve } from 'node:path';
|
||||||
import { stat } from 'node:fs/promises';
|
import { stat } from 'node:fs/promises';
|
||||||
import { writeOutputFile } from './lib/write-output.mjs';
|
import { writeOutputFile } from './lib/write-output.mjs';
|
||||||
import { readActiveConfig } from './lib/active-config-reader.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() {
|
async function main() {
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
if (!requireValidArgs(args, ARG_SPEC)) return;
|
||||||
let targetPath = '.';
|
let targetPath = '.';
|
||||||
let outputFile = null;
|
let outputFile = null;
|
||||||
let jsonMode = false;
|
let jsonMode = false;
|
||||||
|
|
|
||||||
52
tests/lib/cli-args.test.mjs
Normal file
52
tests/lib/cli-args.test.mjs
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
/**
|
||||||
|
* Unit-level companion to `tests/scanners/cli-unknown-flag-rejection.test.mjs`.
|
||||||
|
* That file measures the real CLIs end-to-end; this one pins the decision table
|
||||||
|
* itself, including the cases no CLI happens to exercise today.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import { strict as assert } from 'node:assert';
|
||||||
|
import { findArgError } from '../../scanners/lib/cli-args.mjs';
|
||||||
|
|
||||||
|
const SPEC = { boolean: ['--json', '--raw'], value: ['--output-file', '--context-window'] };
|
||||||
|
|
||||||
|
test('well-formed argv passes', () => {
|
||||||
|
assert.equal(findArgError([], SPEC), null);
|
||||||
|
assert.equal(findArgError(['--json'], SPEC), null);
|
||||||
|
assert.equal(findArgError(['--output-file', 'out.json', '--raw'], SPEC), null);
|
||||||
|
assert.equal(findArgError(['/some/target', '--json'], SPEC), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unknown flag is named in the diagnostic', () => {
|
||||||
|
const err = findArgError(['--zzz'], SPEC);
|
||||||
|
assert.match(err, /unknown flag "--zzz"/, 'the caller must be able to find the offending token');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a value flag followed by another flag is rejected', () => {
|
||||||
|
const err = findArgError(['--output-file', '--json'], SPEC);
|
||||||
|
assert.match(err, /--output-file/);
|
||||||
|
assert.match(err, /--json/, 'both the flag and the thing mistaken for its value must appear');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a value flag with nothing after it is rejected', () => {
|
||||||
|
assert.match(findArgError(['--output-file'], SPEC), /nothing followed it/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a value is never re-read as a flag', () => {
|
||||||
|
// Without the consume step, a value that looks like a positional is harmless,
|
||||||
|
// but a spec change could make this the difference between pass and reject.
|
||||||
|
assert.equal(findArgError(['--output-file', 'report.json'], SPEC), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('positionals and subcommands pass through untouched', () => {
|
||||||
|
assert.equal(findArgError(['init', '/target'], SPEC), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the FIRST error is reported, not the last', () => {
|
||||||
|
// A caller fixing errors one at a time should see them in argv order.
|
||||||
|
assert.match(findArgError(['--zzz', '--output-file'], SPEC), /--zzz/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a spec with no value flags still rejects unknown flags', () => {
|
||||||
|
assert.match(findArgError(['--nope'], { boolean: ['--json'] }), /unknown flag "--nope"/);
|
||||||
|
});
|
||||||
|
|
@ -28,29 +28,43 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import { strict as assert } from 'node:assert';
|
import { strict as assert } from 'node:assert';
|
||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
import { readFile } from 'node:fs/promises';
|
import { readFile, mkdtemp, readdir, rm } from 'node:fs/promises';
|
||||||
import { resolve, dirname } from 'node:path';
|
import { resolve, dirname, join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const SCANNERS_DIR = resolve(__dirname, '..', '..', 'scanners');
|
const SCANNERS_DIR = resolve(__dirname, '..', '..', 'scanners');
|
||||||
|
|
||||||
/** CLIs this guard holds to the invariant, with the argv they need to get past required-arg checks. */
|
/**
|
||||||
|
* 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 = [
|
const GUARDED = [
|
||||||
{ cli: 'campaign-cli.mjs', argv: [] },
|
{ cli: 'campaign-cli.mjs', argv: [], valueFlag: '--output-file' },
|
||||||
{ cli: 'knowledge-refresh-cli.mjs', argv: [] },
|
{ cli: 'knowledge-refresh-cli.mjs', argv: [], valueFlag: '--output-file' },
|
||||||
{ cli: 'campaign-write-cli.mjs', argv: ['init'] },
|
{ cli: 'campaign-write-cli.mjs', argv: ['init'], valueFlag: '--output-file' },
|
||||||
{ cli: 'campaign-export-cli.mjs', argv: ['--repo', '.'] },
|
{ 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
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Same defect, deferred to the v5.14 arg-handling chunk together with their positional-swallow arm. */
|
function run(cli, argv, cwd = resolve(__dirname, '..', '..')) {
|
||||||
const KNOWN_OPEN = ['optimize-lens-cli.mjs', 'token-hotspots-cli.mjs'];
|
|
||||||
|
|
||||||
function run(cli, argv) {
|
|
||||||
return new Promise((res) => {
|
return new Promise((res) => {
|
||||||
const child = spawn(process.execPath, [resolve(SCANNERS_DIR, cli), ...argv], {
|
const child = spawn(process.execPath, [resolve(SCANNERS_DIR, cli), ...argv], { cwd });
|
||||||
cwd: resolve(__dirname, '..', '..'),
|
|
||||||
});
|
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
child.stderr.on('data', (d) => { stderr += d; });
|
child.stderr.on('data', (d) => { stderr += d; });
|
||||||
child.stdout.on('data', () => {});
|
child.stdout.on('data', () => {});
|
||||||
|
|
@ -77,15 +91,56 @@ for (const { cli, argv } of GUARDED) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
test('the deferred CLIs are still deferred, and still counted', () => {
|
/**
|
||||||
assert.equal(
|
* Arm 2 — the value arm, and the sharper of the two.
|
||||||
KNOWN_OPEN.length,
|
*
|
||||||
2,
|
* `else if (a === '--output-file' && args[i + 1])` only asks whether a next token
|
||||||
'When the v5.14 arg-handling chunk closes optimize-lens-cli and token-hotspots-cli,\n' +
|
* EXISTS, never whether it is a value. So `--output-file --json` takes `--json`
|
||||||
'move them from KNOWN_OPEN into GUARDED rather than deleting them — the count is\n' +
|
* as the filename: measured live (#57), `manifest`, `campaign-cli` and
|
||||||
'the record of how wide the class was.',
|
* `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
|
* The caller arm. #45/#46/#47 all taught the same lesson: fixing a CLI does not fix the
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue