vouchington-tooling 0.60.0 → 0.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/cli/commands/sandbox-command-audit.d.mts +7 -0
- package/dist/cli/commands/sandbox-command-audit.mjs +27 -0
- package/dist/cli/index.mjs +2 -0
- package/dist/cli/parse-forwarded-commands.d.mts +3 -0
- package/dist/cli/parse-forwarded-commands.mjs +2 -0
- package/dist/cli/parse.d.mts +3 -0
- package/dist/cli/usage-text.d.mts +1 -1
- package/dist/cli/usage-text.mjs +9 -0
- package/dist/command-policy/payload.d.mts +2 -0
- package/dist/command-policy/payload.mjs +8 -0
- package/dist/sandbox-command-audit/args.d.mts +20 -0
- package/dist/sandbox-command-audit/args.mjs +64 -0
- package/dist/sandbox-command-audit/classify-prefixes.d.mts +23 -0
- package/dist/sandbox-command-audit/classify-prefixes.mjs +50 -0
- package/dist/sandbox-command-audit/classify.d.mts +46 -0
- package/dist/sandbox-command-audit/classify.mjs +74 -0
- package/dist/sandbox-command-audit/claude-extract.d.mts +23 -0
- package/dist/sandbox-command-audit/claude-extract.mjs +76 -0
- package/dist/sandbox-command-audit/claude-tool-uses.d.mts +15 -0
- package/dist/sandbox-command-audit/claude-tool-uses.mjs +53 -0
- package/dist/sandbox-command-audit/codex-extract.d.mts +21 -0
- package/dist/sandbox-command-audit/codex-extract.mjs +77 -0
- package/dist/sandbox-command-audit/codex-scan.d.mts +11 -0
- package/dist/sandbox-command-audit/codex-scan.mjs +98 -0
- package/dist/sandbox-command-audit/codex-spool.d.mts +14 -0
- package/dist/sandbox-command-audit/codex-spool.mjs +46 -0
- package/dist/sandbox-command-audit/discover-files.d.mts +44 -0
- package/dist/sandbox-command-audit/discover-files.mjs +85 -0
- package/dist/sandbox-command-audit/failure-text.d.mts +7 -0
- package/dist/sandbox-command-audit/failure-text.mjs +34 -0
- package/dist/sandbox-command-audit/fixtures.test-helpers.d.mts +34 -0
- package/dist/sandbox-command-audit/fixtures.test-helpers.mjs +41 -0
- package/dist/sandbox-command-audit/index.d.mts +26 -0
- package/dist/sandbox-command-audit/index.mjs +15 -0
- package/dist/sandbox-command-audit/json-record.d.mts +6 -0
- package/dist/sandbox-command-audit/json-record.mjs +16 -0
- package/dist/sandbox-command-audit/limits.d.mts +30 -0
- package/dist/sandbox-command-audit/limits.mjs +66 -0
- package/dist/sandbox-command-audit/repo-scope.d.mts +25 -0
- package/dist/sandbox-command-audit/repo-scope.mjs +79 -0
- package/dist/sandbox-command-audit/report-raw.d.mts +16 -0
- package/dist/sandbox-command-audit/report-raw.mjs +55 -0
- package/dist/sandbox-command-audit/report.d.mts +10 -0
- package/dist/sandbox-command-audit/report.mjs +61 -0
- package/dist/sandbox-command-audit/run.d.mts +36 -0
- package/dist/sandbox-command-audit/run.mjs +70 -0
- package/dist/sandbox-command-audit/scan.d.mts +10 -0
- package/dist/sandbox-command-audit/scan.mjs +79 -0
- package/dist/sandbox-command-audit/transcript-cwd.d.mts +14 -0
- package/dist/sandbox-command-audit/transcript-cwd.mjs +153 -0
- package/dist/sandbox-command-audit/types.d.mts +59 -0
- package/dist/sandbox-command-audit/types.mjs +23 -0
- package/dist/tmux/cli.mjs +1 -1
- package/dist/tmux/reminder-post-tool.d.mts +1 -1
- package/dist/tmux/reminder-post-tool.mjs +2 -2
- package/package.json +6 -1
- package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
- package/dist/tmux/hook-payload.d.mts +0 -8
- package/dist/tmux/hook-payload.mjs +0 -39
|
@@ -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>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { tmpdir } from 'node:os';
|
|
2
|
+
import { openTranscriptLines } from "../retrospective-transcript/index.mjs";
|
|
3
|
+
import { createClaudeRecordExtractor } from "./claude-extract.mjs";
|
|
4
|
+
import { scanCodexFile } from "./codex-scan.mjs";
|
|
5
|
+
import { discoverTranscriptFiles } from "./discover-files.mjs";
|
|
6
|
+
import { appendBounded, resolveLimits } from "./limits.mjs";
|
|
7
|
+
import { emptyScanResult } from "./types.mjs";
|
|
8
|
+
async function scanClaudeFile(file, options) {
|
|
9
|
+
const opened = await openTranscriptLines(file);
|
|
10
|
+
if ('error' in opened)
|
|
11
|
+
return { error: opened.error };
|
|
12
|
+
const extractor = createClaudeRecordExtractor(options);
|
|
13
|
+
try {
|
|
14
|
+
for await (const line of opened.lines)
|
|
15
|
+
extractor.pushLine(line);
|
|
16
|
+
return extractor.result();
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
return { error: err.message };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function mergeRetention(target, source) {
|
|
23
|
+
target.commandTextsTruncated += source.commandTextsTruncated;
|
|
24
|
+
target.errorTextsTruncated += source.errorTextsTruncated;
|
|
25
|
+
target.pendingToolUsesDropped += source.pendingToolUsesDropped;
|
|
26
|
+
target.pendingToolUseBytesDropped += source.pendingToolUseBytesDropped;
|
|
27
|
+
target.recordsDropped += source.recordsDropped;
|
|
28
|
+
target.rawBytesDropped += source.rawBytesDropped;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Discovers transcripts and folds their records into one bounded `ScanResult`. Files are read
|
|
32
|
+
* one at a time so only one stream is ever open and each file's result arrays are released at once.
|
|
33
|
+
*/
|
|
34
|
+
export async function scanTranscripts(options) {
|
|
35
|
+
const limits = resolveLimits(options.limits);
|
|
36
|
+
const { classifyFailure } = options;
|
|
37
|
+
const discovered = await discoverTranscriptFiles(options);
|
|
38
|
+
const result = emptyScanResult();
|
|
39
|
+
result.repoRoots = options.repoRoots;
|
|
40
|
+
result.skippedOtherRepo = discovered.skippedOtherRepo;
|
|
41
|
+
result.skippedUnknownCwd = discovered.skippedUnknownCwd;
|
|
42
|
+
const keep = (records, record) => appendBounded(records, record, result.rawRetention, limits);
|
|
43
|
+
const readError = (file, error) => keep(result.readErrors, `${file}: ${error}`);
|
|
44
|
+
for (const file of discovered.claudeFiles) {
|
|
45
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
46
|
+
const scanned = await scanClaudeFile(file, { classifyFailure, limits });
|
|
47
|
+
if ('error' in scanned) {
|
|
48
|
+
readError(file, scanned.error);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
result.claudeFilesScanned++;
|
|
52
|
+
mergeRetention(result.rawRetention, scanned.rawRetention);
|
|
53
|
+
for (const record of scanned.escalations)
|
|
54
|
+
keep(result.claudeEscalations, record);
|
|
55
|
+
for (const record of scanned.denials)
|
|
56
|
+
keep(result.claudeDenials, record);
|
|
57
|
+
for (const record of scanned.sandboxFailures)
|
|
58
|
+
keep(result.claudeSandboxFailures, record);
|
|
59
|
+
}
|
|
60
|
+
const tempRoot = options.tempRoot ?? tmpdir();
|
|
61
|
+
// Codex output is only classified by the caller's rule, so without one the files are not read.
|
|
62
|
+
const codexFiles = classifyFailure === undefined ? [] : discovered.codexFiles;
|
|
63
|
+
for (const file of codexFiles) {
|
|
64
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
65
|
+
const scanned = await scanCodexFile(file, tempRoot, {
|
|
66
|
+
classifyFailure,
|
|
67
|
+
limits,
|
|
68
|
+
});
|
|
69
|
+
if ('error' in scanned) {
|
|
70
|
+
readError(file, scanned.error);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
result.codexFilesScanned++;
|
|
74
|
+
mergeRetention(result.rawRetention, scanned.rawRetention);
|
|
75
|
+
for (const record of scanned.sandboxFailures)
|
|
76
|
+
keep(result.codexSandboxFailures, record);
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The first `cwd` in a transcript, top-level (Claude records) or at `payload.cwd` (Codex
|
|
3
|
+
* `session_meta`). It reads a 64 KB prefix and streams the whole file only when that prefix is
|
|
4
|
+
* truncated and yielded nothing. First-cwd-wins: a session that later `cd`s into another repo is
|
|
5
|
+
* bucketed by its earliest cwd.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readTranscriptCwd(path: string): Promise<string | undefined>;
|
|
8
|
+
/**
|
|
9
|
+
* Resolves a Claude transcript's cwd from its own session file (or its subagent's owning session)
|
|
10
|
+
* and memoizes it per session file. A session whose owner is missing or unreadable rejects, which
|
|
11
|
+
* discovery counts as an unknown cwd rather than guessing from a sibling session. A rejected
|
|
12
|
+
* lookup is evicted so the next call retries.
|
|
13
|
+
*/
|
|
14
|
+
export declare function claudeSessionCwdResolver(projectsDir: string): (path: string) => Promise<string | undefined>;
|