vouchington-tooling 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +49 -0
  2. package/dist/cli/commands/sandbox-command-audit.d.mts +7 -0
  3. package/dist/cli/commands/sandbox-command-audit.mjs +27 -0
  4. package/dist/cli/index.mjs +2 -0
  5. package/dist/cli/parse-forwarded-commands.d.mts +3 -0
  6. package/dist/cli/parse-forwarded-commands.mjs +2 -0
  7. package/dist/cli/parse.d.mts +3 -0
  8. package/dist/cli/usage-text.d.mts +1 -1
  9. package/dist/cli/usage-text.mjs +9 -0
  10. package/dist/sandbox-command-audit/args.d.mts +20 -0
  11. package/dist/sandbox-command-audit/args.mjs +64 -0
  12. package/dist/sandbox-command-audit/classify-prefixes.d.mts +23 -0
  13. package/dist/sandbox-command-audit/classify-prefixes.mjs +50 -0
  14. package/dist/sandbox-command-audit/classify.d.mts +46 -0
  15. package/dist/sandbox-command-audit/classify.mjs +74 -0
  16. package/dist/sandbox-command-audit/claude-extract.d.mts +23 -0
  17. package/dist/sandbox-command-audit/claude-extract.mjs +76 -0
  18. package/dist/sandbox-command-audit/claude-tool-uses.d.mts +15 -0
  19. package/dist/sandbox-command-audit/claude-tool-uses.mjs +53 -0
  20. package/dist/sandbox-command-audit/codex-extract.d.mts +21 -0
  21. package/dist/sandbox-command-audit/codex-extract.mjs +77 -0
  22. package/dist/sandbox-command-audit/codex-scan.d.mts +11 -0
  23. package/dist/sandbox-command-audit/codex-scan.mjs +98 -0
  24. package/dist/sandbox-command-audit/codex-spool.d.mts +14 -0
  25. package/dist/sandbox-command-audit/codex-spool.mjs +46 -0
  26. package/dist/sandbox-command-audit/discover-files.d.mts +44 -0
  27. package/dist/sandbox-command-audit/discover-files.mjs +85 -0
  28. package/dist/sandbox-command-audit/failure-text.d.mts +7 -0
  29. package/dist/sandbox-command-audit/failure-text.mjs +34 -0
  30. package/dist/sandbox-command-audit/fixtures.test-helpers.d.mts +34 -0
  31. package/dist/sandbox-command-audit/fixtures.test-helpers.mjs +41 -0
  32. package/dist/sandbox-command-audit/index.d.mts +26 -0
  33. package/dist/sandbox-command-audit/index.mjs +15 -0
  34. package/dist/sandbox-command-audit/json-record.d.mts +6 -0
  35. package/dist/sandbox-command-audit/json-record.mjs +16 -0
  36. package/dist/sandbox-command-audit/limits.d.mts +30 -0
  37. package/dist/sandbox-command-audit/limits.mjs +66 -0
  38. package/dist/sandbox-command-audit/repo-scope.d.mts +25 -0
  39. package/dist/sandbox-command-audit/repo-scope.mjs +79 -0
  40. package/dist/sandbox-command-audit/report-raw.d.mts +16 -0
  41. package/dist/sandbox-command-audit/report-raw.mjs +55 -0
  42. package/dist/sandbox-command-audit/report.d.mts +10 -0
  43. package/dist/sandbox-command-audit/report.mjs +61 -0
  44. package/dist/sandbox-command-audit/run.d.mts +36 -0
  45. package/dist/sandbox-command-audit/run.mjs +70 -0
  46. package/dist/sandbox-command-audit/scan.d.mts +10 -0
  47. package/dist/sandbox-command-audit/scan.mjs +79 -0
  48. package/dist/sandbox-command-audit/transcript-cwd.d.mts +14 -0
  49. package/dist/sandbox-command-audit/transcript-cwd.mjs +153 -0
  50. package/dist/sandbox-command-audit/types.d.mts +59 -0
  51. package/dist/sandbox-command-audit/types.mjs +23 -0
  52. package/package.json +6 -1
  53. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
package/README.md CHANGED
@@ -275,6 +275,54 @@ at most `limits.totalBytes` in all. A log that cannot be read is reported throug
275
275
  pieces are exported from `vouchington-tooling/transient-retry` (`rerunKnownTransient`,
276
276
  `buildWorkflowRunContext`, `createGhApi`).
