inspector/scripts/verify-format-coverage.mjs
Cliff Hall 4defa32ac6
chore: close a batch of quality-gate & tidy gaps (#1785 #1787 #1789 #1790 #1767) (#1792)
* chore: close a batch of quality-gate & tidy gaps (#1785 #1787 #1789 #1790 #1767)

Bundles five small, related tidy/gate items into one PR:

- #1785: delete the dead src/types/navigation.ts InspectorTab (0 importers;
  duplicated/drifted from utils/inspectorTabs InspectorTabId). src/types/
  now holds only ambient .d.ts stubs.
- #1787: add src/hooks/** to the web coverage `include` (it was silently
  outside the ≥90 gate) and add tests for the two untested hooks,
  useServerJsonImport and useImportClientConfig, bringing every hook to
  ≥90 on lines/statements/functions/branches.
- #1789: widen clients/{cli,tui,launcher} format/format:check to their
  top-level configs; add root format:shared / format:check:shared covering
  test-servers/src/**, vitest.shared.mts, and the repo-root eslint.config.js.
- #1790: pin prettier to an exact version (3.8.4, dropping the ^3.8.1
  caret) in all five package.json files so the format gate's verdict can't
  shift with an in-range patch bump; lockfiles synced.
- #1767: its root-file format+lint gap is closed here (format:shared +
  a new lint:shared via a second files block in the root eslint.config.js;
  web/server/ was already gated in #1788). Its larger cli/tui __tests__
  typecheck piece (76 type errors) is split out to #1791.

Prettier-normalized the newly-covered files (pure formatting). No runtime
behavior change. `npm run ci` green.

Closes #1785
Closes #1787
Closes #1789
Closes #1790
Closes #1767

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* chore: address PR #1792 review findings

- #1789 gap: widen clients/web format to include .storybook and clients/
  launcher format to include scripts/; reformat the 3 .storybook files
  (were non-conforming under the pinned prettier 3.8.4). Audited all 885
  tracked source files — now fully prettier-clean.
- Export VALIDATE_DEBOUNCE_MS / COLLAPSE_DELAY_MS / HIGHLIGHT_DURATION_MS
  from useServerJsonImport and use them in the test instead of hardcoded
  300/1000/250 (so a tuned constant can't silently desync the test).
- Assert the symmetric renameErrors["alpha"] alongside ["beta"] so a
  one-directional collision-check regression fails.
- Comment the blank-rename test as exercising a UI-unreachable defensive
  branch (canImport gates submit).
- Un-stale the two specification/v2_ux_interfaces_plan.md references to the
  now-removed navigation.ts InspectorTab.

npm run ci green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* docs: sync AGENTS.md format-surface description with the widened globs (#1792 review r2)

1ce3b64 added .storybook to clients/web's format glob and scripts/ to
clients/launcher's, but AGENTS.md:222 still described the pre-fix scope.
Bring it in line and note the non-recursive top-level glob is why nested
dirs are named explicitly. Docs only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* chore: handle PR #1792 round-3 follow-ups in-place (format-coverage guard, uniform globs, theme gate)

Rather than defer these to tickets, fold them into this PR:

- Obs 2: widen every client + root format glob to a uniform
  *.{ts,tsx,mts,cts,js,jsx,mjs,cjs} so a future .mts/.cjs/.tsx top-level
  file can't silently slip the gate.
- Obs 1: add scripts/verify-format-coverage.mjs (wired into `validate`) —
  it parses the format:check globs out of every package.json, enumerates
  all tracked source files, and fails listing any not covered by a glob.
  The durable, standing version of #1789's one-shot audit; negative-tested.
- Obs 3: bring src/theme/** under the coverage gate (21/23 files were
  already ≥90 transitively; add Paper.test.tsx for the one laggard,
  Paper.ts). src/App.tsx (~4.5k lines, ~42% branches) is converted from a
  silent omission into an explicit, documented exclusion (comment on the
  coverage `include` + AGENTS.md) — gating it is a dedicated effort, not a
  whitelist tweak.

npm run ci green (the new guard reports 885/885 tracked source files gated).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* chore: address PR #1792 round-4 findings (guard hardening, docs, exclusion list)

- Harden verify-format-coverage: only harvest format:check globs from
  scripts transitively reachable from `validate` (via npm run refs), so an
  unwired/renamed format:check no longer counts as coverage. Negative-tested
  — renaming clients/web format:check to an unreferenced name now fails the
  guard (627 files flagged) instead of passing.
- Name src/main.tsx and src/index.ts (browser + bin bootstraps) alongside
  src/App.tsx in the coverage-include comment and AGENTS.md, so the
  documented exclusion list is complete rather than claiming App.tsx is the
  only one.
- Doc sync: document verify:format-coverage (AGENTS.md + README script table
  + scripts/ layout line), fix the `validate` ordering (verify:format-
  coverage now runs before validate:core) in AGENTS.md and README, and
  update the quoted globs to the uniform *.{ts,tsx,mts,cts,js,jsx,mjs,cjs} /
  test-servers *.{ts,tsx,mts,cts}.

npm run ci green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

* chore: address PR #1792 round-5 findings (airtight guard + doc/config sync)

- verify-format-coverage: assert the root `validate` chain invokes each
  client's `validate` (cd <dir> && npm run validate), closing the last
  reachability edge — a client dropped from the root chain now fails the
  guard even though its own globs still exist. Negative-tested.
- eslint.config.js: widen the shared `files` block to
  test-servers/src/**/*.{ts,tsx,mts,cts} to match the widened lint:shared
  glob, so a future .mts/.cts there is lint-gated, not just prettier-gated.
