personal-eval 0.0.0-stage → 0.1.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.
package/src/judge.js ADDED
@@ -0,0 +1,177 @@
1
+ // --judge: have Claude label each follow-up message instead of keyword rules.
2
+ // Uses the local `claude` CLI if present (works with a Claude subscription),
3
+ // otherwise the Anthropic API via ANTHROPIC_API_KEY. Results are cached so
4
+ // re-runs only label new messages.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { LABELS } from './classify.js';
11
+
12
+ const BATCH = 40;
13
+ const CONCURRENCY = 4;
14
+ const CACHE = path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'personal-eval', 'judge-v1.json');
15
+
16
+ const SYSTEM = 'You label developer messages to a coding agent. Output only JSON.';
17
+
18
+ const INSTRUCTIONS = `personal-eval-judge: Each item is the end of a coding agent's reply ("agent") and the developer's next message ("next"). Label the developer's next message with exactly one label:
19
+
20
+ - not_meant: the agent misunderstood the request or did the wrong thing ("no, I meant…", "that's not what I asked", "wrong file")
21
+ - undo: asks to revert, remove or roll back something the agent just did
22
+ - redo: dislikes the result and wants it done again or differently, without saying it's broken ("I don't like it", "try again", "make it cleaner")
23
+ - broken: reports the agent's work doesn't work or is still failing (errors, crashes, "still broken", pasted stack traces)
24
+ - nudge: the agent stopped or replied empty and the developer just prods it on ("continue", "?", "go on")
25
+ - none: anything else, including new tasks, answers to the agent's questions, approvals, and follow-up requests
26
+
27
+ Return {"labels":[{"i":<item index>,"label":"<label>"}]} with one entry per item.
28
+
29
+ Items:
30
+ `;
31
+
32
+ const SCHEMA = {
33
+ type: 'object',
34
+ properties: {
35
+ labels: {
36
+ type: 'array',
37
+ items: {
38
+ type: 'object',
39
+ properties: { i: { type: 'integer' }, label: { type: 'string', enum: LABELS } },
40
+ required: ['i', 'label'],
41
+ additionalProperties: false,
42
+ },
43
+ },
44
+ },
45
+ required: ['labels'],
46
+ additionalProperties: false,
47
+ };
48
+
49
+ function loadCache() {
50
+ try {
51
+ return JSON.parse(fs.readFileSync(CACHE, 'utf8'));
52
+ } catch {
53
+ return {};
54
+ }
55
+ }
56
+ function saveCache(cache) {
57
+ fs.mkdirSync(path.dirname(CACHE), { recursive: true });
58
+ fs.writeFileSync(CACHE, JSON.stringify(cache));
59
+ }
60
+
61
+ const keyOf = (model, t) =>
62
+ crypto.createHash('sha1').update(`${model}\0${t.finalText || ''}\0${t.followUp}`).digest('hex').slice(0, 20);
63
+
64
+ function hasClaudeCli() {
65
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['claude'], { encoding: 'utf8' });
66
+ return r.status === 0 && r.stdout.trim().length > 0;
67
+ }
68
+
69
+ export async function judgeTurns(turns, { model, log, status }) {
70
+ const provider = hasClaudeCli() ? 'cli' : process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN ? 'api' : null;
71
+ if (!provider) {
72
+ log('--judge needs the `claude` CLI (Claude Code) or ANTHROPIC_API_KEY. Falling back to keyword rules.');
73
+ return;
74
+ }
75
+ const modelId = model || (provider === 'api' ? 'claude-opus-5-5' : null);
76
+ const cache = loadCache();
77
+ const cacheModel = modelId || 'cli-default';
78
+ const todo = [];
79
+ for (const t of turns) {
80
+ const k = keyOf(cacheModel, t);
81
+ if (cache[k]) t.label = cache[k];
82
+ else todo.push([k, t]);
83
+ }
84
+ if (!todo.length) return;
85
+
86
+ log(`Labeling ${todo.length} follow-up messages with Claude (${provider === 'cli' ? 'claude CLI' : `API, ${modelId}`}). Only short snippets are sent: the agent reply's last 240 chars and your message's first 360.`);
87
+ const batches = [];
88
+ for (let i = 0; i < todo.length; i += BATCH) batches.push(todo.slice(i, i + BATCH));
89
+ let done = 0;
90
+ let failed = 0;
91
+ const run = async (batch) => {
92
+ const items = batch.map(([, t], i) => ({
93
+ i,
94
+ agent: (t.finalText || '').slice(-240),
95
+ next: String(t.followUp).slice(0, 360),
96
+ }));
97
+ const prompt = INSTRUCTIONS + items.map((x) => JSON.stringify(x)).join('\n');
98
+ try {
99
+ const out = provider === 'cli' ? await callCli(prompt, modelId) : await callApi(prompt, modelId);
100
+ for (const { i, label } of out.labels || []) {
101
+ const entry = batch[i];
102
+ if (!entry || !LABELS.includes(label)) continue;
103
+ entry[1].label = label;
104
+ cache[entry[0]] = label;
105
+ }
106
+ } catch (err) {
107
+ failed++;
108
+ if (failed === 1) log(` judge call failed (${String(err.message || err).slice(0, 200)}); those messages keep their keyword labels.`);
109
+ }
110
+ done += batch.length;
111
+ status(`Labeling follow-ups… ${done}/${todo.length}`);
112
+ };
113
+ const queue = [...batches];
114
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
115
+ while (queue.length) await run(queue.shift());
116
+ }));
117
+ saveCache(cache);
118
+ }
119
+
120
+ function extractJSON(text) {
121
+ const s = String(text || '');
122
+ const a = s.indexOf('{');
123
+ const b = s.lastIndexOf('}');
124
+ if (a < 0 || b < a) throw new Error('no JSON in judge reply');
125
+ return JSON.parse(s.slice(a, b + 1));
126
+ }
127
+
128
+ function callCli(prompt, model) {
129
+ // Strip everything from the user's setup (MCP servers, settings, plugins, slash
130
+ // commands, tools): without this one call can carry hundreds of thousands of tokens.
131
+ const args = [
132
+ '-p', '--no-session-persistence', '--output-format', 'json',
133
+ '--system-prompt', SYSTEM, '--tools', '', '--strict-mcp-config', '--setting-sources', '', '--disable-slash-commands',
134
+ ];
135
+ if (model) args.push('--model', model);
136
+ return new Promise((resolve, reject) => {
137
+ const child = spawn('claude', args, { cwd: os.tmpdir(), stdio: ['pipe', 'pipe', 'pipe'] });
138
+ let out = '';
139
+ let err = '';
140
+ child.stdout.on('data', (d) => (out += d));
141
+ child.stderr.on('data', (d) => (err += d));
142
+ child.on('error', reject);
143
+ child.on('close', (code) => {
144
+ try {
145
+ const d = JSON.parse(out);
146
+ if (d.is_error) return reject(new Error(d.result || 'claude CLI error'));
147
+ resolve(extractJSON(d.result));
148
+ } catch (e) {
149
+ reject(new Error(err.trim() || out.slice(0, 200) || `claude exited ${code}`));
150
+ }
151
+ });
152
+ child.stdin.end(prompt);
153
+ });
154
+ }
155
+
156
+ async function callApi(prompt, model) {
157
+ let Anthropic;
158
+ try {
159
+ ({ default: Anthropic } = await import('@anthropic-ai/sdk'));
160
+ } catch {
161
+ throw new Error('the Anthropic SDK is not installed (npm i @anthropic-ai/sdk)');
162
+ }
163
+ const client = new Anthropic();
164
+ const res = await client.beta.messages.create({
165
+ model,
166
+ max_tokens: 4096,
167
+ system: SYSTEM,
168
+ output_config: { effort: 'low', format: { type: 'json_schema', schema: SCHEMA } },
169
+ messages: [{ role: 'user', content: prompt }],
170
+ // If a safety classifier declines, let the server retry on a fallback model.
171
+ betas: ['server-side-fallback-2026-07-01'],
172
+ fallbacks: 'default',
173
+ });
174
+ if (res.stop_reason === 'refusal') throw new Error('request declined');
175
+ const text = res.content.filter((b) => b.type === 'text').map((b) => b.text).join('');
176
+ return extractJSON(text);
177
+ }
package/src/lines.js ADDED
@@ -0,0 +1,89 @@
1
+ import fs from 'node:fs';
2
+ import zlib from 'node:zlib';
3
+ import { spawn } from 'node:child_process';
4
+
5
+ const HEAD = 512;
6
+ const MAX_LINE = 256 * 1024 * 1024;
7
+
8
+ /**
9
+ * Stream a (possibly zstd-compressed) JSONL file line by line.
10
+ *
11
+ * - Splits on "\n" bytes only. node:readline also splits on U+2028/U+2029,
12
+ * which appear raw inside JSON strings in real agent logs.
13
+ * - Works on Buffers so multi-megabyte lines are joined once, not re-scanned
14
+ * per chunk.
15
+ * - `skip(head)` sees the first 512 bytes of each line; returning true drops the
16
+ * line without decoding the rest (agent logs have huge lines we never need).
17
+ */
18
+ export async function* readLines(file, { skip } = {}) {
19
+ const stream = openStream(file);
20
+ let parts = [];
21
+ let size = 0;
22
+ let skipping = false;
23
+ let decided = false;
24
+
25
+ const decide = (buf) => {
26
+ decided = true;
27
+ skipping = !!(skip && skip(buf.subarray(0, HEAD).toString('utf8')));
28
+ };
29
+
30
+ for await (const chunk of stream) {
31
+ let start = 0;
32
+ let nl;
33
+ while ((nl = chunk.indexOf(10, start)) !== -1) {
34
+ const piece = chunk.subarray(start, nl);
35
+ start = nl + 1;
36
+ if (!parts.length) {
37
+ if (!decided) decide(piece);
38
+ if (!skipping && piece.length) yield piece.toString('utf8');
39
+ } else {
40
+ if (!decided) decide(Buffer.concat([...parts, piece]));
41
+ if (!skipping) {
42
+ parts.push(piece);
43
+ const buf = Buffer.concat(parts, size + piece.length);
44
+ if (buf.length <= MAX_LINE) yield buf.toString('utf8');
45
+ }
46
+ }
47
+ parts = [];
48
+ size = 0;
49
+ skipping = false;
50
+ decided = false;
51
+ }
52
+ if (start < chunk.length) {
53
+ const tail = chunk.subarray(start);
54
+ if (!decided && (size + tail.length >= HEAD)) decide(parts.length ? Buffer.concat([...parts, tail]) : tail);
55
+ if (!skipping) {
56
+ parts.push(tail);
57
+ size += tail.length;
58
+ if (size > MAX_LINE) skipping = true;
59
+ } else if (!parts.length) {
60
+ parts.push(Buffer.alloc(0)); // remember we're mid-line
61
+ }
62
+ }
63
+ }
64
+ if (parts.length && !skipping && size) {
65
+ const buf = Buffer.concat(parts, size);
66
+ if (!decided) decide(buf);
67
+ if (!skipping) yield buf.toString('utf8');
68
+ }
69
+ }
70
+
71
+ function openStream(file) {
72
+ if (!file.endsWith('.zst')) return fs.createReadStream(file, { highWaterMark: 1 << 20 });
73
+ if (typeof zlib.createZstdDecompress === 'function') {
74
+ return fs.createReadStream(file, { highWaterMark: 1 << 20 }).pipe(zlib.createZstdDecompress());
75
+ }
76
+ // Older Node without built-in zstd: fall back to the zstd CLI if present.
77
+ const child = spawn('zstd', ['-dc', file], { stdio: ['ignore', 'pipe', 'ignore'] });
78
+ child.on('error', () => child.stdout.destroy(new Error('zstd not available (needs Node 22.15+ or the zstd CLI)')));
79
+ return child.stdout;
80
+ }
81
+
82
+ /** Parse a JSON line, returning null on failure. */
83
+ export function tryJSON(line) {
84
+ try {
85
+ return JSON.parse(line);
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
package/src/metrics.js ADDED
@@ -0,0 +1,203 @@
1
+ // Score each model on the same dimensions as the table people share:
2
+ // how often you had to correct it, how often its tools failed, and how much of
3
+ // its own code got thrown away. Lower is better on every row.
4
+ import { prettyModel } from './models.js';
5
+
6
+ const CORRECTION = new Set(['not_meant', 'broken', 'undo']);
7
+
8
+ /** Group turns by display model name. */
9
+ export function groupByModel(turns) {
10
+ const groups = new Map();
11
+ for (const t of turns) {
12
+ const name = prettyModel(t.model);
13
+ if (!groups.has(name)) groups.set(name, { name, ids: new Set(), agents: new Set(), turns: [] });
14
+ const g = groups.get(name);
15
+ g.ids.add(t.model);
16
+ g.agents.add(t.agent);
17
+ g.turns.push(t);
18
+ }
19
+ return groups;
20
+ }
21
+
22
+ function stats(turns) {
23
+ const s = {
24
+ turns: turns.length,
25
+ followUps: 0,
26
+ not_meant: 0, undo: 0, redo: 0, broken: 0,
27
+ interactiveFollowUps: 0, interactiveCorrections: 0,
28
+ cancelled: 0,
29
+ edit: 0, editErr: 0, shell: 0, shellErr: 0,
30
+ calls: 0, malformed: 0,
31
+ emptyReplies: 0, replied: 0,
32
+ added: 0, sameTurn: 0, later: 0,
33
+ durations: [],
34
+ sessions: new Set(),
35
+ first: Infinity, last: -Infinity,
36
+ };
37
+ for (const t of turns) {
38
+ s.sessions.add(`${t.agent}:${t.session}`);
39
+ if (t.start != null) {
40
+ s.first = Math.min(s.first, t.start);
41
+ s.last = Math.max(s.last, t.start);
42
+ }
43
+ if (t.cancelled) s.cancelled++;
44
+ s.edit += t.tools.edit;
45
+ s.editErr += t.tools.editErr;
46
+ s.shell += t.tools.shell;
47
+ s.shellErr += t.tools.shellErr;
48
+ s.calls += t.tools.calls;
49
+ s.malformed += t.tools.malformed;
50
+ s.added += t.lines.added;
51
+ s.sameTurn += t.lines.sameTurn;
52
+ s.later += t.lines.later;
53
+ if (t.followUp != null) {
54
+ s.followUps++;
55
+ if (t.label && t.label in s) s[t.label]++;
56
+ if (t.interactive) {
57
+ s.interactiveFollowUps++;
58
+ if (CORRECTION.has(t.label)) s.interactiveCorrections++;
59
+ }
60
+ if (!t.cancelled) {
61
+ s.replied++;
62
+ // The model's last message had no text and no tool call: it just stopped.
63
+ if (t.assistantMsgs > 0 && !t.finalText && !t.endedOnTool) s.emptyReplies++;
64
+ }
65
+ }
66
+ if (!t.cancelled && t.assistantMsgs > 0 && t.end != null && t.start != null) {
67
+ const d = (t.end - t.start) / 1000;
68
+ if (d >= 0 && d < 6 * 3600) s.durations.push(d);
69
+ }
70
+ }
71
+ return s;
72
+ }
73
+
74
+ const pct = (n, d, digits = 1) => {
75
+ const v = (100 * n) / d;
76
+ if (n > 0 && v < 10 ** -digits) return `<${(10 ** -digits).toFixed(digits)}%`;
77
+ return `${v.toFixed(digits)}%`;
78
+ };
79
+ const ratio = (n, d) => (n === 0 ? `0/${d}` : `${n}/${d} (${pct(n, d)})`);
80
+ const countRate = (n, d) => (n === 0 ? '0' : `${n} (${pct(n, d, (100 * n) / d < 1 ? 2 : 1)})`);
81
+
82
+ function median(xs) {
83
+ if (!xs.length) return null;
84
+ const a = [...xs].sort((x, y) => x - y);
85
+ const mid = a.length >> 1;
86
+ return a.length % 2 ? a[mid] : (a[mid - 1] + a[mid]) / 2;
87
+ }
88
+
89
+ function fmtDuration(sec) {
90
+ if (sec == null) return '–';
91
+ if (sec < 600) return `${Math.round(sec)} s`;
92
+ if (sec < 7200) return `${(sec / 60).toFixed(1)} min`;
93
+ return `${(sec / 3600).toFixed(1)} h`;
94
+ }
95
+
96
+ /** Row definitions, in the order of the original table. */
97
+ const ROWS = [
98
+ { label: '"Not what I meant" follow-ups', n: 'not_meant', d: 'followUps', fmt: ratio },
99
+ { label: '"Undo / remove that" follow-ups', n: 'undo', d: 'followUps', fmt: ratio },
100
+ { label: '"Don\'t like it, redo" follow-ups', n: 'redo', d: 'followUps', fmt: ratio },
101
+ { label: '"It\'s broken / still broken" follow-ups', n: 'broken', d: 'followUps', fmt: ratio },
102
+ {
103
+ label: 'Intent + broken + undo, interactive work only',
104
+ n: 'interactiveCorrections', d: 'interactiveFollowUps',
105
+ fmt: (n, d) => pct(n, d, 0),
106
+ },
107
+ { label: 'Turns you cancelled', n: 'cancelled', d: 'turns', fmt: ratio },
108
+ { label: 'Failed file edits', n: 'editErr', d: 'edit', fmt: ratio },
109
+ { label: 'Failed shell commands', n: 'shellErr', d: 'shell', fmt: ratio },
110
+ { label: 'Empty replies needing a nudge', n: 'emptyReplies', d: 'replied', fmt: countRate },
111
+ { label: 'Malformed tool calls', n: 'malformed', d: 'calls', fmt: countRate },
112
+ { label: 'Own lines rewritten within the same turn', n: 'sameTurn', d: 'added', fmt: (n, d) => pct(n, d) },
113
+ { label: 'Own lines removed in a later turn', n: 'later', d: 'added', fmt: (n, d) => pct(n, d) },
114
+ { label: 'Median turn duration', duration: true },
115
+ ];
116
+
117
+ /**
118
+ * Two-proportion z-test p-value (two-sided). Used by --strict to call a row a
119
+ * tie when the gap could be noise.
120
+ */
121
+ function pTwoProp(n1, d1, n2, d2) {
122
+ if (!d1 || !d2) return 1;
123
+ const p = (n1 + n2) / (d1 + d2);
124
+ const se = Math.sqrt(p * (1 - p) * (1 / d1 + 1 / d2));
125
+ if (!se) return n1 / d1 === n2 / d2 ? 1 : 0;
126
+ const z = Math.abs(n1 / d1 - n2 / d2) / se;
127
+ return 2 * (1 - normCdf(z));
128
+ }
129
+ function normCdf(z) {
130
+ // Abramowitz–Stegun 7.1.26
131
+ const t = 1 / (1 + 0.3275911 * (z / Math.SQRT2));
132
+ const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-(z * z) / 2);
133
+ return 0.5 * (1 + y);
134
+ }
135
+
136
+ /**
137
+ * Build the scorecard for the chosen models.
138
+ * @returns {{ columns: string[], rows: {label, cells, edge, winner}[], summary, meta }}
139
+ */
140
+ export function scorecard(groups, names, { strict = false, minSample = 1 } = {}) {
141
+ const S = names.map((n) => stats(groups.get(n).turns));
142
+ const edges = new Map(names.map((n) => [n, 0]));
143
+ let ties = 0;
144
+ const rows = [];
145
+
146
+ for (const row of ROWS) {
147
+ let values;
148
+ let cells;
149
+ if (row.duration) {
150
+ values = S.map((s) => median(s.durations));
151
+ cells = values.map(fmtDuration);
152
+ } else {
153
+ values = S.map((s) => (s[row.d] >= minSample && s[row.d] > 0 ? s[row.n] / s[row.d] : null));
154
+ cells = S.map((s, i) => (values[i] == null ? '–' : row.fmt(s[row.n], s[row.d])));
155
+ }
156
+ const valid = values.map((v, i) => [v, i]).filter(([v]) => v != null);
157
+ let edge = '–';
158
+ let winner = null;
159
+ if (valid.length >= 2) {
160
+ valid.sort((a, b) => a[0] - b[0]);
161
+ const [best, bi] = valid[0];
162
+ const [second, si] = valid[1];
163
+ let tie = best === second || cells[bi] === cells[si];
164
+ if (!tie && strict) {
165
+ if (row.duration) tie = second > 0 && (second - best) / second < 0.1;
166
+ else tie = pTwoProp(S[bi][row.n], S[bi][row.d], S[si][row.n], S[si][row.d]) >= 0.05;
167
+ }
168
+ if (tie) {
169
+ edge = 'Tie';
170
+ ties++;
171
+ } else {
172
+ winner = names[bi];
173
+ edge = winner;
174
+ edges.set(winner, edges.get(winner) + 1);
175
+ }
176
+ }
177
+ rows.push({ label: row.label, cells, edge, winner });
178
+ }
179
+
180
+ // Overall winner row.
181
+ const ranked = [...edges.entries()].sort((a, b) => b[1] - a[1]);
182
+ const plural = (n) => `${n} edge${n === 1 ? '' : 's'}`;
183
+ const cells = names.map((n) => `${plural(edges.get(n))}${ties && ranked[0][0] === n ? `, ${ties} tie${ties === 1 ? '' : 's'}` : ''}`);
184
+ let verdict = 'Tie';
185
+ if (names.length >= 2 && ranked[0][1] > ranked[1][1]) {
186
+ const margin = ranked[0][1] - ranked[1][1];
187
+ verdict = margin <= 2 ? `${ranked[0][0]}, narrowly` : ranked[0][0];
188
+ }
189
+ if (names.length === 1) verdict = '–';
190
+ rows.push({ label: 'Overall winner', cells, edge: verdict, winner: verdict === 'Tie' ? null : ranked[0][0], overall: true });
191
+
192
+ const meta = names.map((n, i) => ({
193
+ name: n,
194
+ ids: [...groups.get(n).ids],
195
+ agents: [...groups.get(n).agents],
196
+ turns: S[i].turns,
197
+ sessions: S[i].sessions.size,
198
+ followUps: S[i].followUps,
199
+ first: Number.isFinite(S[i].first) ? S[i].first : null,
200
+ last: Number.isFinite(S[i].last) ? S[i].last : null,
201
+ }));
202
+ return { columns: names, rows, meta, single: names.length === 1 };
203
+ }
package/src/models.js ADDED
@@ -0,0 +1,42 @@
1
+ // Turn raw model ids into the short names people use: "claude-opus-5-5" -> "Opus 5.5".
2
+
3
+ const SPECIAL = { gpt: 'GPT', o: 'o' };
4
+
5
+ export function prettyModel(id) {
6
+ if (!id) return 'unknown';
7
+ let s = String(id).trim();
8
+ s = s.replace(/^.*\//, ''); // provider prefixes: anthropic/, openai/, models/, …
9
+ s = s.replace(/^(us|eu|apac|global)\.anthropic\./, '').replace(/^anthropic\./, '');
10
+ s = s.replace(/-v\d+(:\d+)?$/, ''); // bedrock "-v1:0"
11
+ s = s.replace(/-\d{8}$/, '').replace(/@\d{8}$/, '').replace(/-latest$/, '');
12
+
13
+ // Claude: claude-opus-5-5, claude-3-5-sonnet, claude-sonnet-4-5, claude-haiku-5-5
14
+ let m = s.match(/^claude-(opus|sonnet|haiku|fable|mythos|instant)-(\d+)(?:[-.](\d))?(?:-(.+))?$/i);
15
+ if (m) return `${cap(m[1])} ${m[2]}${m[3] ? `.${m[3]}` : ''}${m[4] ? ` ${words(m[4])}` : ''}`;
16
+ m = s.match(/^claude-(\d+)(?:[-.](\d))?-(opus|sonnet|haiku)$/i);
17
+ if (m) return `${cap(m[3])} ${m[1]}${m[2] ? `.${m[2]}` : ''}`;
18
+
19
+ // OpenAI: gpt-6.1-sol, gpt-5-codex, o3-pro
20
+ m = s.match(/^gpt-([\d.]+o?)(?:-(.+))?$/i);
21
+ if (m) return `GPT-${m[1]}${m[2] ? ` ${words(m[2])}` : ''}`;
22
+ m = s.match(/^(o\d)(?:-(.+))?$/i);
23
+ if (m) return `${m[1]}${m[2] ? ` ${words(m[2])}` : ''}`;
24
+
25
+ // Gemini: gemini-3-pro-preview, gemini-2.5-flash
26
+ m = s.match(/^gemini-(.+)$/i);
27
+ if (m) return `Gemini ${words(m[1])}`;
28
+
29
+ return words(s);
30
+ }
31
+
32
+ function cap(w) {
33
+ return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
34
+ }
35
+
36
+ function words(rest) {
37
+ return rest
38
+ .split(/[-_\s]+/)
39
+ .filter(Boolean)
40
+ .map((w) => (SPECIAL[w.toLowerCase()] ? SPECIAL[w.toLowerCase()] : /^\d/.test(w) ? w : cap(w)))
41
+ .join(' ');
42
+ }
@@ -0,0 +1,93 @@
1
+ // Parse every session file in parallel worker threads and return compact turns.
2
+ import os from 'node:os';
3
+ import fs from 'node:fs';
4
+ import { Worker, isMainThread, parentPort } from 'node:worker_threads';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { READERS, getReader } from './readers/index.js';
7
+ import { buildTurns } from './turns.js';
8
+ import { classifyFollowUp } from './classify.js';
9
+
10
+ const SELF = fileURLToPath(import.meta.url);
11
+
12
+ /** Parse one unit (file or session dir) into turns with heuristic labels. */
13
+ export async function parseUnit(agent, unit) {
14
+ const sessions = await getReader(agent).parse(unit);
15
+ const turns = [];
16
+ for (const s of sessions) {
17
+ for (const t of buildTurns(s)) {
18
+ t.label = t.followUp != null ? classifyFollowUp(t.followUp) : null;
19
+ turns.push(t);
20
+ }
21
+ }
22
+ return turns;
23
+ }
24
+
25
+ export async function discoverAll(agents) {
26
+ const units = [];
27
+ for (const id of agents) {
28
+ const reader = READERS[id];
29
+ if (!reader) continue;
30
+ for (const unit of await reader.discover()) {
31
+ let size = 0;
32
+ try {
33
+ size = fs.statSync(unit).size;
34
+ } catch {}
35
+ units.push({ agent: id, unit, size });
36
+ }
37
+ }
38
+ return units;
39
+ }
40
+
41
+ /**
42
+ * Run parseUnit over all units with a worker pool.
43
+ * @param {{agent, unit, size}[]} units
44
+ * @param {(done:number,total:number)=>void} onProgress
45
+ */
46
+ export async function parseAll(units, onProgress = () => {}) {
47
+ const queue = [...units].sort((a, b) => b.size - a.size); // big files first for balance
48
+ const total = queue.length;
49
+ const n = Math.max(1, Math.min((os.availableParallelism?.() ?? os.cpus().length) - 1, 8, total));
50
+ const results = [];
51
+ const errors = [];
52
+ let done = 0;
53
+
54
+ await Promise.all(
55
+ Array.from({ length: n }, () =>
56
+ new Promise((resolve) => {
57
+ const worker = new Worker(SELF);
58
+ const next = () => {
59
+ const job = queue.shift();
60
+ if (!job) {
61
+ worker.terminate().then(resolve);
62
+ return;
63
+ }
64
+ worker.current = job;
65
+ worker.postMessage(job);
66
+ };
67
+ worker.on('message', (msg) => {
68
+ if (msg.error) errors.push({ unit: worker.current.unit, error: msg.error });
69
+ else for (const t of msg.turns) results.push(t);
70
+ onProgress(++done, total);
71
+ next();
72
+ });
73
+ worker.on('error', (err) => {
74
+ errors.push({ unit: worker.current?.unit, error: String(err?.message || err) });
75
+ onProgress(++done, total);
76
+ resolve();
77
+ });
78
+ next();
79
+ }),
80
+ ),
81
+ );
82
+ return { turns: results, errors };
83
+ }
84
+
85
+ if (!isMainThread && parentPort) {
86
+ parentPort.on('message', async ({ agent, unit }) => {
87
+ try {
88
+ parentPort.postMessage({ turns: await parseUnit(agent, unit) });
89
+ } catch (err) {
90
+ parentPort.postMessage({ error: String(err?.message || err) });
91
+ }
92
+ });
93
+ }