vouchington-tooling 0.69.0 → 0.71.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.
package/README.md CHANGED
@@ -247,6 +247,21 @@ and `git_worktree_main_path` fails when git reports no worktree. Its
247
247
  `scripts/worktree/git-index-lock.sh` removes only a 0-byte `index.lock`. A non-empty lock is left
248
248
  in place.
249
249
 
250
+ `scripts/worktree/operation-lock.sh` holds a host-wide lock across a region of the sourcing script,
251
+ for code that shares shell state with its surroundings and so cannot run under
252
+ `vouchington with-host-lock`, which wraps one command and forbids nesting. The lock is a symlink
253
+ named `lock` whose target is an owner token; a file with that name holds the owner PID. Pass the
254
+ absolute lock root to each call or set `WORKTREE_OPERATION_LOCK_ROOT`; there is no default.
255
+ `worktree_operation_lock_acquire [root]` takes the lock or prints the holder's PID (or says the
256
+ lock is stale) and returns 1 without waiting. `worktree_operation_lock_release` is a no-op unless
257
+ this shell holds the lock, so `trap worktree_operation_lock_release EXIT` is safe.
258
+ `worktree_operation_lock_clear_stale [root]` removes a lock whose owner PID is dead and sets
259
+ `WORKTREE_OPERATION_LOCK_CLEANUP_STATUS` to `missing`, `removed`, `active`, `invalid` or `busy` (another clearer is running, or the lock
260
+ changed during cleanup); it returns 2 for a missing or relative root, 0 for `missing` and
261
+ `removed`, and 1 otherwise. The root must be owned by the calling user and is meant for one user's
262
+ processes; run `clear_stale` only as operator recovery while no operation is starting, because
263
+ releasing and clearing are not serialized against each other.
264
+
250
265
  `scripts/worktree/reset-worktree.sh --base-ref <ref>` checks out a new `reset-<hex>` branch and
251
266
  hard-resets it to `<ref>`. A `remote/branch` ref is fetched first; `refs/...` and a local ref are
252
267
  not. It refuses uncommitted or untracked changes unless `--force` is set, refuses a non-empty
@@ -413,15 +428,29 @@ exact versioned `deb`/`apk`/`rpm` purls, a `Not exploitable: <reason>. Cleanup:
413
428
  statement (the URL must start with `--cleanup-url-prefix` when given, else any GitHub issue) and an
414
429
  `expired_at` UTC date after today and at most `--max-expiry-days` (default 30) away.
415
430
 
416
- `vouchington docker-image-mirror [--mirror <host>]` reports every Docker Hub image reference in
431
+ `vouchington docker-image-mirror [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]` reports every Docker Hub image reference in
417
432
  tracked workflows, composite actions and Dockerfiles: `docker run|pull|create`, `container:`,
418
433
  `services:`, `docker://` uses, `docker/setup-buildx-action` drivers, `FROM`, `COPY --from` and
419
434
  `# syntax=`. An image is accepted when it names a registry host; `--mirror` (default
420
435
  `mirror.gcr.io`) is the host the message tells you to use.
421
436
 
437
+ `--allow-registry <prefix>` (repeatable) turns the check into an allowlist: every image reference
438
+ above, including `FROM`, `COPY --from` and `# syntax=`, must start with one of the prefixes, so
439
+ `mirror.gcr.io` and Docker Hub are rejected unless listed. `--require-digest` additionally requires
440
+ `@sha256:` followed by 64 lowercase hex characters. Earlier stage aliases, numeric `COPY --from`
441
+ indexes and `scratch` stay exempt. A reference that expands a variable (`${{ }}`, `$VAR`) is
442
+ checked by its literal text before the first variable: it passes only when that text already starts
443
+ with an allowed prefix, so a wholly dynamic reference is rejected, and a variable-expanded digest
444
+ never satisfies `--require-digest`. Without `--allow-registry`, behavior is unchanged (only Docker
445
+ Hub is rejected). Violations name the file, the image and the allowed prefixes or the digest requirement:
446
+
447
+ ```bash
448
+ vouchington docker-image-mirror --allow-registry ghcr.io/vouchington/dependency- --require-digest
449
+ ```
450
+
422
451
  The checks are exported as `checkTrivyPolicy(root, trackedFiles, options)` from
423
452
  `vouchington-tooling/trivy-policy` (plus the command parsers and `validateIgnoreRegistry`) and
424
- `checkDockerImageMirrors(root, trackedFiles, { mirror })` from `vouchington-tooling/docker-image-mirror`;
453
+ `checkDockerImageMirrors(root, trackedFiles, { mirror, allowRegistries, requireDigest })` from `vouchington-tooling/docker-image-mirror`;
425
454
  both return violation strings.