- AGENTS.md: scope the "uniform extension set" claim to client globs
  (core stays {ts,tsx}, shared {ts,tsx,mts,cts}), with verify:format-coverage
  as the backstop — removing the self-contradiction with the line below.

npm run ci green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XNdjEPKLG637X8YmhDiEk5

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 10:43:11 -04:00

237 lines
8 KiB
JavaScript

#!/usr/bin/env node
// Durable guard for the "every first-party source file is format-gated" invariant
// that #1789 established by a one-shot manual audit (PR #1792). A prettier
// `format`/`format:check` glob that stops covering a file fails silently — the
// file is simply skipped, not reported — so a nested dir (`.storybook/`, a
// client `scripts/`) or a new extension can re-open the gap unnoticed. This is
// the format-coverage analog of `verify:build-gate`: it enumerates every tracked
// source file and asserts each is matched by at least one `prettier --check`
// glob declared across the repo's `package.json`s. Exits non-zero, listing the
// offenders, on any miss.
//
// Source of truth is the `format:check*` scripts themselves — this parser reads
// the globs out of them, so widening/narrowing a glob is reflected here with no
// second list to keep in sync.
import { readFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"..",
);
// File extensions prettier formats as first-party source here. Kept in sync with
// the union of the format globs; a file with one of these extensions that no
// glob matches is the failure this guard exists to catch.
const SOURCE_EXTENSIONS = [
"ts",
"tsx",
"mts",
"cts",
"js",
"jsx",
"mjs",
"cjs",
];
// The `package.json`s whose `format:check*` scripts define the gate. The root
// carries the split `format:check:core|scripts|shared`; each client carries a
// single `format:check`. Paths are relative to the repo root; each glob resolves
// relative to its manifest's directory (prettier's cwd for that script).
const MANIFESTS = [
".",
"clients/web",
"clients/cli",
"clients/tui",
"clients/launcher",
];
/** Split a shell-ish command string into args, honoring double quotes. */
function tokenize(command) {
const tokens = [];
const re = /"([^"]*)"|(\S+)/g;
let m;
while ((m = re.exec(command)) !== null) {
tokens.push(m[1] !== undefined ? m[1] : m[2]);
}
return tokens;
}
/**
* Names of scripts transitively reachable from `entry` by following `npm run
* <name>` references within a manifest. Used so we only trust a `format:check`
* glob that CI actually runs — a `prettier --check` script that nothing invokes
* from `validate` doesn't gate anything, and counting its globs would let the
* gate be silently unwired (the file still "matches a glob" that never runs).
*/
function reachableScripts(scripts, entry = "validate") {
const reached = new Set();
const queue = [entry];
const runRef = /npm run ([\w:-]+)/g;
while (queue.length > 0) {
const name = queue.shift();
if (reached.has(name)) continue;
reached.add(name);
const cmd = scripts?.[name];
if (typeof cmd !== "string") continue;
for (const m of cmd.matchAll(runRef)) queue.push(m[1]);
}
return reached;
}
/**
* Extract the path/glob args from every `prettier --check …` in a manifest's
* scripts that is reachable from `validate`. Restricting to reachable scripts is
* what makes the guard assert "this file is checked by CI", not merely "some
* glob covers it".
*/
function prettierCheckArgs(scripts) {
const reachable = reachableScripts(scripts);
const args = [];
for (const [name, value] of Object.entries(scripts ?? {})) {
if (!reachable.has(name)) continue;
if (typeof value !== "string" || !value.includes("prettier --check"))
continue;
// A manifest may chain `prettier --check …` inside a larger script; take the
// segment starting at each occurrence up to the next `&&`/`||`/`;`.
for (const segment of value.split(/&&|\|\||;/)) {
const trimmed = segment.trim();
if (!trimmed.startsWith("prettier --check")) continue;
const tokens = tokenize(trimmed).slice(2); // drop `prettier` `--check`
for (const t of tokens) {
if (t.startsWith("-")) continue; // a flag, not a path
args.push(t);
}
}
}
return args;
}
const GLOB_CHARS = /[*?{}[\]]/;
/** Convert a prettier glob to an anchored RegExp over repo-relative POSIX paths. */
function globToRegExp(glob) {
let re = "";
for (let i = 0; i < glob.length; i++) {
const c = glob[i];
if (c === "*") {
if (glob[i + 1] === "*") {
// `**` (optionally `**/`) crosses path separators.
if (glob[i + 2] === "/") {
re += "(?:.*/)?";
i += 2;
} else {
re += ".*";
i += 1;
}
} else {
re += "[^/]*"; // `*` stays within a segment
}
} else if (c === "?") {
re += "[^/]";
} else if (c === "{") {
re += "(?:";
} else if (c === "}") {
re += ")";
} else if (c === ",") {
re += "|";
} else if (".+^$()|\\/".includes(c)) {
re += "\\" + c;
} else {
re += c;
}
}
return new RegExp("^" + re + "$");
}
/**
* Assert the root `validate` chain actually invokes each non-root manifest's
* `validate` (via `cd <dir> && npm run validate`). Without this, a client's
* globs would still be harvested from its own `validate` and count as coverage
* even if the root chain stopped running that client — the same "gate silently
* stops gating" failure as the reachable-script check, one level up. Returns the
* list of manifest dirs the root chain does NOT reach.
*/
function clientsUnreachedFromRoot() {
const rootPkg = JSON.parse(
readFileSync(path.join(repoRoot, "package.json"), "utf8"),
);
const reachedNames = reachableScripts(rootPkg.scripts);
const reachedCommands = [...reachedNames]
.map((n) => rootPkg.scripts?.[n])
.filter((c) => typeof c === "string");
return MANIFESTS.filter((dir) => dir !== ".").filter(
(dir) =>
!reachedCommands.some(
(c) => c.includes(`cd ${dir}`) && /npm run validate/.test(c),
),
);
}
/** Build the set of coverage predicates from all manifests' format globs. */
function buildMatchers() {
const matchers = [];
for (const manifestDir of MANIFESTS) {
const manifestPath = path.join(repoRoot, manifestDir, "package.json");
const pkg = JSON.parse(readFileSync(manifestPath, "utf8"));
for (const arg of prettierCheckArgs(pkg.scripts)) {
const rel = manifestDir === "." ? arg : path.posix.join(manifestDir, arg);
if (GLOB_CHARS.test(arg)) {
const re = globToRegExp(rel);
matchers.push((f) => re.test(f));
} else {
// A bare path: a directory prettier recurses into, or an exact file.
matchers.push((f) => f === rel || f.startsWith(rel + "/"));
}
}
}
return matchers;
}
function trackedSourceFiles() {
const out = execFileSync(
"git",
["ls-files", ...SOURCE_EXTENSIONS.map((e) => `*.${e}`)],
{ cwd: repoRoot, encoding: "utf8" },
);
return out.split("\n").filter(Boolean);
}
const unreachedClients = clientsUnreachedFromRoot();
if (unreachedClients.length > 0) {
console.error(
`verify:format-coverage — the root \`validate\` chain does not invoke ${unreachedClients.length} client validation(s):\n`,
);
for (const dir of unreachedClients)
console.error(` ${dir} (expected \`cd ${dir} && npm run validate\`)`);
console.error(
"\nA client whose `validate` the root chain never runs is not format-gated by CI,",
);
console.error(
"even though its globs exist. Restore the `validate:<client>` link in the root `validate`.",
);
process.exit(1);
}
const matchers = buildMatchers();
const files = trackedSourceFiles();
const ungated = files.filter((f) => !matchers.some((m) => m(f)));
if (ungated.length > 0) {
console.error(
`verify:format-coverage — ${ungated.length} tracked source file(s) are not covered by any prettier format glob:\n`,
);
for (const f of ungated) console.error(" " + f);
console.error(
"\nAdd the file's directory (or a matching glob) to the relevant `format`/`format:check` script,",
);
console.error("or widen the extension set. See AGENTS.md.");
process.exit(1);
}
console.log(
`verify:format-coverage — OK: all ${files.length} tracked source files are format-gated.`,
);