vouchington-tooling 0.64.0 → 0.65.1

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.
package/README.md CHANGED
@@ -412,21 +412,35 @@ grace at half the budget.
412
412
 
413
413
  ## Reclaiming finished worktrees
414
414
 
415
- `vouchington worktree reclaim [--yes] [--json]` removes git worktrees whose work is done. It is a
415
+ `vouchington worktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]` removes git worktrees whose work is done. It is a
416
416
  dry run unless `--yes` is passed. It prints one line per worktree (`reclaimed`, `would reclaim`, or
417
- `kept: <reason>`, control characters escaped), or `{ dryRun, worktrees }` with `--json`.
417
+ `kept: <reason>`, control characters escaped), or `{ dryRun, worktrees, hasMore, nextAfter? }` with `--json`. Progress and elapsed time go to stderr.
418
+
419
+ Scans default to at most 100 registered worktrees and 30 seconds of read-only work. Read calls share
420
+ that deadline; a deletion already started is allowed to finish. An incomplete scan returns `hasMore`
421
+ and a path cursor (`nextAfter`) and prints `--after` instructions. Pass that cursor with the same
422
+ limits and `--yes` selection to resume; path ordering lets the cursor survive deletion of its worktree.
423
+ Increase `--timeout-ms` if a single slow worktree repeatedly exhausts the budget.
424
+ The cursor is an exclusive path boundary: newly added paths before it are covered by the next scan
425
+ from the beginning. When using a consumer cleanup wrapper that owns a resource lock, resume through
426
+ that wrapper rather than invoking the CLI directly.
418
427
 
419
428
  It skips the main checkout, the caller's own worktree, and locked, bare, detached and missing
420
429
  worktrees. Any other worktree is kept, with a reason, unless all of these hold:
421
430
 
422
431
  - `git status` (untracked files and submodules included) is empty, and no index entry is
423
432
  assume-unchanged or skip-worktree.
