vouchington-tooling 0.59.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 (141) hide show
  1. package/README.md +108 -0
  2. package/dist/cli/commands/hook.d.mts +2 -0
  3. package/dist/cli/commands/hook.mjs +19 -0
  4. package/dist/cli/commands/sandbox-command-audit.d.mts +7 -0
  5. package/dist/cli/commands/sandbox-command-audit.mjs +27 -0
  6. package/dist/cli/index.mjs +8 -0
  7. package/dist/cli/parse-forwarded-commands.d.mts +9 -0
  8. package/dist/cli/parse-forwarded-commands.mjs +6 -0
  9. package/dist/cli/parse.d.mts +9 -0
  10. package/dist/cli/usage-text.d.mts +1 -0
  11. package/dist/cli/usage-text.mjs +179 -0
  12. package/dist/cli/usage.d.mts +2 -1
  13. package/dist/cli/usage.mjs +2 -156
  14. package/dist/command-policy/engine.d.mts +7 -0
  15. package/dist/command-policy/engine.mjs +58 -0
  16. package/dist/command-policy/git-patterns.d.mts +20 -0
  17. package/dist/command-policy/git-patterns.mjs +82 -0
  18. package/dist/command-policy/git-process.d.mts +4 -0
  19. package/dist/command-policy/git-process.mjs +54 -0
  20. package/dist/command-policy/github-checkout-owners.d.mts +22 -0
  21. package/dist/command-policy/github-checkout-owners.mjs +122 -0
  22. package/dist/command-policy/github-command-context.d.mts +6 -0
  23. package/dist/command-policy/github-command-context.mjs +19 -0
  24. package/dist/command-policy/github-command-cwd.d.mts +8 -0
  25. package/dist/command-policy/github-command-cwd.mjs +130 -0
  26. package/dist/command-policy/github-command-position.d.mts +7 -0
  27. package/dist/command-policy/github-command-position.mjs +12 -0
  28. package/dist/command-policy/github-configured-base.d.mts +25 -0
  29. package/dist/command-policy/github-configured-base.mjs +59 -0
  30. package/dist/command-policy/github-invocation.d.mts +9 -0
  31. package/dist/command-policy/github-invocation.mjs +80 -0
  32. package/dist/command-policy/github-merge-authority.d.mts +21 -0
  33. package/dist/command-policy/github-merge-authority.mjs +86 -0
  34. package/dist/command-policy/github-option-flags.d.mts +3 -0
  35. package/dist/command-policy/github-option-flags.mjs +67 -0
  36. package/dist/command-policy/github-options.d.mts +12 -0
  37. package/dist/command-policy/github-options.mjs +73 -0
  38. package/dist/command-policy/github-stack-workflow.d.mts +9 -0
  39. package/dist/command-policy/github-stack-workflow.mjs +94 -0
  40. package/dist/command-policy/github-workflow.d.mts +7 -0
  41. package/dist/command-policy/github-workflow.mjs +50 -0
  42. package/dist/command-policy/hook/args.d.mts +11 -0
  43. package/dist/command-policy/hook/args.mjs +49 -0
  44. package/dist/command-policy/hook/harness.d.mts +26 -0
  45. package/dist/command-policy/hook/harness.mjs +119 -0
  46. package/dist/command-policy/hook/policy-module.d.mts +7 -0
  47. package/dist/command-policy/hook/policy-module.mjs +48 -0
  48. package/dist/command-policy/hook/post-tool-use.d.mts +9 -0
  49. package/dist/command-policy/hook/post-tool-use.mjs +51 -0
  50. package/dist/command-policy/hook/pre-tool-use.d.mts +21 -0
  51. package/dist/command-policy/hook/pre-tool-use.mjs +45 -0
  52. package/dist/command-policy/hook/run.d.mts +17 -0
  53. package/dist/command-policy/hook/run.mjs +69 -0
  54. package/dist/command-policy/hook/types.d.mts +33 -0
  55. package/dist/command-policy/hook/types.mjs +5 -0
  56. package/dist/command-policy/index.d.mts +29 -0
  57. package/dist/command-policy/index.mjs +23 -0
  58. package/dist/command-policy/path-references.d.mts +14 -0
  59. package/dist/command-policy/path-references.mjs +68 -0
  60. package/dist/command-policy/path-rules.d.mts +11 -0
  61. package/dist/command-policy/path-rules.mjs +37 -0
  62. package/dist/command-policy/payload.d.mts +8 -0
  63. package/dist/command-policy/payload.mjs +54 -0
  64. package/dist/command-policy/types.d.mts +77 -0
  65. package/dist/command-policy/types.mjs +1 -0
  66. package/dist/index.d.mts +2 -0
  67. package/dist/index.mjs +1 -0
  68. package/dist/sandbox-command-audit/args.d.mts +20 -0
  69. package/dist/sandbox-command-audit/args.mjs +64 -0
  70. package/dist/sandbox-command-audit/classify-prefixes.d.mts +23 -0
  71. package/dist/sandbox-command-audit/classify-prefixes.mjs +50 -0
  72. package/dist/sandbox-command-audit/classify.d.mts +46 -0
  73. package/dist/sandbox-command-audit/classify.mjs +74 -0
  74. package/dist/sandbox-command-audit/claude-extract.d.mts +23 -0
  75. package/dist/sandbox-command-audit/claude-extract.mjs +76 -0
  76. package/dist/sandbox-command-audit/claude-tool-uses.d.mts +15 -0
  77. package/dist/sandbox-command-audit/claude-tool-uses.mjs +53 -0
  78. package/dist/sandbox-command-audit/codex-extract.d.mts +21 -0
  79. package/dist/sandbox-command-audit/codex-extract.mjs +77 -0
  80. package/dist/sandbox-command-audit/codex-scan.d.mts +11 -0
  81. package/dist/sandbox-command-audit/codex-scan.mjs +98 -0
  82. package/dist/sandbox-command-audit/codex-spool.d.mts +14 -0
  83. package/dist/sandbox-command-audit/codex-spool.mjs +46 -0
  84. package/dist/sandbox-command-audit/discover-files.d.mts +44 -0
  85. package/dist/sandbox-command-audit/discover-files.mjs +85 -0
  86. package/dist/sandbox-command-audit/failure-text.d.mts +7 -0
  87. package/dist/sandbox-command-audit/failure-text.mjs +34 -0
  88. package/dist/sandbox-command-audit/fixtures.test-helpers.d.mts +34 -0
  89. package/dist/sandbox-command-audit/fixtures.test-helpers.mjs +41 -0
  90. package/dist/sandbox-command-audit/index.d.mts +26 -0
  91. package/dist/sandbox-command-audit/index.mjs +15 -0
  92. package/dist/sandbox-command-audit/json-record.d.mts +6 -0
  93. package/dist/sandbox-command-audit/json-record.mjs +16 -0
  94. package/dist/sandbox-command-audit/limits.d.mts +30 -0
  95. package/dist/sandbox-command-audit/limits.mjs +66 -0
  96. package/dist/sandbox-command-audit/repo-scope.d.mts +25 -0
  97. package/dist/sandbox-command-audit/repo-scope.mjs +79 -0
  98. package/dist/sandbox-command-audit/report-raw.d.mts +16 -0
  99. package/dist/sandbox-command-audit/report-raw.mjs +55 -0
  100. package/dist/sandbox-command-audit/report.d.mts +10 -0
  101. package/dist/sandbox-command-audit/report.mjs +61 -0
  102. package/dist/sandbox-command-audit/run.d.mts +36 -0
  103. package/dist/sandbox-command-audit/run.mjs +70 -0
  104. package/dist/sandbox-command-audit/scan.d.mts +10 -0
  105. package/dist/sandbox-command-audit/scan.mjs +79 -0
  106. package/dist/sandbox-command-audit/transcript-cwd.d.mts +14 -0
  107. package/dist/sandbox-command-audit/transcript-cwd.mjs +153 -0
  108. package/dist/sandbox-command-audit/types.d.mts +59 -0
  109. package/dist/sandbox-command-audit/types.mjs +23 -0
  110. package/dist/tmux/cli-shared.d.mts +18 -0
  111. package/dist/tmux/cli-shared.mjs +8 -0
  112. package/dist/tmux/cli.d.mts +3 -0
  113. package/dist/tmux/cli.mjs +34 -0
  114. package/dist/tmux/config.d.mts +24 -0
  115. package/dist/tmux/config.mjs +91 -0
  116. package/dist/tmux/fake-tmux.test-helpers.d.mts +46 -0
  117. package/dist/tmux/fake-tmux.test-helpers.mjs +105 -0
  118. package/dist/tmux/hook-payload.d.mts +8 -0
  119. package/dist/tmux/hook-payload.mjs +39 -0
  120. package/dist/tmux/index.d.mts +9 -0
  121. package/dist/tmux/index.mjs +7 -0
  122. package/dist/tmux/launcher.d.mts +11 -0
  123. package/dist/tmux/launcher.mjs +127 -0
  124. package/dist/tmux/reminder-post-tool.d.mts +21 -0
  125. package/dist/tmux/reminder-post-tool.mjs +88 -0
  126. package/dist/tmux/runner.d.mts +11 -0
  127. package/dist/tmux/runner.mjs +26 -0
  128. package/dist/tmux/session-name.d.mts +5 -0
  129. package/dist/tmux/session-name.mjs +10 -0
  130. package/dist/tmux/shell-quote.d.mts +9 -0
  131. package/dist/tmux/shell-quote.mjs +16 -0
  132. package/dist/tmux/up.d.mts +2 -0
  133. package/dist/tmux/up.mjs +73 -0
  134. package/dist/tmux/windows.d.mts +18 -0
  135. package/dist/tmux/windows.mjs +50 -0
  136. package/package.json +16 -1
  137. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  138. package/scripts/tmux/tmux-agent-reminder.sh +68 -0
  139. package/scripts/tmux/tmux-name.sh +34 -0
  140. package/scripts/tmux/tmux-read-title.sh +13 -0
  141. package/scripts/tmux/tmux-target.sh +130 -0
