vouchington-tooling 0.66.2 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +65 -0
  2. package/dist/cli/commands/coverage-scope-check.d.mts +7 -0
  3. package/dist/cli/commands/coverage-scope-check.mjs +69 -0
  4. package/dist/cli/index.mjs +2 -0
  5. package/dist/cli/parse-forwarded-commands.d.mts +3 -0
  6. package/dist/cli/parse-forwarded-commands.mjs +2 -0
  7. package/dist/cli/parse.d.mts +3 -0
  8. package/dist/cli/usage-text-coverage-scope.d.mts +1 -0
  9. package/dist/cli/usage-text-coverage-scope.mjs +7 -0
  10. package/dist/cli/usage-text.d.mts +1 -1
  11. package/dist/cli/usage-text.mjs +3 -0
  12. package/dist/coverage-scope/check.d.mts +16 -0
  13. package/dist/coverage-scope/check.mjs +26 -0
  14. package/dist/coverage-scope/coverage-scope.test-helpers.d.mts +4 -0
  15. package/dist/coverage-scope/coverage-scope.test-helpers.mjs +38 -0
  16. package/dist/coverage-scope/index.d.mts +3 -0
  17. package/dist/coverage-scope/index.mjs +2 -0
  18. package/dist/coverage-scope/mismatches.d.mts +3 -0
  19. package/dist/coverage-scope/mismatches.mjs +17 -0
  20. package/dist/request-query-profile/baseline-validation.d.mts +2 -0
  21. package/dist/request-query-profile/baseline-validation.mjs +57 -0
  22. package/dist/request-query-profile/baseline.d.mts +49 -0
  23. package/dist/request-query-profile/baseline.mjs +66 -0
  24. package/dist/request-query-profile/index.d.mts +6 -0
  25. package/dist/request-query-profile/index.mjs +5 -0
  26. package/dist/request-query-profile/line.d.mts +21 -0
  27. package/dist/request-query-profile/line.mjs +48 -0
  28. package/dist/request-query-profile/observations.d.mts +13 -0
  29. package/dist/request-query-profile/observations.mjs +107 -0
  30. package/dist/request-query-profile/stale-report.d.mts +23 -0
  31. package/dist/request-query-profile/stale-report.mjs +52 -0
  32. package/dist/request-query-profile/types.d.mts +11 -0
  33. package/dist/request-query-profile/types.mjs +1 -0
  34. package/package.json +12 -1
  35. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  36. package/skills/agent-workflow/references/implementation.md +5 -0
  37. package/skills/manifest.json +20 -20
  38. package/skills/pr-description/SKILL.md +26 -11
  39. package/skills/pr-description/references/examples.md +53 -0
package/README.md CHANGED
@@ -369,6 +369,29 @@ The pieces are exported from `vouchington-tooling/cloc` (`loadClocConfig`, `norm
369
369
  `countFiles`, `buildRows`, `formatRows`, `createClassifier`, `createPathPolicy`,
370
370
  `compilePatterns`).
371
371
 
372
+ ## Checking the coverage collector scope
373
+
374
+ `vouchington coverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]...
375
+ [--exclude <glob>]...` fails when a `git ls-files -z` entry that a
376
+ [`coverage-check`](https://www.npmjs.com/package/coverage-check) rules file (default
377
+ `.coverage-rules.yml`) gives a `patch_coverage_min` above 0, and whose `scope` does not ignore, is
378
+ outside the collector's scope. Such a file would be required to have coverage that the collector can
379
+ never produce. Every mismatch is printed to stderr and the exit code is 1; 2 is a usage error.
380
+
381
+ The collector's scope is consumer input, mirroring the Vitest `coverage.include` and
382
+ `coverage.exclude` arrays: repeat `--include`/`--exclude`, or point `--scope-file` at a JSON file
383
+ `{ "include": [...], "exclude": [...] }` written from the Vitest config so the two cannot drift. Both
384
+ sources are combined, and at least one include glob is required.
385
+
386
+ ```bash
387
+ vouchington coverage-scope-check --scope-file coverage-scope.json
388
+ vouchington coverage-scope-check --include '**/*.{mts,ts,tsx}' --exclude '**/fixtures/**'
389
+ ```
390
+
391
+ The pure `findCoverageScopeMismatches(files, config, instrumentedScope)` and
392
+ `checkCoverageScope({ cwd, rulesFile, instrumentedScope, listFiles })` (which returns the
393
+ mismatches) are exported from `vouchington-tooling/coverage-scope`.
394
+
372
395
  ## Running the Storybook browser tests
373
396
 
374
397
  `vouchington storybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]...
@@ -1196,6 +1219,48 @@ touching it. `tmux post-tool` reads an agent post-tool hook payload on stdin and
1196
1219
  reminder at plan, PR, push and reset checkpoints; reminders name `TMUX_NAME_COMMAND` (default
1197
1220
  `vouchington tmux name`).
1198
1221
 
1222
+ ## Request query profiles
1223
+
1224
+ `vouchington-tooling/request-query-profile` is the test-only rule layer on top of a per-request
1225
+ query telemetry summary. It has no runtime dependencies: the summary is a structural type
1226
+ (`{ totalQueries, serialDepth, repeats: { annotation, count }[] }`) and the route resolver is a
1227
+ function you pass in.
1228
+
1229
+ ```ts
1230
+ import {
1231
+ buildStaleReport,
1232
+ findUnbaselinedRepeats,
1233
+ formatRequestProfileLine,
1234
+ formatUnbaselinedRepeats,
1235
+ parseRepeatBaseline,
1236
+ parseRequestProfileLine,
1237
+ } from 'vouchington-tooling/request-query-profile'
1238
+
1239
+ const baseline = parseRepeatBaseline(JSON.parse(baselineJson))
1240
+ const line = formatRequestProfileLine('GET /orders/:id', summary, { all: false }) // null if no repeats
1241
+ const parsed = parseRequestProfileLine(line ?? '') // { route, queries, serialDepth, repeats }
1242
+ const bad = findUnbaselinedRepeats('GET /orders/:id', summary.repeats, baseline)
1243
+ if (bad.length > 0)
1244
+ throw new Error(
1245
+ formatUnbaselinedRepeats('GET /orders/:id', bad, { baselineFile: 'test/query-baseline.json' }),
1246
+ )
1247
+ const report = buildStaleReport(baseline, [logText], (route) => route) // report-only
1248
+ ```
1249
+
1250
+ - A baseline entry names an `annotation`, a `reason`, exact `routes` (`METHOD /path`, optionally
1251
+ followed by ` tools/call <name>`) and optional `workers: [{ queue, job }]`, a `maxCount` (an
1252
+ integer of at least 2, or `null` for unbounded), and either `issue` (a positive issue number, a
1253
+ temporary entry) or `permanent: true` with `code` (`<repo path>:<line, range or symbol>`).
1254
+ `parseRepeatBaseline` throws naming every malformed or duplicate-scope entry.
1255
+ - `formatClosedBaselineIssues(baseline, states, { issueGroup })` reports temporary entries whose
1256
+ issue is not open; `states` maps issue numbers to their GitHub state.
1257
+ - `formatRequestProfileLine` and `parseRequestProfileLine` are inverses and live in one module, so
1258
+ the line format cannot drift. `collectProfileObservations` also reads
1259
+ `{"kind":"pg-worker-profile", ...}` JSON lines, including nested `children`.
1260
+ - `buildStaleReport(baseline, logTexts, resolveRoute)` and `findStaleBaselineEntries` never treat a
1261
+ missing or malformed diagnostic kind as evidence of absence: `sufficient` is false then, and the
1262
+ scopes of that kind stay unreported.
1263
+
1199
1264
  ## PostgreSQL test faults and lock waits
1200
1265
 
