vouchington-tooling 0.62.0 → 0.64.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 (113) hide show
  1. package/README.md +147 -0
  2. package/dist/cli/commands/cloc.d.mts +7 -0
  3. package/dist/cli/commands/cloc.mjs +47 -0
  4. package/dist/cli/commands/storybook-browser-runner.d.mts +7 -0
  5. package/dist/cli/commands/storybook-browser-runner.mjs +29 -0
  6. package/dist/cli/index.mjs +4 -0
  7. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  8. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  9. package/dist/cli/parse.d.mts +6 -0
  10. package/dist/cli/usage-text.d.mts +1 -1
  11. package/dist/cli/usage-text.mjs +18 -0
  12. package/dist/cloc/child-process.d.mts +3 -0
  13. package/dist/cloc/child-process.mjs +14 -0
  14. package/dist/cloc/classify.d.mts +8 -0
  15. package/dist/cloc/classify.mjs +20 -0
  16. package/dist/cloc/config-load.d.mts +7 -0
  17. package/dist/cloc/config-load.mjs +26 -0
  18. package/dist/cloc/config.d.mts +55 -0
  19. package/dist/cloc/config.mjs +109 -0
  20. package/dist/cloc/count.d.mts +9 -0
  21. package/dist/cloc/count.mjs +33 -0
  22. package/dist/cloc/index.d.mts +12 -0
  23. package/dist/cloc/index.mjs +7 -0
  24. package/dist/cloc/layout.test-helpers.d.mts +8 -0
  25. package/dist/cloc/layout.test-helpers.mjs +42 -0
  26. package/dist/cloc/paths.d.mts +7 -0
  27. package/dist/cloc/paths.mjs +29 -0
  28. package/dist/cloc/patterns.d.mts +10 -0
  29. package/dist/cloc/patterns.mjs +25 -0
  30. package/dist/cloc/rows.d.mts +13 -0
  31. package/dist/cloc/rows.mjs +42 -0
  32. package/dist/cloc/scc.d.mts +10 -0
  33. package/dist/cloc/scc.mjs +55 -0
  34. package/dist/cloc/tracked.d.mts +4 -0
  35. package/dist/cloc/tracked.mjs +40 -0
  36. package/dist/postgres-test-faults/fault-support.d.mts +11 -0
  37. package/dist/postgres-test-faults/fault-support.mjs +61 -0
  38. package/dist/postgres-test-faults/fault-types.d.mts +43 -0
  39. package/dist/postgres-test-faults/fault-types.mjs +1 -0
  40. package/dist/postgres-test-faults/index.d.mts +5 -0
  41. package/dist/postgres-test-faults/index.mjs +4 -0
  42. package/dist/postgres-test-faults/lock-observers.d.mts +20 -0
  43. package/dist/postgres-test-faults/lock-observers.mjs +14 -0
  44. package/dist/postgres-test-faults/lock-wait.d.mts +13 -0
  45. package/dist/postgres-test-faults/lock-wait.mjs +62 -0
  46. package/dist/postgres-test-faults/lock-waiter.d.mts +19 -0
  47. package/dist/postgres-test-faults/lock-waiter.mjs +95 -0
  48. package/dist/postgres-test-faults/observation-queue.d.mts +2 -0
  49. package/dist/postgres-test-faults/observation-queue.mjs +22 -0
  50. package/dist/postgres-test-faults/polling.d.mts +6 -0
  51. package/dist/postgres-test-faults/polling.mjs +33 -0
  52. package/dist/postgres-test-faults/pool-query-failure.d.mts +8 -0
  53. package/dist/postgres-test-faults/pool-query-failure.mjs +136 -0
  54. package/dist/postgres-test-faults/query-failure.d.mts +8 -0
  55. package/dist/postgres-test-faults/query-failure.mjs +108 -0
  56. package/dist/postgres-test-faults/test-cluster.test-helpers.d.mts +13 -0
  57. package/dist/postgres-test-faults/test-cluster.test-helpers.mjs +84 -0
  58. package/dist/provider-replay/abort-listeners.d.mts +4 -0
  59. package/dist/provider-replay/abort-listeners.mjs +19 -0
  60. package/dist/provider-replay/aws-replay-abort-signal.d.mts +5 -0
  61. package/dist/provider-replay/aws-replay-abort-signal.mjs +63 -0
  62. package/dist/provider-replay/aws-replay-request-handler.d.mts +38 -0
  63. package/dist/provider-replay/aws-replay-request-handler.mjs +66 -0
  64. package/dist/provider-replay/force-client-option.d.mts +6 -0
  65. package/dist/provider-replay/force-client-option.mjs +13 -0
  66. package/dist/provider-replay/index.d.mts +6 -0
  67. package/dist/provider-replay/index.mjs +6 -0
  68. package/dist/provider-replay/provider-replay.d.mts +32 -0
  69. package/dist/provider-replay/provider-replay.mjs +54 -0
  70. package/dist/provider-replay/recorded-response.d.mts +17 -0
  71. package/dist/provider-replay/recorded-response.mjs +42 -0
  72. package/dist/provider-replay/replay-response.d.mts +8 -0
  73. package/dist/provider-replay/replay-response.mjs +38 -0
  74. package/dist/storybook-browser-runner/args.d.mts +8 -0
  75. package/dist/storybook-browser-runner/args.mjs +52 -0
  76. package/dist/storybook-browser-runner/attempt-result.d.mts +41 -0
  77. package/dist/storybook-browser-runner/attempt-result.mjs +108 -0
  78. package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +35 -0
  79. package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +138 -0
  80. package/dist/storybook-browser-runner/cache-plan.d.mts +22 -0
  81. package/dist/storybook-browser-runner/cache-plan.mjs +53 -0
  82. package/dist/storybook-browser-runner/diagnostics.d.mts +8 -0
  83. package/dist/storybook-browser-runner/diagnostics.mjs +29 -0
  84. package/dist/storybook-browser-runner/env.d.mts +2 -0
  85. package/dist/storybook-browser-runner/env.mjs +59 -0
  86. package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +49 -0
  87. package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +95 -0
  88. package/dist/storybook-browser-runner/index.d.mts +15 -0
  89. package/dist/storybook-browser-runner/index.mjs +70 -0
  90. package/dist/storybook-browser-runner/observer-state.d.mts +22 -0
  91. package/dist/storybook-browser-runner/observer-state.mjs +21 -0
  92. package/dist/storybook-browser-runner/options.d.mts +18 -0
  93. package/dist/storybook-browser-runner/options.mjs +49 -0
  94. package/dist/storybook-browser-runner/output-observer.d.mts +37 -0
  95. package/dist/storybook-browser-runner/output-observer.mjs +130 -0
  96. package/dist/storybook-browser-runner/output-patterns.d.mts +14 -0
  97. package/dist/storybook-browser-runner/output-patterns.mjs +26 -0
  98. package/dist/storybook-browser-runner/quiet-output.d.mts +16 -0
  99. package/dist/storybook-browser-runner/quiet-output.mjs +79 -0
  100. package/dist/storybook-browser-runner/run-attempt.d.mts +14 -0
  101. package/dist/storybook-browser-runner/run-attempt.mjs +111 -0
  102. package/dist/storybook-browser-runner/runtime-metadata.d.mts +12 -0
  103. package/dist/storybook-browser-runner/runtime-metadata.mjs +50 -0
  104. package/dist/storybook-browser-runner/session-deps.d.mts +11 -0
  105. package/dist/storybook-browser-runner/session-deps.mjs +70 -0
  106. package/dist/storybook-browser-runner/types.d.mts +49 -0
  107. package/dist/storybook-browser-runner/types.mjs +1 -0
  108. package/dist/storybook-browser-runner/vite-detectors.d.mts +6 -0
  109. package/dist/storybook-browser-runner/vite-detectors.mjs +20 -0
  110. package/dist/storybook-browser-runner/watchdog.d.mts +23 -0
  111. package/dist/storybook-browser-runner/watchdog.mjs +55 -0
  112. package/package.json +27 -1
  113. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