@@ -0,0 +1,34 @@
1
+ const E2BIG_PATTERN = /\bE2BIG\b/;
2
+ // Deliberately conservative: `is_error: true` on a Bash tool_result also covers ordinary
3
+ // application failures (a failed test run, a grep with no matches), so only known
4
+ // permission/access signatures count. ECONNREFUSED is excluded on purpose: it is the generic
5
+ // "nothing is listening" error and carries no permission semantics.
6
+ const GENUINE_FAILURE_PATTERNS = [
7
+ /operation not permitted/i,
8
+ /permission denied/i,
9
+ /\bEACCES\b/,
10
+ /\bEPERM\b/,
11
+ /could not start .*sandbox/i,
12
+ ];
13
+ // A timeout against a loopback target is a sandbox's signature for a silently dropped
14
+ // connection. Requiring both tokens keeps it narrow: a bare "timed out" (a slow test run) or a
15
+ // bare loopback mention carries no sandbox signal on its own.
16
+ const TIMEOUT_PATTERN = /\bETIMEDOUT\b|\btimed out\b/i;
17
+ const LOOPBACK_PATTERN = /\blocalhost\b|\b127\.0\.0\.1\b|(?<![\w:])::1(?!\w)/i;
18
+ /**
19
+ * Sorts a failed Bash result into `e2big`, a caller-defined kind, `genuine`, or nothing. The
20
+ * caller's rule sits between the E2BIG check and the generic signatures, so it can claim a failure
21
+ * that would otherwise count as a genuine bypass candidate.
22
+ */
23
+ export function classifyFailureText(command, text, source, classify) {
24
+ if (E2BIG_PATTERN.test(text))
25
+ return 'e2big';
26
+ const custom = classify?.(command, text, source);
27
+ if (custom !== undefined)
28
+ return custom;
29
+ if (GENUINE_FAILURE_PATTERNS.some((pattern) => pattern.test(text)))
30
+ return 'genuine';
31
+ if (TIMEOUT_PATTERN.test(text) && LOOPBACK_PATTERN.test(text))
32
+ return 'genuine';
33
+ return undefined;
34
+ }
@@ -0,0 +1,34 @@
1
+ import { type AuditLimits } from './limits.mts';
2
+ export declare const limits: (overrides?: Partial<AuditLimits>) => AuditLimits;
3
+ export declare const jsonl: (...records: unknown[]) => string[];
4
+ export declare function bashUse(id: string, command: string, input?: Record<string, unknown>): {
5
+ type: string;
6
+ message: {
7
+ content: {
8
+ type: string;
9
+ id: string;
10
+ name: string;
11
+ input: {
12
+ command: string;
13
+ };
14
+ }[];
15
+ };
16
+ };
17
+ export declare function toolResult(id: string, content: unknown, extra?: {
18
+ isError?: boolean;
19
+ toolDenialKind?: string;
20
+ }): {
21
+ message: {
22
+ content: {
23
+ type: string;
24
+ tool_use_id: string;
25
+ is_error: boolean;
26
+ content: unknown;
27
+ }[];
28
+ };
29
+ toolDenialKind?: string;
30
+ type: string;
31
+ };
32
+ /** A temporary directory removed after the test. */
33
+ export declare function tempDir(): string;
34
+ export declare function writeLines(path: string, lines: string[]): string;
@@ -0,0 +1,41 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { afterEach } from 'vitest';
5
+ import { resolveLimits } from "./limits.mjs";
6
+ export const limits = (overrides = {}) => resolveLimits(overrides);
7
+ export const jsonl = (...records) => records.map((record) => JSON.stringify(record));
8
+ export function bashUse(id, command, input = {}) {
9
+ return {
10
+ type: 'assistant',
11
+ message: {
12
+ content: [{ type: 'tool_use', id, name: 'Bash', input: { command, ...input } }],
13
+ },
14
+ };
15
+ }
16
+ export function toolResult(id, content, extra = {}) {
17
+ const { isError = true, toolDenialKind } = extra;
18
+ return {
19
+ type: 'user',
20
+ ...(toolDenialKind === undefined ? {} : { toolDenialKind }),
21
+ message: {
22
+ content: [{ type: 'tool_result', tool_use_id: id, is_error: isError, content }],
23
+ },
24
+ };
25
+ }
26
+ const roots = [];
27
+ afterEach(() => {
28
+ for (const root of roots.splice(0))
29
+ rmSync(root, { recursive: true, force: true });
30
+ });
31
+ /** A temporary directory removed after the test. */
32
+ export function tempDir() {
33
+ const root = mkdtempSync(join(tmpdir(), 'sandbox-audit-test-'));
34
+ roots.push(root);
35
+ return root;
36
+ }
37
+ export function writeLines(path, lines) {
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ writeFileSync(path, `${lines.join('\n')}\n`);
40
+ return path;
41
+ }
@@ -0,0 +1,26 @@
1
+ export { parseAuditArgs } from './args.mts';
2
+ export type { AuditArgs } from './args.mts';
3
+ export { classifyAudit } from './classify.mts';
4
+ export type { BlockCandidate, CategorizedAudit, CoverageList, CoveragePolicy, EscalationPressure, GenuineBypassCandidate, KindCount, PrefixCount, } from './classify.mts';
5
+ export { createClaudeRecordExtractor, extractClaudeRecords } from './claude-extract.mts';
6
+ export type { ClaudeExtraction, ClaudeRecordExtractor } from './claude-extract.mts';
7
+ export { scanCodexFile } from './codex-scan.mts';
8
+ export { createCodexRecordExtractor, extractCodexRecords } from './codex-extract.mts';
9
+ export type { CodexExtraction, CodexRecordExtractor } from './codex-extract.mts';
10
+ export { discoverTranscriptFiles } from './discover-files.mts';
11
+ export type { DiscoverOptions, DiscoveredFiles } from './discover-files.mts';
12
+ export { classifyFailureText } from './failure-text.mts';
13
+ export { DEFAULT_LIMITS, resolveLimits } from './limits.mts';
14
+ export type { AuditLimits, RawRetention } from './limits.mts';
15
+ export { HEADER, formatMarkdown, formatReport } from './report.mts';
16
+ export type { ReportOptions } from './report.mts';
17
+ export { formatRaw } from './report-raw.mts';
18
+ export { isWithinRepoRoots, resolveRepoRoots } from './repo-scope.mts';
19
+ export type { RepoScopeDeps, RepoScopeOptions } from './repo-scope.mts';
20
+ export { loadAuditRules, runAudit } from './run.mts';
21
+ export type { AuditRules, PolicyContext } from './run.mts';
22
+ export { scanTranscripts } from './scan.mts';
23
+ export type { ScanOptions } from './scan.mts';
24
+ export { claudeSessionCwdResolver, readTranscriptCwd } from './transcript-cwd.mts';
25
+ export { emptyScanResult } from './types.mts';
26
+ export type { ClassifyFailure, ClaudeDenialRecord, ClaudeEscalationRecord, ClaudeSandboxFailureRecord, ClaudeToolDenialKind, CodexSandboxFailureRecord, FailureKind, ScanResult, ScanRules, SkipCounts, } from './types.mts';
@@ -0,0 +1,15 @@
1
+ export { parseAuditArgs } from "./args.mjs";
2
+ export { classifyAudit } from "./classify.mjs";
3
+ export { createClaudeRecordExtractor, extractClaudeRecords } from "./claude-extract.mjs";
4
+ export { scanCodexFile } from "./codex-scan.mjs";
5
+ export { createCodexRecordExtractor, extractCodexRecords } from "./codex-extract.mjs";
6
+ export { discoverTranscriptFiles } from "./discover-files.mjs";
7
+ export { classifyFailureText } from "./failure-text.mjs";
8
+ export { DEFAULT_LIMITS, resolveLimits } from "./limits.mjs";
9
+ export { HEADER, formatMarkdown, formatReport } from "./report.mjs";
10
+ export { formatRaw } from "./report-raw.mjs";
11
+ export { isWithinRepoRoots, resolveRepoRoots } from "./repo-scope.mjs";
12
+ export { loadAuditRules, runAudit } from "./run.mjs";
13
+ export { scanTranscripts } from "./scan.mjs";
14
+ export { claudeSessionCwdResolver, readTranscriptCwd } from "./transcript-cwd.mjs";
15
+ export { emptyScanResult } from "./types.mjs";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Parses one transcript line into an object, or undefined for a blank, malformed, partially
3
+ * written or non-object line. Only parsing is guarded: callers run their own logic outside it, so
4
+ * an error from an injected rule is never mistaken for a malformed line.
5
+ */
6
+ export declare function parseJsonRecord(line: string): Record<string, unknown> | undefined;
@@ -0,0 +1,16 @@
1
+ import { asRecord } from "../retrospective-transcript/index.mjs";
2
+ /**
3
+ * Parses one transcript line into an object, or undefined for a blank, malformed, partially
4
+ * written or non-object line. Only parsing is guarded: callers run their own logic outside it, so
5
+ * an error from an injected rule is never mistaken for a malformed line.
6
+ */
7
+ export function parseJsonRecord(line) {
8
+ if (!line.trim())
9
+ return undefined;
10
+ try {
11
+ return asRecord(JSON.parse(line));
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ }
@@ -0,0 +1,30 @@
1
+ /** Caps that keep a scan bounded. Every field can be overridden through `resolveLimits`. */
2
+ export type AuditLimits = {
3
+ /** Claude tool_use blocks held while waiting for their tool_result. */
4
+ maxPendingToolUses: number;
5
+ /** Combined size of those pending tool_use blocks. */
6
+ maxPendingToolUseBytes: number;
7
+ /** Characters kept of one command or error text before it is truncated. */
8
+ maxRetainedRawTextChars: number;
9
+ /** Records kept per result bucket. */
10
+ maxRetainedRecords: number;
11
+ /** Combined JSON size of every retained record. */
12
+ maxRetainedRawBytes: number;
13
+ /** Bytes spooled while a forked Codex child replays inherited history. */
14
+ maxInheritedCodexSpoolBytes: number;
15
+ };
16
+ export declare const DEFAULT_LIMITS: AuditLimits;
17
+ export type RawRetention = {
18
+ commandTextsTruncated: number;
19
+ errorTextsTruncated: number;
20
+ pendingToolUsesDropped: number;
21
+ pendingToolUseBytesDropped: number;
22
+ recordsDropped: number;
23
+ rawBytesDropped: number;
24
+ retainedRawBytes: number;
25
+ };
26
+ export declare function resolveLimits(overrides?: Partial<AuditLimits>): AuditLimits;
27
+ export declare function emptyRawRetention(): RawRetention;
28
+ export declare function truncateRawText(text: string, retention: RawRetention, kind: 'command' | 'error', limits: AuditLimits): string;
29
+ export declare function appendBounded<T>(records: T[], record: T, retention: RawRetention, limits: AuditLimits): void;
30
+ export declare function extractToolResultText(content: unknown): string;
@@ -0,0 +1,66 @@
1
+ import { asRecord } from "../retrospective-transcript/index.mjs";
2
+ export const DEFAULT_LIMITS = {
3
+ maxPendingToolUses: 10_000,
4
+ maxPendingToolUseBytes: 2 * 1024 * 1024,
5
+ maxRetainedRawTextChars: 64 * 1024,
6
+ maxRetainedRecords: 10_000,
7
+ maxRetainedRawBytes: 2 * 1024 * 1024,
8
+ maxInheritedCodexSpoolBytes: 512 * 1024 * 1024,
9
+ };
10
+ export function resolveLimits(overrides = {}) {
11
+ const resolved = { ...DEFAULT_LIMITS };
12
+ for (const key of Object.keys(DEFAULT_LIMITS)) {
13
+ const value = overrides[key];
14
+ if (value === undefined)
15
+ continue;
16
+ if (!Number.isSafeInteger(value) || value < 0) {
17
+ throw new RangeError(`limits.${key} must be a non-negative integer`);
18
+ }
19
+ resolved[key] = value;
20
+ }
21
+ return resolved;
22
+ }
23
+ export function emptyRawRetention() {
24
+ return {
25
+ commandTextsTruncated: 0,
26
+ errorTextsTruncated: 0,
27
+ pendingToolUsesDropped: 0,
28
+ pendingToolUseBytesDropped: 0,
29
+ recordsDropped: 0,
30
+ rawBytesDropped: 0,
31
+ retainedRawBytes: 0,
32
+ };
33
+ }
34
+ export function truncateRawText(text, retention, kind, limits) {
35
+ if (text.length <= limits.maxRetainedRawTextChars)
36
+ return text;
37
+ if (kind === 'command')
38
+ retention.commandTextsTruncated++;
39
+ else
40
+ retention.errorTextsTruncated++;
41
+ return `${text.slice(0, limits.maxRetainedRawTextChars)}… [truncated]`;
42
+ }
43
+ export function appendBounded(records, record, retention, limits) {
44
+ const bytes = Buffer.byteLength(JSON.stringify(record));
45
+ if (records.length >= limits.maxRetainedRecords ||
46
+ retention.retainedRawBytes + bytes > limits.maxRetainedRawBytes) {
47
+ retention.recordsDropped++;
48
+ retention.rawBytesDropped += bytes;
49
+ return;
50
+ }
51
+ records.push(record);
52
+ retention.retainedRawBytes += bytes;
53
+ }
54
+ export function extractToolResultText(content) {
55
+ if (typeof content === 'string')
56
+ return content;
57
+ if (!Array.isArray(content))
58
+ return '';
59
+ let text = '';
60
+ for (const [index, block] of content.entries()) {
61
+ const record = asRecord(block);
62
+ const next = record?.type === 'text' && typeof record.text === 'string' ? record.text : '';
63
+ text += `${index > 0 ? '\n' : ''}${next}`;
64
+ }
65
+ return text;
66
+ }
@@ -0,0 +1,25 @@
1
+ export type RepoScopeDeps = {
2
+ gitToplevel?: (cwd: string) => Promise<string>;
3
+ gitWorktreePaths?: (cwd: string) => Promise<string[]>;
4
+ };
5
+ export type RepoScopeOptions = {
6
+ /** Explicit repository roots; relative paths resolve against `cwd`. Skips git entirely. */
7
+ explicit?: string[];
8
+ /**
9
+ * Worktree layouts, as globs relative to each repository root, for checkouts that `git
10
+ * worktree list` cannot report (for example a directory of worktrees that were since pruned).
11
+ * Each match becomes an extra root.
12
+ */
13
+ worktreeGlobs?: string[];
14
+ deps?: RepoScopeDeps;
15
+ };
16
+ /**
17
+ * The roots a run treats as "this repository": the explicit roots when given, otherwise the
18
+ * current checkout's top level unioned with every `git worktree list` entry, plus any `worktreeGlobs` matches, then
19
+ * minimized. A git failure (not a repository, no `git`) rejects; callers report it and point at
20
+ * the explicit roots. Every root is canonicalized once so a symlinked path compares correctly with
21
+ * a transcript's recorded cwd.
22
+ */
23
+ export declare function resolveRepoRoots(cwd: string, options?: RepoScopeOptions): Promise<string[]>;
24
+ /** Path-boundary safe: `/repo-two` never matches root `/repo` on a shared string prefix. */
25
+ export declare function isWithinRepoRoots(cwd: string, roots: string[]): Promise<boolean>;
@@ -0,0 +1,79 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, globSync } from 'node:fs';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { join, resolve, sep } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { parseWorktreeList } from "../git-worktrees/list.mjs";
7
+ const execFileAsync = promisify(execFile);
8
+ // A path that no longer exists (a deleted worktree, a recorded cwd since removed) falls back to
9
+ // its lexically normalized form: canonicalization resolves symlinks, it does not validate.
10
+ async function safeRealpath(path) {
11
+ try {
12
+ return await realpath(path);
13
+ }
14
+ catch {
15
+ return resolve(path);
16
+ }
17
+ }
18
+ async function defaultGitToplevel(cwd) {
19
+ const { stdout } = await execFileAsync('git', ['-C', cwd, 'rev-parse', '--show-toplevel']);
20
+ return stdout.trim();
21
+ }
22
+ async function defaultGitWorktreePaths(cwd) {
23
+ const { stdout } = await execFileAsync('git', [
24
+ '-C',
25
+ cwd,
26
+ 'worktree',
27
+ 'list',
28
+ '--porcelain',
29
+ '-z',
30
+ ]);
31
+ return parseWorktreeList(stdout)
32
+ .map((record) => record.path)
33
+ .filter((path) => !isMetadataDirectory(path));
34
+ }
35
+ // The list reports a submodule's `.git/modules/<name>` (and a bare repository) as a worktree. A
36
+ // real checkout has a `.git` entry; a path that no longer exists is kept, because a deleted
37
+ // worktree can still own past transcripts.
38
+ function isMetadataDirectory(path) {
39
+ return existsSync(path) && !existsSync(join(path, '.git'));
40
+ }
41
+ function isWithinRoot(candidate, root) {
42
+ const boundary = root.endsWith(sep) ? root : `${root}${sep}`;
43
+ return candidate === root || candidate.startsWith(boundary);
44
+ }
45
+ // Drops any root already inside another, so the per-file check stays a short list however many
46
+ // worktrees exist.
47
+ function minimizeRoots(roots) {
48
+ const unique = [...new Set(roots)];
49
+ return unique.filter((root) => !unique.some((other) => other !== root && isWithinRoot(root, other)));
50
+ }
51
+ function expandGlobs(roots, globs) {
52
+ return globs.flatMap((pattern) => roots.flatMap((root) => globSync(pattern, { cwd: root }).map((match) => resolve(root, match))));
53
+ }
54
+ async function baseRoots(cwd, options) {
55
+ if (options.explicit !== undefined && options.explicit.length > 0) {
56
+ return Promise.all(options.explicit.map((root) => safeRealpath(resolve(cwd, root))));
57
+ }
58
+ const gitToplevel = options.deps?.gitToplevel ?? defaultGitToplevel;
59
+ const gitWorktreePaths = options.deps?.gitWorktreePaths ?? defaultGitWorktreePaths;
60
+ const [toplevel, worktrees] = await Promise.all([gitToplevel(cwd), gitWorktreePaths(cwd)]);
61
+ return Promise.all([toplevel, ...worktrees].map(safeRealpath));
62
+ }
63
+ /**
64
+ * The roots a run treats as "this repository": the explicit roots when given, otherwise the
65
+ * current checkout's top level unioned with every `git worktree list` entry, plus any `worktreeGlobs` matches, then
66
+ * minimized. A git failure (not a repository, no `git`) rejects; callers report it and point at
67
+ * the explicit roots. Every root is canonicalized once so a symlinked path compares correctly with
68
+ * a transcript's recorded cwd.
69
+ */
70
+ export async function resolveRepoRoots(cwd, options = {}) {
71
+ const roots = await baseRoots(cwd, options);
72
+ const extra = await Promise.all(expandGlobs(roots, options.worktreeGlobs ?? []).map(safeRealpath));
73
+ return minimizeRoots([...roots, ...extra]);
74
+ }
75
+ /** Path-boundary safe: `/repo-two` never matches root `/repo` on a shared string prefix. */
76
+ export async function isWithinRepoRoots(cwd, roots) {
77
+ const resolvedCwd = await safeRealpath(cwd);
78
+ return roots.some((root) => isWithinRoot(resolvedCwd, root));
79
+ }
@@ -0,0 +1,16 @@
1
+ import type { ScanResult, SkipCounts } from './types.mts';
2
+ export declare const HEADER = "=== Sandbox Command Audit ===";
3
+ type ScopeInfo = {
4
+ repoRoots: string[];
5
+ claudeFilesScanned: number;
6
+ codexFilesScanned: number;
7
+ skippedOtherRepo: SkipCounts;
8
+ skippedUnknownCwd: SkipCounts;
9
+ };
10
+ /** Names the repo scope and what it dropped, so a cross-repo leak shows up in the report. */
11
+ export declare function scopeLine(info: ScopeInfo): string;
12
+ /** Warns that caps dropped or truncated records, so a bounded run never looks complete. */
13
+ export declare function rawRetentionLines(retention: ScanResult['rawRetention']): string[];
14
+ /** The one rendering that crosses the privacy boundary; it is only reachable behind `--raw`. */
15
+ export declare function formatRaw(scan: ScanResult): string;
16
+ export {};
@@ -0,0 +1,55 @@
1
+ export const HEADER = '=== Sandbox Command Audit ===';
2
+ const RAW_WARNING = '⚠ RAW MODE — full commands and sandbox-failure text below. Local inspection only. Never paste this section into a retro (privacy boundary).';
3
+ /** Names the repo scope and what it dropped, so a cross-repo leak shows up in the report. */
4
+ export function scopeLine(info) {
5
+ const [primaryRoot, ...worktreeRoots] = info.repoRoots;
6
+ const root = primaryRoot ?? '(no repo root resolved)';
7
+ const plural = worktreeRoots.length === 1 ? '' : 's';
8
+ const worktreeSuffix = worktreeRoots.length > 0 ? ` (+${worktreeRoots.length} worktree${plural})` : '';
9
+ const otherRepo = info.skippedOtherRepo.claude + info.skippedOtherRepo.codex;
10
+ const unknownCwd = info.skippedUnknownCwd.claude + info.skippedUnknownCwd.codex;
11
+ const skipParts = [
12
+ otherRepo > 0 ? `${otherRepo} skipped (other repo)` : undefined,
13
+ unknownCwd > 0 ? `${unknownCwd} skipped (cwd unknown)` : undefined,
14
+ ].filter((part) => part !== undefined);
15
+ const skipSuffix = skipParts.length > 0 ? `; ${skipParts.join(', ')}` : '';
16
+ return `Scope: ${root}${worktreeSuffix} — ${info.claudeFilesScanned} Claude / ${info.codexFilesScanned} Codex files scanned${skipSuffix}`;
17
+ }
18
+ /** Warns that caps dropped or truncated records, so a bounded run never looks complete. */
19
+ export function rawRetentionLines(retention) {
20
+ const count = retention.commandTextsTruncated +
21
+ retention.errorTextsTruncated +
22
+ retention.pendingToolUsesDropped +
23
+ retention.recordsDropped;
24
+ if (count === 0)
25
+ return [];
26
+ return [
27
+ `Raw retention bounded: ${retention.commandTextsTruncated} command text(s), ${retention.errorTextsTruncated} error text(s), ${retention.pendingToolUsesDropped} pending tool use(s), ${retention.recordsDropped} record(s) truncated or dropped; ${retention.pendingToolUseBytesDropped} pending and ${retention.rawBytesDropped} raw byte(s) evicted. Aggregate output may be incomplete.`,
28
+ ];
29
+ }
30
+ /** The one rendering that crosses the privacy boundary; it is only reachable behind `--raw`. */
31
+ export function formatRaw(scan) {
32
+ const failure = (record) => ` - [${record.kind}] ${record.command ?? '(unresolved)'}: ${record.errorText}`;
33
+ const lines = [
34
+ HEADER,
35
+ scopeLine(scan),
36
+ RAW_WARNING,
37
+ '',
38
+ `## Claude escalations (dangerouslyDisableSandbox) — ${scan.claudeEscalations.length}`,
39
+ ...scan.claudeEscalations.map((record) => ` - ${record.command}`),
40
+ '',
41
+ `## Claude denials — ${scan.claudeDenials.length}`,
42
+ ...scan.claudeDenials.map((record) => ` - [${record.kind}] ${record.command ?? '(unresolved)'}`),
43
+ '',
44
+ `## Claude sandbox failures — ${scan.claudeSandboxFailures.length}`,
45
+ ...scan.claudeSandboxFailures.map(failure),
46
+ '',
47
+ `## Codex sandbox failures — ${scan.codexSandboxFailures.length}`,
48
+ ...scan.codexSandboxFailures.map(failure),
49
+ '',
50
+ `## Read errors — ${scan.readErrors.length}`,
51
+ ...scan.readErrors.map((error) => ` - ${error}`),
52
+ ...rawRetentionLines(scan.rawRetention),
53
+ ];
54
+ return `${lines.join('\n')}\n`;
55
+ }
@@ -0,0 +1,10 @@
1
+ import type { CategorizedAudit } from './classify.mts';
2
+ import type { ScanResult } from './types.mts';
3
+ export { HEADER } from './report-raw.mts';
4
+ export type ReportOptions = {
5
+ json?: boolean;
6
+ raw?: boolean;
7
+ };
8
+ /** Default rendering: normalized prefixes and counts only, never full command or error text. */
9
+ export declare function formatMarkdown(audit: CategorizedAudit): string;
10
+ export declare function formatReport(scan: ScanResult, audit: CategorizedAudit, options?: ReportOptions): string;
@@ -0,0 +1,61 @@
1
+ import { HEADER, formatRaw, rawRetentionLines, scopeLine } from "./report-raw.mjs";
2
+ export { HEADER } from "./report-raw.mjs";
3
+ const NONE = [' (none)'];
4
+ function rows(entries, note) {
5
+ return entries.length > 0
6
+ ? entries.map((entry) => ` - ${entry.prefix} (${entry.count})${note(entry)}`)
7
+ : NONE;
8
+ }
9
+ function unresolvedNote(count) {
10
+ return count > 0 ? [` (+${count} with an unresolved command — rerun with --raw to inspect)`] : [];
11
+ }
12
+ function otherFailureLines(audit) {
13
+ if (audit.otherFailures.length === 0)
14
+ return [];
15
+ const total = audit.otherFailures.reduce((sum, entry) => sum + entry.count, 0);
16
+ return [
17
+ `## Other classified sandbox failures (not allow-list candidates): ${total}`,
18
+ ...audit.otherFailures.map((entry) => ` - ${entry.kind} (${entry.count})`),
19
+ ' (rerun with --raw to inspect the failure text)',
20
+ '',
21
+ ];
22
+ }
23
+ /** Default rendering: normalized prefixes and counts only, never full command or error text. */
24
+ export function formatMarkdown(audit) {
25
+ const pressure = audit.escalationPressure;
26
+ const lines = [
27
+ HEADER,
28
+ scopeLine(audit),
29
+ '',
30
+ '## 1. Genuine bypass candidates (real permission/access failures, not E2BIG)',
31
+ ...rows(audit.genuineBypassCandidates, (e) => e.alreadyInAllowList ? ' [already allowed]' : ''),
32
+ ...unresolvedNote(audit.genuineBypassUnresolvedCount),
33
+ '',
34
+ '## 2. Block candidates (human explicitly rejected the command)',
35
+ ...rows(audit.blockCandidates, (e) => (e.alreadyDenied ? ' [already denied]' : '')),
36
+ ...unresolvedNote(audit.blockCandidateUnresolvedCount),
37
+ '',
38
+ '## 3. Escalation pressure (root cause — dangerouslyDisableSandbox)',
39
+ 'Claude — already covered by the excluded-commands list:',
40
+ ...rows(pressure.claudeCovered, () => ''),
41
+ 'Claude — NOT covered (candidates to add to the excluded-commands list):',
42
+ ...rows(pressure.claudeUncovered, () => ''),
43
+ ...unresolvedNote(pressure.claudeUnresolvedCount),
44
+ `E2BIG failures (argument-list-too-long sandbox artifact, separate root cause — not a candidate list): ${pressure.e2bigCount}`,
45
+ '',
46
+ `## Denial hygiene (block policy already working as intended): ${audit.policyBlockCount}`,
47
+ '',
48
+ ...otherFailureLines(audit),
49
+ `Scanned ${audit.claudeFilesScanned} Claude transcript file(s), ${audit.codexFilesScanned} Codex transcript file(s).`,
50
+ ...(audit.readErrorCount > 0
51
+ ? [`Read errors: ${audit.readErrorCount} (rerun with --raw to inspect)`]
52
+ : []),
53
+ ...rawRetentionLines(audit.rawRetention),
54
+ ];
55
+ return `${lines.join('\n')}\n`;
56
+ }
57
+ export function formatReport(scan, audit, options = {}) {
58
+ if (options.json)
59
+ return `${JSON.stringify(options.raw ? scan : audit, null, 2)}\n`;
60
+ return options.raw ? formatRaw(scan) : formatMarkdown(audit);
61
+ }
@@ -0,0 +1,36 @@
1
+ import type { AuditArgs } from './args.mts';
2
+ import { type CoveragePolicy } from './classify.mts';
3
+ import type { ScanRules } from './types.mts';
4
+ export type PolicyContext = {
5
+ settingsPath?: string;
6
+ cwd: string;
7
+ };
8
+ /**
9
+ * What a repository injects. `loadPolicy` turns the settings location into the repository's
10
+ * coverage answer (or `{ error }` when it cannot); `classifyFailure` and `limits` extend the scan;
11
+ * `worktreeGlobs` names extra worktree layouts to scope transcripts to.
12
+ */
13
+ export type AuditRules = ScanRules & {
14
+ loadPolicy: (context: PolicyContext) => CoveragePolicy | {
15
+ error: string;
16
+ } | Promise<CoveragePolicy | {
17
+ error: string;
18
+ }>;
19
+ worktreeGlobs?: string[];
20
+ };
21
+ export type LoadRulesModule = (specifier: string) => Promise<unknown>;
22
+ export declare const importRulesModule: LoadRulesModule;
23
+ /**
24
+ * Imports a `--rules` module. The default export or a named `rules` export must be an object with
25
+ * a `loadPolicy` function (or a function returning one); a relative path resolves against `cwd`.
26
+ */
27
+ export declare function loadAuditRules(specifier: string, cwd: string, load?: LoadRulesModule): Promise<AuditRules>;
28
+ export type RunDeps = {
29
+ cwd: string;
30
+ load?: LoadRulesModule;
31
+ };
32
+ /**
33
+ * Scan, classify, report. A repository that cannot be resolved or a policy that cannot load yields
34
+ * an `unavailable` report rather than an error, so a retrospective can still embed the output.
35
+ */
36
+ export declare function runAudit(args: AuditArgs, deps: RunDeps): Promise<string>;
@@ -0,0 +1,70 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { resolve } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ import { classifyAudit } from "./classify.mjs";
12
+ import { HEADER, formatReport } from "./report.mjs";
13
+ import { resolveRepoRoots } from "./repo-scope.mjs";
14
+ import { scanTranscripts } from "./scan.mjs";
15
+ export const importRulesModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
16
+ /**
17
+ * Imports a `--rules` module. The default export or a named `rules` export must be an object with
18
+ * a `loadPolicy` function (or a function returning one); a relative path resolves against `cwd`.
19
+ */
20
+ export async function loadAuditRules(specifier, cwd, load = importRulesModule) {
21
+ const loaded = (await load(pathToFileURL(resolve(cwd, specifier)).href));
22
+ const exported = loaded.rules ?? loaded.default;
23
+ const rules = typeof exported === 'function' ? await exported() : exported;
24
+ const loadPolicy = rules?.loadPolicy;
25
+ if (typeof loadPolicy !== 'function') {
26
+ throw new Error(`rules module ${specifier} must export an object with a loadPolicy function`);
27
+ }
28
+ return rules;
29
+ }
30
+ // Honors --json so a consumer parsing the output always gets a machine-readable status.
31
+ function unavailable(reason, json) {
32
+ if (json)
33
+ return `${JSON.stringify({ status: 'unavailable', reason }, null, 2)}\n`;
34
+ return `${HEADER}\nStatus: unavailable (${reason})\n`;
35
+ }
36
+ /**
37
+ * Scan, classify, report. A repository that cannot be resolved or a policy that cannot load yields
38
+ * an `unavailable` report rather than an error, so a retrospective can still embed the output.
39
+ */
40
+ export async function runAudit(args, deps) {
41
+ const rules = await loadAuditRules(args.rules, deps.cwd, deps.load);
42
+ let repoRoots;
43
+ try {
44
+ repoRoots = await resolveRepoRoots(deps.cwd, {
45
+ worktreeGlobs: [...(rules.worktreeGlobs ?? []), ...args.worktreeGlobs],
46
+ ...(args.repoRoots === undefined ? {} : { explicit: args.repoRoots }),
47
+ });
48
+ }
49
+ catch (err) {
50
+ const reason = err instanceof Error ? err.message : String(err);
51
+ return unavailable(`repo root resolution failed: ${reason} — pass --repo-root to skip git and scope discovery explicitly`, args.json);
52
+ }
53
+ const policy = await rules.loadPolicy({
54
+ cwd: deps.cwd,
55
+ ...(args.settingsPath === undefined ? {} : { settingsPath: args.settingsPath }),
56
+ });
57
+ if ('error' in policy)
58
+ return unavailable(policy.error, args.json);
59
+ const scan = await scanTranscripts({
60
+ projectsDir: args.projectsDir,
61
+ codexSessionsDir: args.codexSessionsDir,
62
+ maxFilesPerRoot: args.maxFilesPerRoot,
63
+ repoRoots,
64
+ ...(args.sinceDays === undefined ? {} : { sinceDays: args.sinceDays }),
65
+ ...(args.sessionId === undefined ? {} : { sessionId: args.sessionId }),
66
+ ...(rules.classifyFailure === undefined ? {} : { classifyFailure: rules.classifyFailure }),
67
+ ...(rules.limits === undefined ? {} : { limits: rules.limits }),
68
+ });
69
+ return formatReport(scan, classifyAudit(scan, policy), args);
70
+ }
@@ -0,0 +1,10 @@
1
+ import { type DiscoverOptions } from './discover-files.mts';
2
+ import { type ScanResult, type ScanRules } from './types.mts';
3
+ export type ScanOptions = DiscoverOptions & ScanRules & {
4
+ tempRoot?: string;
5
+ };
6
+ /**
7
+ * Discovers transcripts and folds their records into one bounded `ScanResult`. Files are read
8
+ * one at a time so only one stream is ever open and each file's result arrays are released at once.
9
+ */
10
+ export declare function scanTranscripts(options: ScanOptions): Promise<ScanResult>;