1201
1266
  `vouchington-tooling/postgres-test-faults` injects real PostgreSQL failures and observes real lock
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `vouchington coverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]...
3
+ * [--exclude <glob>]...`: fails when a tracked file under a positive-threshold coverage rule is not
4
+ * instrumented by the given include/exclude globs. Exits 0 on success, 2 on a usage error, 1 on a
5
+ * mismatch or when the rules cannot be loaded.
6
+ */
7
+ export declare function runCoverageScopeCheckCommand(args: readonly string[], cwd?: string): number;
@@ -0,0 +1,69 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { checkCoverageScope } from "../../coverage-scope/check.mjs";
5
+ import { commandUsage } from "../usage.mjs";
6
+ function readGlobs(path, value, name) {
7
+ if (value === undefined)
8
+ return [];
9
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string'))
10
+ return value;
11
+ throw new Error(`${path}: "${name}" must be an array of strings`);
12
+ }
13
+ function parse(args, cwd) {
14
+ const { values } = parseArgs({
15
+ args: [...args],
16
+ allowPositionals: false,
17
+ options: {
18
+ rules: { type: 'string', default: '.coverage-rules.yml' },
19
+ 'scope-file': { type: 'string' },
20
+ include: { type: 'string', multiple: true, default: [] },
21
+ exclude: { type: 'string', multiple: true, default: [] },
22
+ },
23
+ });
24
+ const path = values['scope-file'];
25
+ const file = path === undefined
26
+ ? {}
27
+ : JSON.parse(readFileSync(resolve(cwd, path), 'utf8'));
28
+ const include = [...readGlobs(String(path), file.include, 'include'), ...values.include];
29
+ if (include.length === 0)
30
+ throw new Error('at least one include glob is required');
31
+ return {
32
+ rules: values.rules,
33
+ include,
34
+ exclude: [...readGlobs(String(path), file.exclude, 'exclude'), ...values.exclude],
35
+ };
36
+ }
37
+ /**
38
+ * `vouchington coverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]...
39
+ * [--exclude <glob>]...`: fails when a tracked file under a positive-threshold coverage rule is not
40
+ * instrumented by the given include/exclude globs. Exits 0 on success, 2 on a usage error, 1 on a
41
+ * mismatch or when the rules cannot be loaded.
42
+ */
43
+ export function runCoverageScopeCheckCommand(args, cwd = process.cwd()) {
44
+ let options;
45
+ try {
46
+ options = parse(args, cwd);
47
+ }
48
+ catch (error) {
49
+ const message = error.message;
50
+ process.stderr.write(`vouchington: ${message}\n${commandUsage('coverage-scope-check')}`);
51
+ return 2;
52
+ }
53
+ try {
54
+ const mismatches = checkCoverageScope({
55
+ cwd,
56
+ rulesFile: options.rules,
57
+ instrumentedScope: options,
58
+ });
59
+ if (mismatches.length === 0)
60
+ return 0;
61
+ const lines = mismatches.map((file) => ` ${file}`).join('\n');
62
+ process.stderr.write(`Coverage rules require files that the collector does not instrument:\n${lines}\n`);
63
+ return 1;
64
+ }
65
+ catch (error) {
66
+ process.stderr.write(`vouchington: ${error.message}\n`);
67
+ return 1;
68
+ }
69
+ }
@@ -110,6 +110,8 @@ export function runCli(argv = process.argv) {
110
110
  return import("./commands/transient-retry.mjs").then((command) => command.runTransientRetryCommand(parsed.args));
111
111
  case 'sandbox-command-audit':
112
112
  return import("./commands/sandbox-command-audit.mjs").then((command) => command.runSandboxCommandAuditCommand(parsed.args));
113
+ case 'coverage-scope-check':
114
+ return import("./commands/coverage-scope-check.mjs").then((command) => command.runCoverageScopeCheckCommand(parsed.args));
113
115
  case 'cloc':
114
116
  return import("./commands/cloc.mjs").then((command) => command.runClocCommand(parsed.args));
115
117
  case 'storybook-browser-runner':
@@ -61,6 +61,9 @@ type ForwardedCommand = {
61
61
  } | {
62
62
  kind: 'cloc';
63
63
  args: string[];
64
+ } | {
65
+ kind: 'coverage-scope-check';
66
+ args: string[];
64
67
  } | {
65
68
  kind: 'storybook-browser-runner';
66
69
  args: string[];
@@ -41,6 +41,8 @@ export function parseForwardedCommand(command, args) {
41
41
  return { kind: 'sandbox-command-audit', args };
42
42
  if (command === 'cloc')
43
43
  return { kind: 'cloc', args };
44
+ if (command === 'coverage-scope-check')
45
+ return { kind: 'coverage-scope-check', args };
44
46
  if (command === 'storybook-browser-runner')
45
47
  return { kind: 'storybook-browser-runner', args };
46
48
  if (command === 'tmux')
@@ -92,6 +92,9 @@ export type ParsedCli = {
92
92
  } | {
93
93
  kind: 'cloc';
94
94
  args: string[];
95
+ } | {
96
+ kind: 'coverage-scope-check';
97
+ args: string[];
95
98
  } | {
96
99
  kind: 'storybook-browser-runner';
97
100
  args: string[];
@@ -0,0 +1 @@
1
+ export declare const COVERAGE_SCOPE_CHECK_USAGE = "coverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n";
@@ -0,0 +1,7 @@
1
+ export const COVERAGE_SCOPE_CHECK_USAGE = `coverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...
2
+ Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)
3
+ gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's
4
+ scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the
5
+ include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.
6
+ At least one include glob is required.
7
+ `;
@@ -1 +1 @@
1
- export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n sandbox-command-audit Audit agent transcripts for sandbox escalations and denials\n cloc Count tracked lines of code by category and service with scc\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\nstorybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]\n Spawns <cmd> (default pnpm) in its own process group with <argv> (default \"exec vitest run\n --project <name>\") plus the coverage args (default --coverage) and supervises it: a Vite optimizer\n cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget\n watchdogs. --result-file paths are removed before each attempt and --completion-file is the one\n whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,\n _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE\n (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
1
+ export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n sandbox-command-audit Audit agent transcripts for sandbox escalations and denials\n cloc Count tracked lines of code by category and service with scc\n coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\nstorybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]\n Spawns <cmd> (default pnpm) in its own process group with <argv> (default \"exec vitest run\n --project <name>\") plus the coverage args (default --coverage) and supervises it: a Vite optimizer\n cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget\n watchdogs. --result-file paths are removed before each attempt and --completion-file is the one\n whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,\n _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE\n (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
@@ -1,3 +1,4 @@
1
+ import { COVERAGE_SCOPE_CHECK_USAGE } from "./usage-text-coverage-scope.mjs";
1
2
  export const USAGE = `Usage: vouchington <command> [options]
2
3
 
3
4
  Commands:
@@ -58,6 +59,7 @@ Commands:
58
59
  transient-retry Rerun a failed GitHub Actions run when an injected rule matches
59
60
  sandbox-command-audit Audit agent transcripts for sandbox escalations and denials
60
61
  cloc Count tracked lines of code by category and service with scc
62
+ coverage-scope-check Check positive-threshold coverage rules against the Vitest scope
61
63
  storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog
62
64
 
63
65
  Options:
@@ -180,6 +182,7 @@ cloc --config <file> [--scc-bin <path>] [--json]
180
182
  defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,
181
183
  excludedDirs, ignoredDirs, sccBin, missingSccHint.
182
184
 
185
+ ${COVERAGE_SCOPE_CHECK_USAGE}
183
186
  storybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]
184
187
  Spawns <cmd> (default pnpm) in its own process group with <argv> (default "exec vitest run
185
188
  --project <name>") plus the coverage args (default --coverage) and supervises it: a Vite optimizer
@@ -0,0 +1,16 @@
1
+ /** Globs of the files the coverage collector instruments (Vitest `coverage.include`/`exclude`). */
2
+ export interface InstrumentedGlobs {
3
+ include: readonly string[];
4
+ exclude: readonly string[];
5
+ }
6
+ export interface CheckCoverageScopeOptions {
7
+ cwd: string;
8
+ /** Rules file, relative to `cwd`. Defaults to `.coverage-rules.yml`. */
9
+ rulesFile?: string;
10
+ instrumentedScope: InstrumentedGlobs;
11
+ /** Tracked repository paths. Defaults to `git ls-files -z` in `cwd`. */
12
+ listFiles?: (cwd: string) => readonly string[];
13
+ }
14
+ export declare function listTrackedFiles(cwd: string): string[];
15
+ /** Returns tracked paths a positive-threshold rule requires but the collector would not instrument. */
16
+ export declare function checkCoverageScope(options: CheckCoverageScopeOptions): string[];
@@ -0,0 +1,26 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import { loadCoverageConfig } from 'coverage-check';
4
+ import { findCoverageScopeMismatches } from "./mismatches.mjs";
5
+ export function listTrackedFiles(cwd) {
6
+ return execFileSync('git', ['ls-files', '-z'], {
7
+ cwd,
8
+ encoding: 'utf8',
9
+ maxBuffer: 256 * 1024 * 1024,
10
+ })
11
+ .split('\0')
12
+ .filter(Boolean);
13
+ }
14
+ /** Returns tracked paths a positive-threshold rule requires but the collector would not instrument. */
15
+ export function checkCoverageScope(options) {
16
+ const { cwd, rulesFile = '.coverage-rules.yml', instrumentedScope } = options;
17
+ const instrumented = {
18
+ version: 1,
19
+ analyzer: 'javascript',
20
+ include: [...instrumentedScope.include],
21
+ ignored: [...instrumentedScope.exclude],
22
+ };
23
+ const config = loadCoverageConfig(resolve(cwd, rulesFile));
24
+ const files = (options.listFiles ?? listTrackedFiles)(cwd);
25
+ return findCoverageScopeMismatches(files, config, instrumented);
26
+ }
@@ -0,0 +1,4 @@
1
+ /** A temp directory holding `.coverage-rules.yml` and the given files, optionally a git repo. */
2
+ export declare function fixtureRepo(files: readonly string[], options: {
3
+ git: boolean;
4
+ }): string;
@@ -0,0 +1,38 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { afterEach } from 'vitest';
6
+ const RULES = [
7
+ 'scope:',
8
+ ' version: 1',
9
+ ' analyzer: javascript',
10
+ ' include: ["**/*.mts"]',
11
+ ' ignored: ["**/*.test.mts"]',
12
+ 'rules:',
13
+ ' - paths: "app/**"',
14
+ ' patch_coverage_min: 1',
15
+ ' - paths: "scripts/**"',
16
+ ' patch_coverage_min: 0',
17
+ '',
18
+ ].join('\n');
19
+ const dirs = [];
20
+ afterEach(() => {
21
+ for (const dir of dirs.splice(0))
22
+ rmSync(dir, { recursive: true, force: true });
23
+ });
24
+ /** A temp directory holding `.coverage-rules.yml` and the given files, optionally a git repo. */
25
+ export function fixtureRepo(files, options) {
26
+ const cwd = mkdtempSync(join(tmpdir(), 'coverage-scope-'));
27
+ dirs.push(cwd);
28
+ writeFileSync(join(cwd, '.coverage-rules.yml'), RULES);
29
+ for (const file of files) {
30
+ mkdirSync(dirname(join(cwd, file)), { recursive: true });
31
+ writeFileSync(join(cwd, file), 'export const fixture = true\n');
32
+ }
33
+ if (options.git) {
34
+ execFileSync('git', ['init', '--quiet'], { cwd });
35
+ execFileSync('git', ['add', '--', '.coverage-rules.yml', ...files], { cwd });
36
+ }
37
+ return cwd;
38
+ }
@@ -0,0 +1,3 @@
1
+ export { checkCoverageScope, listTrackedFiles } from './check.mts';
2
+ export type { CheckCoverageScopeOptions, InstrumentedGlobs } from './check.mts';
3
+ export { findCoverageScopeMismatches } from './mismatches.mts';
@@ -0,0 +1,2 @@
1
+ export { checkCoverageScope, listTrackedFiles } from "./check.mjs";
2
+ export { findCoverageScopeMismatches } from "./mismatches.mjs";
@@ -0,0 +1,3 @@
1
+ import { type CoverageConfig, type CoverageScope } from 'coverage-check';
2
+ /** Positive-threshold paths that the coverage gate expects but Vitest will not instrument. */
3
+ export declare function findCoverageScopeMismatches(files: readonly string[], config: CoverageConfig, instrumentedScope: CoverageScope): string[];
@@ -0,0 +1,17 @@
1
+ import { coverageDisposition } from 'coverage-check';
2
+ // `coverage-check` exports matchRule only through its documented `./src/*.mts` subpath.
3
+ import { matchRule } from 'coverage-check/src/rules.mts';
4
+ /** Positive-threshold paths that the coverage gate expects but Vitest will not instrument. */
5
+ export function findCoverageScopeMismatches(files, config, instrumentedScope) {
6
+ const scope = config.scope;
7
+ if (scope === undefined)
8
+ throw new Error('coverage rules file is missing its scope block');
9
+ return files.filter((file) => {
10
+ if (coverageDisposition(file, scope) === 'ignored')
11
+ return false;
12
+ const rule = matchRule(file, config.rules);
13
+ return (rule !== null &&
14
+ rule.patch_coverage_min > 0 &&
15
+ coverageDisposition(file, instrumentedScope) === 'ignored');
16
+ });
17
+ }
@@ -0,0 +1,2 @@
1
+ /** Validates the exact temporary or permanent metadata shape of one query-profile exception. */
2
+ export declare function baselineEntryProblem(entry: unknown): string | undefined;
@@ -0,0 +1,57 @@
1
+ const CODE_POINTER = /^[\w./-]+\.\w+:(?:[1-9]\d*(?:-[1-9]\d*)?|[A-Za-z_$][\w$.]*)$/;
2
+ const ROUTE = /^[A-Z]+ \/[^?\s]*(?: tools\/call [^?\s]+)?$/;
3
+ function rangeIsOrdered(code) {
4
+ const range = /:(\d+)-(\d+)$/.exec(code);
5
+ return range === null || Number(range[1]) <= Number(range[2]);
6
+ }
7
+ /** Validates the exact temporary or permanent metadata shape of one query-profile exception. */
8
+ export function baselineEntryProblem(entry) {
9
+ if (typeof entry !== 'object' || entry === null)
10
+ return 'is not an object';
11
+ const { annotation, reason, routes, workers, maxCount, ...rest } = entry;
12
+ if (typeof annotation !== 'string' || annotation.trim() === '')
13
+ return 'needs a non-empty annotation';
14
+ if (typeof reason !== 'string' || reason.trim() === '')
15
+ return 'needs a non-empty reason';
16
+ if (!Array.isArray(routes) ||
17
+ routes.some((route) => typeof route !== 'string' || !ROUTE.test(route)))
18
+ return 'needs `routes` as an array of exact method and path identities without queries';
19
+ if (workers !== undefined &&
20
+ (!Array.isArray(workers) ||
21
+ workers.some((worker) => {
22
+ if (typeof worker !== 'object' || worker === null)
23
+ return true;
24
+ const { queue, job, ...extra } = worker;
25
+ return (Object.keys(extra).length > 0 ||
26
+ typeof queue !== 'string' ||
27
+ queue.trim() === '' ||
28
+ queue.includes('*') ||
29
+ typeof job !== 'string' ||
30
+ job.trim() === '' ||
31
+ job.includes('*'));
32
+ })))
33
+ return 'needs `workers` as exact { queue, job } identities';
34
+ if (routes.length === 0 && (!workers || workers.length === 0))
35
+ return 'needs at least one route or worker identity';
36
+ if (maxCount !== null && (!Number.isInteger(maxCount) || maxCount < 2))
37
+ return 'needs `maxCount` as an integer at least 2, or null';
38
+ const keys = Object.keys(rest).toSorted().join(',');
39
+ if (keys === 'issue') {
40
+ const { issue } = rest;
41
+ if (typeof issue !== 'number' || !Number.isInteger(issue) || issue <= 0)
42
+ return 'needs `issue` to be a positive issue number';
43
+ return undefined;
44
+ }
45
+ if (keys === 'code,permanent') {
46
+ if (rest.permanent !== true)
47
+ return 'needs `permanent: true`';
48
+ if (typeof rest.code !== 'string' ||
49
+ !CODE_POINTER.test(rest.code) ||
50
+ rest.code.startsWith('/') ||
51
+ !rangeIsOrdered(rest.code) ||
52
+ rest.code.split(':')[0].split('/').includes('..'))
53
+ return 'needs `code` as "<repo path>:<line or symbol>"';
54
+ return undefined;
55
+ }
56
+ return 'must be temporary { annotation, reason, issue } or permanent { annotation, reason, permanent: true, code }';
57
+ }
@@ -0,0 +1,49 @@
1
+ import type { RepeatedAnnotation } from './types.mts';
2
+ /** A repeat tolerated until the open `issue` removes it. */
3
+ export interface BaselineScope {
4
+ /** Exact request identities, including MCP tool-call identities. */
5
+ routes: string[];
6
+ /** Exact worker identities. Worker scopes never excuse a request repeat. */
7
+ workers?: Array<{
8
+ queue: string;
9
+ job: string;
10
+ }>;
11
+ /** Null preserves an intentional unbounded exception within the named scopes. */
12
+ maxCount: number | null;
13
+ }
14
+ export interface TemporaryBaselineEntry extends BaselineScope {
15
+ annotation: string;
16
+ reason: string;
17
+ /** Number of the open GitHub issue that owns removing the repeat. */
18
+ issue: number;
19
+ }
20
+ /** A repeat the code needs on purpose; the reason names the mechanism. */
21
+ export interface PermanentBaselineEntry extends BaselineScope {
22
+ annotation: string;
23
+ reason: string;
24
+ permanent: true;
25
+ /** `<repo path>:<line or symbol>` of the code that needs the repeat. */
26
+ code: string;
27
+ }
28
+ export type RepeatBaselineEntry = TemporaryBaselineEntry | PermanentBaselineEntry;
29
+ /** Parsed baseline, or an error naming every malformed or duplicate entry. */
30
+ export declare function parseRepeatBaseline(raw: unknown): RepeatBaselineEntry[];
31
+ /** Temporary entries, whose `issue` must stay open. */
32
+ export declare function temporaryBaselineEntries(baseline: readonly RepeatBaselineEntry[]): TemporaryBaselineEntry[];
33
+ /** Repeats outside their exact baseline scope and maximum, in the order given. */
34
+ export declare function findUnbaselinedRepeats(route: string, repeats: readonly RepeatedAnnotation[], baseline: readonly RepeatBaselineEntry[]): RepeatedAnnotation[];
35
+ /**
36
+ * Failure text for one request: names the route and every unbaselined annotation.
37
+ * `baselineFile` is the repository path of the baseline, shown in the remediation hint.
38
+ */
39
+ export declare function formatUnbaselinedRepeats(route: string, repeats: readonly RepeatedAnnotation[], options: {
40
+ baselineFile: string;
41
+ }): string;
42
+ /**
43
+ * Failure text for temporary entries whose issue is not open, one line per entry. `states` maps an
44
+ * issue number to its GitHub state; an issue missing from it counts as not found. `issueGroup`
45
+ * names where replacement issues live (for example a milestone or issue group title).
46
+ */
47
+ export declare function formatClosedBaselineIssues(baseline: readonly RepeatBaselineEntry[], states: ReadonlyMap<number, string>, options: {
48
+ issueGroup: string;
49
+ }): string[];
@@ -0,0 +1,66 @@
1
+ import { baselineEntryProblem } from "./baseline-validation.mjs";
2
+ function entryScopes(scoped) {
3
+ return [
4
+ ...scoped.routes.map((route) => JSON.stringify([scoped.annotation, 'route', route])),
5
+ ...(scoped.workers ?? []).map(({ queue, job }) => JSON.stringify([scoped.annotation, 'worker', queue, job])),
6
+ ];
7
+ }
8
+ /** Parsed baseline, or an error naming every malformed or duplicate entry. */
9
+ export function parseRepeatBaseline(raw) {
10
+ if (!Array.isArray(raw))
11
+ throw new Error('Query-profile baseline must be an array of entries');
12
+ const problems = [];
13
+ const seenScopes = new Set();
14
+ raw.forEach((entry, index) => {
15
+ const problem = baselineEntryProblem(entry);
16
+ const name = entry?.annotation;
17
+ if (problem)
18
+ problems.push(`entry ${index} (${JSON.stringify(name)}) ${problem}`);
19
+ else {
20
+ for (const scope of entryScopes(entry)) {
21
+ if (seenScopes.has(scope))
22
+ problems.push(`entry ${index} (${JSON.stringify(name)}) has a duplicate scope ${scope}`);
23
+ seenScopes.add(scope);
24
+ }
25
+ }
26
+ });
27
+ if (problems.length > 0) {
28
+ throw new Error(`Malformed query-profile baseline:\n${problems.join('\n')}`);
29
+ }
30
+ return raw;
31
+ }
32
+ /** Temporary entries, whose `issue` must stay open. */
33
+ export function temporaryBaselineEntries(baseline) {
34
+ return baseline.filter((entry) => 'issue' in entry);
35
+ }
36
+ /** Repeats outside their exact baseline scope and maximum, in the order given. */
37
+ export function findUnbaselinedRepeats(route, repeats, baseline) {
38
+ return repeats.filter(({ annotation, count }) => {
39
+ return !baseline.some((entry) => entry.annotation === annotation &&
40
+ entry.routes.includes(route) &&
41
+ (entry.maxCount === null || count <= entry.maxCount));
42
+ });
43
+ }
44
+ /**
45
+ * Failure text for one request: names the route and every unbaselined annotation.
46
+ * `baselineFile` is the repository path of the baseline, shown in the remediation hint.
47
+ */
48
+ export function formatUnbaselinedRepeats(route, repeats, options) {
49
+ const list = repeats.map(({ annotation, count }) => `${annotation} (x${count})`).join(', ');
50
+ return `Unbaselined repeated query in ${route}: ${list}. Remove the repeat, or baseline it in ${options.baselineFile} with a reason and an open issue (temporary), or a code pointer (permanent).`;
51
+ }
52
+ /**
53
+ * Failure text for temporary entries whose issue is not open, one line per entry. `states` maps an
54
+ * issue number to its GitHub state; an issue missing from it counts as not found. `issueGroup`
55
+ * names where replacement issues live (for example a milestone or issue group title).
56
+ */
57
+ export function formatClosedBaselineIssues(baseline, states, options) {
58
+ return temporaryBaselineEntries(baseline).flatMap(({ annotation, issue }) => {
59
+ const state = states.get(issue)?.toLowerCase();
60
+ if (state === 'open')
61
+ return [];
62
+ return [
63
+ `Baseline entry ${annotation} points at #${issue}, which is ${state ?? 'not found'}. Remove the repeat, or re-point the entry at an open issue in "${options.issueGroup}"; a repeat the code needs on purpose becomes a permanent entry.`,
64
+ ];
65
+ });
66
+ }
@@ -0,0 +1,6 @@
1
+ export { findUnbaselinedRepeats, formatClosedBaselineIssues, formatUnbaselinedRepeats, parseRepeatBaseline, temporaryBaselineEntries, type BaselineScope, type PermanentBaselineEntry, type RepeatBaselineEntry, type TemporaryBaselineEntry, } from './baseline.mts';
2
+ export { baselineEntryProblem } from './baseline-validation.mts';
3
+ export { formatRequestProfileLine, parseRequestProfileLine, REQUEST_PROFILE_PREFIX, type ParsedRequestProfileLine, } from './line.mts';
4
+ export { collectProfileObservations, type ProfileObservations } from './observations.mts';
5
+ export { buildStaleReport, findStaleBaselineEntries, MIN_STALE_EVIDENCE_LOGS, type StaleBaselineCandidate, type StaleReport, } from './stale-report.mts';
6
+ export type { RepeatedAnnotation, RequestQuerySummary } from './types.mts';
@@ -0,0 +1,5 @@
1
+ export { findUnbaselinedRepeats, formatClosedBaselineIssues, formatUnbaselinedRepeats, parseRepeatBaseline, temporaryBaselineEntries, } from "./baseline.mjs";
2
+ export { baselineEntryProblem } from "./baseline-validation.mjs";
3
+ export { formatRequestProfileLine, parseRequestProfileLine, REQUEST_PROFILE_PREFIX, } from "./line.mjs";
4
+ export { collectProfileObservations } from "./observations.mjs";
5
+ export { buildStaleReport, findStaleBaselineEntries, MIN_STALE_EVIDENCE_LOGS, } from "./stale-report.mjs";
@@ -0,0 +1,21 @@
1
+ import type { RepeatedAnnotation, RequestQuerySummary } from './types.mts';
2
+ export declare const REQUEST_PROFILE_PREFIX = "[pg-request-profile]";
3
+ /** A parsed request profile line. */
4
+ export interface ParsedRequestProfileLine {
5
+ route: string;
6
+ queries: number;
7
+ serialDepth: number;
8
+ repeats: RepeatedAnnotation[];
9
+ }
10
+ /**
11
+ * One stderr line for a request, or null when it has nothing to report and `all` is off.
12
+ * Annotations are written verbatim, so one containing a comma does not survive parsing.
13
+ */
14
+ export declare function formatRequestProfileLine(route: string, summary: RequestQuerySummary, options: {
15
+ all: boolean;
16
+ }): string | null;
17
+ /**
18
+ * Parse a line containing the profile prefix (leading log noise is skipped), or undefined when it
19
+ * is malformed. The inverse of `formatRequestProfileLine`.
20
+ */
21
+ export declare function parseRequestProfileLine(line: string): ParsedRequestProfileLine | undefined;
@@ -0,0 +1,48 @@
1
+ export const REQUEST_PROFILE_PREFIX = '[pg-request-profile]';
2
+ /**
3
+ * One stderr line for a request, or null when it has nothing to report and `all` is off.
4
+ * Annotations are written verbatim, so one containing a comma does not survive parsing.
5
+ */
6
+ export function formatRequestProfileLine(route, summary, options) {
7
+ if (summary.repeats.length === 0 && !options.all)
8
+ return null;
9
+ const repeats = summary.repeats
10
+ .map(({ annotation, count }) => `${annotation}(x${count})`)
11
+ .join(',');
12
+ return `${REQUEST_PROFILE_PREFIX} route=${route} queries=${summary.totalQueries} serialDepth=${summary.serialDepth} repeats=${repeats || 'none'}\n`;
13
+ }
14
+ /** Parse the repeats field; undefined when any entry is malformed or counts fewer than 2. */
15
+ function parseRepeats(repeats) {
16
+ if (repeats === '' || repeats === 'none')
17
+ return [];
18
+ const parsed = [];
19
+ for (const value of repeats.split(',')) {
20
+ const match = /^(.+?)\(x(\d+)\)$/.exec(value);
21
+ if (!match?.[1]?.trim() || Number(match[2]) < 2)
22
+ return undefined;
23
+ parsed.push({ annotation: match[1], count: Number(match[2]) });
24
+ }
25
+ return parsed;
26
+ }
27
+ /**
28
+ * Parse a line containing the profile prefix (leading log noise is skipped), or undefined when it
29
+ * is malformed. The inverse of `formatRequestProfileLine`.
30
+ */
31
+ export function parseRequestProfileLine(line) {
32
+ const start = line.indexOf(REQUEST_PROFILE_PREFIX);
33
+ if (start === -1)
34
+ return undefined;
35
+ const profile = line.slice(start).trimEnd();
36
+ const match = / route=(.+?) queries=(\d+) serialDepth=(\d+) repeats=(.*)$/.exec(profile);
37
+ const route = match?.[1];
38
+ const repeats = match?.[4];
39
+ const parsed = repeats === undefined ? undefined : parseRepeats(repeats);
40
+ if (!route || parsed === undefined)
41
+ return undefined;
42
+ return {
43
+ route,
44
+ queries: Number(match?.[2]),
45
+ serialDepth: Number(match?.[3]),
46
+ repeats: parsed,
47
+ };
48
+ }
@@ -0,0 +1,13 @@
1
+ export interface ProfileObservations {
2
+ requestProfileCount: number;
3
+ workerProfileCount: number;
4
+ malformedRequestProfileCount: number;
5
+ malformedWorkerProfileCount: number;
6
+ routeScopes: Set<string>;
7
+ workerScopes: Set<string>;
8
+ }
9
+ /**
10
+ * Collect exact repeated-query scopes and valid request/worker diagnostics from run logs. Worker
11
+ * lines are recognized by the compact `"kind":"pg-worker-profile"` form `JSON.stringify` writes.
12
+ */
13
+ export declare function collectProfileObservations(logTexts: readonly string[], resolveRoute: (route: string) => string): ProfileObservations;
@@ -0,0 +1,107 @@
1
+ import { parseRequestProfileLine, REQUEST_PROFILE_PREFIX } from "./line.mjs";
2
+ /**
3
+ * Collect exact repeated-query scopes and valid request/worker diagnostics from run logs. Worker
4
+ * lines are recognized by the compact `"kind":"pg-worker-profile"` form `JSON.stringify` writes.
5
+ */
6
+ export function collectProfileObservations(logTexts, resolveRoute) {
7
+ const observations = {
8
+ requestProfileCount: 0,
9
+ workerProfileCount: 0,
10
+ malformedRequestProfileCount: 0,
11
+ malformedWorkerProfileCount: 0,
12
+ routeScopes: new Set(),
13
+ workerScopes: new Set(),
14
+ };
15
+ for (const logText of logTexts) {
16
+ for (const line of logText.split('\n')) {
17
+ if (line.includes('"kind":"pg-worker-profile"')) {
18
+ collectWorkerLine(line, observations);
19
+ }
20
+ else if (line.includes(REQUEST_PROFILE_PREFIX)) {
21
+ collectRequestLine(line, observations, resolveRoute);
22
+ }
23
+ }
24
+ }
25
+ return observations;
26
+ }
27
+ function collectRequestLine(line, observations, resolveRoute) {
28
+ const parsed = parseRequestProfileLine(line);
29
+ if (parsed === undefined) {
30
+ observations.malformedRequestProfileCount += 1;
31
+ return;
32
+ }
33
+ observations.requestProfileCount += 1;
34
+ const resolvedRoute = resolveRoute(parsed.route);
35
+ for (const { annotation } of parsed.repeats) {
36
+ observations.routeScopes.add(JSON.stringify([annotation, resolvedRoute]));
37
+ }
38
+ }
39
+ function collectWorkerLine(line, observations) {
40
+ const marker = line.indexOf('"kind":"pg-worker-profile"');
41
+ const start = line.lastIndexOf('{', marker);
42
+ if (start === -1) {
43
+ observations.malformedWorkerProfileCount += 1;
44
+ return;
45
+ }
46
+ let report;
47
+ try {
48
+ report = JSON.parse(line.slice(start));
49
+ }
50
+ catch {
51
+ observations.malformedWorkerProfileCount += 1;
52
+ return;
53
+ }
54
+ const root = asRecord(report);
55
+ if (root?.kind !== 'pg-worker-profile' || !collectWorkerProfile(root.profile, observations)) {
56
+ observations.malformedWorkerProfileCount += 1;
57
+ }
58
+ }
59
+ function collectWorkerProfile(profileValue, observations) {
60
+ const profile = asRecord(profileValue);
61
+ if (!profile)
62
+ return false;
63
+ const identity = asRecord(profile.identity);
64
+ const summary = asRecord(profile.summary);
65
+ const queue = identity?.queue;
66
+ const jobs = Array.isArray(identity?.jobs) ? identity.jobs : [];
67
+ const validJobs = jobs.length > 0 &&
68
+ jobs.every((jobValue) => {
69
+ const job = asRecord(jobValue);
70
+ return typeof job?.name === 'string' && job.name.trim() !== '';
71
+ });
72
+ const jobNames = validJobs ? jobs.map((jobValue) => jobValue.name) : [];
73
+ const repeats = summary?.repeats;
74
+ const repeatEntries = Array.isArray(repeats) ? repeats : [];
75
+ const validRepeats = Array.isArray(repeats) &&
76
+ repeatEntries.every((repeatValue) => {
77
+ const repeat = asRecord(repeatValue);
78
+ return (typeof repeat?.annotation === 'string' &&
79
+ repeat.annotation.trim() !== '' &&
80
+ Number.isInteger(repeat.count) &&
81
+ repeat.count >= 2);
82
+ });
83
+ const valid = typeof queue === 'string' && queue.trim() !== '' && validJobs && validRepeats;
84
+ if (valid) {
85
+ observations.workerProfileCount += 1;
86
+ for (const jobName of jobNames) {
87
+ for (const repeatValue of repeatEntries) {
88
+ const { annotation } = repeatValue;
89
+ observations.workerScopes.add(JSON.stringify([annotation, queue, jobName]));
90
+ }
91
+ }
92
+ }
93
+ let childrenValid = profile.children === undefined;
94
+ if (Array.isArray(profile.children)) {
95
+ childrenValid = true;
96
+ for (const child of profile.children) {
97
+ if (!collectWorkerProfile(child, observations))
98
+ childrenValid = false;
99
+ }
100
+ }
101
+ return valid && childrenValid;
102
+ }
103
+ function asRecord(value) {
104
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
105
+ ? value
106
+ : undefined;
107
+ }
@@ -0,0 +1,23 @@
1
+ import type { RepeatBaselineEntry } from './baseline.mts';
2
+ /** A report-only candidate containing only the absent scopes from one baseline entry. */
3
+ export interface StaleBaselineCandidate {
4
+ index: number;
5
+ entry: RepeatBaselineEntry;
6
+ fullyStale: boolean;
7
+ }
8
+ /** Report-only candidates. Missing diagnostic kinds are never treated as evidence of absence. */
9
+ export interface StaleReport {
10
+ logCount: number;
11
+ requestProfileCount: number;
12
+ workerProfileCount: number;
13
+ malformedRequestProfileCount: number;
14
+ malformedWorkerProfileCount: number;
15
+ sufficient: boolean;
16
+ stale: StaleBaselineCandidate[];
17
+ }
18
+ /** One complete run is sufficient when it contains every diagnostic kind the baseline uses. */
19
+ export declare const MIN_STALE_EVIDENCE_LOGS = 1;
20
+ /** Report scopes absent from complete-run request and worker profile logs. */
21
+ export declare function buildStaleReport(baseline: readonly RepeatBaselineEntry[], logTexts: readonly string[], resolveRoute: (route: string) => string): StaleReport;
22
+ /** Return copies of entries with only missing named scopes, preserving baseline order. */
23
+ export declare function findStaleBaselineEntries(baseline: readonly RepeatBaselineEntry[], observedRouteScopes: ReadonlySet<string>, observedWorkerScopes: ReadonlySet<string>): StaleBaselineCandidate[];
@@ -0,0 +1,52 @@
1
+ import { collectProfileObservations } from "./observations.mjs";
2
+ /** One complete run is sufficient when it contains every diagnostic kind the baseline uses. */
3
+ export const MIN_STALE_EVIDENCE_LOGS = 1;
4
+ /** Report scopes absent from complete-run request and worker profile logs. */
5
+ export function buildStaleReport(baseline, logTexts, resolveRoute) {
6
+ const observed = collectProfileObservations(logTexts, resolveRoute);
7
+ const requiresRequests = baseline.some((entry) => entry.routes.length > 0);
8
+ const requiresWorkers = baseline.some((entry) => (entry.workers?.length ?? 0) > 0);
9
+ const sufficient = logTexts.length >= MIN_STALE_EVIDENCE_LOGS &&
10
+ (observed.requestProfileCount > 0 || observed.workerProfileCount > 0) &&
11
+ (!requiresRequests || observed.requestProfileCount > 0) &&
12
+ (!requiresWorkers || observed.workerProfileCount > 0) &&
13
+ observed.malformedRequestProfileCount === 0 &&
14
+ observed.malformedWorkerProfileCount === 0;
15
+ const routeScopes = observed.requestProfileCount > 0 && observed.malformedRequestProfileCount === 0
16
+ ? observed.routeScopes
17
+ : new Set(baseline.flatMap((entry) => entry.routes.map((route) => JSON.stringify([entry.annotation, route]))));
18
+ const workerScopes = observed.workerProfileCount > 0 && observed.malformedWorkerProfileCount === 0
19
+ ? observed.workerScopes
20
+ : new Set(baseline.flatMap((entry) => (entry.workers ?? []).map((worker) => JSON.stringify([entry.annotation, worker.queue, worker.job]))));
21
+ return {
22
+ logCount: logTexts.length,
23
+ requestProfileCount: observed.requestProfileCount,
24
+ workerProfileCount: observed.workerProfileCount,
25
+ malformedRequestProfileCount: observed.malformedRequestProfileCount,
26
+ malformedWorkerProfileCount: observed.malformedWorkerProfileCount,
27
+ sufficient,
28
+ stale: findStaleBaselineEntries(baseline, routeScopes, workerScopes),
29
+ };
30
+ }
31
+ /** Return copies of entries with only missing named scopes, preserving baseline order. */
32
+ export function findStaleBaselineEntries(baseline, observedRouteScopes, observedWorkerScopes) {
33
+ return baseline.flatMap((entry, index) => {
34
+ const routes = entry.routes.filter((route) => !observedRouteScopes.has(JSON.stringify([entry.annotation, route])));
35
+ const workers = (entry.workers ?? []).filter((worker) => !observedWorkerScopes.has(JSON.stringify([entry.annotation, worker.queue, worker.job])));
36
+ if (routes.length === 0 && workers.length === 0)
37
+ return [];
38
+ const total = entry.routes.length + (entry.workers?.length ?? 0);
39
+ const stale = routes.length + workers.length;
40
+ return [
41
+ {
42
+ index,
43
+ entry: {
44
+ ...entry,
45
+ routes,
46
+ ...(entry.workers === undefined ? {} : { workers }),
47
+ },
48
+ fullyStale: stale === total,
49
+ },
50
+ ];
51
+ });
52
+ }
@@ -0,0 +1,11 @@
1
+ /** One annotation that ran more than once within a request or worker job. */
2
+ export interface RepeatedAnnotation {
3
+ annotation: string;
4
+ count: number;
5
+ }
6
+ /** Structural shape of a per-request query summary; any compatible telemetry summary fits. */
7
+ export interface RequestQuerySummary {
8
+ totalQueries: number;
9
+ serialDepth: number;
10
+ repeats: readonly RepeatedAnnotation[];
11
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.66.2",
3
+ "version": "0.68.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -421,6 +421,16 @@
421
421
  "import": "./dist/postgres-test-faults/index.mjs",
422
422
  "default": "./dist/postgres-test-faults/index.mjs"
423
423
  },
424
+ "./request-query-profile": {
425
+ "types": "./dist/request-query-profile/index.d.mts",
426
+ "import": "./dist/request-query-profile/index.mjs",
427
+ "default": "./dist/request-query-profile/index.mjs"
428
+ },
429
+ "./coverage-scope": {
430
+ "types": "./dist/coverage-scope/index.d.mts",
431
+ "import": "./dist/coverage-scope/index.mjs",
432
+ "default": "./dist/coverage-scope/index.mjs"
433
+ },
424
434
  "./package.json": "./package.json",
425
435
  "./basic-auth-doc-sync": {
426
436
  "types": "./dist/basic-auth-doc-sync/index.d.mts",
@@ -471,6 +481,7 @@
471
481
  "@types/unist": "3.0.3",
472
482
  "@typescript-eslint/parser": "^8.71.2",
473
483
  "agent-blackboard": "^0.7.0",
484
+ "coverage-check": "0.18.0",
474
485
  "csv-parse": "7.0.3",
475
486
  "csv-stringify": "6.9.0",
476
487
  "dockerfile-ast": "0.7.1",
@@ -1,5 +1,10 @@
1
1
  # Implementation
2
2
 
3
+ Before fixing an issue, find out why the affected code exists: read its history, callers, tests,
4
+ and linked issues. A fix that ignores the code's original purpose often breaks it or patches a
5
+ symptom. If the code no longer serves a purpose, or its job is done elsewhere, delete it instead of
6
+ fixing it, along with its tests, configuration, and documentation.
7
+
3
8
  For cross-cutting work, track accepted interface, data, validation, and ownership decisions that
4
9
  could otherwise be lost during coding. Start from a failing behavioral test when practical and
5
10
  complete the real path rather than adding placeholders or compatibility shims without a requirement.
@@ -4,7 +4,7 @@
4
4
  {
5
5
  "name": "agent-workflow",
6
6
  "plugin": "vouchington-workflow",
7
- "pluginVersion": "0.14.1",
7
+ "pluginVersion": "0.14.2",
8
8
  "path": "agent-workflow/SKILL.md",
9
9
  "prerequisites": [
10
10
  "blackboard",
@@ -24,7 +24,7 @@
24
24
  {
25
25
  "name": "blackboard",
26
26
  "plugin": "vouchington-workflow",
27
- "pluginVersion": "0.14.1",
27
+ "pluginVersion": "0.14.2",
28
28
  "path": "blackboard/SKILL.md"
29
29
  },
30
30
  {
@@ -36,7 +36,7 @@
36
36
  {
37
37
  "name": "dependabot",
38
38
  "plugin": "vouchington-workflow",
39
- "pluginVersion": "0.14.1",
39
+ "pluginVersion": "0.14.2",
40
40
  "path": "dependabot/SKILL.md",
41
41
  "prerequisites": ["github-actions-checklist"]
42
42
  },
@@ -50,26 +50,26 @@
50
50
  {
51
51
  "name": "git-commit-checklist",
52
52
  "plugin": "vouchington-workflow",
53
- "pluginVersion": "0.14.1",
53
+ "pluginVersion": "0.14.2",
54
54
  "path": "git-commit-checklist/SKILL.md"
55
55
  },
56
56
  {
57
57
  "name": "github-actions-authoring",
58
58
  "plugin": "vouchington-workflow",
59
- "pluginVersion": "0.14.1",
59
+ "pluginVersion": "0.14.2",
60
60
  "path": "github-actions-authoring/SKILL.md",
61
61
  "prerequisites": ["github-actions-checklist"]
62
62
  },
63
63
  {
64
64
  "name": "github-actions-checklist",
65
65
  "plugin": "vouchington-workflow",
66
- "pluginVersion": "0.14.1",
66
+ "pluginVersion": "0.14.2",
67
67
  "path": "github-actions-checklist/SKILL.md"
68
68
  },
69
69
  {
70
70
  "name": "github-issue",
71
71
  "plugin": "vouchington-workflow",
72
- "pluginVersion": "0.14.1",
72
+ "pluginVersion": "0.14.2",
73
73
  "path": "github-issue/SKILL.md"
74
74
  },
75
75
  {
@@ -82,26 +82,26 @@
82
82
  {
83
83
  "name": "npm-publishing",
84
84
  "plugin": "vouchington-workflow",
85
- "pluginVersion": "0.14.1",
85
+ "pluginVersion": "0.14.2",
86
86
  "path": "npm-publishing/SKILL.md"
87
87
  },
88
88
  {
89
89
  "name": "organize-github-issues",
90
90
  "plugin": "vouchington-workflow",
91
- "pluginVersion": "0.14.1",
91
+ "pluginVersion": "0.14.2",
92
92
  "path": "organize-github-issues/SKILL.md",
93
93
  "prerequisites": ["github-issue"]
94
94
  },
95
95
  {
96
96
  "name": "package-json-checklist",
97
97
  "plugin": "vouchington-workflow",
98
- "pluginVersion": "0.14.1",
98
+ "pluginVersion": "0.14.2",
99
99
  "path": "package-json-checklist/SKILL.md"
100
100
  },
101
101
  {
102
102
  "name": "planning",
103
103
  "plugin": "vouchington-workflow",
104
- "pluginVersion": "0.14.1",
104
+ "pluginVersion": "0.14.2",
105
105
  "path": "planning/SKILL.md",
106
106
  "prerequisites": ["github-issue"]
107
107
  },
@@ -133,53 +133,53 @@
133
133
  {
134
134
  "name": "pr-description",
135
135
  "plugin": "vouchington-workflow",
136
- "pluginVersion": "0.14.1",
136
+ "pluginVersion": "0.14.2",
137
137
  "path": "pr-description/SKILL.md"
138
138
  },
139
139
  {
140
140
  "name": "retrospective",
141
141
  "plugin": "vouchington-workflow",
142
- "pluginVersion": "0.14.1",
142
+ "pluginVersion": "0.14.2",
143
143
  "path": "retrospective/SKILL.md"
144
144
  },
145
145
  {
146
146
  "name": "retrospective-distill",
147
147
  "plugin": "vouchington-workflow",
148
- "pluginVersion": "0.14.1",
148
+ "pluginVersion": "0.14.2",
149
149
  "path": "retrospective-distill/SKILL.md",
150
150
  "prerequisites": ["github-issue"]
151
151
  },
152
152
  {
153
153
  "name": "review-ci-logs",
154
154
  "plugin": "vouchington-workflow",
155
- "pluginVersion": "0.14.1",
155
+ "pluginVersion": "0.14.2",
156
156
  "path": "review-ci-logs/SKILL.md",
157
157
  "prerequisites": ["github-actions-checklist", "pr-description"]
158
158
  },
159
159
  {
160
160
  "name": "review-github-issue-taxonomy",
161
161
  "plugin": "vouchington-workflow",
162
- "pluginVersion": "0.14.1",
162
+ "pluginVersion": "0.14.2",
163
163
  "path": "review-github-issue-taxonomy/SKILL.md",
164
164
  "prerequisites": ["github-issue"]
165
165
  },
166
166
  {
167
167
  "name": "revisit-followups",
168
168
  "plugin": "vouchington-workflow",
169
- "pluginVersion": "0.14.1",
169
+ "pluginVersion": "0.14.2",
170
170
  "path": "revisit-followups/SKILL.md",
171
171
  "prerequisites": ["github-issue"]
172
172
  },
173
173
  {
174
174
  "name": "stacked-prs",
175
175
  "plugin": "vouchington-workflow",
176
- "pluginVersion": "0.14.1",
176
+ "pluginVersion": "0.14.2",
177
177
  "path": "stacked-prs/SKILL.md"
178
178
  },
179
179
  {
180
180
  "name": "static-analysis-checklist",
181
181
  "plugin": "vouchington-workflow",
182
- "pluginVersion": "0.14.1",
182
+ "pluginVersion": "0.14.2",
183
183
  "path": "static-analysis-checklist/SKILL.md",
184
184
  "prerequisites": ["github-actions-checklist"]
185
185
  },
@@ -206,7 +206,7 @@
206
206
  {
207
207
  "name": "triage-prs",
208
208
  "plugin": "vouchington-workflow",
209
- "pluginVersion": "0.14.1",
209
+ "pluginVersion": "0.14.2",
210
210
  "path": "triage-prs/SKILL.md",
211
211
  "prerequisites": [
212
212
  "pr-description",
@@ -12,14 +12,29 @@ Local policy overrides these defaults; do not reload an already-read adapter or
12
12
  Use before opening or updating a pull request, after diagnosing a CI failure, or at handoff. Read local
13
13
  `AGENTS.md`, pull-request template, and issue-linking policy first.
14
14
 
15
- Keep the description understandable without the conversation. Its short visible core explains:
15
+ Write for a reviewer who has not seen the conversation or the code. Use plain language and short
16
+ bullets, not dense paragraphs of internal terms. Its visible core explains:
16
17
 
17
- - **Summary:** what changed, why, and the concrete before/after behavior. For a fix, explain its
18
- root cause as well as the symptom. A reader should understand the outcome before implementation
19
- details.
20
- - **Impact:** who or what is affected and how their behavior changes. Name the actual audience,
21
- such as end users, staff, API clients, operators, or contributors. Keep material risks and
22
- limitations visible. For internal work, describe the affected development or operational flow.
18
+ - **Summary:** open with one or two sentences on the outcome in plain terms. Then give a
19
+ **Why:** that names the concrete problem or risk, such as who could do what before this change.
20
+ For a fix, give the root cause as well as the symptom.
21
+ - **Before/after table:** for any behavior change, add a visible table whose rows are concrete
22
+ scenarios, such as requests, configurations, environments, inputs, or user actions. Its columns
23
+ are the situation, the behavior before, and the behavior after. Include the unchanged cases a
24
+ reviewer would worry about, and the error or status each failure case returns.
25
+ - **Diagram:** when a request or event crosses components, add a Mermaid `sequenceDiagram` of the
26
+ new flow. Use a `flowchart` for decision logic or changed architecture. Keep the main diagram
27
+ visible.
28
+ - **Impact:** one bullet per affected audience, such as end users, staff, native or API clients,
29
+ operators, or contributors, saying what each one sees. Say when the change is active: what
30
+ enables it, such as a plan tier, feature flag, environment, configuration value, or rollout
31
+ step, and whether current deployments already satisfy it. Name the configuration it reads and
32
+ its defaults. Keep risks, limitations, and dependent follow-ups visible.
33
+
34
+ Put implementation detail under **Details**, grouped by subsystem with short headings. Name the
35
+ files and functions that carry each part, so a reviewer can find them. Leave CI history, rebase
36
+ narrative, and local test lists out of the body; the Shepherd Journal and evidence record hold
37
+ them.
23
38
 
24
39
  Add detail only where the change warrants it:
25
40
 
@@ -32,11 +47,11 @@ Add detail only where the change warrants it:
32
47
  producer/consumer changes and any justified exceptions. Link the policy and concrete evidence.
33
48
  - For API, workflow, or independently deployed changes, explain the affected contract, lifecycle,
34
49
  or operational safety. Follow the consumer's compatibility and deployment policy.
35
- - Use a before/after table or meaningful Mermaid diagram when it makes behavior, relationships,
36
- workflow topology, or lifecycle easier to understand. Prose is sufficient for a simple change.
50
+ - A one-line fix with no new scenarios needs only prose. Skip the table and diagram there.
37
51
 
38
- Put long comparisons, inventories, diagrams, calculations, and failure evidence in collapsed
39
- `<details>` sections. Keep the short conclusions and material risks outside them. Keep the
52
+ Put long inventories, secondary diagrams, calculations, and failure evidence in collapsed
53
+ `<details>` sections. Keep the summary, the main before/after table, the main diagram, and
54
+ material risks outside them. Keep the
40
55
  consumer's required visible core headings outside disclosure containers. Put opening/closing tags
41
56
  on separate lines, with a blank line after `</summary>` and before `</details>` so Markdown renders.
42
57
  Read [description examples](references/examples.md) when choosing a comparison, diagram, or failure
@@ -20,6 +20,59 @@ clears the old selection after the exit animation.
20
20
 
21
21
  No diagram, cost calculation, database inventory, or local successful-test list is needed.
22
22
 
23
+ ## Request-flow change with activation conditions
24
+
25
+ ````markdown
26
+ ## Summary
27
+
28
+ Writes from sessions the edge flags as likely automated must now pass a challenge first. The web
29
+ app shows the challenge and retries the request on its own.
30
+
31
+ **Why:** the plan limit applies only to the agent API. A script holding a copied session cookie
32
+ could use the REST API to do what the agent API refuses.
33
+
34
+ | Request | Before | After |
35
+ | ------------------------------------- | ------- | ------------------------------------------------------------ |
36
+ | Cookie-session write, bot score 30–99 | Allowed | Allowed, unchanged |
37
+ | Cookie-session write, bot score 1–29 | Allowed | `403 CHALLENGE_REQUIRED`, then one retry after the challenge |
38
+ | Any read | Allowed | Allowed, never challenged |
39
+ | OAuth or API-key request | Allowed | Allowed; keeps its own admission path |
40
+ | No score supplied | Allowed | Allowed; check skipped |
41
+
42
+ ```mermaid
43
+ sequenceDiagram
44
+ participant B as Browser
45
+ participant E as Edge proxy
46
+ participant A as API
47
+ B->>E: POST (session cookie)
48
+ E->>A: forward + score header (only if the edge supplied one)
49
+ alt score missing or 30–99
50
+ A-->>B: normal response
51
+ else score 1–29
52
+ A-->>B: 403 CHALLENGE_REQUIRED
53
+ B->>E: same request + challenge token
54
+ E->>A: forward
55
+ A-->>B: normal response, or 400 if the token fails
56
+ end
57
+ ```
58
+
59
+ ## Impact
60
+
61
+ **Not active yet.** The score comes from a paid edge plan, and every check is skipped without it.
62
+ It switches on with no code change once the score is available.
63
+
64
+ - **Normal users:** nothing changes.
65
+ - **Flagged users:** a short, usually invisible challenge before each write.
66
+ - **Scripts with a copied cookie:** writes fail.
67
+ - **OAuth and API-key clients:** unaffected.
68
+ - **Limitation:** automation driving a real browser can often pass the challenge. Session binding
69
+ remains the main defense.
70
+ ````
71
+
72
+ The table covers the unchanged paths a reviewer would worry about. The Impact opens by saying
73
+ when the change takes effect. A real description adds Details grouped by subsystem, naming the
74
+ files and functions involved.
75
+
23
76
  ## Database relationship change
24
77
 
25
78
  ```markdown