424
- - `gh pr list --head <branch>` has a merged or closed pull request from this repository (not a
433
+ - Shared repository-wide PR discovery has a merged or closed pull request from this repository (not a
425
434
  fork) whose `headRefOid` equals HEAD, and no open pull request from this repository. That PR also
426
435
  proves HEAD is published, so squash merges whose branch was deleted are reclaimed. A `gh` failure,
427
- or a query returning 1000 results, keeps the worktree.
428
-
429
- With `--yes`, HEAD and cleanliness are checked again right before `git worktree remove <path>` runs.
436
+ or an incomplete open-PR list, keeps the worktree. Discovery reads open and recent PR lists once
437
+ across all branches (paginated internally by `gh`). Each list is capped by `--pr-limit` (default
438
+ 1000, maximum 10000); worktrees without matching history are kept. Increase the limit to include
439
+ older finished PRs. A full recent-history page can prove a candidate; a full open page cannot
440
+ prove the absence of an open PR.
441
+
442
+ With `--yes`, candidates receive fresh branch-specific open/history PR checks, then HEAD,
443
+ cleanliness and registration are checked again right before `git worktree remove <path>` runs.
430
444
  It is never forced, and a refusal from git is reported as kept. Ignored files (for example `.env`, `node_modules`, build output) are deleted with the worktree, exactly as `git worktree remove` does; keep anything you need outside ignored paths or commit it. An unexpected error on one worktree is reported as `kept: error: <message>` and the run carries on. There is no `prune`, no branch
431
445
  deletion, and git runs with `core.fsmonitor=false`.
432
446
 
@@ -583,7 +597,7 @@ repository's own policy module, which default-exports a `HookPolicy` (`defineHoo
583
597
  `command` rule table, post-tool-use `checkers`, an optional `reminder`, and an optional `onPayload`
584
598
  callback (for example to persist the harness session id). `pre-tool-use` exits 2 to block, including
585
599
  when the module cannot load; `post-tool-use` is advisory and always exits 0, folding checker warnings
586
- and the reminder into one `additionalContext`. `--root` defaults to the working directory. `--automation-env NAME` (repeatable) names an extra environment variable that marks the run unattended when it is set and not empty, `0`, or `false`; CI markers and `claude -p` always count. Register `post-tool-use` with an edit-only matcher (for example `Edit|Write|apply_patch`): the command treats every `file_path` it sees as an edit, and it emits the Claude/Codex `hookSpecificOutput` shape for every harness.
600
+ and the reminder into one `additionalContext`. `--root` defaults to the working directory. `--automation-env NAME` (repeatable) names an extra environment variable that marks the run unattended when it is set and not empty, `0`, or `false`; CI markers and `claude -p` always count. Register `post-tool-use` with an edit-only matcher (for example `Edit|Write|apply_patch`): the command treats every `file_path` it sees as an edit, and it emits the Claude/Codex `hookSpecificOutput` shape for Claude and Codex. Grok ignores stdout for passive events and its hooks contract documents no other channel for PostToolUse text (https://docs.x.ai/build/features/hooks#the-script-contract), so with `--harness grok` (or a Grok environment marker) it prints nothing. `pre-tool-use` also checks commands inside `$(...)` and backtick substitutions within double quotes, one level deep and best effort; single-quoted text and plain quoted arguments stay ignored.
587
601
 
588
602
  `processDiffCommand` runs a caller-supplied `git diff` or `gh pr diff` executable and argv without
589
603
  a shell, emitting complete unified-diff file blocks without accumulating the whole patch. It keeps
@@ -1,2 +1,2 @@
1
- /** `vouchington worktree reclaim [--yes] [--json]`: exits 2 on bad usage, 1 when git cannot list. */
1
+ /** Reclamation is a dry run unless --yes; scan limits return an explicit resume cursor. */
2
2
  export declare function runWorktreeCommand(args: readonly string[], env?: NodeJS.ProcessEnv, cwd?: string): number;
@@ -1,17 +1,64 @@
1
- import { formatReport, reclaimWorktrees } from "../../git-worktrees/reclaim.mjs";
1
+ import { formatReport, reclaimWorktrees, } from "../../git-worktrees/reclaim.mjs";
2
2
  import { commandUsage } from "../usage.mjs";
3
- /** `vouchington worktree reclaim [--yes] [--json]`: exits 2 on bad usage, 1 when git cannot list. */
3
+ function parseFlags(flags) {
4
+ const options = { yes: false, json: false };
5
+ const seen = new Set();
6
+ for (let i = 0; i < flags.length; i += 1) {
7
+ const flag = flags[i];
8
+ if (seen.has(flag))
9
+ throw new Error('duplicate flag');
10
+ seen.add(flag);
11
+ if (flag === '--yes') {
12
+ options.yes = true;
13
+ continue;
14
+ }
15
+ if (flag === '--json') {
16
+ options.json = true;
17
+ continue;
18
+ }
19
+ const value = flags[++i];
20
+ if (value === undefined || value.startsWith('--'))
21
+ throw new Error('missing flag value');
22
+ if (flag === '--after')
23
+ options.after = value;
24
+ else if (flag === '--max-worktrees' || flag === '--timeout-ms' || flag === '--pr-limit') {
25
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))
26
+ throw new Error('scan limits must be positive integers');
27
+ if (flag === '--max-worktrees')
28
+ options.maxWorktrees = Number(value);
29
+ else if (flag === '--timeout-ms')
30
+ options.timeoutMs = Number(value);
31
+ else {
32
+ if (Number(value) > 10_000)
33
+ throw new Error('PR limit exceeds 10000');
34
+ options.prLimit = Number(value);
35
+ }
36
+ }
37
+ else
38
+ throw new Error('unknown flag');
39
+ }
40
+ return options;
41
+ }
42
+ /** Reclamation is a dry run unless --yes; scan limits return an explicit resume cursor. */
4
43
  export function runWorktreeCommand(args, env = process.env, cwd = process.cwd()) {
5
44
  const [subcommand, ...flags] = args;
6
- const unknown = flags.find((flag) => flag !== '--yes' && flag !== '--json');
7
- if (subcommand !== 'reclaim' || unknown !== undefined) {
8
- process.stderr.write(`vouchington: expected: reclaim [--yes] [--json]\n${commandUsage('worktree')}`);
45
+ let options;
46
+ try {
47
+ if (subcommand !== 'reclaim')
48
+ throw new Error('unknown subcommand');
49
+ options = parseFlags(flags);
50
+ }
51
+ catch {
52
+ process.stderr.write(`vouchington: expected: reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n${commandUsage('worktree')}`);
9
53
  return 2;
10
54
  }
11
55
  try {
12
- const report = reclaimWorktrees(flags.includes('--yes'), { cwd, env });
13
- const json = flags.includes('--json');
56
+ const start = Date.now();
57
+ process.stderr.write('worktree reclaim: scanning local worktrees and shared PR lists\n');
58
+ const report = reclaimWorktrees(options.yes, { cwd, env }, options);
59
+ const json = options.json;
14
60
  process.stdout.write(json ? `${JSON.stringify(report)}\n` : formatReport(report));
61
+ process.stderr.write(`worktree reclaim: ${report.hasMore ? 'scan incomplete' : 'complete'} in ${((Date.now() - start) / 1000).toFixed(1)}s\n`);
15
62
  return 0;
16
63
  }
17
64
  catch (error) {
@@ -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]\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 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";
@@ -156,7 +156,7 @@ hook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <mod
156
156
  Each --automation-env NAME (repeatable) marks the run unattended when that environment variable
157
157
  is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.
158
158
 
159
- worktree reclaim [--yes] [--json]
159
+ worktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]
160
160
  Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the
161
161
  branch is merged or closed at exactly HEAD, using git worktree remove (never forced).
162
162
  Skips the main checkout, the current worktree, and locked, bare or detached worktrees.
@@ -1,4 +1,4 @@
1
- import { commandsToInspectForGitPolicy, isInteractiveRebaseContinue, } from "../shell-parse/index.mjs";
1
+ import { commandsToInspectForGitPolicy, commandsToInspectPreservingQuotes, extractShellCommandSubstitutions, isInteractiveRebaseContinue, } from "../shell-parse/index.mjs";
2
2
  import { findBlockedPatternReason } from "./git-patterns.mjs";
3
3
  import { findGitHubWorkflowBlock } from "./github-workflow.mjs";
4
4
  import { findInteractiveMergeConfirm } from "./github-merge-authority.mjs";
@@ -37,7 +37,7 @@ export function evaluateCommandPolicy(payload, policy, options = {}) {
37
37
  findInteractiveMergeConfirm(command, automationContext, policy.mergeGuidance ?? ''));
38
38
  }