277
277
 
278
+ ## Auditing sandbox escalations
279
+
280
+ `vouchington sandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]...
281
+ [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>]
282
+ [--limit N] [--since DAYS] [--json] [--raw]` scans agent transcripts for Bash calls that left the
283
+ sandbox (`dangerouslyDisableSandbox`), were denied, or failed on a permission signature, and groups
284
+ them by command prefix. Transcript roots default to `CLAUDE_CONFIG_DIR/projects` and
285
+ `CODEX_HOME/sessions` (else `~/.claude` and `~/.codex`). Discovery is scoped to the repository so
286
+ other projects' commands are not reported as this repository's gaps: the roots are the current
287
+ checkout plus every worktree `git worktree list` knows, or the `--repo-root` values, plus the
288
+ matches of each `--worktree-glob` (a glob relative to each root, for worktree layouts git no longer
289
+ lists). A transcript is attributed by its first recorded `cwd`; files whose cwd is unknown or
290
+ outside the roots are counted on the `Scope:` line, never dropped silently. `--limit` caps files per
291
+ source after scoping and `--since` is a day window. The default report holds only prefixes and
292
+ counts; `--raw` adds full command and failure text for local inspection and `--json` serializes
293
+ either view.
294
+
295
+ The package ships no classification. The module named by `--rules` default-exports (or exports as
296
+ `rules`) an object, or a function returning one:
297
+
298
+ ```js
299
+ export default {
300
+ // Required. Turns the settings location into the repository's coverage answer, or { error }.
301
+ loadPolicy: ({ settingsPath, cwd }) => ({
302
+ // list is 'allow' | 'deny' | 'excluded'. 'allow' and 'excluded' receive a normalized
303
+ // command prefix; 'deny' receives each raw command.
304
+ covers: (list, commandOrPrefix) =>
305
+ myPolicy[list].some((rule) => matches(rule, commandOrPrefix)),
306
+ }),
307
+ // Optional. Claims a failed Bash result for a bucket of your own (any string); it runs after the
308
+ // E2BIG check and before the generic permission signatures, and its kinds are reported
309
+ // separately from bypass candidates. It also runs on Codex CommandExecution output, and Codex
310
+ // transcripts are only read when this rule is set.
311
+ classifyFailure: (command, text, source) =>
312
+ /read-only file system/.test(text) ? 'write-path' : undefined,
313
+ // Optional. Overrides any scan cap (see AuditLimits); each must be a non-negative integer.
314
+ limits: { maxRetainedRecords: 1000 },
315
+ worktreeGlobs: ['../checkouts/*'],
316
+ }
317
+ ```
318
+
319
+ Built-in failure kinds are `genuine` (permission denied, `EACCES`, `EPERM`, sandbox start failures,
320
+ and a timeout against a loopback address) and `e2big`. A missing or unreadable policy, or an
321
+ unresolvable repository, prints a `Status: unavailable` report so a retrospective can still embed
322
+ the output. The pieces are exported from `vouchington-tooling/sandbox-command-audit`
323
+ (`scanTranscripts`, `discoverTranscriptFiles`, `resolveRepoRoots`, `classifyAudit`, `formatReport`,
324
+ `runAudit`). Codex escalations are not scanned: Codex agents journal those separately.
325
+
278
326
  ## Reclaiming finished worktrees
279
327
 
280
328
  `vouchington worktree reclaim [--yes] [--json]` removes git worktrees whose work is done. It is a
@@ -357,6 +405,7 @@ import {
357
405
  writeGeneratedFiles,
358
406
  } from 'vouchington-tooling/api-fixtures'
359
407
  import { decide, deriveRetryAttempt } from 'vouchington-tooling/transient-retry'
408
+ import { scanTranscripts, classifyAudit } from 'vouchington-tooling/sandbox-command-audit'
360
409
  import { parseCsvRows, streamCsvRows } from 'vouchington-tooling/csv'
