agentblame 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +197 -2
- package/bin/agentblame.js +129 -0
- package/package.json +40 -4
- package/src/attribute.js +180 -0
- package/src/cache.js +56 -0
- package/src/commands/blame.js +76 -0
- package/src/commands/map-template.js +133 -0
- package/src/commands/map.js +53 -0
- package/src/commands/notes.js +67 -0
- package/src/commands/pr.js +254 -0
- package/src/commands/stats.js +71 -0
- package/src/format.js +28 -0
- package/src/git.js +56 -0
- package/src/normalize.js +60 -0
- package/src/progress.js +24 -0
- package/src/redact.js +55 -0
- package/src/sources/claude.js +202 -0
- package/src/sources/codex.js +213 -0
- package/src/sources/shell.js +187 -0
- package/src/sources/walk.js +13 -0
package/src/format.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
2
|
+
const c = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
3
|
+
export const dim = c('2'), bold = c('1'), cyan = c('36'), magenta = c('35'), yellow = c('33'), green = c('32'), gray = c('90');
|
|
4
|
+
|
|
5
|
+
export function who(r) {
|
|
6
|
+
if (r.kind === 'agent' || r.kind === 'modified') {
|
|
7
|
+
const m = shortModel(r.event.model) || r.event.source;
|
|
8
|
+
return r.kind === 'agent' ? `AI ${m}` : `AI~ ${m}`;
|
|
9
|
+
}
|
|
10
|
+
if (r.kind === 'human') return r.blame?.uncommitted ? 'human (uncommitted)' : `human ${r.blame?.author || ''}`.trim();
|
|
11
|
+
if (r.kind === 'unknown') return `? ${r.blame?.author || ''}`.trim();
|
|
12
|
+
return '';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function shortModel(m) {
|
|
16
|
+
if (!m) return null;
|
|
17
|
+
return m.replace(/^claude-/, '').replace(/-\d{8}$/, '').replace(/\[.*\]$/, '');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function pad(s, n) {
|
|
21
|
+
s = String(s ?? '');
|
|
22
|
+
if (s.length > n) return s.slice(0, n - 1) + '…';
|
|
23
|
+
return s + ' '.repeat(n - s.length);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function pct(x) { return `${(x * 100).toFixed(1)}%`; }
|
|
27
|
+
|
|
28
|
+
export function date(ms) { return ms ? new Date(ms).toISOString().slice(0, 10) : '—'; }
|
package/src/git.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
export function git(cwd, args, opts = {}) {
|
|
5
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], ...opts });
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function repoRoot(cwd) {
|
|
9
|
+
try { return realpathSync(git(cwd, ['rev-parse', '--show-toplevel']).trim()); } catch { return null; }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function trackedFiles(root) {
|
|
13
|
+
return git(root, ['ls-files', '-z']).split('\0').filter(Boolean);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `git blame --line-porcelain` on the working tree. We pass -w (ignore
|
|
18
|
+
* whitespace) and -M/-C (follow moved/copied lines) so formatter runs and
|
|
19
|
+
* refactors don't reset a line's origin commit.
|
|
20
|
+
* Returns one entry per line: { commit, authorTime, committerTime, author, uncommitted }.
|
|
21
|
+
*/
|
|
22
|
+
export function blame(root, relPath) {
|
|
23
|
+
let out;
|
|
24
|
+
try { out = git(root, ['blame', '--line-porcelain', '-w', '-M', '-C', '--', relPath]); }
|
|
25
|
+
catch { return null; }
|
|
26
|
+
const lines = [];
|
|
27
|
+
const commits = new Map();
|
|
28
|
+
let cur = null;
|
|
29
|
+
for (const l of out.split('\n')) {
|
|
30
|
+
if (l.startsWith('\t')) { lines.push(cur); cur = null; continue; }
|
|
31
|
+
const head = l.match(/^([0-9a-f]{40}) \d+ (\d+)/);
|
|
32
|
+
if (head) {
|
|
33
|
+
const sha = head[1];
|
|
34
|
+
cur = commits.get(sha) || { commit: sha, uncommitted: /^0+$/.test(sha) };
|
|
35
|
+
commits.set(sha, cur);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (!cur) continue;
|
|
39
|
+
if (l.startsWith('author ')) cur.author = l.slice(7);
|
|
40
|
+
else if (l.startsWith('author-time ')) cur.authorTime = Number(l.slice(12)) * 1000;
|
|
41
|
+
else if (l.startsWith('committer-time ')) cur.committerTime = Number(l.slice(15)) * 1000;
|
|
42
|
+
}
|
|
43
|
+
return lines;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function readNotes(root, ref = 'agentblame') {
|
|
47
|
+
const out = new Map();
|
|
48
|
+
let list;
|
|
49
|
+
try { list = git(root, ['notes', `--ref=${ref}`, 'list']); } catch { return out; }
|
|
50
|
+
for (const line of list.split('\n')) {
|
|
51
|
+
const [noteSha, commit] = line.trim().split(/\s+/);
|
|
52
|
+
if (!noteSha || !commit) continue;
|
|
53
|
+
try { out.set(commit, JSON.parse(git(root, ['cat-file', '-p', noteSha]))); } catch {}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
package/src/normalize.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Normalization is what lets attribution survive formatters (prettier, black,
|
|
5
|
+
* gofmt): indentation, whitespace runs, quote style, trailing commas and
|
|
6
|
+
* semicolons are ignored. Two lines that differ only in those ways are the
|
|
7
|
+
* "same" line for attribution purposes.
|
|
8
|
+
*/
|
|
9
|
+
export function normalizeLine(line) {
|
|
10
|
+
return line
|
|
11
|
+
.replace(/\r$/, '')
|
|
12
|
+
.trim()
|
|
13
|
+
.replace(/[;,]+$/, '')
|
|
14
|
+
.replace(/["'`]/g, '"')
|
|
15
|
+
.replace(/\s+/g, ' ')
|
|
16
|
+
.replace(/\s*([(){}\[\]:=<>+\-*/,.])\s*/g, '$1');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function hash(s) {
|
|
20
|
+
return createHash('sha1').update(s).digest('hex').slice(0, 16);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Lines too generic to attribute to anyone: braces, blank lines, `else {`,
|
|
25
|
+
* `return;`, import-free one-word lines. Counting these would inflate
|
|
26
|
+
* "% written by agents" and create false matches.
|
|
27
|
+
*/
|
|
28
|
+
export function isTrivial(line) {
|
|
29
|
+
const n = normalizeLine(line);
|
|
30
|
+
if (n.length === 0) return true;
|
|
31
|
+
const alnum = n.replace(/[^A-Za-z0-9_]/g, '');
|
|
32
|
+
if (alnum.length < 4) return true;
|
|
33
|
+
if (/^(else|try|finally|do|return|break|continue|pass|end|fi|done|default)\b.{0,3}$/.test(n)) return true;
|
|
34
|
+
if (/^(\/\/|#|\*|\/\*|\*\/|<!--|-->)\s*$/.test(n)) return true;
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Character-trigram Dice similarity in [0,1]; used for "agent-written, human-modified". */
|
|
39
|
+
export function similarity(a, b) {
|
|
40
|
+
const A = trigrams(normalizeLine(a));
|
|
41
|
+
const B = trigrams(normalizeLine(b));
|
|
42
|
+
if (A.size === 0 || B.size === 0) return 0;
|
|
43
|
+
let inter = 0;
|
|
44
|
+
for (const g of A) if (B.has(g)) inter++;
|
|
45
|
+
return (2 * inter) / (A.size + B.size);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function trigrams(s) {
|
|
49
|
+
const out = new Set();
|
|
50
|
+
const p = ` ${s} `;
|
|
51
|
+
for (let i = 0; i < p.length - 2; i++) out.add(p.slice(i, i + 3));
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function splitLines(text) {
|
|
56
|
+
if (text == null) return [];
|
|
57
|
+
const lines = String(text).split('\n');
|
|
58
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
59
|
+
return lines;
|
|
60
|
+
}
|
package/src/progress.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Progress line for transcript scanning. Silent unless enabled (stderr is a TTY,
|
|
3
|
+
* not --json) and scanning has run longer than `thresholdMs`, so fast runs
|
|
4
|
+
* print nothing at all.
|
|
5
|
+
*/
|
|
6
|
+
export function progressReporter({ enabled = false, label = 'scanning transcripts', stream = process.stderr, thresholdMs = 1500 } = {}) {
|
|
7
|
+
const start = Date.now();
|
|
8
|
+
let total = 0, done = 0, shown = false, lastDraw = 0;
|
|
9
|
+
const draw = (force) => {
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
if (!shown) {
|
|
12
|
+
if (now - start < thresholdMs) return;
|
|
13
|
+
shown = true;
|
|
14
|
+
}
|
|
15
|
+
if (!force && now - lastDraw < 100) return;
|
|
16
|
+
lastDraw = now;
|
|
17
|
+
stream.write(`\r\x1b[2m${label} ${done}/${total}…\x1b[0m\x1b[K`);
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
add(n) { if (!enabled) return; total += n; draw(false); },
|
|
21
|
+
tick() { if (!enabled) return; done++; draw(false); },
|
|
22
|
+
finish() { if (enabled && shown) stream.write('\r\x1b[K'); },
|
|
23
|
+
};
|
|
24
|
+
}
|
package/src/redact.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Prompts can contain secrets and personal data. Anything that leaves the
|
|
2
|
+
// terminal (HTML map, git notes, --json) goes through redact() first.
|
|
3
|
+
// Home directories run first. Otherwise the blob rule below sees a long
|
|
4
|
+
// absolute path as one run of base64-looking characters and hides the
|
|
5
|
+
// readable path segments.
|
|
6
|
+
const HOME_PATTERNS = [
|
|
7
|
+
[/\b([A-Za-z]:[\\/]Users[\\/])[^\\/\s]+/gi, '$1[user]'],
|
|
8
|
+
[/\/(Users|home)\/[^/\s]+/g, '/$1/[user]'],
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
// Order matters. The quoted "key": "value" rule must run before the unquoted
|
|
12
|
+
// key=value rule, so a quoted value containing spaces is replaced in full.
|
|
13
|
+
// The unquoted rule skips values the quoted rule already replaced.
|
|
14
|
+
const PATTERNS = [
|
|
15
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[private-key]'],
|
|
16
|
+
[/\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{10,}\b/g, '[api-key]'],
|
|
17
|
+
[/\bnpm_[A-Za-z0-9]{30,}\b/g, '[npm-token]'],
|
|
18
|
+
[/\bglpat-[A-Za-z0-9_-]{20,}\b/g, '[gitlab-token]'],
|
|
19
|
+
[/\b(sk|pk|rk)-[A-Za-z0-9_-]{16,}\b/g, '[api-key]'],
|
|
20
|
+
[/\bsk-ant-[A-Za-z0-9_-]{16,}\b/g, '[api-key]'],
|
|
21
|
+
[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, '[github-token]'],
|
|
22
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, '[github-token]'],
|
|
23
|
+
[/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, '[slack-token]'],
|
|
24
|
+
[/\bAKIA[0-9A-Z]{16}\b/g, '[aws-key]'],
|
|
25
|
+
[/\bAIza[0-9A-Za-z_-]{35}\b/g, '[google-key]'],
|
|
26
|
+
[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[jwt]'],
|
|
27
|
+
[/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/g, '$1 [redacted]'],
|
|
28
|
+
[/(["']?(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret)["']?\s*[:=]\s*)(["'])[^"']{4,}\2/gi, '$1$2[redacted]$2'],
|
|
29
|
+
[/\b[\w.+-]+@[\w-]+\.[\w.-]+\b/g, '[email]'],
|
|
30
|
+
[/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*(?!["']?\[redacted\])\S+/gi, '$1=[redacted]'],
|
|
31
|
+
[/\b[A-Fa-f0-9]{40,}\b/g, '[hex]'],
|
|
32
|
+
[/(?<![\w/])[A-Za-z0-9+/]{48,}={0,2}/g, (m) => (looksLikeBlob(m) ? '[blob]' : m)],
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
// A secret-looking run (48+ characters, already matched by the rule above)
|
|
36
|
+
// has a digit and at least one letter, and does not read as a path (a
|
|
37
|
+
// "/segment/" with lowercase words).
|
|
38
|
+
function looksLikeBlob(m) {
|
|
39
|
+
if (/\/[a-z]{2,}\//.test(m)) return false;
|
|
40
|
+
return /\d/.test(m) && /[A-Za-z]/.test(m);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function redact(s) {
|
|
44
|
+
if (!s) return s;
|
|
45
|
+
let out = String(s);
|
|
46
|
+
for (const [re, rep] of HOME_PATTERNS) out = out.replace(re, rep);
|
|
47
|
+
for (const [re, rep] of PATTERNS) out = out.replace(re, rep);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function truncate(s, n = 280) {
|
|
52
|
+
if (!s) return s;
|
|
53
|
+
const one = s.replace(/\s+/g, ' ').trim();
|
|
54
|
+
return one.length > n ? `${one.slice(0, n - 1)}…` : one;
|
|
55
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { readdirSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { splitLines } from '../normalize.js';
|
|
5
|
+
import { cachedTranscript } from '../cache.js';
|
|
6
|
+
import { walkJsonl } from './walk.js';
|
|
7
|
+
import { heredocWrites } from './shell.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Parse Claude Code transcripts (~/.claude/projects/**\/*.jsonl, including
|
|
11
|
+
* subagents/) into write events: "at time T, session S, answering prompt P,
|
|
12
|
+
* added these lines to file F".
|
|
13
|
+
*
|
|
14
|
+
* Precision matters more than recall here, so we prefer the tool *result*
|
|
15
|
+
* (`toolUseResult.structuredPatch`, which records the lines actually added on
|
|
16
|
+
* disk) over the tool *input*, and we drop edits whose result was an error.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Claude Code names a session's project dir after its cwd, with every non-alphanumeric char replaced by '-'. */
|
|
20
|
+
export function encodeProjectDir(p) {
|
|
21
|
+
return p.replace(/[^A-Za-z0-9]/g, '-');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Project dirs that can hold sessions touching `root`: sessions started in
|
|
26
|
+
* `root` itself, in a parent of it, or in a subdirectory/worktree under it.
|
|
27
|
+
* Both the path as given and its macOS /private-less form are considered.
|
|
28
|
+
*/
|
|
29
|
+
export function projectDirsFor(claudeDir, root) {
|
|
30
|
+
let names;
|
|
31
|
+
try {
|
|
32
|
+
names = readdirSync(claudeDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
33
|
+
} catch { return []; }
|
|
34
|
+
const encs = [...new Set([root, root.replace(/^\/private(?=\/)/, '')].map(encodeProjectDir))];
|
|
35
|
+
return names
|
|
36
|
+
.filter((D) => encs.some((enc) => D === enc || enc.startsWith(`${D}-`) || D.startsWith(`${enc}-`)))
|
|
37
|
+
.map((D) => join(claudeDir, D));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {object} [opts]
|
|
42
|
+
* @param {string} [opts.root] repo root; limits the walk to matching project dirs
|
|
43
|
+
* @param {boolean} [opts.deep] walk every project dir regardless of `root`
|
|
44
|
+
* @param {boolean} [opts.cache] read/write the per-transcript cache
|
|
45
|
+
* @param {object} [opts.progress] reporter with add(n) / tick()
|
|
46
|
+
*/
|
|
47
|
+
export function loadClaudeEvents(claudeDir, { root, deep = false, cache = true, progress } = {}) {
|
|
48
|
+
const dirs = !root || deep ? [claudeDir] : projectDirsFor(claudeDir, root);
|
|
49
|
+
const files = dirs.flatMap((d) => [...walkJsonl(d)]);
|
|
50
|
+
progress?.add(files.length);
|
|
51
|
+
const events = [];
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
for (const ev of cachedTranscript(file, (text, f) => parseClaudeTranscript(text, f), { cache })) events.push(ev);
|
|
54
|
+
progress?.tick();
|
|
55
|
+
}
|
|
56
|
+
return events;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const WRITE_TOOLS = new Set(['Edit', 'MultiEdit', 'Write']);
|
|
60
|
+
const TOOL_HINT = /"name":"(?:Edit|Write|MultiEdit|Bash)"/;
|
|
61
|
+
|
|
62
|
+
export function parseClaudeTranscript(text, transcriptPath = '<memory>') {
|
|
63
|
+
const pending = new Map(); // tool_use id -> call info
|
|
64
|
+
const events = [];
|
|
65
|
+
let prompt = null;
|
|
66
|
+
let promptTs = null;
|
|
67
|
+
const subagent = /\/subagents\//.test(transcriptPath);
|
|
68
|
+
|
|
69
|
+
for (const raw of text.split('\n')) {
|
|
70
|
+
if (!raw) continue;
|
|
71
|
+
// Prefilter: skip lines that cannot change any state below. Every line we
|
|
72
|
+
// need carries one of the literal markers checked here.
|
|
73
|
+
if (raw.startsWith('{"type":"api-request')) continue;
|
|
74
|
+
const isUser = raw.includes('"type":"user"');
|
|
75
|
+
const isAssistant = raw.includes('"type":"assistant"');
|
|
76
|
+
if (!isUser && !isAssistant) continue;
|
|
77
|
+
let want = false;
|
|
78
|
+
if (isAssistant && raw.includes('"tool_use"') && TOOL_HINT.test(raw)) want = true;
|
|
79
|
+
// Prompt candidates are always parsed, however large: a pasted prompt over 200k chars still sets the prompt.
|
|
80
|
+
if (isUser) want = want || (raw.includes('"tool_result"') ? referencesPending(raw, pending) : true);
|
|
81
|
+
if (!want) continue;
|
|
82
|
+
|
|
83
|
+
let d;
|
|
84
|
+
try { d = JSON.parse(raw); } catch { continue; }
|
|
85
|
+
const msg = d.message;
|
|
86
|
+
if (!msg) continue;
|
|
87
|
+
const ts = Date.parse(d.timestamp) || null;
|
|
88
|
+
|
|
89
|
+
if (d.type === 'user') {
|
|
90
|
+
const content = msg.content;
|
|
91
|
+
const toolResults = Array.isArray(content) ? content.filter((b) => b && b.type === 'tool_result') : [];
|
|
92
|
+
if (toolResults.length) {
|
|
93
|
+
for (const tr of toolResults) {
|
|
94
|
+
const call = pending.get(tr.tool_use_id);
|
|
95
|
+
if (!call) continue;
|
|
96
|
+
pending.delete(tr.tool_use_id);
|
|
97
|
+
if (tr.is_error) continue; // rejected or failed edit: nothing landed on disk
|
|
98
|
+
events.push(...eventsFromCall(call, d.toolUseResult, { transcriptPath, subagent }));
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (d.isMeta) continue;
|
|
103
|
+
const p = promptText(content);
|
|
104
|
+
if (p) { prompt = p; promptTs = ts; }
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (d.type === 'assistant' && Array.isArray(msg.content)) {
|
|
109
|
+
for (const b of msg.content) {
|
|
110
|
+
if (b?.type !== 'tool_use') continue;
|
|
111
|
+
const isWrite = WRITE_TOOLS.has(b.name);
|
|
112
|
+
const isBash = b.name === 'Bash';
|
|
113
|
+
if (!isWrite && !isBash) continue;
|
|
114
|
+
pending.set(b.id, {
|
|
115
|
+
id: b.id, tool: b.name, input: b.input || {}, ts, model: msg.model || d.requestedModel || null,
|
|
116
|
+
sessionId: d.sessionId, cwd: d.cwd, prompt, promptTs,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return events;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function referencesPending(raw, pending) {
|
|
125
|
+
for (const m of raw.matchAll(/"tool_use_id":"([^"]+)"/g)) if (pending.has(m[1])) return true;
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function promptText(content) {
|
|
130
|
+
let s = '';
|
|
131
|
+
if (typeof content === 'string') s = content;
|
|
132
|
+
else if (Array.isArray(content)) s = content.filter((b) => b?.type === 'text').map((b) => b.text).join('\n');
|
|
133
|
+
s = s.trim();
|
|
134
|
+
if (!s) return null;
|
|
135
|
+
if (/^<(system-reminder|task-notification|local-command-stdout|local-command-caveat)/.test(s)) return null;
|
|
136
|
+
if (s.startsWith('[Request interrupted')) return null;
|
|
137
|
+
const cmd = s.match(/<command-name>([^<]*)<\/command-name>(?:[\s\S]*?<command-args>([^<]*)<\/command-args>)?/);
|
|
138
|
+
if (cmd) s = `${cmd[1]} ${cmd[2] || ''}`.trim();
|
|
139
|
+
return s;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function eventsFromCall(call, result, meta) {
|
|
143
|
+
const base = {
|
|
144
|
+
source: 'claude', sessionId: call.sessionId, ts: call.ts, model: call.model, prompt: call.prompt,
|
|
145
|
+
promptTs: call.promptTs, transcript: meta.transcriptPath, tool: call.tool, toolUseId: call.id,
|
|
146
|
+
subagent: meta.subagent, userModified: !!result?.userModified,
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
if (call.tool === 'Bash') {
|
|
150
|
+
// sed -i and other in-place edits of existing files carry a diff (bashEditDiff), which is verified.
|
|
151
|
+
const files = Array.isArray(result?.bashEditDiff?.files) ? result.bashEditDiff.files : [];
|
|
152
|
+
const out = files.map((f) => ({ ...base, file: f.filePath, added: addedFromHunks(f.hunks), verified: true }));
|
|
153
|
+
// Files created by a heredoc (`cat > f <<'EOF'`) get no diff, so read the command. Unverified:
|
|
154
|
+
// the body is what was written, but nothing on disk confirmed it.
|
|
155
|
+
const covered = new Set(files.map((f) => normPath(f.filePath)));
|
|
156
|
+
for (const w of heredocWrites(call.input.command, call.cwd, homedir())) {
|
|
157
|
+
if (covered.has(normPath(w.file))) continue;
|
|
158
|
+
out.push({ ...base, file: w.file, added: w.body.map((text, i) => ({ text, block: 0, pos: i })), verified: false });
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const file = result?.filePath || call.input.file_path;
|
|
164
|
+
if (!file) return [];
|
|
165
|
+
|
|
166
|
+
if (result && Array.isArray(result.structuredPatch) && result.structuredPatch.length) {
|
|
167
|
+
return [{ ...base, file, added: addedFromHunks(result.structuredPatch), verified: true }];
|
|
168
|
+
}
|
|
169
|
+
if (result && result.type === 'create') {
|
|
170
|
+
const lines = splitLines(result.content ?? call.input.content);
|
|
171
|
+
return [{ ...base, file, added: lines.map((text, i) => ({ text, block: 0, pos: i })), verified: true }];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Fallback for older transcripts with no structured result: use the tool
|
|
175
|
+
// input. Unchanged lines a Write re-emits are filtered later by git history.
|
|
176
|
+
let lines = [];
|
|
177
|
+
if (call.tool === 'Write') lines = splitLines(call.input.content);
|
|
178
|
+
else if (call.tool === 'Edit') lines = splitLines(call.input.new_string);
|
|
179
|
+
else if (call.tool === 'MultiEdit') lines = (call.input.edits || []).flatMap((e) => splitLines(e.new_string));
|
|
180
|
+
if (result && typeof result.originalFile === 'string') {
|
|
181
|
+
const before = new Set(splitLines(result.originalFile));
|
|
182
|
+
lines = lines.filter((l) => !before.has(l));
|
|
183
|
+
}
|
|
184
|
+
return [{ ...base, file, added: lines.map((text, i) => ({ text, block: 0, pos: i })), verified: false }];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Compare paths with the macOS /private prefix removed, as relPathFor does. */
|
|
188
|
+
function normPath(p) {
|
|
189
|
+
return typeof p === 'string' ? p.replace(/^\/private(?=\/)/, '') : p;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function addedFromHunks(hunks) {
|
|
193
|
+
const out = [];
|
|
194
|
+
(hunks || []).forEach((h, hi) => {
|
|
195
|
+
let pos = h.newStart || 0;
|
|
196
|
+
for (const l of h.lines || []) {
|
|
197
|
+
if (l.startsWith('+')) { out.push({ text: l.slice(1), block: hi, pos }); pos++; }
|
|
198
|
+
else if (l.startsWith(' ')) pos++;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { walkJsonl } from './walk.js';
|
|
4
|
+
import { heredocWrites } from './shell.js';
|
|
5
|
+
import { cachedTranscript } from '../cache.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Experimental: parse Codex CLI rollouts (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl).
|
|
9
|
+
*
|
|
10
|
+
* Schema, from openai/codex (commit d0b140efb5d326ae481d77aaf40b925226a74cae):
|
|
11
|
+
* every line is { timestamp, type, payload }, where type is one of
|
|
12
|
+
* session_meta (payload.cwd, payload.id), turn_context (payload.cwd, payload.model),
|
|
13
|
+
* response_item (payload is a ResponseItem tagged by payload.type) or event_msg.
|
|
14
|
+
*
|
|
15
|
+
* Edits this source reads:
|
|
16
|
+
* - apply_patch is a freeform tool, so the call is response_item custom_tool_call
|
|
17
|
+
* with name "apply_patch" and the patch text in payload.input.
|
|
18
|
+
* - Its result is response_item custom_tool_call_output with payload.output as a string.
|
|
19
|
+
* A successful patch starts with "Success. Updated the following files:"; a failed one
|
|
20
|
+
* starts with an error such as "apply_patch verification failed:". An event_msg
|
|
21
|
+
* patch_apply_end (persisted by default) also carries `success` and wins when present.
|
|
22
|
+
* - Shell commands are response_item function_call with name exec_command and JSON
|
|
23
|
+
* arguments { cmd, workdir }. Their result is function_call_output.
|
|
24
|
+
*
|
|
25
|
+
* Calls are collected in file order and resolved at the end, because the result arrives
|
|
26
|
+
* after the call. Each event captures the cwd, model and prompt in effect at the call.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// Bump the namespace when the emitted events change, so stale parse caches are not reused.
|
|
30
|
+
const CACHE_NAMESPACE = 'codex-v2\0';
|
|
31
|
+
|
|
32
|
+
// User-role messages the harness injects. They are context, not something the user asked for.
|
|
33
|
+
const CONTEXT_PREFIXES = [
|
|
34
|
+
'# AGENTS.md instructions',
|
|
35
|
+
'<environment_context>',
|
|
36
|
+
'<user_shell_command>',
|
|
37
|
+
'<turn_aborted>',
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const PATCH_SUCCESS = 'Success. Updated the following files:';
|
|
41
|
+
|
|
42
|
+
export function loadCodexEvents(root, { cache = true, progress } = {}) {
|
|
43
|
+
const files = [...walkJsonl(root)];
|
|
44
|
+
progress?.add(files.length);
|
|
45
|
+
const events = [];
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
for (const ev of cachedTranscript(file, parseCodexFile, { cache, namespace: CACHE_NAMESPACE })) events.push(ev);
|
|
48
|
+
progress?.tick();
|
|
49
|
+
}
|
|
50
|
+
return events;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseCodexFile(text, file) {
|
|
54
|
+
if (!text.includes('*** Begin Patch') && !text.includes('<<')) return [];
|
|
55
|
+
return parseCodexRollout(text, file);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function parseCodexRollout(text, transcriptPath = '<memory>') {
|
|
59
|
+
let cwd = null, model = null, sessionId = null, prompt = null, promptTs = null;
|
|
60
|
+
const calls = []; // { kind, callId, name, ts, cwd, model, prompt, promptTs, sessionId, patch?, command?, workdir? }
|
|
61
|
+
const outputs = new Map(); // call_id -> output text
|
|
62
|
+
const patchOutcomes = new Map(); // call_id -> success flag from event_msg patch_apply_end
|
|
63
|
+
|
|
64
|
+
for (const raw of text.split('\n')) {
|
|
65
|
+
if (!raw) continue;
|
|
66
|
+
let d;
|
|
67
|
+
try { d = JSON.parse(raw); } catch { continue; }
|
|
68
|
+
if (!d || typeof d !== 'object') continue;
|
|
69
|
+
const p = d.payload && typeof d.payload === 'object' ? d.payload : {};
|
|
70
|
+
const ts = Date.parse(d.timestamp) || null;
|
|
71
|
+
|
|
72
|
+
if (d.type === 'session_meta') { cwd = p.cwd || cwd; sessionId = p.id || p.session_id || sessionId; continue; }
|
|
73
|
+
if (d.type === 'turn_context') { cwd = p.cwd || cwd; model = p.model || model; continue; }
|
|
74
|
+
|
|
75
|
+
if (d.type === 'event_msg') {
|
|
76
|
+
if (p.type === 'patch_apply_end' && p.call_id) patchOutcomes.set(p.call_id, p.success === true);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (d.type !== 'response_item') continue;
|
|
80
|
+
|
|
81
|
+
if (p.type === 'message' && p.role === 'user') {
|
|
82
|
+
const t = contentText(p.content).trim();
|
|
83
|
+
if (t && !isContextMessage(t)) { prompt = t; promptTs = ts; }
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (p.type === 'custom_tool_call_output' || p.type === 'function_call_output') {
|
|
88
|
+
if (p.call_id) outputs.set(p.call_id, outputText(p.output));
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const base = { callId: p.call_id || null, ts, cwd, model, prompt, promptTs, sessionId };
|
|
93
|
+
|
|
94
|
+
if (p.type === 'custom_tool_call' && p.name === 'apply_patch' && typeof p.input === 'string') {
|
|
95
|
+
calls.push({ ...base, kind: 'patch', name: 'apply_patch', patch: p.input });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (p.type === 'function_call') {
|
|
100
|
+
const args = parseArgs(p.arguments);
|
|
101
|
+
if (p.name === 'apply_patch') {
|
|
102
|
+
const patch = typeof args.input === 'string' ? args.input : typeof p.arguments === 'string' ? p.arguments : null;
|
|
103
|
+
if (patch && patch.includes('*** Begin Patch')) calls.push({ ...base, kind: 'patch', name: 'apply_patch', patch });
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (SHELL_TOOLS.has(p.name)) {
|
|
107
|
+
const command = shellCommand(args);
|
|
108
|
+
if (command && command.includes('<<')) {
|
|
109
|
+
calls.push({ ...base, kind: 'shell', name: p.name, command, workdir: typeof args.workdir === 'string' ? args.workdir : null });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (p.type === 'local_shell_call' && p.action && p.action.type === 'exec') {
|
|
116
|
+
const command = Array.isArray(p.action.command) ? p.action.command.at(-1) : null;
|
|
117
|
+
if (typeof command === 'string' && command.includes('<<')) {
|
|
118
|
+
calls.push({ ...base, kind: 'shell', name: 'local_shell', command, workdir: p.action.working_directory || null });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const events = [];
|
|
124
|
+
for (const c of calls) {
|
|
125
|
+
const out = c.callId ? outputs.get(c.callId) : undefined;
|
|
126
|
+
const common = {
|
|
127
|
+
source: 'codex', sessionId: c.sessionId, ts: c.ts, model: c.model, prompt: c.prompt,
|
|
128
|
+
promptTs: c.promptTs, transcript: transcriptPath, tool: c.name, toolUseId: c.callId,
|
|
129
|
+
subagent: false, userModified: false,
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
if (c.kind === 'patch') {
|
|
133
|
+
// A patch landed only if the harness says so. Anything else (a verification failure,
|
|
134
|
+
// a missing result) is dropped.
|
|
135
|
+
const landed = patchOutcomes.has(c.callId) ? patchOutcomes.get(c.callId) : isPatchSuccess(out);
|
|
136
|
+
if (!landed) continue;
|
|
137
|
+
for (const f of parsePatch(c.patch)) {
|
|
138
|
+
const file = isAbsolute(f.path) || !c.cwd ? f.path : resolve(c.cwd, f.path);
|
|
139
|
+
events.push({ ...common, file, added: f.added, verified: false });
|
|
140
|
+
}
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Shell heredoc. Unlike a patch, the result text does not say whether the write landed,
|
|
145
|
+
// so only a missing result or an explicit non-zero exit drops it.
|
|
146
|
+
if (out === undefined || exitFailed(out)) continue;
|
|
147
|
+
for (const w of heredocWrites(c.command, c.workdir || c.cwd, homedir())) {
|
|
148
|
+
events.push({ ...common, file: w.file, added: w.body.map((text, i) => ({ text, block: 0, pos: i })), verified: false });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return events;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const SHELL_TOOLS = new Set(['exec_command', 'shell', 'shell_command']);
|
|
155
|
+
|
|
156
|
+
function isContextMessage(text) {
|
|
157
|
+
return CONTEXT_PREFIXES.some((prefix) => text.startsWith(prefix));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function contentText(content) {
|
|
161
|
+
if (typeof content === 'string') return content;
|
|
162
|
+
if (!Array.isArray(content)) return '';
|
|
163
|
+
return content.filter((c) => c && typeof c.text === 'string').map((c) => c.text).join('\n');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// function_call_output.output is a string, or an array of content items.
|
|
167
|
+
function outputText(output) {
|
|
168
|
+
if (typeof output === 'string') return output;
|
|
169
|
+
if (Array.isArray(output)) return output.filter((c) => c && typeof c.text === 'string').map((c) => c.text).join('\n');
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isPatchSuccess(out) {
|
|
174
|
+
return typeof out === 'string' && out.startsWith(PATCH_SUCCESS);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Best effort: a non-zero exit is reported as "Process exited with code N" at the start of a line.
|
|
178
|
+
function exitFailed(out) {
|
|
179
|
+
return typeof out === 'string' && /^Process exited with code [1-9]/m.test(out);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseArgs(arguments_) {
|
|
183
|
+
if (arguments_ && typeof arguments_ === 'object') return arguments_;
|
|
184
|
+
if (typeof arguments_ !== 'string') return {};
|
|
185
|
+
try { const v = JSON.parse(arguments_); return v && typeof v === 'object' ? v : {}; } catch { return {}; }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// exec_command carries `cmd`. Other shell tools may carry `command` as a string or an argv
|
|
189
|
+
// array such as ["bash", "-lc", "<script>"], where the script is the last element.
|
|
190
|
+
function shellCommand(args) {
|
|
191
|
+
if (typeof args.cmd === 'string') return args.cmd;
|
|
192
|
+
if (typeof args.command === 'string') return args.command;
|
|
193
|
+
if (Array.isArray(args.command) && typeof args.command.at(-1) === 'string') return args.command.at(-1);
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function parsePatch(patch) {
|
|
198
|
+
const files = [];
|
|
199
|
+
let cur = null, block = 0, pos = 0;
|
|
200
|
+
for (const line of patch.split('\n')) {
|
|
201
|
+
const m = line.match(/^\*\*\* (Add|Update) File: (.+)$/);
|
|
202
|
+
if (m) { cur = { path: m[2].trim(), added: [] }; files.push(cur); block = 0; pos = 0; continue; }
|
|
203
|
+
// `*** Move to:` renames the file being updated. Its later hunks belong to the new path.
|
|
204
|
+
const mv = line.match(/^\*\*\* Move to: (.+)$/);
|
|
205
|
+
if (mv) { if (cur) cur.path = mv[1].trim(); continue; }
|
|
206
|
+
if (/^\*\*\* (Delete File|End Patch|End of File)/.test(line)) { cur = null; continue; }
|
|
207
|
+
if (!cur) continue;
|
|
208
|
+
if (line.startsWith('@@')) { block++; continue; }
|
|
209
|
+
if (line.startsWith('+')) cur.added.push({ text: line.slice(1), block, pos: pos++ });
|
|
210
|
+
else pos++;
|
|
211
|
+
}
|
|
212
|
+
return files;
|
|
213
|
+
}
|