39
39
  function findScriptBlock(command, policy) {
40
- const scripts = commandsToInspectForGitPolicy(command);
40
+ const scripts = [...commandsToInspectForGitPolicy(command), ...quotedSubstitutionScripts(command)];
41
41
  for (const script of scripts) {
42
42
  const reason = findBlockedPatternReason(script, policy.commandPatterns ?? []);
43
43
  if (reason !== null)
@@ -56,3 +56,10 @@ function findScriptBlock(command, policy) {
56
56
  }
57
57
  return null;
58
58
  }
59
+ // Quoted text is blanked so a message mentioning `--force` passes, but a `$(...)` or backtick
60
+ // substitution inside double quotes still runs. Best effort: one level, no deeper quoting analysis.
61
+ function quotedSubstitutionScripts(command) {
62
+ return commandsToInspectPreservingQuotes(command)
63
+ .flatMap(extractShellCommandSubstitutions)
64
+ .flatMap(commandsToInspectForGitPolicy);
65
+ }
@@ -39,6 +39,9 @@ async function reminderOf(policy, context) {
39
39
  * hook is advisory and never blocks, so failures here are swallowed.
40
40
  */
41
41
  export async function postToolUseOutput(context, policy) {
42
+ // Grok ignores stdout for passive events and documents no other channel, so stay silent.
43
+ if (context.harness === 'grok')
44
+ return '';
42
45
  const warnings = editedPaths(context).flatMap((path) => checkFile(path, context.root, policy.checkers));
43
46
  const lines = warnings.map(({ level, message }) => `[${level}] ${message}`);
44
47
  const reminder = await reminderOf(policy, context);
@@ -1,4 +1,16 @@
1
1
  import { type RunOptions } from './run.mts';
2
+ export interface PullRequest {
3
+ readonly headRefName?: string;
4
+ readonly state?: string;
5
+ readonly headRefOid?: string;
6
+ readonly isCrossRepository?: boolean;
7
+ readonly headRepository?: {
8
+ readonly name?: string;
9
+ } | null;
10
+ readonly headRepositoryOwner?: {
11
+ readonly login?: string;
12
+ } | null;
13
+ }
2
14
  export type Assessment = {
3
15
  readonly head: string;
4
16
  } | {
@@ -12,3 +24,6 @@ export declare function assessLocal(worktree: RunOptions): Assessment;
12
24
  * also proves HEAD is published on GitHub, so deleted branches (squash merges) need no remote ref.
13
25
  */
14
26
  export declare function assessPullRequest(branch: string, head: string, repository: string | undefined, main: RunOptions): string | undefined;
27
+ /** A complete open list protects active branches; bounded recent history only proves candidates. */
28
+ export declare function readPullSnapshot(main: RunOptions, limit: number): readonly PullRequest[] | undefined;
29
+ export declare function assessListedPulls(pulls: readonly PullRequest[] | undefined, branch: string, head: string, repository: string | undefined): string | undefined;
@@ -11,7 +11,7 @@ function parseJson(text) {
11
11
  /** Repo-local git variables, GH_REPO and GH_HOST must not redirect the lookup away from the main checkout. */
12
12
  function runGh(args, main) {
13
13
  const env = withoutVariables(main.env, [...LOCAL_ENV, 'GH_REPO', 'GH_HOST']);
14
- return run('gh', args, { cwd: main.cwd, env });
14
+ return run('gh', args, { ...main, env });
15
15
  }
16
16
  export function readRepository(main) {
17
17
  const repo = parseJson(runGh(['repo', 'view', '--json', 'nameWithOwner'], main));
@@ -37,11 +37,16 @@ export function assessLocal(worktree) {
37
37
  return { head };
38
38
  }
39
39
  const PAGE = 1000;
40
- function listPulls(branch, state, main) {
41
- const fields = 'state,headRefOid,isCrossRepository,headRepository,headRepositoryOwner';
42
- const args = ['pr', 'list', '--head', branch, '--state', state, '--limit', String(PAGE)];
40
+ function listPulls(branch, state, main, limit = PAGE) {
41
+ const fields = 'state,headRefName,headRefOid,isCrossRepository,headRepository,headRepositoryOwner';
42
+ const args = ['pr', 'list', '--state', state, '--limit', String(limit)];
43
+ if (branch !== undefined)
44
+ args.push('--head', branch);
43
45
  const listed = parseJson(runGh([...args, '--json', fields], main));
44
- return Array.isArray(listed) && listed.length < PAGE ? listed : undefined;
46
+ return Array.isArray(listed) &&
47
+ (listed.length < limit || (branch === undefined && state === 'all'))
48
+ ? listed
49
+ : undefined;
45
50
  }
46
51
  /**
47
52
  * Needs a merged or closed same-repository PR for this branch whose head is exactly HEAD. That
@@ -55,7 +60,21 @@ export function assessPullRequest(branch, head, repository, main) {
55
60
  const all = listPulls(branch, 'all', main);
56
61
  if (open === undefined || all === undefined)
57
62
  return 'cannot read PR state';
58
- const own = [...open, ...all].filter((pr) => pr.isCrossRepository === false &&
63
+ return assessListedPulls([...open, ...all], branch, head, repository);
64
+ }
65
+ /** A complete open list protects active branches; bounded recent history only proves candidates. */
66
+ export function readPullSnapshot(main, limit) {
67
+ const open = listPulls(undefined, 'open', main, limit);
68
+ const all = listPulls(undefined, 'all', main, limit);
69
+ return open === undefined || all === undefined ? undefined : [...open, ...all];
70
+ }
71
+ export function assessListedPulls(pulls, branch, head, repository) {
72
+ if (repository === undefined)
73
+ return 'cannot read repository';
74
+ if (pulls === undefined)
75
+ return 'cannot read PR state';
76
+ const own = pulls.filter((pr) => pr.headRefName === branch &&
77
+ pr.isCrossRepository === false &&
59
78
  `${pr.headRepositoryOwner?.login}/${pr.headRepository?.name}`.toLowerCase() === repository);
60
79
  if (own.some((pr) => pr.state === 'OPEN'))
61
80
  return 'open PR';
@@ -5,11 +5,24 @@ interface ReclaimEntry {
5
5
  readonly status: 'reclaimed' | 'would reclaim' | 'kept';
6
6
  readonly reason?: string;
7
7
  }
8
- export interface ReclaimReport {
8
+ export type ReclaimReport = {
9
9
  readonly dryRun: boolean;
10
10
  readonly worktrees: ReclaimEntry[];
11
+ } & ({
12
+ readonly hasMore: true;
13
+ readonly nextAfter: string;
14
+ } | {
15
+ readonly hasMore: false;
16
+ readonly nextAfter?: never;
17
+ });
18
+ export interface ReclaimOptions {
19
+ readonly prLimit?: number;
20
+ readonly maxWorktrees?: number;
21
+ readonly timeoutMs?: number;
22
+ readonly after?: string;
23
+ readonly now?: () => number;
11
24
  }
12
25
  /** Lists finished worktrees and, with `yes`, removes them with a plain (never forced) `git worktree remove`. */
13
- export declare function reclaimWorktrees(yes: boolean, runtime: RunOptions): ReclaimReport;
26
+ export declare function reclaimWorktrees(yes: boolean, runtime: RunOptions, options?: ReclaimOptions): ReclaimReport;
14
27
  export declare function formatReport(report: ReclaimReport): string;
15
28
  export {};
@@ -1,6 +1,6 @@
1
1
  import { existsSync, realpathSync } from 'node:fs';
2
2
  import { sep } from 'node:path';
3
- import { assessLocal, assessPullRequest, readRepository } from "./assess.mjs";
3
+ import { assessLocal, assessPullRequest, assessListedPulls, readPullSnapshot, readRepository, } from "./assess.mjs";
4
4
  import { parseWorktreeList } from "./list.mjs";
5
5
  import { git } from "./run.mjs";
6
6
  /** Assesses (and with `yes` removes) one worktree; undefined means it is not a candidate. */
@@ -15,46 +15,73 @@ function reclaimOne(record, context) {
15
15
  if (nests(context.registered)) {
16
16
  return keep('contains another worktree');
17
17
  }
18
- const worktree = { cwd: path, env: context.runtime.env };
18
+ const worktree = { ...context.runtime, cwd: path };
19
19
  const local = assessLocal(worktree);
20
20
  if ('reason' in local)
21
21
  return keep(local.reason);
22
- const reason = assessPullRequest(branch, local.head, context.repository, context.mainRun);
22
+ const reason = assessListedPulls(context.pulls, branch, local.head, context.repository);
23
23
  if (reason !== undefined)
24
24
  return keep(reason);
25
25
  if (!context.yes)
26
26
  return { path, branch, status: 'would reclaim' };
27
- const again = assessLocal(worktree);
28
27
  const pullAgain = assessPullRequest(branch, local.head, context.repository, context.mainRun);
28
+ const again = assessLocal(worktree);
29
29
  const listed = parseWorktreeList(git(['worktree', 'list', '--porcelain', '-z'], context.runtime));
30
30
  const same = listed.some((entry) => entry.path === path && entry.branch === branch && entry.head === local.head);
31
31
  if (nests(listed.map((entry) => entry.path)))
32
32
  return keep('contains another worktree');
33
33
  if ('reason' in again || again.head !== local.head || pullAgain !== undefined || !same)
34
34
  return keep('changed since check');
35
+ if (context.now() >= context.deadline)
36
+ return keep('scan budget exhausted');
35
37
  if (git(['worktree', 'remove', path], { ...context.mainRun, timeout: 0 }) === undefined) {
36
38
  return keep('git worktree remove refused');
37
39
  }
38
40
  return { path, branch, status: 'reclaimed' };
39
41
  }
40
42
  /** Lists finished worktrees and, with `yes`, removes them with a plain (never forced) `git worktree remove`. */
41
- export function reclaimWorktrees(yes, runtime) {
43
+ export function reclaimWorktrees(yes, runtime, options = {}) {
44
+ const prLimit = options.prLimit ?? 1000;
45
+ const maxWorktrees = options.maxWorktrees ?? 100;
46
+ const timeoutMs = options.timeoutMs ?? 30_000;
47
+ if (!Number.isSafeInteger(prLimit) ||
48
+ prLimit < 1 ||
49
+ prLimit > 10_000 ||
50
+ !Number.isSafeInteger(maxWorktrees) ||
51
+ maxWorktrees < 1 ||
52
+ !Number.isSafeInteger(timeoutMs) ||
53
+ timeoutMs < 1)
54
+ throw new Error('scan limits must be positive integers; PR limit must not exceed 10000');
55
+ const now = options.now ?? Date.now;
56
+ const deadline = now() + timeoutMs;
57
+ runtime = { ...runtime, deadline, now };
42
58
  const listing = git(['worktree', 'list', '--porcelain', '-z'], runtime);
43
59
  const self = git(['rev-parse', '--show-toplevel'], runtime)?.replace(/\n$/, '');
44
60
  const [main, ...others] = parseWorktreeList(listing);
45
61
  if (main === undefined || !self)
46
62
  throw new Error('not inside a git worktree');
47
- const mainRun = { cwd: main.path, env: runtime.env };
63
+ const mainRun = { ...runtime, cwd: main.path };
64
+ const repository = readRepository(mainRun);
48
65
  const context = {
49
66
  yes,
67
+ now,
68
+ deadline,
50
69
  runtime,
51
70
  mainRun,
52
71
  selfReal: realpathSync(self),
53
72
  registered: [main, ...others].map((record) => record.path),
54
- repository: readRepository(mainRun),
73
+ repository,
74
+ pulls: repository === undefined ? undefined : readPullSnapshot(mainRun, prLimit),
55
75
  };
56
76
  const worktrees = [];
57
- for (const record of others) {
77
+ const pending = others
78
+ .filter((record) => options.after === undefined || record.path > options.after)
79
+ .sort((a, b) => Number(a.path > b.path) - Number(a.path < b.path));
80
+ let processed = 0;
81
+ let nextAfter = options.after ?? '';
82
+ for (const record of pending) {
83
+ if (processed >= maxWorktrees || now() >= deadline)
84
+ break;
58
85
  try {
59
86
  const entry = reclaimOne(record, context);
60
87
  if (entry !== undefined)
@@ -64,17 +91,28 @@ export function reclaimWorktrees(yes, runtime) {
64
91
  const reason = `error: ${error.message}`;
65
92
  worktrees.push({ path: record.path, branch: record.branch, status: 'kept', reason });
66
93
  }
94
+ if (now() >= deadline)
95
+ break;
96
+ processed += 1;
97
+ nextAfter = record.path;
67
98
  }
68
- return { dryRun: !yes, worktrees };
99
+ const hasMore = processed < pending.length;
100
+ return hasMore
101
+ ? { dryRun: !yes, worktrees, hasMore: true, nextAfter }
102
+ : { dryRun: !yes, worktrees, hasMore: false };
69
103
  }
70
104
  function escape(text) {
71
105
  return text.replace(/\p{Cc}/gu, (char) => `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`);
72
106
  }
73
107
  export function formatReport(report) {
74
- return report.worktrees
108
+ return (report.worktrees
75
109
  .map((entry) => {
76
110
  const status = entry.status === 'kept' ? `kept: ${entry.reason}` : entry.status;
77
111
  return `${escape(entry.path)}: ${escape(status)}\n`;
78
112
  })
79
- .join('');
113
+ .join('') +
114
+ (report.hasMore ? `Scan incomplete; resume with --after ${quote(report.nextAfter)}\n` : ''));
115
+ }
116
+ function quote(value) {
117
+ return "'" + value.replaceAll("'", "'\\''") + "'";
80
118
  }
@@ -18,8 +18,9 @@ if (env.FAKE_GH_GARBAGE) {
18
18
  process.exit(0)
19
19
  }
20
20
  const state = args[args.indexOf('--state') + 1]
21
+ if (env.FAKE_GH_LOG) fs.appendFileSync(env.FAKE_GH_LOG, JSON.stringify(args) + '\\n')
21
22
  // Simulates a change that lands between the first assessment and the re-check.
22
- if (state === 'all') {
23
+ if (state === 'all' && args.includes('--head')) {
23
24
  const { execFileSync } = require('node:child_process')
24
25
  const run = (cwd, ...a) => execFileSync('git', a, { cwd, stdio: 'ignore' })
25
26
  if (env.FAKE_GH_NEST && !fs.existsSync(env.FAKE_GH_DIR + '/nested')) {
@@ -33,15 +34,19 @@ if (state === 'all') {
33
34
  run(env.FAKE_GH_ADVANCE, 'push', 'origin', 'HEAD')
34
35
  }
35
36
  }
36
- const branch = args[args.indexOf('--head') + 1]
37
- const file = env.FAKE_GH_DIR + '/' + branch.replaceAll('/', '_') + '.json'
38
- let pulls = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : []
37
+ const branch = args.includes('--head') ? args[args.indexOf('--head') + 1] : undefined
38
+ const file = env.FAKE_GH_DIR + '/' + (branch || '').replaceAll('/', '_') + '.json'
39
+ let pulls = branch === undefined
40
+ ? fs.readdirSync(env.FAKE_GH_DIR).filter(name => name.endsWith('.json')).flatMap(name => JSON.parse(fs.readFileSync(env.FAKE_GH_DIR + '/' + name, 'utf8')))
41
+ : fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : []
39
42
  if (state === 'open') pulls = pulls.filter((pr) => pr.state === 'OPEN')
40
43
  const pad = Number(env['FAKE_GH_PAD_' + state.toUpperCase()] || 0)
41
44
  for (let i = 0; i < pad; i += 1) pulls.push({ state: 'CLOSED' })
42
45
  console.log(JSON.stringify(pulls))
43
46
  // Reopen every PR after the first full answer, as if it changed before the re-check.
44
47
  if (state === 'all' && env.FAKE_GH_REOPEN && !fs.existsSync(file + '.reopened')) {
48
+ const target = branch === undefined ? fs.readdirSync(env.FAKE_GH_DIR).find(name => name.endsWith('.json')) : undefined
49
+ if (target) fs.writeFileSync(env.FAKE_GH_DIR + '/' + target, JSON.stringify(pulls.map(pr => ({ ...pr, state: 'OPEN' }))))
45
50
  fs.writeFileSync(file, JSON.stringify(pulls.map((pr) => ({ ...pr, state: 'OPEN' }))))
46
51
  fs.writeFileSync(file + '.reopened', '')
47
52
  }
@@ -56,7 +61,7 @@ export function createFixture() {
56
61
  writeFileSync(join(bin, 'gh'), FAKE_GH);
57
62
  chmodSync(join(bin, 'gh'), 0o755);
58
63
  // A git wrapper that fails any invocation containing the words in FAKE_GIT_FAIL, to reach error paths.
59
- writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase " $* " in *" $FAKE_GIT_FAIL "*) [ -n "$FAKE_GIT_FAIL" ] && exit 1;; esac\nexec '${realGit}' "$@"\n`);
64
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\n[ -z "$FAKE_GIT_LOG" ] || printf '%s\\n' "$*" >> "$FAKE_GIT_LOG"\ncase " $* " in *" $FAKE_GIT_FAIL "*) [ -n "$FAKE_GIT_FAIL" ] && exit 1;; esac\nexec '${realGit}' "$@"\n`);
60
65
  chmodSync(join(bin, 'git'), 0o755);
61
66
  const env = {
62
67
  ...process.env,
@@ -100,6 +105,7 @@ export function createFixture() {
100
105
  setPrs: (branch, prs) => {
101
106
  const tip = git(main, 'rev-parse', `refs/heads/${branch}`).trim();
102
107
  const filled = prs.map((pr) => ({
108
+ headRefName: branch,
103
109
  headRefOid: tip,
104
110
  isCrossRepository: false,
105
111
  headRepository: { name: 'Widgets' },
@@ -3,6 +3,8 @@ export interface RunOptions {
3
3
  readonly env: NodeJS.ProcessEnv;
4
4
  /** Milliseconds before a read-only call is killed; 0 for none (worktree removal). */
5
5
  readonly timeout?: number;
6
+ readonly deadline?: number;
7
+ readonly now?: () => number;
6
8
  }
7
9
  /** Runs a command without a shell; returns stdout, or undefined when it fails to start or exits non-zero. */
8
10
  export declare function run(file: string, args: readonly string[], options: RunOptions): string | undefined;
@@ -1,6 +1,9 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  /** Runs a command without a shell; returns stdout, or undefined when it fails to start or exits non-zero. */
3
3
  export function run(file, args, options) {
4
+ const remaining = options.deadline === undefined ? Infinity : options.deadline - (options.now ?? Date.now)();
5
+ if (remaining <= 0 && options.timeout !== 0)
6
+ return undefined;
4
7
  try {
5
8
  return execFileSync(file, args, {
6
9
  cwd: options.cwd,
@@ -8,7 +11,7 @@ export function run(file, args, options) {
8
11
  encoding: 'utf8',
9
12
  maxBuffer: 64 * 1024 * 1024,
10
13
  stdio: ['ignore', 'pipe', 'ignore'],
11
- timeout: options.timeout ?? 120_000,
14
+ timeout: options.timeout === 0 ? 0 : Math.max(1, Math.min(options.timeout ?? 120_000, remaining)),
12
15
  });
13
16
  }
14
17
  catch {
@@ -20,7 +20,7 @@ export function stripNonShellHeredocBodies(command) {
20
20
  }
21
21
  // The hook does not pair each operator with its body, so a line with a shell-read heredoc
22
22
  // inspects every body on it.
23
- const isShellScriptHeredoc = lineFeedsShellHeredoc(line);
23
+ const isShellScriptHeredoc = lineFeedsShellHeredoc(line) || lineFeedsShellHeredoc(logicalLine(lines, index));
24
24
  for (const spec of specs) {
25
25
  const bodyLines = [];
26
26
  index += 1;
@@ -79,6 +79,14 @@ function heredocBodySubstitutions(body) {
79
79
  }
80
80
  return substitutions;
81
81
  }
82
+ // A line ending in an odd run of backslashes continues onto the next, so the command that owns a
83
+ // heredoc operator may start on earlier lines (`bash \\\n-s <<'EOF'`).
84
+ function logicalLine(lines, index) {
85
+ let start = index;
86
+ while (start > 0 && /(?:^|[^\\])(?:\\\\)*\\$/.test(lines[start - 1]))
87
+ start -= 1;
88
+ return lines.slice(start, index + 1).join('\n');
89
+ }
82
90
  function heredocLineDelimiter(line, spec) {
83
91
  return spec.stripLeadingTabs ? line.replace(/^\t+/, '') : line;
84
92
  }
@@ -33,10 +33,8 @@ export async function deriveRuleAttempts(env, { priorCounts, rules, runAttempt,
33
33
  const priorReruns = new Map();
34
34
  let replayCount = rules.length;
35
35
  for (let attempt = 1; attempt < runAttempt; attempt += 1) {
36
- // An attempt that created no jobs has no failure signal; the shared attempt already discounts it.
37
- if (priorCounts[attempt - 1] === 0)
38
- continue;
39
- const jobs = await fetchJobs(env, attempt);
36
+ // An attempt that created no jobs still counts when a rule matches its run-level evidence.
37
+ const jobs = priorCounts[attempt - 1] === 0 ? [] : await fetchJobs(env, attempt);
40
38
  const replayRules = rules.slice(0, replayCount);
41
39
  const context = {
42
40
  ...buildJobsContext(env, jobs, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.64.0",
3
+ "version": "0.65.1",
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": {
@@ -482,7 +482,7 @@
482
482
  "yaml": "2.9.1"
483
483
  },
484
484
  "devDependencies": {
485
- "@ast-grep/cli": "0.50.0",
485
+ "@ast-grep/cli": "0.51.0",
486
486
  "@modelcontextprotocol/sdk": "1.32.1",
487
487
  "@playwright/test": "1.64.1",
488
488
  "@types/pg": "8.23.1",
@@ -62,9 +62,12 @@ report the blocker.
62
62
 
63
63
  ## Journaling policy
64
64
 
65
- 1. Capture consequential observations before filing an issue: failed or recovered checks, denied or
66
- approved permissions, repeated fixes, scope changes, first-party tool behavior, and architectural
67
- findings. Record useful resolved outcomes as well as unresolved gaps. Include bounded evidence,
65
+ 1. Friction is the primary thing to journal: failed or recovered checks, denied or approved
66
+ permissions, scope changes, repeated fixes, and reusable tool gaps. Capture it before filing an
67
+ issue. Broader consequential observations, such as first-party tool behavior and architectural
68
+ findings, are allowed but secondary: add them after the friction is recorded, never in place of
69
+ it. A consumer wrapper may add repository-specific triggers but does not narrow this list.
70
+ Record useful resolved outcomes as well as unresolved gaps. Include bounded evidence,
68
71
  affected areas, an explicit disposition, and an existing tracking reference when present.
69
72
  Journal meaningful skips or bypasses of applicable configured workflows before completion, with
70
73
  the owning workflow or command-catalog entrypoint, reason, and observed result/action.
@@ -4,7 +4,7 @@
4
4
  {
5
5
  "name": "agent-workflow",
6
6
  "plugin": "vouchington-workflow",
7
- "pluginVersion": "0.14.0",
7
+ "pluginVersion": "0.14.1",
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.0",
27
+ "pluginVersion": "0.14.1",
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.0",
39
+ "pluginVersion": "0.14.1",
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.0",
53
+ "pluginVersion": "0.14.1",
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.0",
59
+ "pluginVersion": "0.14.1",
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.0",
66
+ "pluginVersion": "0.14.1",
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.0",
72
+ "pluginVersion": "0.14.1",
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.0",
85
+ "pluginVersion": "0.14.1",
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.0",
91
+ "pluginVersion": "0.14.1",
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.0",
98
+ "pluginVersion": "0.14.1",
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.0",
104
+ "pluginVersion": "0.14.1",
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.0",
136
+ "pluginVersion": "0.14.1",
137
137
  "path": "pr-description/SKILL.md"
138
138
  },
139
139
  {
140
140
  "name": "retrospective",
141
141
  "plugin": "vouchington-workflow",
142
- "pluginVersion": "0.14.0",
142
+ "pluginVersion": "0.14.1",
143
143
  "path": "retrospective/SKILL.md"
144
144
  },
145
145
  {
146
146
  "name": "retrospective-distill",
147
147
  "plugin": "vouchington-workflow",
148
- "pluginVersion": "0.14.0",
148
+ "pluginVersion": "0.14.1",
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.0",
155
+ "pluginVersion": "0.14.1",
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.0",
162
+ "pluginVersion": "0.14.1",
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.0",
169
+ "pluginVersion": "0.14.1",
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.0",
176
+ "pluginVersion": "0.14.1",
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.0",
182
+ "pluginVersion": "0.14.1",
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.0",
209
+ "pluginVersion": "0.14.1",
210
210
  "path": "triage-prs/SKILL.md",
211
211
  "prerequisites": [
212
212
  "pr-description",
@@ -108,10 +108,9 @@ difference is a conflicting payload and stays quarantined.
108
108
  alone makes a stale checkpoint-only, journal-only, or zero-entry session eligible, so a
109
109
  retrospective-only gate cannot strand it. Everything else is not yet eligible; skip it with a
110
110
  reason.
111
- - Export unfiltered rather than with `inactiveForHours`: a zero-entry session has no last entry and
112
- never matches that filter, which would hide the feedback gaps this pass exists to sweep up.
113
- Derive age from the cutoffs above; they supply the delay for outboxes in removed worktrees or on
114
- other machines.
111
+ - Export unfiltered; the retrospective and session cutoffs above decide eligibility, and too-new
112
+ sessions must still appear as skipped with a reason. Derive age from the cutoffs above; they supply the delay for outboxes in
113
+ removed worktrees or on other machines.
115
114
  - Journal-only and zero-entry evidence get full issue-filing rights, subject to the same duplicate,
116
115
  current-state, and dependency checks as retrospective evidence, plus redaction: never quote a
117
116
  journal entry's raw command string or stderr in an issue body, since a journal entry can carry