package/README.md CHANGED
@@ -323,6 +323,93 @@ the output. The pieces are exported from `vouchington-tooling/sandbox-command-au
323
323
  (`scanTranscripts`, `discoverTranscriptFiles`, `resolveRepoRoots`, `classifyAudit`, `formatReport`,
324
324
  `runAudit`). Codex escalations are not scanned: Codex agents journal those separately.
325
325
 
326
+ ## Counting lines of code
327
+
328
+ `vouchington cloc --config <file> [--scc-bin <path>] [--json]` counts git-tracked lines with
329
+ [`scc`](https://github.com/boyter/scc) (`--by-file` CSV, streamed), classifies each file into
330
+ `source`, `tests` or `tooling` and into a service, and prints an aligned table with a `total` row
331
+ (`--json` prints the rows). The binary is `--scc-bin`, else `SCC_BIN`, else the config's `sccBin`,
332
+ else `scc`. Exits 0, 2 on a usage error, and 1 when the config or the count fails.
333
+
334
+ `<file>` is a `.json` file, or a module whose default (or `config`) export is the layout (or a
335
+ function returning it). Every field is optional:
336
+
337
+ ```json
338
+ {
339
+ "services": [
340
+ { "name": "api", "match": ["api/"] },
341
+ { "name": "web", "match": ["web/", "e2e/"] }
342
+ ],
343
+ "defaultService": "tooling",
344
+ "categories": { "tests": "specs" },
345
+ "testPatterns": ["*.test.*", "**/__tests__/**"],
346
+ "toolingPatterns": [".github/", "**/scripts/**", "package.json", "*.config.*"],
347
+ "countedRoots": ["api", "web", "e2e", ".github"],
348
+ "countedRootFiles": ["package.json"],
349
+ "excludedDirs": ["node_modules", "dist"],
350
+ "ignoredDirs": ["fixtures", "__snapshots__"],
351
+ "missingSccHint": "Install scc with your package manager."
352
+ }
353
+ ```
354
+
355
+ - `services`: ordered; the first rule with a matching pattern wins, and the order is the row order.
356
+ `defaultService` (default `other`) takes the rest and is appended when not listed.
357
+ - Patterns: no `/` matches the basename anywhere (`*.test.*`, `package.json`); a trailing `/` or a
358
+ `/` without glob characters matches the path or anything under it; a `/` with glob characters is
359
+ a full-path glob (`**/tests/**`). Dotfiles match. Tests are checked first, then tooling; the rest
360
+ is source.
361
+ - `countedRoots` and `countedRootFiles` limit what is counted and what scc is given; omit both to
362
+ count every tracked file. `excludedDirs` is passed to scc (defaults cover VCS, build and
363
+ `node_modules` directories); `ignoredDirs` drops files under those directory names at any depth
364
+ (defaults: `fixtures`, `__fixtures__`, `__snapshots__`).
365
+ - `categories` renames the three column labels; `missingSccHint` is appended to the error shown when
366
+ the binary is not found.
367
+
368
+ The pieces are exported from `vouchington-tooling/cloc` (`loadClocConfig`, `normalizeClocConfig`,
369
+ `countFiles`, `buildRows`, `formatRows`, `createClassifier`, `createPathPolicy`,
370
+ `compilePatterns`).
371
+
372
+ ## Running the Storybook browser tests
373
+
374
+ `vouchington storybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]...
375
+ [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>]
376
+ [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]` runs the Storybook Vitest browser
377
+ project under a watchdog. It spawns `<cmd>` (default `pnpm`) in its own process group with `<argv>`
378
+ (default `exec vitest run --project <name>`) plus the coverage args (default `--coverage`, dropped
379
+ when `<PREFIX>_COVERAGE=0`), supervised by `browser-session-runner`. Arguments after `--` replace the
380
+ default argv and may begin with a dash; flag values that begin with a dash use `--flag=value`.
381
+
382
+ The runner keeps a Vite optimizer cache: a persistent one in CI (`.cache/vite/storybook-browser`, or
383
+ `<PREFIX>_PERSISTENT_CACHE_DIR`; `<PREFIX>_PERSISTENT_CACHE=0` turns it off) and a per-attempt one
384
+ otherwise. A successful attempt that used a fresh cache is promoted to the persistent one. It
385
+ retries (at most 3 attempts, `<PREFIX>_STARTUP_ATTEMPTS`) on known Vite and browser start-up flakes:
386
+ a failed dynamic import from the Vite server, `ERR_NETWORK_CHANGED` before any test progress, the
387
+ Storybook add-on's "Vitest failed to find the runner", an optimizer that stops progressing
388
+ (`_OPTIMIZER_STALL_MS`, default 30000), and a tester-connection hang (`_HANG_MS`, default 120000).
389
+ A start-up failure clears the persistent cache and the retry uses a fresh attempt cache. A stall
390
+ after test progress began, an expired session budget (`_SESSION_BUDGET_MS`, default 300000) and a
391
+ spawn failure are never retried. When Vite discovers new `optimizeDeps` and reloads, the run is not
392
+ retried and the guidance names `--optimize-deps-config`. Progress markers and `vite:deps` debug
393
+ output are kept out of the log and replayed from a bounded tail when an attempt fails, and a
394
+ diagnostics file (`_DIAGNOSTICS_FILE`, default `storybook-browser-diagnostics.log`) holds the
395
+ per-attempt summaries and the output tail.
396
+
397
+ Everything repository-specific is a parameter: the Vitest project name (also the browser-project
398
+ output marker), the command and argv, the `--result-file` paths removed before each attempt, the
399
+ `--completion-file` whose appearance is recorded, the optimizeDeps config path named in the
400
+ guidance, the env var prefix (default `STORYBOOK_BROWSER`) and the progress marker prefix (default
401
+ `[vitest-browser-progress]`, the one `createVitestStorybookProgressReporter` writes). The Vitest
402
+ config must read `VITEST_STORYBOOK_BROWSER`, `VITEST_STORYBOOK_BROWSER_API_PORT` and
403
+ `VITEST_STORYBOOK_BROWSER_CACHE_DIR`, which the runner sets for each attempt, and
404
+ `VITEST_COVERAGE_SCOPE`, set to the project name. The module is exported from
405
+ `vouchington-tooling/storybook-browser-runner` as `runStorybookBrowserTests(project, { env }, deps)`,
406
+ which resolves with the exit code; every effect (`spawn`, clock, timers, filesystem, streams) is
407
+ injectable through `deps`. Exits 2 on a usage error. The runner is POSIX-only (it signals process
408
+ groups) and the command exits 1 on Windows. Semantic progress comes from the progress-marker reporter
409
+ (`createVitestStorybookProgressReporter`); without it only the first project result counts as progress.
410
+ A session budget of 5000 ms or less caps the termination
411
+ grace at half the budget.
412
+
326
413
  ## Reclaiming finished worktrees
327
414
 
328
415
  `vouchington worktree reclaim [--yes] [--json]` removes git worktrees whose work is done. It is a
@@ -385,6 +472,15 @@ import {
385
472
  import { createArtifactClassifier, runCleanup } from 'vouchington-tooling/gha-artifacts-cleanup'
386
473
  import { ensureLabels, labelsFromPaths } from 'vouchington-tooling/agent-issue-labels'
387
474
  import { validateOptionalHttpOrigin } from 'vouchington-tooling/http-origin'
475
+ // Replay recorded raw `.http` responses through an SDK `fetch` or AWS SDK v3 `requestHandler`:
476
+ // const replay = createProviderReplay({ chunkBytes: 3 })
477
+ // replay.respondWith(loadRecordedResponse('ok.http', { fixtureRoot: new URL('./fixtures/', import.meta.url) }))
478
+ // new Sdk({ fetch: replay.fetch }) or new AwsClient({ requestHandler: createAwsReplayRequestHandler(replay) })
479
+ import {
480
+ createAwsReplayRequestHandler,
481
+ createProviderReplay,
482
+ loadRecordedResponse,
483
+ } from 'vouchington-tooling/provider-replay'
388
484
  import { boundPendingLine, splitCompleteLines } from 'vouchington-tooling/process-line-buffer'
389
485
  import {
390
486
  isProcessGroupAlive,
@@ -407,6 +503,7 @@ import {
407
503
  } from 'vouchington-tooling/api-fixtures'
408
504
  import { decide, deriveRetryAttempt } from 'vouchington-tooling/transient-retry'
409
505
  import { scanTranscripts, classifyAudit } from 'vouchington-tooling/sandbox-command-audit'
506
+ import { runStorybookBrowserTests } from 'vouchington-tooling/storybook-browser-runner'
410
507
  import { parseCsvRows, streamCsvRows } from 'vouchington-tooling/csv'
411
508
  import {
412
509
  extractLooseMarkdownTableRows,
@@ -1075,3 +1172,53 @@ from `TMUX_TARGET_BIN`, the worktree from `TMUX_TARGET_ROOT` (default: current d
1075
1172
  touching it. `tmux post-tool` reads an agent post-tool hook payload on stdin and prints a rename
1076
1173
  reminder at plan, PR, push and reset checkpoints; reminders name `TMUX_NAME_COMMAND` (default
1077
1174
  `vouchington tmux name`).
1175
+
1176
+ ## PostgreSQL test faults and lock waits
1177
+
1178
+ `vouchington-tooling/postgres-test-faults` injects real PostgreSQL failures and observes real lock
1179
+ waits for any `pg.Pool` application. It needs the optional peer `pg` (>=8) and `@types/pg`; no
1180
+ product code is imported, so pools and request ownership are passed in.
1181
+
1182
+ ```ts
1183
+ import {
1184
+ createPostgresLockObservers,
1185
+ withPostgresPoolQueryFailureForTest,
1186
+ withPostgresQueryFailureForTest,
1187
+ } from 'vouchington-tooling/postgres-test-faults'
1188
+
1189
+ const { result, error } = await withPostgresQueryFailureForTest(
1190
+ '/* orders:insert */', // exact leading block comment that marks the statement to fail
1191
+ () => placeOrder().catch((err: unknown) => err), // absorb the injected error
1192
+ { pools: [readPool, writePool], command: 'INSERT' },
1193
+ )
1194
+ // error.code === '25P02': PostgreSQL rejected the marked statement on an aborted transaction.
1195
+ ```
1196
+
1197
+ - `withPostgresQueryFailureForTest(marker, operation, options)` fails one marked statement on a
1198
+ client leased from `options.pools` with the promise form of `pool.connect()` (the callback
1199
+ overload is not instrumented), inside a transaction the operation began with `BEGIN`. A
1200
+ division by zero aborts that transaction, so PostgreSQL itself answers `25P02`.
1201
+ - `withPostgresPoolQueryFailureForTest(marker, operation, options)` does the same for a marked
1202
+ `pool.query({ text })` call: it leases a real client, aborts its transaction, and hands the client
1203
+ to the unchanged `pg.Pool#query` core.
1204
+ - Both resolve to `{ result, error }` only when the operation absorbs the injected `25P02` (catch
1205
+ or translate it, and return the outcome as `result`). If the operation lets the error
1206
+ propagate, the helper rejects with that error; it also rejects when the marked SQL never ran.
1207
+ Observers give up after `timeoutMs` even when a query never settles; `signal` is checked between
1208
+ steps, not inside a pending query. `options` is
1209
+ `{ pools, command?, requestId?, isOwnedRequest?, endTimeoutMs? }`. A statement is owned by the
1210
+ operation's async context, or by `requestId` when `isOwnedRequest(requestId)` returns true
1211
+ (use it for work that runs outside that context, such as a request handler). Scopes are
1212
+ serialized and cannot be nested.
1213
+ - `createPostgresLockObservers({ write, advisoryLockPool?, timeoutMs?, intervalMs? })` binds the
1214
+ observers to your executors (any `({ text, values }) => Promise<{ rows }>`, for example
1215
+ `query => pool.query(query)`), with defaults of 5000 ms and 10 ms. It returns
1216
+ `getTestPostgresBackendProcessId(executor)`, `getTestPostgresAdvisoryLockHolderProcessId({ key,
1217
+ mode?, namespace? })`, `waitForTestPostgresLockWaiter(holderPid, marker, observer?, onDiagnostic?,
1218
+ signal?, waiterPid?)` and `waitForTestPostgresBlockedLockChain(holderPid, directMarker,
1219
+ blockedMarkers, observer?)`. The waiters poll `pg_stat_activity` and `pg_blocking_pids`; the
1220
+ observer is `'write'`, `'advisoryLock'` or a reserved executor.
1221
+
1222
+ The package's own tests start a throwaway cluster with `initdb`/`pg_ctl` found through
1223
+ `POSTGRES_BIN_DIR`, `PATH` or a standard install location. They skip where no server can run and
1224
+ fail under `CI`.
@@ -0,0 +1,7 @@
1
+ import { type LoadModule } from '../../cloc/config-load.mts';
2
+ /**
3
+ * `vouchington cloc --config <file> [--scc-bin <path>] [--json]`: counts tracked lines of code with
4
+ * scc, classified by the layout config into categories and services, and prints a table. Exits 0
5
+ * on success, 2 on a usage error, 1 when the config cannot load or counting fails.
6
+ */
7
+ export declare function runClocCommand(args: readonly string[], env?: NodeJS.ProcessEnv, load?: LoadModule): Promise<number>;
@@ -0,0 +1,47 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { loadClocConfig } from "../../cloc/config-load.mjs";
3
+ import { countFiles } from "../../cloc/count.mjs";
4
+ import { buildRows, formatRows } from "../../cloc/rows.mjs";
5
+ import { commandUsage } from "../usage.mjs";
6
+ /**
7
+ * `vouchington cloc --config <file> [--scc-bin <path>] [--json]`: counts tracked lines of code with
8
+ * scc, classified by the layout config into categories and services, and prints a table. Exits 0
9
+ * on success, 2 on a usage error, 1 when the config cannot load or counting fails.
10
+ */
11
+ export async function runClocCommand(args, env = process.env, load) {
12
+ let values;
13
+ try {
14
+ const parsed = parseArgs({
15
+ args: [...args],
16
+ allowPositionals: false,
17
+ options: {
18
+ config: { type: 'string' },
19
+ 'scc-bin': { type: 'string' },
20
+ json: { type: 'boolean' },
21
+ },
22
+ });
23
+ values = parsed.values;
24
+ if (values.config === undefined)
25
+ throw new Error('--config <file> is required');
26
+ }
27
+ catch (error) {
28
+ process.stderr.write(`vouchington: ${error.message}\n${commandUsage('cloc')}`);
29
+ return 2;
30
+ }
31
+ try {
32
+ const cwd = process.cwd();
33
+ const config = await loadClocConfig(values.config, cwd, load);
34
+ const files = await countFiles(config, {
35
+ cwd,
36
+ env,
37
+ ...(values['scc-bin'] === undefined ? {} : { sccBin: values['scc-bin'] }),
38
+ });
39
+ const rows = buildRows(files, config);
40
+ process.stdout.write(values.json ? `${JSON.stringify(rows, null, 2)}\n` : `${formatRows(rows, config)}\n`);
41
+ return 0;
42
+ }
43
+ catch (error) {
44
+ process.stderr.write(`vouchington: ${error instanceof Error ? error.message : String(error)}\n`);
45
+ return 1;
46
+ }
47
+ }
@@ -0,0 +1,7 @@
1
+ import { runStorybookBrowserTests } from '../../storybook-browser-runner/index.mts';
2
+ /**
3
+ * `vouchington storybook-browser-runner --project <name> [flags] [-- <argv>...]`: runs the
4
+ * Storybook Vitest browser project under the cache, retry and watchdog runner. Exits with the test
5
+ * command's resolved code, or 2 on a usage error.
6
+ */
7
+ export declare function runStorybookBrowserRunnerCommand(args: readonly string[], run?: typeof runStorybookBrowserTests, platform?: NodeJS.Platform): Promise<number>;
@@ -0,0 +1,29 @@
1
+ import { parseStorybookBrowserRunnerArgs } from "../../storybook-browser-runner/args.mjs";
2
+ import { runStorybookBrowserTests } from "../../storybook-browser-runner/index.mjs";
3
+ import { commandUsage } from "../usage.mjs";
4
+ /**
5
+ * `vouchington storybook-browser-runner --project <name> [flags] [-- <argv>...]`: runs the
6
+ * Storybook Vitest browser project under the cache, retry and watchdog runner. Exits with the test
7
+ * command's resolved code, or 2 on a usage error.
8
+ */
9
+ export async function runStorybookBrowserRunnerCommand(args, run = runStorybookBrowserTests, platform = process.platform) {
10
+ if (platform === 'win32') {
11
+ process.stderr.write('vouchington: storybook-browser-runner is POSIX-only (process groups)\n');
12
+ return 1;
13
+ }
14
+ let project;
15
+ try {
16
+ project = parseStorybookBrowserRunnerArgs(args);
17
+ }
18
+ catch (error) {
19
+ process.stderr.write(`vouchington: ${error.message}\n${commandUsage('storybook-browser-runner')}`);
20
+ return 2;
21
+ }
22
+ try {
23
+ return await run(project);
24
+ }
25
+ catch (error) {
26
+ process.stderr.write(`vouchington: ${error instanceof Error ? error.message : String(error)}\n`);
27
+ return 1;
28
+ }
29
+ }
@@ -110,6 +110,10 @@ 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 'cloc':
114
+ return import("./commands/cloc.mjs").then((command) => command.runClocCommand(parsed.args));
115
+ case 'storybook-browser-runner':
116
+ return import("./commands/storybook-browser-runner.mjs").then((command) => command.runStorybookBrowserRunnerCommand(parsed.args));
113
117
  case 'hook':
