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.
@@ -0,0 +1,187 @@
1
+ import { basename, isAbsolute, join, normalize } from 'node:path';
2
+
3
+ /**
4
+ * Recover the files a Bash command wrote with a heredoc. Supported forms:
5
+ *
6
+ * cat > PATH <<'EOF' ... EOF cat <<'EOF' > PATH cat >> PATH <<EOF
7
+ * tee PATH <<EOF ... EOF tee -a PATH <<EOF
8
+ *
9
+ * The delimiter can be any word, quoted or not; `<<-` strips leading tabs from
10
+ * body and delimiter. Several heredocs may appear in one command, joined by
11
+ * `&&`, `;`, `|` or newlines. Anything else that reads a heredoc
12
+ * (`python3 - <<EOF`, `git commit -F - <<EOF`, `node -e`) writes no file this
13
+ * module can name, so it yields nothing.
14
+ *
15
+ * This is a small shell reader, not a shell. It is built to be conservative:
16
+ * when a path or a directory cannot be known for certain (it contains `$` or a
17
+ * backtick, a `cd` target is unresolvable), the write is dropped.
18
+ */
19
+
20
+ const OPS = ['&&', '||', '>>', '>&', '&>', '>|', '<<<', '<<-', '<<', '<', '>', ';', '|', '&'];
21
+ const SEPARATORS = new Set(['&&', '||', ';', '|', '&']);
22
+ const WRITE_OPS = new Set(['>', '>>', '>|']);
23
+ const BARE = /[ \t&;|<>]/;
24
+ const PREFIX_WORDS = new Set(['(', '{', '!']);
25
+
26
+ /**
27
+ * @param {string} command the Bash tool's input.command
28
+ * @param {string|null} cwd working directory of the call (transcript line cwd)
29
+ * @param {string|null} home home directory, for a leading ~
30
+ * @returns {{ file: string, body: string[] }[]} one entry per written file, absolute path
31
+ */
32
+ export function heredocWrites(command, cwd = null, home = null) {
33
+ if (typeof command !== 'string' || !command.includes('<<')) return [];
34
+ const lines = command.split('\n');
35
+ const writes = []; // { file, append, heredoc }
36
+ let dir = cwd || null;
37
+ let i = 0;
38
+ while (i < lines.length) {
39
+ const toks = tokenize(lines[i++]);
40
+ const segs = [[]];
41
+ for (const t of toks) {
42
+ if (t.kind === 'op') segs.push([]);
43
+ else segs[segs.length - 1].push(t);
44
+ }
45
+ // Resolve paths as the shell would, in order: a `cd` applies to later segments.
46
+ for (const seg of segs) {
47
+ const cmd = commandOf(seg);
48
+ if (!cmd) continue;
49
+ if (cmd.name === 'cd') { dir = cdTarget(cmd.args, dir, home); continue; }
50
+ const hds = seg.filter((t) => t.kind === 'heredoc');
51
+ if (!hds.length) continue;
52
+ const hd = hds[hds.length - 1]; // the last heredoc is the command's stdin
53
+ for (const t of writeTargets(cmd, seg)) {
54
+ writes.push({ file: resolvePath(t.path, dir, home), append: t.append, heredoc: hd });
55
+ }
56
+ }
57
+ // Bodies start on the line after the command, one per heredoc, in order.
58
+ for (const h of toks) {
59
+ if (h.kind !== 'heredoc') continue;
60
+ const body = [];
61
+ let closed = false;
62
+ while (i < lines.length) {
63
+ const raw = lines[i++];
64
+ const line = h.strip ? raw.replace(/^\t+/, '') : raw;
65
+ if (line === h.delim) { closed = true; break; }
66
+ body.push(line);
67
+ }
68
+ h.body = closed ? body : null;
69
+ }
70
+ }
71
+
72
+ const byFile = new Map();
73
+ for (const w of writes) {
74
+ if (!w.file || !w.heredoc.body) continue; // unresolvable path, or an unterminated heredoc
75
+ const prev = byFile.get(w.file);
76
+ if (w.append && prev) prev.body = prev.body.concat(w.heredoc.body);
77
+ else byFile.set(w.file, { file: w.file, body: w.heredoc.body.slice() });
78
+ }
79
+ return [...byFile.values()];
80
+ }
81
+
82
+ /** Resolve a path the way the shell would; null when it cannot be known for certain. */
83
+ export function resolvePath(p, dir, home) {
84
+ if (typeof p !== 'string' || !p || /[$`]/.test(p)) return null;
85
+ if (p === '/dev/null' || p.startsWith('/dev/')) return null;
86
+ let q = p;
87
+ if (q === '~' || q.startsWith('~/')) {
88
+ if (!home) return null;
89
+ q = home + q.slice(1);
90
+ }
91
+ if (isAbsolute(q)) return normalize(q);
92
+ if (!dir) return null;
93
+ return join(dir, q);
94
+ }
95
+
96
+ function cdTarget(args, dir, home) {
97
+ const a = args.find((t) => t.value !== '--' && !/^-[LPe]+$/.test(t.value));
98
+ if (!a) return home || null;
99
+ if (a.value === '-') return null;
100
+ return resolvePath(a.value, dir, home);
101
+ }
102
+
103
+ function commandOf(seg) {
104
+ const words = seg.filter((t) => t.kind === 'word');
105
+ let k = 0;
106
+ while (k < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[k].value) || PREFIX_WORDS.has(words[k].value))) k++;
107
+ if (k >= words.length) return null;
108
+ return { name: basename(words[k].value), args: words.slice(k + 1) };
109
+ }
110
+
111
+ function writeTargets(cmd, seg) {
112
+ if (cmd.name === 'cat') {
113
+ const r = seg.filter((t) => t.kind === 'redir' && WRITE_OPS.has(t.op)).pop();
114
+ return r ? [{ path: r.value, append: r.op === '>>' }] : [];
115
+ }
116
+ if (cmd.name === 'tee') {
117
+ const append = cmd.args.some((a) => a.value === '--append' || /^-[a-zA-Z]*a/.test(a.value));
118
+ return cmd.args.filter((a) => !a.value.startsWith('-')).map((a) => ({ path: a.value, append }));
119
+ }
120
+ return [];
121
+ }
122
+
123
+ /**
124
+ * Split one line into tokens. `word` carries its end offset so `2>file` can be
125
+ * told apart from `2 >file`. Heredoc operators become `heredoc` tokens whose
126
+ * body is filled in by the caller; redirections become `redir` tokens; command
127
+ * separators become `op` tokens.
128
+ */
129
+ function tokenize(line) {
130
+ const toks = [];
131
+ let i = 0;
132
+ while (i < line.length) {
133
+ const c = line[i];
134
+ if (c === ' ' || c === '\t' || c === '\r') { i++; continue; }
135
+ if (c === '#') break; // comment to end of line
136
+ const op = OPS.find((o) => line.startsWith(o, i));
137
+ if (!op) {
138
+ const w = readWord(line, i);
139
+ toks.push({ kind: 'word', value: w.value, end: w.end });
140
+ i = w.end > i ? w.end : i + 1;
141
+ continue;
142
+ }
143
+ const start = i;
144
+ i += op.length;
145
+ if (op === '<<' || op === '<<-') {
146
+ const w = readWord(line, i);
147
+ i = w.end;
148
+ toks.push({ kind: 'heredoc', delim: w.value, strip: op === '<<-', body: null });
149
+ } else if (op === '<<<' || op === '<') {
150
+ i = readWord(line, i).end; // here-string or input redirect: not a write
151
+ } else if (SEPARATORS.has(op)) {
152
+ toks.push({ kind: 'op', op });
153
+ } else {
154
+ // Output redirections. A bare fd number right before the operator (2>, 2>&1) is dropped.
155
+ const prev = toks[toks.length - 1];
156
+ if (prev && prev.kind === 'word' && prev.end === start && /^\d+$/.test(prev.value)) toks.pop();
157
+ const w = readWord(line, i);
158
+ i = w.end;
159
+ if (op === '>&') continue; // fd duplication such as >&2
160
+ toks.push({ kind: 'redir', op: op === '&>' ? '>' : op, value: w.value });
161
+ }
162
+ }
163
+ return toks;
164
+ }
165
+
166
+ /** Read one shell word starting at `i` (skipping leading blanks), removing quotes and backslashes. */
167
+ function readWord(s, i) {
168
+ while (s[i] === ' ' || s[i] === '\t') i++;
169
+ let value = '';
170
+ while (i < s.length) {
171
+ const c = s[i];
172
+ if (c === '"' || c === "'") {
173
+ i++;
174
+ while (i < s.length && s[i] !== c) {
175
+ if (c === '"' && s[i] === '\\' && i + 1 < s.length) { value += s[i + 1]; i += 2; }
176
+ else value += s[i++];
177
+ }
178
+ i++; // closing quote
179
+ continue;
180
+ }
181
+ if (c === '\\' && i + 1 < s.length) { value += s[i + 1]; i += 2; continue; }
182
+ if (BARE.test(c)) break;
183
+ value += c;
184
+ i++;
185
+ }
186
+ return { value, end: i };
187
+ }
@@ -0,0 +1,13 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ export function* walkJsonl(dir, depth = 0) {
5
+ if (depth > 6) return;
6
+ let entries;
7
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
8
+ for (const e of entries) {
9
+ const p = join(dir, e.name);
10
+ if (e.isDirectory()) yield* walkJsonl(p, depth + 1);
11
+ else if (e.isFile() && e.name.endsWith('.jsonl')) yield p;
12
+ }
13
+ }