361
410
  import {
362
411
  extractLooseMarkdownTableRows,
@@ -0,0 +1,7 @@
1
+ import { type LoadRulesModule } from '../../sandbox-command-audit/run.mts';
2
+ /**
3
+ * `vouchington sandbox-command-audit --rules <module> [flags]`: scans Claude and Codex transcripts
4
+ * for sandbox escalations, denials and permission failures, scoped to the repository, and prints a
5
+ * report. Exits 0 with a report, 2 on a usage error, 1 when the rules module cannot load.
6
+ */
7
+ export declare function runSandboxCommandAuditCommand(args: readonly string[], env?: NodeJS.ProcessEnv, load?: LoadRulesModule): Promise<number>;
@@ -0,0 +1,27 @@
1
+ import { parseAuditArgs } from "../../sandbox-command-audit/args.mjs";
2
+ import { runAudit } from "../../sandbox-command-audit/run.mjs";
3
+ import { commandUsage } from "../usage.mjs";
4
+ /**
5
+ * `vouchington sandbox-command-audit --rules <module> [flags]`: scans Claude and Codex transcripts
6
+ * for sandbox escalations, denials and permission failures, scoped to the repository, and prints a
7
+ * report. Exits 0 with a report, 2 on a usage error, 1 when the rules module cannot load.
8
+ */
9
+ export async function runSandboxCommandAuditCommand(args, env = process.env, load) {
10
+ let parsed;
11
+ try {
12
+ parsed = parseAuditArgs(args, env);
13
+ }
14
+ catch (error) {
15
+ const usage = commandUsage('sandbox-command-audit');
16
+ process.stderr.write(`vouchington: ${error.message}\n${usage}`);
17
+ return 2;
18
+ }
19
+ try {
20
+ process.stdout.write(await runAudit(parsed, { cwd: process.cwd(), ...(load ? { load } : {}) }));
21
+ return 0;
22
+ }
23
+ catch (error) {
24
+ process.stderr.write(`vouchington: ${error instanceof Error ? error.message : String(error)}\n`);
25
+ return 1;
26
+ }
27
+ }
@@ -108,6 +108,8 @@ export function runCli(argv = process.argv) {
108
108
  return runMcpCommand(parsed.args);
109
109
  case 'transient-retry':
110
110
  return import("./commands/transient-retry.mjs").then((command) => command.runTransientRetryCommand(parsed.args));
111
+ case 'sandbox-command-audit':
112
+ return import("./commands/sandbox-command-audit.mjs").then((command) => command.runSandboxCommandAuditCommand(parsed.args));
111
113
  case 'hook':
112
114
  return runHookCommand(parsed.args);
113
115
  case 'worktree':
@@ -55,6 +55,9 @@ type ForwardedCommand = {
55
55
  } | {
56
56
  kind: 'transient-retry';
57
57
  args: string[];
58
+ } | {
59
+ kind: 'sandbox-command-audit';
60
+ args: string[];
58
61
  } | {
59
62
  kind: 'tmux';
60
63
  args: string[];
@@ -37,6 +37,8 @@ export function parseForwardedCommand(command, args) {
37
37
  return { kind: 'worktree', args };
38
38
  if (command === 'transient-retry')
39
39
  return { kind: 'transient-retry', args };
40
+ if (command === 'sandbox-command-audit')
41
+ return { kind: 'sandbox-command-audit', args };
40
42
  if (command === 'tmux')
41
43
  return { kind: 'tmux', args };
42
44
  return undefined;
@@ -86,6 +86,9 @@ export type ParsedCli = {
86
86
  } | {
87
87
  kind: 'transient-retry';
88
88
  args: string[];
89
+ } | {
90
+ kind: 'sandbox-command-audit';
91
+ args: string[];
89
92
  } | {
90
93
  kind: 'tmux';
91
94
  args: string[];
@@ -1 +1 @@
1
- export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n\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\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\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
@@ -56,6 +56,7 @@ Commands:
56
56
  tmux Run configured dev windows in tmux; name panes; agent reminders
57
57
  story-coverage Check component exports are imported by stories
58
58
  transient-retry Rerun a failed GitHub Actions run when an injected rule matches
59
+ sandbox-command-audit Audit agent transcripts for sandbox escalations and denials
59
60
 
60
61
  Options:
61
62
  -h, --help Show this help
@@ -162,6 +163,14 @@ transient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-r
162
163
  Loads a module exporting "rules" (and optionally "limits"), evaluates them against the failed run,
163
164
  and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.
164
165
 
166
+ sandbox-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]
167
+ Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob
168
+ layouts) and reports Bash escalations, denials and permission failures by command prefix.
169
+ <module> exports an object (default or "rules") with loadPolicy({ settingsPath, cwd }), which
170
+ returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and
171
+ optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots
172
+ default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.
173
+
165
174
  tmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]
166
175
  tmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>
167
176
  Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.
@@ -0,0 +1,20 @@
1
+ export type AuditArgs = {
2
+ rules: string;
3
+ projectsDir: string;
4
+ codexSessionsDir: string;
5
+ settingsPath?: string;
6
+ maxFilesPerRoot: number;
7
+ sinceDays?: number;
8
+ sessionId?: string;
9
+ json: boolean;
10
+ raw: boolean;
11
+ /** Undefined resolves the roots from git. */
12
+ repoRoots?: string[];
13
+ worktreeGlobs: string[];
14
+ };
15
+ /**
16
+ * Parses the `sandbox-command-audit` flags. Transcript roots default to the harnesses' own
17
+ * (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`, else the home directory), matching transcript resolution.
18
+ * Throws an Error whose message names the first problem.
19
+ */
20
+ export declare function parseAuditArgs(argv: readonly string[], env: NodeJS.ProcessEnv): AuditArgs;
@@ -0,0 +1,64 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { SESSION_ID } from "../retrospective-transcript/resolve-transcript-file.mjs";
5
+ const DEFAULT_LIMIT = 50;
6
+ function positiveInteger(raw, flag) {
7
+ const parsed = Number(raw);
8
+ if (!Number.isSafeInteger(parsed) || parsed <= 0)
9
+ throw new Error(`${flag} requires a positive integer`);
10
+ return parsed;
11
+ }
12
+ function value(raw, flag) {
13
+ if (raw.length === 0 || raw.startsWith('-'))
14
+ throw new Error(`${flag} requires a value`);
15
+ return raw;
16
+ }
17
+ /**
18
+ * Parses the `sandbox-command-audit` flags. Transcript roots default to the harnesses' own
19
+ * (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`, else the home directory), matching transcript resolution.
20
+ * Throws an Error whose message names the first problem.
21
+ */
22
+ export function parseAuditArgs(argv, env) {
23
+ const { values } = parseArgs({
24
+ args: [...argv],
25
+ strict: true,
26
+ options: {
27
+ rules: { type: 'string' },
28
+ json: { type: 'boolean' },
29
+ raw: { type: 'boolean' },
30
+ limit: { type: 'string' },
31
+ since: { type: 'string' },
32
+ 'session-id': { type: 'string' },
33
+ 'projects-dir': { type: 'string' },
34
+ 'codex-sessions-dir': { type: 'string' },
35
+ 'settings-path': { type: 'string' },
36
+ 'repo-root': { type: 'string', multiple: true },
37
+ 'worktree-glob': { type: 'string', multiple: true },
38
+ },
39
+ });
40
+ if (values.rules === undefined)
41
+ throw new Error('--rules <module> is required');
42
+ const home = homedir();
43
+ const sessionId = values['session-id'];
44
+ if (sessionId !== undefined && !SESSION_ID.test(sessionId)) {
45
+ throw new Error(`--session-id has an invalid format: ${sessionId}`);
46
+ }
47
+ const many = (flag) => values[flag]?.map((entry) => value(entry, `--${flag}`));
48
+ const since = values.since;
49
+ return {
50
+ rules: value(values.rules, '--rules'),
51
+ projectsDir: value(values['projects-dir'] ?? join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'projects'), '--projects-dir'),
52
+ codexSessionsDir: value(values['codex-sessions-dir'] ?? join(env.CODEX_HOME || join(home, '.codex'), 'sessions'), '--codex-sessions-dir'),
53
+ maxFilesPerRoot: values.limit === undefined ? DEFAULT_LIMIT : positiveInteger(values.limit, '--limit'),
54
+ json: values.json === true,
55
+ raw: values.raw === true,
56
+ worktreeGlobs: many('worktree-glob') ?? [],
57
+ ...(values['settings-path'] === undefined
58
+ ? {}
59
+ : { settingsPath: value(values['settings-path'], '--settings-path') }),
60
+ ...(since === undefined ? {} : { sinceDays: positiveInteger(since, '--since') }),
61
+ ...(sessionId === undefined ? {} : { sessionId: sessionId.toLowerCase() }),
62
+ ...(many('repo-root') === undefined ? {} : { repoRoots: many('repo-root') }),
63
+ };
64
+ }
@@ -0,0 +1,23 @@
1
+ export type PrefixCount = {
2
+ prefix: string;
3
+ count: number;
4
+ };
5
+ /** Which list of an injected policy a command is checked against. */
6
+ export type CoverageList = 'allow' | 'deny' | 'excluded';
7
+ /**
8
+ * The repository's own answer to "is this already handled": the caller loads its settings from
9
+ * wherever and in whatever format it keeps them, and exposes only this question. `allow` and
10
+ * `excluded` receive a normalized prefix; `deny` receives each raw command.
11
+ */
12
+ export type CoveragePolicy = {
13
+ covers: (list: CoverageList, commandOrPrefix: string) => boolean;
14
+ };
15
+ export declare function groupByPrefix(commands: Array<string | undefined>): Map<string, number>;
16
+ export declare function toSortedPrefixCounts(counts: Map<string, number>): PrefixCount[];
17
+ export declare function unresolvedCount(counts: Map<string, number>): number;
18
+ export declare function coverageByPrefix(commands: Array<string | undefined>, list: CoverageList, policy: CoveragePolicy): Map<string, boolean>;
19
+ export declare function splitByCoverage(counts: Map<string, number>, list: CoverageList, policy: CoveragePolicy): {
20
+ covered: PrefixCount[];
21
+ uncovered: PrefixCount[];
22
+ unresolvedCount: number;
23
+ };
@@ -0,0 +1,50 @@
1
+ import { normalizeCommandPrefix } from "../retrospective-transcript/index.mjs";
2
+ // A command that could not be normalized (uncorrelated, or no command text) is still counted so
3
+ // it is never a silent drop; it just cannot anchor a per-prefix row.
4
+ const UNRESOLVED_PREFIX = '';
5
+ export function groupByPrefix(commands) {
6
+ const counts = new Map();
7
+ for (const command of commands) {
8
+ const prefix = command ? normalizeCommandPrefix(command) : UNRESOLVED_PREFIX;
9
+ counts.set(prefix, (counts.get(prefix) ?? 0) + 1);
10
+ }
11
+ return counts;
12
+ }
13
+ export function toSortedPrefixCounts(counts) {
14
+ const entries = [];
15
+ for (const [prefix, count] of counts) {
16
+ if (prefix !== UNRESOLVED_PREFIX)
17
+ entries.push({ prefix, count });
18
+ }
19
+ return entries.toSorted((a, b) => b.count - a.count || a.prefix.localeCompare(b.prefix));
20
+ }
21
+ export function unresolvedCount(counts) {
22
+ return counts.get(UNRESOLVED_PREFIX) ?? 0;
23
+ }
24
+ // Checked per raw command, because deny rules can run deeper than the two-token prefix depth. A
25
+ // prefix group is "covered" only when every command in it is: one uncovered instance leaves the
26
+ // group for human review.
27
+ export function coverageByPrefix(commands, list, policy) {
28
+ const coverage = new Map();
29
+ for (const command of commands) {
30
+ if (!command)
31
+ continue;
32
+ const prefix = normalizeCommandPrefix(command);
33
+ coverage.set(prefix, (coverage.get(prefix) ?? true) && policy.covers(list, command));
34
+ }
35
+ return coverage;
36
+ }
37
+ export function splitByCoverage(counts, list, policy) {
38
+ const covered = new Map();
39
+ const uncovered = new Map();
40
+ for (const [prefix, count] of counts) {
41
+ if (prefix === UNRESOLVED_PREFIX)
42
+ continue;
43
+ (policy.covers(list, prefix) ? covered : uncovered).set(prefix, count);
44
+ }
45
+ return {
46
+ covered: toSortedPrefixCounts(covered),
47
+ uncovered: toSortedPrefixCounts(uncovered),
48
+ unresolvedCount: unresolvedCount(counts),
49
+ };
50
+ }
@@ -0,0 +1,46 @@
1
+ import { type CoveragePolicy, type PrefixCount } from './classify-prefixes.mts';
2
+ import type { ScanResult, SkipCounts } from './types.mts';
3
+ export type { CoverageList, CoveragePolicy, PrefixCount } from './classify-prefixes.mts';
4
+ export type GenuineBypassCandidate = PrefixCount & {
5
+ alreadyInAllowList: boolean;
6
+ };
7
+ export type BlockCandidate = PrefixCount & {
8
+ alreadyDenied: boolean;
9
+ };
10
+ export type KindCount = {
11
+ kind: string;
12
+ count: number;
13
+ };
14
+ export type EscalationPressure = {
15
+ claudeCovered: PrefixCount[];
16
+ claudeUncovered: PrefixCount[];
17
+ claudeUnresolvedCount: number;
18
+ e2bigCount: number;
19
+ };
20
+ /**
21
+ * The privacy boundary: this is what `--json` serializes, so it carries only normalized prefixes
22
+ * and counts. Read-error paths and failure text exist only on `ScanResult`, as counts here.
23
+ */
24
+ export type CategorizedAudit = {
25
+ genuineBypassCandidates: GenuineBypassCandidate[];
26
+ genuineBypassUnresolvedCount: number;
27
+ blockCandidates: BlockCandidate[];
28
+ blockCandidateUnresolvedCount: number;
29
+ escalationPressure: EscalationPressure;
30
+ policyBlockCount: number;
31
+ /** Failures a caller rule put in its own bucket, by kind. Never counted as bypass candidates. */
32
+ otherFailures: KindCount[];
33
+ claudeFilesScanned: number;
34
+ codexFilesScanned: number;
35
+ readErrorCount: number;
36
+ repoRoots: string[];
37
+ skippedOtherRepo: SkipCounts;
38
+ skippedUnknownCwd: SkipCounts;
39
+ rawRetention: ScanResult['rawRetention'];
40
+ };
41
+ /**
42
+ * Sorts a scan into report buckets against the caller's policy. Bypass candidates come from
43
+ * Claude's real permission failures; Codex escalations are not scanned here because Codex agents
44
+ * journal them separately.
45
+ */
46
+ export declare function classifyAudit(scan: ScanResult, policy: CoveragePolicy): CategorizedAudit;
@@ -0,0 +1,74 @@
1
+ import { coverageByPrefix, groupByPrefix, splitByCoverage, toSortedPrefixCounts, unresolvedCount, } from "./classify-prefixes.mjs";
2
+ const BUILT_IN_KINDS = new Set(['genuine', 'e2big']);
3
+ function classifyGenuine(scan, policy) {
4
+ const commands = scan.claudeSandboxFailures
5
+ .filter((record) => record.kind === 'genuine')
6
+ .map((record) => record.command);
7
+ const counts = groupByPrefix(commands);
8
+ const candidates = toSortedPrefixCounts(counts).map((entry) => ({
9
+ ...entry,
10
+ alreadyInAllowList: policy.covers('allow', entry.prefix),
11
+ }));
12
+ return { candidates, unresolvedCount: unresolvedCount(counts) };
13
+ }
14
+ function classifyBlocks(scan, policy) {
15
+ const commands = scan.claudeDenials
16
+ .filter((record) => record.kind === 'user-rejected')
17
+ .map((record) => record.command);
18
+ const counts = groupByPrefix(commands);
19
+ const denied = coverageByPrefix(commands, 'deny', policy);
20
+ const candidates = toSortedPrefixCounts(counts).map((entry) => ({
21
+ ...entry,
22
+ alreadyDenied: denied.get(entry.prefix) === true,
23
+ }));
24
+ return { candidates, unresolvedCount: unresolvedCount(counts) };
25
+ }
26
+ function classifyEscalations(scan, policy) {
27
+ const counts = groupByPrefix(scan.claudeEscalations.map((record) => record.command));
28
+ const split = splitByCoverage(counts, 'excluded', policy);
29
+ return {
30
+ claudeCovered: split.covered,
31
+ claudeUncovered: split.uncovered,
32
+ claudeUnresolvedCount: split.unresolvedCount,
33
+ e2bigCount: scan.claudeSandboxFailures.filter((record) => record.kind === 'e2big').length,
34
+ };
35
+ }
36
+ function otherFailureCounts(scan) {
37
+ const counts = new Map();
38
+ // Built-in kinds feed the bypass and E2BIG sections, which read Claude failures only; a Codex
39
+ // failure of any kind has no other section, so it is always counted here.
40
+ const failures = [
41
+ ...scan.claudeSandboxFailures.filter(({ kind }) => !BUILT_IN_KINDS.has(kind)),
42
+ ...scan.codexSandboxFailures,
43
+ ];
44
+ for (const { kind } of failures)
45
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
46
+ return [...counts]
47
+ .map(([kind, count]) => ({ kind, count }))
48
+ .toSorted((a, b) => b.count - a.count || a.kind.localeCompare(b.kind));
49
+ }
50
+ /**
51
+ * Sorts a scan into report buckets against the caller's policy. Bypass candidates come from
52
+ * Claude's real permission failures; Codex escalations are not scanned here because Codex agents
53
+ * journal them separately.
54
+ */
55
+ export function classifyAudit(scan, policy) {
56
+ const genuine = classifyGenuine(scan, policy);
57
+ const block = classifyBlocks(scan, policy);
58
+ return {
59
+ genuineBypassCandidates: genuine.candidates,
60
+ genuineBypassUnresolvedCount: genuine.unresolvedCount,
61
+ blockCandidates: block.candidates,
62
+ blockCandidateUnresolvedCount: block.unresolvedCount,
63
+ escalationPressure: classifyEscalations(scan, policy),
64
+ policyBlockCount: scan.claudeDenials.filter((record) => record.kind === 'permission-rule' || record.kind === 'automode-blocked').length,
65
+ otherFailures: otherFailureCounts(scan),
66
+ claudeFilesScanned: scan.claudeFilesScanned,
67
+ codexFilesScanned: scan.codexFilesScanned,
68
+ readErrorCount: scan.readErrors.length,
69
+ repoRoots: scan.repoRoots,
70
+ skippedOtherRepo: scan.skippedOtherRepo,
71
+ skippedUnknownCwd: scan.skippedUnknownCwd,
72
+ rawRetention: scan.rawRetention,
73
+ };
74
+ }
@@ -0,0 +1,23 @@
1
+ import { type AuditLimits, type RawRetention } from './limits.mts';
2
+ import type { ClassifyFailure, ClaudeDenialRecord, ClaudeEscalationRecord, ClaudeSandboxFailureRecord } from './types.mts';
3
+ export type ClaudeExtraction = {
4
+ escalations: ClaudeEscalationRecord[];
5
+ denials: ClaudeDenialRecord[];
6
+ sandboxFailures: ClaudeSandboxFailureRecord[];
7
+ rawRetention: RawRetention;
8
+ };
9
+ export type ClaudeRecordExtractor = {
10
+ pushLine: (line: string) => void;
11
+ result: () => ClaudeExtraction;
12
+ };
13
+ export type ClaudeExtractOptions = {
14
+ classifyFailure?: ClassifyFailure | undefined;
15
+ limits: AuditLimits;
16
+ };
17
+ /**
18
+ * Streams Claude transcript lines into escalation, denial and sandbox-failure records. A
19
+ * tool_use always precedes its tool_result in file order, so one forward pass correlates every
20
+ * result with its command. A malformed or partially written line never hides earlier records.
21
+ */
22
+ export declare function createClaudeRecordExtractor(options: ClaudeExtractOptions): ClaudeRecordExtractor;
23
+ export declare function extractClaudeRecords(lines: string[], options: ClaudeExtractOptions): ClaudeExtraction;
@@ -0,0 +1,76 @@
1
+ import { asArray, asRecord } from "../retrospective-transcript/index.mjs";
2
+ import { recordClaudeToolUse } from "./claude-tool-uses.mjs";
3
+ import { classifyFailureText } from "./failure-text.mjs";
4
+ import { parseJsonRecord } from "./json-record.mjs";
5
+ import { appendBounded, emptyRawRetention, extractToolResultText, truncateRawText, } from "./limits.mjs";
6
+ const DENIAL_KINDS = ['user-rejected', 'permission-rule', 'automode-blocked'];
7
+ function isDenialKind(value) {
8
+ return typeof value === 'string' && DENIAL_KINDS.includes(value);
9
+ }
10
+ function recordToolResult(record, pending, out, options) {
11
+ const denialKind = isDenialKind(record.toolDenialKind) ? record.toolDenialKind : undefined;
12
+ for (const block of asArray(asRecord(record.message)?.content)) {
13
+ const value = asRecord(block);
14
+ if (!value || value.type !== 'tool_result')
15
+ continue;
16
+ const toolUseId = typeof value.tool_use_id === 'string' ? value.tool_use_id : undefined;
17
+ const toolUse = toolUseId ? pending.toolUses.get(toolUseId) : undefined;
18
+ if (toolUseId && toolUse) {
19
+ pending.toolUses.delete(toolUseId);
20
+ pending.bytes.value -= toolUse.bytes;
21
+ }
22
+ if (value.is_error !== true || toolUse?.name !== 'Bash')
23
+ continue;
24
+ const { rawRetention, denials, sandboxFailures } = out;
25
+ if (denialKind) {
26
+ const denial = { source: 'claude', kind: denialKind, command: toolUse.command };
27
+ appendBounded(denials, denial, rawRetention, options.limits);
28
+ continue;
29
+ }
30
+ const text = extractToolResultText(value.content);
31
+ const kind = classifyFailureText(toolUse.command, text, 'claude', options.classifyFailure);
32
+ if (!kind)
33
+ continue;
34
+ const errorText = truncateRawText(text, rawRetention, 'error', options.limits);
35
+ const failure = { source: 'claude', kind, command: toolUse.command, errorText };
36
+ appendBounded(sandboxFailures, failure, rawRetention, options.limits);
37
+ }
38
+ }
39
+ /**
40
+ * Streams Claude transcript lines into escalation, denial and sandbox-failure records. A
41
+ * tool_use always precedes its tool_result in file order, so one forward pass correlates every
42
+ * result with its command. A malformed or partially written line never hides earlier records.
43
+ */
44
+ export function createClaudeRecordExtractor(options) {
45
+ const rawRetention = emptyRawRetention();
46
+ const out = { escalations: [], denials: [], sandboxFailures: [], rawRetention };
47
+ const pending = { toolUses: new Map(), bytes: { value: 0 } };
48
+ return {
49
+ pushLine(line) {
50
+ const record = parseJsonRecord(line);
51
+ if (record?.type === 'assistant') {
52
+ for (const block of asArray(asRecord(record.message)?.content)) {
53
+ const { toolUses, bytes } = pending;
54
+ const { escalations } = out;
55
+ recordClaudeToolUse(block, toolUses, escalations, rawRetention, bytes, options.limits);
56
+ }
57
+ }
58
+ else if (record?.type === 'user') {
59
+ recordToolResult(record, pending, out, options);
60
+ }
61
+ },
62
+ result: () => {
63
+ const { escalations, denials, sandboxFailures } = out;
64
+ const result = { escalations, denials, sandboxFailures, rawRetention };
65
+ // Keep the enumerable JSON contract stable; the scanner reads this accounting field directly.
66
+ Object.defineProperty(result, 'rawRetention', { enumerable: false, value: rawRetention });
67
+ return result;
68
+ },
69
+ };
70
+ }
71
+ export function extractClaudeRecords(lines, options) {
72
+ const extractor = createClaudeRecordExtractor(options);
73
+ for (const line of lines)
74
+ extractor.pushLine(line);
75
+ return extractor.result();
76
+ }
@@ -0,0 +1,15 @@
1
+ import { type AuditLimits, type RawRetention } from './limits.mts';
2
+ import type { ClaudeEscalationRecord } from './types.mts';
3
+ export type ToolUseInfo = {
4
+ name: string;
5
+ command?: string | undefined;
6
+ bytes: number;
7
+ };
8
+ /**
9
+ * Remembers a Claude tool_use so its later tool_result can be correlated to the command, and
10
+ * records an escalation when a Bash call asked to leave the sandbox. Pending state is bounded by
11
+ * `limits`; a block too large to hold is dropped (its escalation is still recorded).
12
+ */
13
+ export declare function recordClaudeToolUse(block: unknown, toolUses: Map<string, ToolUseInfo>, escalations: ClaudeEscalationRecord[], retention: RawRetention, pendingBytes: {
14
+ value: number;
15
+ }, limits: AuditLimits): void;