114
118
  return runHookCommand(parsed.args);
115
119
  case 'worktree':
@@ -58,6 +58,12 @@ type ForwardedCommand = {
58
58
  } | {
59
59
  kind: 'sandbox-command-audit';
60
60
  args: string[];
61
+ } | {
62
+ kind: 'cloc';
63
+ args: string[];
64
+ } | {
65
+ kind: 'storybook-browser-runner';
66
+ args: string[];
61
67
  } | {
62
68
  kind: 'tmux';
63
69
  args: string[];
@@ -39,6 +39,10 @@ export function parseForwardedCommand(command, args) {
39
39
  return { kind: 'transient-retry', args };
40
40
  if (command === 'sandbox-command-audit')
41
41
  return { kind: 'sandbox-command-audit', args };
42
+ if (command === 'cloc')
43
+ return { kind: 'cloc', args };
44
+ if (command === 'storybook-browser-runner')
45
+ return { kind: 'storybook-browser-runner', args };
42
46
  if (command === 'tmux')
43
47
  return { kind: 'tmux', args };
44
48
  return undefined;
@@ -89,6 +89,12 @@ export type ParsedCli = {
89
89
  } | {
90
90
  kind: 'sandbox-command-audit';
91
91
  args: string[];
92
+ } | {
93
+ kind: 'cloc';
94
+ args: string[];
95
+ } | {
96
+ kind: 'storybook-browser-runner';
97
+ args: string[];
92
98
  } | {
93
99
  kind: 'tmux';
94
100
  args: string[];
@@ -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\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]\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\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 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]\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";
@@ -57,6 +57,8 @@ Commands:
57
57
  story-coverage Check component exports are imported by stories
58
58
  transient-retry Rerun a failed GitHub Actions run when an injected rule matches
59
59
  sandbox-command-audit Audit agent transcripts for sandbox escalations and denials
60
+ cloc Count tracked lines of code by category and service with scc
61
+ storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog
60
62
 
61
63
  Options:
62
64
  -h, --help Show this help
@@ -171,6 +173,22 @@ sandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <di
171
173
  optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots
172
174
  default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.
173
175
 
176
+ cloc --config <file> [--scc-bin <path>] [--json]
177
+ Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else "scc"), classified into
178
+ source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json
179
+ file or a module whose default (or "config") export is the layout: services [{ name, match }],
180
+ defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,
181
+ excludedDirs, ignoredDirs, sccBin, missingSccHint.
182
+
183
+ 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
+ Spawns <cmd> (default pnpm) in its own process group with <argv> (default "exec vitest run
185
+ --project <name>") plus the coverage args (default --coverage) and supervises it: a Vite optimizer
186
+ cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget
187
+ watchdogs. --result-file paths are removed before each attempt and --completion-file is the one
188
+ whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,
189
+ _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE
190
+ (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.
191
+
174
192
  tmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]
175
193
  tmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>
176
194
  Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.
@@ -0,0 +1,3 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ export declare function requireSuccess(child: ChildProcess, label: string): Promise<void>;
3
+ export declare function terminateChild(child: ChildProcess, completion: Promise<void>): Promise<void>;
@@ -0,0 +1,14 @@
1
+ export async function requireSuccess(child, label) {
2
+ const code = await new Promise((resolve, reject) => {
3
+ child.once('error', reject);
4
+ child.once('close', resolve);
5
+ });
6
+ if (code !== 0)
7
+ throw new Error(`${label} exited with status ${String(code)}`);
8
+ }
9
+ export async function terminateChild(child, completion) {
10
+ child.stdout?.destroy();
11
+ if (child.exitCode === null && child.signalCode === null)
12
+ child.kill();
13
+ await completion.catch(() => { });
14
+ }
@@ -0,0 +1,8 @@
1
+ import type { ClocCategories, ClocConfig } from './config.mts';
2
+ export type CategoryKey = keyof ClocCategories;
3
+ export type Classification = {
4
+ category: CategoryKey;
5
+ service: string;
6
+ };
7
+ /** Builds the path classifier for a layout: tests, then tooling, else source; first service wins. */
8
+ export declare function createClassifier(config: ClocConfig): (filePath: string) => Classification;
@@ -0,0 +1,20 @@
1
+ import { compilePatterns, normalizePath } from "./patterns.mjs";
2
+ /** Builds the path classifier for a layout: tests, then tooling, else source; first service wins. */
3
+ export function createClassifier(config) {
4
+ const isTest = compilePatterns(config.testPatterns);
5
+ const isTooling = compilePatterns(config.toolingPatterns);
6
+ const rules = config.services.map((rule) => ({
7
+ name: rule.name,
8
+ matches: compilePatterns(rule.match),
9
+ }));
10
+ return (filePath) => {
11
+ const normalized = normalizePath(filePath);
12
+ const category = isTest(normalized)
13
+ ? 'tests'
14
+ : isTooling(normalized)
15
+ ? 'tooling'
16
+ : 'source';
17
+ const service = rules.find((rule) => rule.matches(normalized))?.name ?? config.defaultService;
18
+ return { category, service };
19
+ };
20
+ }
@@ -0,0 +1,7 @@
1
+ import { type ClocConfig } from './config.mts';
2
+ export type LoadModule = (specifier: string) => Promise<unknown>;
3
+ /**
4
+ * Loads a layout config. A `.json` file is parsed; anything else is imported, and its default (or
5
+ * named `config`) export is the config object or a function returning one.
6
+ */
7
+ export declare function loadClocConfig(file: string, cwd: string, load?: LoadModule): Promise<ClocConfig>;
@@ -0,0 +1,26 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { readFile } from 'node:fs/promises';
10
+ import { resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { normalizeClocConfig } from "./config.mjs";
13
+ const importModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
14
+ /**
15
+ * Loads a layout config. A `.json` file is parsed; anything else is imported, and its default (or
16
+ * named `config`) export is the config object or a function returning one.
17
+ */
18
+ export async function loadClocConfig(file, cwd, load = importModule) {
19
+ const absolute = resolve(cwd, file);
20
+ if (absolute.endsWith('.json')) {
21
+ return normalizeClocConfig(JSON.parse(await readFile(absolute, 'utf8')));
22
+ }
23
+ const loaded = (await load(pathToFileURL(absolute).href));
24
+ const exported = loaded.config ?? loaded.default;
25
+ return normalizeClocConfig(typeof exported === 'function' ? await exported() : exported);
26
+ }
@@ -0,0 +1,55 @@
1
+ export type ClocCategories = {
2
+ source: string;
3
+ tests: string;
4
+ tooling: string;
5
+ };
6
+ export type ClocServiceRule = {
7
+ name: string;
8
+ match: string[];
9
+ };
10
+ export type ClocServiceRuleInput = {
11
+ name: string;
12
+ match?: string[];
13
+ };
14
+ /** The repository layout, as a consumer writes it. Every field is optional. */
15
+ export type ClocConfigInput = {
16
+ /** Ordered rules; the first whose `match` patterns match a file wins. Also the table row order. */
17
+ services?: ClocServiceRuleInput[];
18
+ /** Service for files no rule matches. Appended after the listed services when not among them. */
19
+ defaultService?: string;
20
+ /** Column names for the three categories. */
21
+ categories?: Partial<ClocCategories>;
22
+ /** Patterns marking test files; checked first. */
23
+ testPatterns?: string[];
24
+ /** Patterns marking tooling files; checked after tests. Everything else is source. */
25
+ toolingPatterns?: string[];
26
+ /** Directories counted (themselves or anything under). Omit both root lists to count everything. */
27
+ countedRoots?: string[];
28
+ /** Individual files counted at exact paths. */
29
+ countedRootFiles?: string[];
30
+ /** Directory names scc skips. */
31
+ excludedDirs?: string[];
32
+ /** Directory names whose files are never counted, at any depth. */
33
+ ignoredDirs?: string[];
34
+ /** scc binary; `--scc-bin` and `SCC_BIN` override it. */
35
+ sccBin?: string;
36
+ /** Appended to the error shown when the scc binary cannot be found. */
37
+ missingSccHint?: string;
38
+ };
39
+ export type ClocConfig = {
40
+ services: ClocServiceRule[];
41
+ defaultService: string;
42
+ categories: ClocCategories;
43
+ testPatterns: string[];
44
+ toolingPatterns: string[];
45
+ countedRoots: string[];
46
+ countedRootFiles: string[];
47
+ excludedDirs: string[];
48
+ ignoredDirs: string[];
49
+ sccBin?: string;
50
+ missingSccHint?: string;
51
+ };
52
+ export declare const DEFAULT_EXCLUDED_DIRS: string[];
53
+ export declare const DEFAULT_IGNORED_DIRS: string[];
54
+ /** Validates a raw config value and fills defaults. Throws a descriptive error when malformed. */
55
+ export declare function normalizeClocConfig(raw: unknown): ClocConfig;