426
455
 
427
456
  ## Running the Storybook browser tests
@@ -1339,6 +1368,10 @@ const { result, error } = await withPostgresQueryFailureForTest(
1339
1368
  blockedMarkers, observer?)`. The waiters poll `pg_stat_activity` and `pg_blocking_pids`; the
1340
1369
  observer is `'write'`, `'advisoryLock'` or a reserved executor.
1341
1370
 
1371
+ - `runPoolObservationExclusively(operation)` is the queue the two helpers above share. Wrap your own
1372
+ fault injection or pool observation in it so it never overlaps theirs on the same pool; it
1373
+ rejects when nested.
1374
+
1342
1375
  The package's own tests start a throwaway cluster with `initdb`/`pg_ctl` found through
1343
1376
  `POSTGRES_BIN_DIR`, `PATH` or a standard install location. They skip where no server can run and
1344
1377
  fail under `CI`.
@@ -16,20 +16,34 @@ export async function runDockerImageMirrorCommand(args, dependencies = {}) {
16
16
  values = parseArgs({
17
17
  args: [...args],
18
18
  allowPositionals: false,
19
- options: { root: { type: 'string' }, mirror: { type: 'string' } },
19
+ options: {
20
+ root: { type: 'string' },
21
+ mirror: { type: 'string' },
22
+ 'allow-registry': { type: 'string', multiple: true },
23
+ 'require-digest': { type: 'boolean' },
24
+ },
20
25
  }).values;
21
26
  }
22
27
  catch (error) {
23
28
  stderr.write(`vouchington: ${error.message}\n${commandUsage('docker-image-mirror')}`);
24
29
  return 2;
25
30
  }
31
+ const allowRegistries = values['allow-registry'];
32
+ if (allowRegistries?.includes('')) {
33
+ stderr.write(`vouchington: --allow-registry needs a non-empty prefix\n${commandUsage('docker-image-mirror')}`);
34
+ return 2;
35
+ }
26
36
  const root = resolve(values.root ?? process.cwd());
27
37
  const context = await (dependencies.buildContext ?? buildSharedContext)(root);
28
38
  if (!context.isInsideGitRepo) {
29
39
  stderr.write(`vouchington: ${root} is not inside a git repository\n`);
30
40
  return 1;
31
41
  }
32
- const errors = checkDockerImageMirrors(context.repoRoot, context.trackedFiles, values);
42
+ const errors = checkDockerImageMirrors(context.repoRoot, context.trackedFiles, {
43
+ mirror: values.mirror,
44
+ allowRegistries,
45
+ requireDigest: values['require-digest'],
46
+ });
33
47
  if (errors.length === 0) {
34
48
  stdout.write('Docker image mirror policy: ok\n');
35
49
  return 0;
@@ -1,2 +1,2 @@
1
1
  export declare const POLICY_COMMANDS = " coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n trivy-policy Check tracked Trivy workflow scans and the exception registry\n docker-image-mirror Require tracked Docker images to come from a Docker Hub mirror\n";
2
- export declare const POLICY_USAGE = "\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>]\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use.\n\n";
2
+ export declare const POLICY_USAGE = "\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use. --allow-registry (repeatable) instead requires every image,\n including FROM and COPY --from, to start with one of the prefixes; a reference that expands a\n variable passes only when its literal text before the variable starts with a prefix. --require-digest\n requires @sha256: plus 64 lowercase hex characters. Stage aliases and scratch stay exempt.\n\n";
@@ -16,10 +16,13 @@ trivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NA
16
16
  packages, a "Not exploitable: ... Cleanup: <issue URL>" statement (URL must start with
17
17
  --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).
18
18
 
19
- docker-image-mirror [--root <dir>] [--mirror <host>]
19
+ docker-image-mirror [--root <dir>] [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]
20
20
  Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):
21
21
  run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,
22
22
  COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is
23
- the host the message tells you to use.
23
+ the host the message tells you to use. --allow-registry (repeatable) instead requires every image,
24
+ including FROM and COPY --from, to start with one of the prefixes; a reference that expands a
25
+ variable passes only when its literal text before the variable starts with a prefix. --require-digest
26
+ requires @sha256: plus 64 lowercase hex characters. Stage aliases and scratch stay exempt.
24
27
 
25
28
  `;
@@ -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 coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n trivy-policy Check tracked Trivy workflow scans and the exception registry\n docker-image-mirror Require tracked Docker images to come from a Docker Hub mirror\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>]\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use.\n\nstorybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]\n Spawns <cmd> (default pnpm) in its own process group with <argv> (default \"exec vitest run\n --project <name>\") plus the coverage args (default --coverage) and supervises it: a Vite optimizer\n cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget\n watchdogs. --result-file paths are removed before each attempt and --completion-file is the one\n whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,\n _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE\n (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
1
+ export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n sandbox-command-audit Audit agent transcripts for sandbox escalations and denials\n cloc Count tracked lines of code by category and service with scc\n coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n trivy-policy Check tracked Trivy workflow scans and the exception registry\n docker-image-mirror Require tracked Docker images to come from a Docker Hub mirror\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use. --allow-registry (repeatable) instead requires every image,\n including FROM and COPY --from, to start with one of the prefixes; a reference that expands a\n variable passes only when its literal text before the variable starts with a prefix. --require-digest\n requires @sha256: plus 64 lowercase hex characters. Stage aliases and scratch stay exempt.\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,4 +1,5 @@
1
- export declare const DEFAULT_MIRROR = "mirror.gcr.io";
1
+ import { type ImagePolicy } from './policy.mts';
2
+ export { DEFAULT_MIRROR } from './policy.mts';
2
3
  type Step = {
3
4
  name?: string;
4
5
  run?: string;
@@ -20,6 +21,5 @@ export type Document = {
20
21
  image?: string;
21
22
  };
22
23
  };
23
- export declare function workflowImageViolations(path: string, document: Document, mirror?: string): string[];
24
- export declare function dockerfileViolations(path: string, source: string): string[];
25
- export {};
24
+ export declare function workflowImageViolations(path: string, document: Document, mirror?: string, policy?: ImagePolicy): string[];
25
+ export declare function dockerfileViolations(path: string, source: string, policy?: ImagePolicy, mirror?: string): string[];
@@ -1,28 +1,10 @@
1
1
  import { withoutShellComment } from "../trivy-policy/shell.mjs";
2
+ import { DEFAULT_MIRROR, imageReasons, policyActive } from "./policy.mjs";
3
+ export { DEFAULT_MIRROR } from "./policy.mjs";
2
4
  // Unauthenticated Docker Hub pulls from hosted runners hit its rate limit. A pull-through mirror
3
5
  // serves the same pinned digest without credentials, so every image must name a non-Hub registry.
4
6
  // Shell scripts are not workflow bodies and are outside this scan.
5
- export const DEFAULT_MIRROR = 'mirror.gcr.io';
6
- const HUB_HOSTS = ['docker.io', 'index.docker.io', 'registry-1.docker.io'];
7
7
  const VALUE_FLAGS = new Set('-e --env -p --publish -v --volume --name --network --net --add-host --entrypoint -u --user -w --workdir --tmpfs --platform --mount --label -l --env-file --health-cmd --health-interval --health-retries --health-timeout --health-start-period -m --memory --cpus --restart --cap-add --cap-drop --shm-size --log-driver --ulimit -h --hostname --pull --pids-limit --group-add --device --dns --ipc --pid --cgroupns --stop-signal --stop-timeout --gpus --cidfile --link --volumes-from --cpuset-cpus --cpu-shares --cgroup-parent --dns-search --dns-option --ip --ip6 --mac-address --blkio-weight --memory-swap --memory-reservation --kernel-memory --oom-score-adj --runtime --security-opt --sysctl --userns --uts --annotation --network-alias --expose --label-file --isolation --log-opt --storage-opt --cpu-quota --cpu-period --domainname --detach-keys -a --attach --cpuset-mems --device-cgroup-rule'.split(' '));
8
- function isHubImage(reference) {
9
- const image = reference.replace(/^["']|["'),;]+$/gu, '');
10
- if (image === '' || image === 'scratch')
11
- return false;
12
- // Only the part before a variable is knowable; a wholly dynamic reference or registry is not.
13
- const dynamicAt = image.search(/\$|\{\{/u);
14
- const known = dynamicAt === -1 ? image : image.slice(0, dynamicAt);
15
- if (known === '')
16
- return false;
17
- if (dynamicAt !== -1 && !known.includes('/') && image.slice(dynamicAt).includes('/'))
18
- return false;
19
- const [first = ''] = known.split('/');
20
- if (!known.includes('/'))
21
- return true;
22
- if (HUB_HOSTS.includes(first))
23
- return true;
24
- return !(first.includes('.') || first.includes(':') || first === 'localhost');
25
- }
26
8
  const GLOBAL_VALUE_OPTIONS = new Set('--config --context -c --host -H --log-level -l --tlscacert --tlscert --tlskey'.split(' '));
27
9
  function dockerCommandImages(script) {
28
10
  const logical = withoutShellComment(script).replace(/\\\r?\n/gu, ' ');
@@ -60,7 +42,7 @@ function stepImages(step) {
60
42
  ...(step.uses?.startsWith('docker://') ? [step.uses.slice('docker://'.length)] : []),
61
43
  ];
62
44
  }
63
- export function workflowImageViolations(path, document, mirror = DEFAULT_MIRROR) {
45
+ export function workflowImageViolations(path, document, mirror = DEFAULT_MIRROR, policy = {}) {
64
46
  const found = [];
65
47
  for (const [jobId, job] of Object.entries(document.jobs ?? {})) {
66
48
  const container = typeof job.container === 'string' ? job.container : job.container?.image;
@@ -81,26 +63,33 @@ export function workflowImageViolations(path, document, mirror = DEFAULT_MIRROR)
81
63
  for (const step of document.runs?.steps ?? []) {
82
64
  found.push(...stepImages(step).map((image) => ['composite', image]));
83
65
  }
84
- return found.flatMap(([where, image]) => isHubImage(image) ? [`${path}#${where}: ${image} must come from ${mirror}/`] : []);
66
+ return found.flatMap(([where, image]) => {
67
+ const reasons = imageReasons(image, mirror, policy);
68
+ return reasons.length > 0 ? [`${path}#${where}: ${image} ${reasons.join('; ')}`] : [];
69
+ });
85
70
  }
86
- export function dockerfileViolations(path, source) {
71
+ export function dockerfileViolations(path, source, policy = {}, mirror = DEFAULT_MIRROR) {
87
72
  const stages = new Set();
88
73
  const violations = [];
74
+ const check = (label, image) => {
75
+ const reasons = imageReasons(image, mirror, policy);
76
+ if (reasons.length === 0)
77
+ return;
78
+ violations.push(`${path}: ${label}${policyActive(policy) ? ` ${reasons.join('; ')}` : ''}`);
79
+ };
89
80
  const syntax = /^#\s*syntax\s*=\s*(\S+)/imu.exec(source)?.[1];
90
- if (syntax && isHubImage(syntax))
91
- violations.push(`${path}: # syntax=${syntax}`);
81
+ if (syntax)
82
+ check(`# syntax=${syntax}`, syntax);
92
83
  for (const line of source.replace(/\\\r?\n/gu, ' ').split('\n')) {
93
84
  const copyFrom = /^\s*COPY\s+(?:--\S+\s+)*--from=(\S+)/iu.exec(line)?.[1];
94
85
  if (copyFrom && !/^\d+$/u.test(copyFrom) && !stages.has(copyFrom.toLowerCase())) {
95
- if (isHubImage(copyFrom))
96
- violations.push(`${path}: COPY --from=${copyFrom}`);
86
+ check(`COPY --from=${copyFrom}`, copyFrom);
97
87
  }
98
88
  const from = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/iu.exec(line);
99
89
  if (!from)
100
90
  continue;
101
- if (!stages.has(from[1].toLowerCase()) && isHubImage(from[1])) {
102
- violations.push(`${path}: FROM ${from[1]}`);
103
- }
91
+ if (!stages.has(from[1].toLowerCase()))
92
+ check(`FROM ${from[1]}`, from[1]);
104
93
  if (from[2])
105
94
  stages.add(from[2].toLowerCase());
106
95
  }
@@ -1,11 +1,14 @@
1
+ import { type ImagePolicy } from './policy.mts';
1
2
  export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from './images.mts';
2
3
  export type { Document } from './images.mts';
3
- export interface DockerImageMirrorOptions {
4
+ export type { ImagePolicy } from './policy.mts';
5
+ export interface DockerImageMirrorOptions extends ImagePolicy {
4
6
  /**
5
- * Registry host named in violation messages as the place to pull from. Any registry other than
6
- * Docker Hub passes; this value does not restrict them. Default `mirror.gcr.io`.
7
+ * Registry host named in violation messages as the place to pull from. Without
8
+ * `allowRegistries`, any registry other than Docker Hub passes; this value does not restrict
9
+ * them. Default `mirror.gcr.io`.
7
10
  */
8
- readonly mirror?: string;
11
+ readonly mirror?: string | undefined;
9
12
  }
10
13
  export declare function isDockerfilePath(path: string): boolean;
11
14
  /**
@@ -1,7 +1,8 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parse } from 'yaml';
4
- import { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations, } from "./images.mjs";
4
+ import { dockerfileViolations, workflowImageViolations } from "./images.mjs";
5
+ import { DEFAULT_MIRROR } from "./policy.mjs";
5
6
  export { DEFAULT_MIRROR, dockerfileViolations, workflowImageViolations } from "./images.mjs";
6
7
  function parseDocument(path, source) {
7
8
  try {
@@ -21,6 +22,10 @@ export function isDockerfilePath(path) {
21
22
  */
22
23
  export function checkDockerImageMirrors(root, trackedFiles, options = {}) {
23
24
  const mirror = options.mirror ?? DEFAULT_MIRROR;
25
+ const policy = {
26
+ allowRegistries: options.allowRegistries,
27
+ requireDigest: options.requireDigest,
28
+ };
24
29
  const errors = [];
25
30
  for (const path of trackedFiles) {
26
31
  const yaml = /^\.github\/workflows\/[^/]+\.ya?ml$/u.test(path) ||
@@ -32,8 +37,8 @@ export function checkDockerImageMirrors(root, trackedFiles, options = {}) {
32
37
  continue;
33
38
  const source = readFileSync(join(root, path), 'utf8');
34
39
  errors.push(...(yaml
35
- ? workflowImageViolations(path, parseDocument(path, source), mirror)
36
- : dockerfileViolations(path, source)));
40
+ ? workflowImageViolations(path, parseDocument(path, source), mirror, policy)
41
+ : dockerfileViolations(path, source, policy, mirror)));
37
42
  }
38
43
  return errors;
39
44
  }
@@ -0,0 +1,10 @@
1
+ export declare const DEFAULT_MIRROR = "mirror.gcr.io";
2
+ export interface ImagePolicy {
3
+ /** Prefixes every image reference must start with. Empty or omitted keeps the Docker Hub check. */
4
+ readonly allowRegistries?: readonly string[] | undefined;
5
+ /** Require `@sha256:` followed by 64 lowercase hex characters. */
6
+ readonly requireDigest?: boolean | undefined;
7
+ }
8
+ export declare function policyActive(policy: ImagePolicy): boolean;
9
+ /** Reasons (empty when acceptable) that an image reference breaks the policy. */
10
+ export declare function imageReasons(reference: string, mirror: string, policy?: ImagePolicy): string[];
@@ -0,0 +1,53 @@
1
+ // Image policy shared by workflow and Dockerfile scans. Without `allowRegistries`, only Docker Hub
2
+ // is rejected. With it, every reference must start with one of the prefixes. A reference that
3
+ // expands a variable (`${{ }}`, `$VAR`) is judged by the text before the first variable, so it
4
+ // passes only when that literal text already starts with an allowed prefix; a wholly dynamic
5
+ // reference is rejected. `requireDigest` needs a literal `@sha256:<64 lowercase hex>` suffix, so a
6
+ // variable-expanded digest is rejected too.
7
+ export const DEFAULT_MIRROR = 'mirror.gcr.io';
8
+ const HUB_HOSTS = ['docker.io', 'index.docker.io', 'registry-1.docker.io'];
9
+ const DIGEST = /@sha256:[0-9a-f]{64}$/u;
10
+ export function policyActive(policy) {
11
+ return (policy.allowRegistries?.length ?? 0) > 0 || policy.requireDigest === true;
12
+ }
13
+ function cleanImage(reference) {
14
+ return reference.replace(/^["']|["'),;]+$/gu, '');
15
+ }
16
+ function knownPrefix(image) {
17
+ const dynamicAt = image.search(/\$|\{\{/u);
18
+ return dynamicAt === -1 ? image : image.slice(0, dynamicAt);
19
+ }
20
+ function isHubImage(image) {
21
+ // Only the part before a variable is knowable; a wholly dynamic reference or registry is not.
22
+ const known = knownPrefix(image);
23
+ if (known === '')
24
+ return false;
25
+ if (known !== image && !known.includes('/') && image.slice(known.length).includes('/')) {
26
+ return false;
27
+ }
28
+ const [first = ''] = known.split('/');
29
+ if (!known.includes('/'))
30
+ return true;
31
+ if (HUB_HOSTS.includes(first))
32
+ return true;
33
+ return !(first.includes('.') || first.includes(':') || first === 'localhost');
34
+ }
35
+ /** Reasons (empty when acceptable) that an image reference breaks the policy. */
36
+ export function imageReasons(reference, mirror, policy = {}) {
37
+ const image = cleanImage(reference);
38
+ if (image === '' || image === 'scratch')
39
+ return [];
40
+ const allowed = policy.allowRegistries ?? [];
41
+ const reasons = [];
42
+ if (allowed.length === 0) {
43
+ if (isHubImage(image))
44
+ reasons.push(`must come from ${mirror}/`);
45
+ }
46
+ else if (!allowed.some((prefix) => knownPrefix(image).startsWith(prefix))) {
47
+ reasons.push(`must start with ${allowed.map((prefix) => `"${prefix}"`).join(' or ')}`);
48
+ }
49
+ if (policy.requireDigest === true && !DIGEST.test(image)) {
50
+ reasons.push('must be pinned with @sha256:<64 lowercase hex characters>');
51
+ }
52
+ return reasons;
53
+ }
@@ -1,5 +1,14 @@
1
1
  export { withPostgresPoolQueryFailureForTest } from './pool-query-failure.mts';
2
2
  export { withPostgresQueryFailureForTest } from './query-failure.mts';
3
+ /**
4
+ * Runs `operation` while holding the package-wide queue that serializes `pg.Pool` instrumentation.
5
+ * `withPostgresQueryFailureForTest` and `withPostgresPoolQueryFailureForTest` already use it, so
6
+ * their scopes never wrap the same pool at once. Wrap your own fault injection or lock observation
7
+ * in it when it patches or watches a pool and may overlap those helpers. Callers wait their turn in
8
+ * arrival order; the next one starts when `operation` settles, even if it rejects. Calling it from
9
+ * inside `operation` (nesting) rejects instead of deadlocking.
10
+ */
11
+ export { runPoolObservationExclusively } from './observation-queue.mts';
3
12
  export { createPostgresLockObservers, type PostgresLockObservers } from './lock-observers.mts';
4
13
  export { getTestPostgresBackendProcessId } from './lock-wait.mts';
5
14
  export type { FaultCommand, LockObserverConfig, LockWaiterDiagnostic, ObserverPool, PollOptions, PostgresFaultOptions, PostgresFaultResult, QueryExecutor, } from './fault-types.mts';
@@ -1,4 +1,13 @@
1
1
  export { withPostgresPoolQueryFailureForTest } from "./pool-query-failure.mjs";
2
2
  export { withPostgresQueryFailureForTest } from "./query-failure.mjs";
3
+ /**
4
+ * Runs `operation` while holding the package-wide queue that serializes `pg.Pool` instrumentation.
5
+ * `withPostgresQueryFailureForTest` and `withPostgresPoolQueryFailureForTest` already use it, so
6
+ * their scopes never wrap the same pool at once. Wrap your own fault injection or lock observation
7
+ * in it when it patches or watches a pool and may overlap those helpers. Callers wait their turn in
8
+ * arrival order; the next one starts when `operation` settles, even if it rejects. Calling it from
9
+ * inside `operation` (nesting) rejects instead of deadlocking.
10
+ */
11
+ export { runPoolObservationExclusively } from "./observation-queue.mjs";
3
12
  export { createPostgresLockObservers } from "./lock-observers.mjs";
4
13
  export { getTestPostgresBackendProcessId } from "./lock-wait.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.69.0",
3
+ "version": "0.71.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env bash
2
+ # Source this file for a host-wide operation lock held by the sourcing shell.
3
+ #
4
+ # The lock is a symlink named `lock` under a root directory. Its target is an owner token, and a
5
+ # file with that token's name inside the root holds the owner PID. Creating the symlink is atomic,
6
+ # so exactly one process holds the lock. A holder whose PID is gone is stale and can be cleared.
7
+ #
8
+ # Unlike with-host-lock.sh, which wraps one command, these functions protect a region of a
9
+ # sourcing script that shares shell state with the code around it.
10
+ #
11
+ # The root is the first argument, or WORKTREE_OPERATION_LOCK_ROOT. There is no default.
12
+ #
13
+ # Functions:
14
+ # worktree_operation_lock_acquire [root] - take the lock, or print why not and return 1
15
+ # worktree_operation_lock_release - release a lock this shell holds; no-op otherwise
16
+ # worktree_operation_lock_clear_stale [root] - remove a lock whose owner PID is dead
17
+ #
18
+ # Variables set:
19
+ # WORKTREE_OPERATION_LOCK_TOKEN owner token while the lock is held
20
+ # WORKTREE_OPERATION_LOCK_HELD_ROOT root of the lock this shell holds
21
+ # WORKTREE_OPERATION_LOCK_CLEANUP_STATUS after clear_stale: missing, removed, active, invalid or busy
22
+ #
23
+ # Release with a trap, for example: `trap worktree_operation_lock_release EXIT`.
24
+
25
+ _worktree_operation_lock_resolve_root() {
26
+ local root=${1:-${WORKTREE_OPERATION_LOCK_ROOT:-}}
27
+ if [ -z "$root" ]; then
28
+ echo "Error: worktree operation lock root is not set (pass it or set WORKTREE_OPERATION_LOCK_ROOT)." >&2
29
+ return 1
30
+ fi
31
+ case "$root" in
32
+ /*) ;;
33
+ *)
34
+ echo "Error: worktree operation lock root must be an absolute path: $root" >&2
35
+ return 1
36
+ ;;
37
+ esac
38
+ printf '%s' "$root"
39
+ }
40
+
41
+ _worktree_operation_lock_pid_is_live() {
42
+ local error
43
+ [[ "$1" =~ ^[0-9]+$ ]] || return 1
44
+ error=$(export LC_ALL=C; kill -0 "$1" 2>&1) && return 0
45
+ # A live process owned by another user answers "not permitted".
46
+ case "$error" in
47
+ *[Oo]peration*not*permitted* | *[Pp]ermission*denied*) return 0 ;;
48
+ esac
49
+ return 1
50
+ }
51
+
52
+ # Set WORKTREE_OPERATION_LOCK_SELF_PID to the PID of the running (sub)shell. $$ names the
53
+ # top-level shell, and Bash 3.2 has no BASHPID, so a child shell is asked for its parent. This
54
+ # cannot be a command substitution, which would report its own subshell.
55
+ _worktree_operation_lock_set_self_pid() {
56
+ if [ -n "${BASHPID:-}" ]; then
57
+ WORKTREE_OPERATION_LOCK_SELF_PID=$BASHPID
58
+ else
59
+ WORKTREE_OPERATION_LOCK_SELF_PID=$(exec sh -c 'printf %s "$PPID"')
60
+ fi
61
+ }
62
+
63
+ worktree_operation_lock_acquire() {
64
+ local lock_root lock_path token owner_path held_owner_path held_pid held_token self_pid
65
+ _worktree_operation_lock_set_self_pid
66
+ self_pid=$WORKTREE_OPERATION_LOCK_SELF_PID
67
+ if [ -n "${WORKTREE_OPERATION_LOCK_TOKEN:-}" ]; then
68
+ echo "Error: this shell already holds a worktree operation lock: ${WORKTREE_OPERATION_LOCK_HELD_ROOT:-}" >&2
69
+ return 1
70
+ fi
71
+ lock_root=$(_worktree_operation_lock_resolve_root "${1:-}") || return 1
72
+ lock_path="$lock_root/lock"
73
+ token="owner.$self_pid.$RANDOM$RANDOM"
74
+ owner_path="$lock_root/$token"
75
+
76
+ mkdir -p "$lock_root" || return 1
77
+ # Owner files are PID records, so the root must be private to one user: another user's
78
+ # process could not be probed or trusted, and a shared root would let it delete live locks.
79
+ if [ ! -O "$lock_root" ]; then
80
+ echo "Error: worktree operation lock root is not owned by this user: $lock_root" >&2
81
+ return 1
82
+ fi
83
+ if ! printf '%s\n' "$self_pid" >"$owner_path"; then
84
+ rm -f "$owner_path"
85
+ echo "Error: cannot record the worktree operation lock owner: $owner_path" >&2
86
+ return 1
87
+ fi
88
+
89
+ if [ -e "$lock_path" ] && [ ! -L "$lock_path" ]; then
90
+ rm -f "$owner_path"
91
+ echo "Error: worktree operation lock is not a symbolic link: $lock_path" >&2
92
+ return 1
93
+ fi
94
+ if ln -s "$token" "$lock_path" 2>/dev/null; then
95
+ if [ "$(readlink "$lock_path" 2>/dev/null || true)" = "$token" ]; then
96
+ WORKTREE_OPERATION_LOCK_TOKEN=$token
97
+ WORKTREE_OPERATION_LOCK_HELD_ROOT=$lock_root
98
+ return 0
99
+ fi
100
+ # `ln -s` onto a symlink to a directory creates the link inside that directory.
101
+ held_token=$(readlink "$lock_path" 2>/dev/null || true)
102
+ if [[ "$held_token" =~ ^owner\.[0-9]+\.[0-9]+$ ]] \
103
+ && [ -L "$lock_root/$held_token/$token" ] \
104
+ && [ "$(readlink "$lock_root/$held_token/$token")" = "$token" ]; then
105
+ rm -f "$lock_root/$held_token/$token"
106
+ fi
107
+ fi
108
+ if [ ! -L "$lock_path" ]; then
109
+ rm -f "$owner_path"
110
+ echo "Error: worktree operation lock is not a symbolic link: $lock_path" >&2
111
+ return 1
112
+ fi
113
+ held_token=$(readlink "$lock_path")
114
+ if [[ ! "$held_token" =~ ^owner\.[0-9]+\.[0-9]+$ ]]; then
115
+ rm -f "$owner_path"
116
+ echo "Error: worktree operation lock has an invalid owner: $lock_path" >&2
117
+ return 1
118
+ fi
119
+ held_owner_path="$lock_root/$held_token"
120
+ held_pid=$(cat "$held_owner_path" 2>/dev/null || true)
121
+ rm -f "$owner_path"
122
+ if _worktree_operation_lock_pid_is_live "$held_pid"; then
123
+ echo "Error: another worktree operation is running (PID $held_pid)." >&2
124
+ else
125
+ echo "Error: the worktree operation lock is stale; clear it with worktree_operation_lock_clear_stale when no operation is running: $lock_path" >&2
126
+ fi
127
+ return 1
128
+ }
129
+
130
+ worktree_operation_lock_clear_stale() {
131
+ local lock_root lock_path clearing_path clearer_pid status
132
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=missing
133
+ lock_root=$(_worktree_operation_lock_resolve_root "${1:-}") || return 2
134
+ lock_path="$lock_root/lock"
135
+ [ -L "$lock_path" ] || return 0
136
+ # Serialize clearers so one cannot delete a lock another clearer replaced. The mutex is a
137
+ # symlink to the clearer's PID, created atomically, so a clearer that died holding it is
138
+ # recognizable and its mutex is recovered.
139
+ clearing_path="$lock_root/clearing"
140
+ _worktree_operation_lock_set_self_pid
141
+ clearer_pid=$WORKTREE_OPERATION_LOCK_SELF_PID
142
+ if ! ln -s "$clearer_pid" "$clearing_path" 2>/dev/null; then
143
+ status=$(readlink "$clearing_path" 2>/dev/null || true)
144
+ if _worktree_operation_lock_pid_is_live "$status" \
145
+ || [ "$(readlink "$clearing_path" 2>/dev/null || true)" != "$status" ]; then
146
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=busy
147
+ return 1
148
+ fi
149
+ rm -f "$clearing_path"
150
+ if ! ln -s "$clearer_pid" "$clearing_path" 2>/dev/null; then
151
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=busy
152
+ return 1
153
+ fi
154
+ fi
155
+ status=0
156
+ _worktree_operation_lock_clear_locked "$lock_root" || status=$?
157
+ rm -f "$clearing_path"
158
+ return "$status"
159
+ }
160
+
161
+ _worktree_operation_lock_clear_locked() {
162
+ local lock_root=$1 lock_path="$1/lock" held_owner_path held_pid held_token
163
+ [ -L "$lock_path" ] || return 0
164
+ held_token=$(readlink "$lock_path")
165
+ if [[ ! "$held_token" =~ ^owner\.[0-9]+\.[0-9]+$ ]]; then
166
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=invalid
167
+ return 1
168
+ fi
169
+ held_owner_path="$lock_root/$held_token"
170
+ held_pid=$(cat "$held_owner_path" 2>/dev/null || true)
171
+ if _worktree_operation_lock_pid_is_live "$held_pid"; then
172
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=active
173
+ return 1
174
+ fi
175
+ # Another process may have cleared and re-taken the lock since the read above.
176
+ [ "$(readlink "$lock_path" 2>/dev/null || true)" = "$held_token" ] || return 1
177
+ rm -f "$lock_path"
178
+ rm -f "$held_owner_path"
179
+ WORKTREE_OPERATION_LOCK_CLEANUP_STATUS=removed
180
+ }
181
+
182
+ worktree_operation_lock_release() {
183
+ local token=${WORKTREE_OPERATION_LOCK_TOKEN:-}
184
+ local lock_root=${WORKTREE_OPERATION_LOCK_HELD_ROOT:-}
185
+ [ -n "$token" ] && [ -n "$lock_root" ] || return 0
186
+ # A subshell inherits these variables but must not release its parent's lock.
187
+ _worktree_operation_lock_set_self_pid
188
+ case "$token" in
189
+ owner."$WORKTREE_OPERATION_LOCK_SELF_PID".*) ;;
190
+ *) return 0 ;;
191
+ esac
192
+ if [ "$(readlink "$lock_root/lock" 2>/dev/null || true)" = "$token" ]; then
193
+ rm -f "$lock_root/lock"
194
+ fi
195
+ rm -f "$lock_root/$token"
196
+ unset WORKTREE_OPERATION_LOCK_TOKEN WORKTREE_OPERATION_LOCK_HELD_ROOT WORKTREE_OPERATION_LOCK_SELF_PID
197
+ }