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/text.js ADDED
@@ -0,0 +1,204 @@
1
+ // Shared text helpers: telling human prompts from harness-injected messages,
2
+ // tool-kind detection, and line extraction for edit tracking.
3
+
4
+ /** Messages that look like user turns but were written by the harness. */
5
+ const HARNESS_PREFIXES = [
6
+ '<task-notification>',
7
+ '<system-reminder>',
8
+ '<local-command-stdout>',
9
+ '<local-command-stderr>',
10
+ '<local-command-caveat>',
11
+ '<bash-input>',
12
+ '<bash-stdout>',
13
+ '<bash-stderr>',
14
+ '<user-prompt-submit-hook>',
15
+ '<fork-boilerplate>',
16
+ '<turn_aborted>',
17
+ '<user_shell_command>',
18
+ '<subagent_notification>',
19
+ '<heartbeat>',
20
+ '<automation',
21
+ 'Caveat: The messages below were generated',
22
+ 'This session is being continued from a previous conversation',
23
+ 'Base directory for this skill:',
24
+ '[SYSTEM NOTIFICATION',
25
+ 'Your response above was cut off',
26
+ 'Your response above was stopped',
27
+ '[Request interrupted by user',
28
+ 'Continue where you left off.',
29
+ 'Continue from where you left off.',
30
+ 'personal-eval-judge:',
31
+ ];
32
+
33
+ /** Wrapper blocks harnesses prepend to the real prompt; stripped before deciding. */
34
+ const WRAPPER_BLOCKS = [
35
+ 'system_instruction',
36
+ 'system-instruction',
37
+ 'environment_context',
38
+ 'user_instructions',
39
+ 'INSTRUCTIONS',
40
+ 'permissions instructions',
41
+ 'collaboration_mode',
42
+ 'skill',
43
+ 'system-reminder',
44
+ 'ide_selection',
45
+ 'ide_opened_file',
46
+ 'in-app-browser-context',
47
+ 'app-context',
48
+ ];
49
+
50
+ const WRAPPER_RE = new RegExp(
51
+ `<(${WRAPPER_BLOCKS.map((t) => t.replace(/[-]/g, '\\-')).join('|')})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,
52
+ 'g',
53
+ );
54
+
55
+ /**
56
+ * Return the human-written part of a user message, or null if the message
57
+ * was injected by the harness (tool output, notifications, skill bodies…).
58
+ */
59
+ export function humanText(raw) {
60
+ if (typeof raw !== 'string') return null;
61
+ let text = raw.replace(WRAPPER_RE, '').trim();
62
+ // Codex prepends AGENTS.md contents as a heading block.
63
+ if (/^# AGENTS\.md instructions for /.test(text)) return null;
64
+ if (!text) return null;
65
+ for (const p of HARNESS_PREFIXES) if (text.startsWith(p)) return null;
66
+ // Answers to the agent's multiple-choice questions: keep just what the user picked.
67
+ const reply = text.match(/^<send_user_message_question_reply>([\s\S]*)<\/send_user_message_question_reply>$/);
68
+ if (reply) {
69
+ let answers = [];
70
+ try {
71
+ answers = JSON.parse(reply[1].trim()).map((a) => a?.answer).filter(Boolean);
72
+ } catch {}
73
+ return answers.length ? answers.join('\n') : null;
74
+ }
75
+ // Anything else that is one machine-written tag block (e.g. <foo>…</foo>) isn't typed by a person.
76
+ if (/^<([A-Za-z][\w-]*)(\s[^>]*)?>[\s\S]*<\/\1>$/.test(text) && !/^<command-/.test(text)) return null;
77
+ // Slash commands are human-initiated; keep the command and its args.
78
+ const cmd = text.match(/<command-name>([^<]*)<\/command-name>/);
79
+ if (cmd) {
80
+ const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/);
81
+ text = `${cmd[1].trim()} ${args ? args[1].trim() : ''}`.trim();
82
+ }
83
+ // Pasted images are rendered as "[Image: …]" placeholders.
84
+ text = text.replace(/\[Image[^\]]*\]/g, '').trim();
85
+ return text || '[image]';
86
+ }
87
+
88
+ export function isInterruptText(raw) {
89
+ return typeof raw === 'string' && /^\s*\[Request interrupted by user/.test(raw);
90
+ }
91
+
92
+ const SHELL_TOOLS = new Set([
93
+ 'bash', 'shell', 'run_shell_command', 'exec_command', 'local_shell', 'local_shell_call',
94
+ 'powershell', 'terminal', 'run_terminal_cmd', 'execute_command', 'run_command', 'container.exec',
95
+ ]);
96
+ const EDIT_TOOLS = new Set([
97
+ 'edit', 'multiedit', 'write', 'notebookedit', 'str_replace_based_edit_tool', 'str_replace_editor',
98
+ 'apply_patch', 'replace', 'write_file', 'edit_file', 'create_file', 'patch', 'search_replace',
99
+ 'multi_edit', 'write_to_file', 'replace_in_file',
100
+ ]);
101
+
102
+ export function toolKind(name) {
103
+ const n = String(name || '').toLowerCase();
104
+ if (SHELL_TOOLS.has(n)) return 'shell';
105
+ if (EDIT_TOOLS.has(n)) return 'edit';
106
+ return 'other';
107
+ }
108
+
109
+ const REJECTED_RE =
110
+ /doesn't want to proceed|tool use was rejected|user (rejected|denied|declined)|rejected by (the )?user|permission denied by (the )?user|was blocked by the user|user cancelled|aborted by user|operation was cancelled/i;
111
+ const MALFORMED_RE =
112
+ /InputValidationError|Invalid tool parameters|No such tool available|is not a valid tool|unknown tool|tool .* not found|failed to parse (function |tool )?(call )?arguments|unsupported call|invalid (tool )?(arguments|params|parameters|input)\b|missing (required )?(field|parameter|argument)|unexpected (field|parameter|argument)|invalid json|params must have required property|must NOT have additional properties/i;
113
+
114
+ /** Classify a tool result that the harness flagged as an error. */
115
+ export function classifyToolError(text) {
116
+ const t = String(text || '').slice(0, 2000);
117
+ if (REJECTED_RE.test(t)) return 'rejected';
118
+ if (MALFORMED_RE.test(t)) return 'malformed';
119
+ return 'error';
120
+ }
121
+
122
+ export function isMalformedText(text) {
123
+ return MALFORMED_RE.test(String(text || '').slice(0, 2000));
124
+ }
125
+ export function isRejectedText(text) {
126
+ return REJECTED_RE.test(String(text || '').slice(0, 2000));
127
+ }
128
+
129
+ /** Lines worth tracking for churn: skip blanks and lone punctuation like "}" or ");". */
130
+ export function meaningfulLines(text) {
131
+ if (typeof text !== 'string' || !text) return [];
132
+ const out = [];
133
+ for (const line of text.split('\n')) {
134
+ const t = line.trim();
135
+ if (t.length < 3) continue;
136
+ if (!/[A-Za-z0-9]/.test(t)) continue;
137
+ out.push(t);
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /**
143
+ * Turn a before/after pair into the lines actually removed and added,
144
+ * cancelling unchanged lines (multiset difference).
145
+ */
146
+ export function diffLines(before, after) {
147
+ const a = meaningfulLines(before);
148
+ const b = meaningfulLines(after);
149
+ const counts = new Map();
150
+ for (const l of a) counts.set(l, (counts.get(l) || 0) + 1);
151
+ const added = [];
152
+ for (const l of b) {
153
+ const c = counts.get(l) || 0;
154
+ if (c > 0) counts.set(l, c - 1);
155
+ else added.push(l);
156
+ }
157
+ const removed = [];
158
+ for (const [l, c] of counts) for (let i = 0; i < c; i++) removed.push(l);
159
+ return { removed, added };
160
+ }
161
+
162
+ /** Parse a unified diff body ("@@ … @@", "+x", "-y") into removed/added lines. */
163
+ export function unifiedDiffLines(diff) {
164
+ const minus = [];
165
+ const plus = [];
166
+ for (const line of String(diff || '').split('\n')) {
167
+ if (line.startsWith('+++') || line.startsWith('---')) continue;
168
+ if (line.startsWith('+')) plus.push(line.slice(1));
169
+ else if (line.startsWith('-')) minus.push(line.slice(1));
170
+ }
171
+ return diffLines(minus.join('\n'), plus.join('\n'));
172
+ }
173
+
174
+ /**
175
+ * Parse an apply_patch envelope ("*** Begin Patch / *** Update File: …") into
176
+ * per-file edits.
177
+ */
178
+ export function applyPatchEdits(patch) {
179
+ const edits = [];
180
+ let cur = null;
181
+ for (const line of String(patch || '').split('\n')) {
182
+ const m = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/);
183
+ if (m) {
184
+ cur = { path: m[2].trim(), op: m[1].toLowerCase(), minus: [], plus: [] };
185
+ edits.push(cur);
186
+ continue;
187
+ }
188
+ if (!cur || line.startsWith('***') || line.startsWith('@@')) continue;
189
+ if (line.startsWith('+')) cur.plus.push(line.slice(1));
190
+ else if (line.startsWith('-')) cur.minus.push(line.slice(1));
191
+ }
192
+ return edits.map((e) =>
193
+ e.op === 'delete'
194
+ ? { path: e.path, mode: 'delete', removed: [], added: [] }
195
+ : { path: e.path, mode: 'patch', ...diffLines(e.minus.join('\n'), e.plus.join('\n')) },
196
+ );
197
+ }
198
+
199
+ export function toMs(ts) {
200
+ if (ts == null) return null;
201
+ if (typeof ts === 'number') return ts < 1e12 ? ts * 1000 : ts;
202
+ const n = Date.parse(ts);
203
+ return Number.isFinite(n) ? n : null;
204
+ }
package/src/turns.js ADDED
@@ -0,0 +1,157 @@
1
+ // Group a session's normalized events into turns and attribute everything
2
+ // (tool outcomes, line churn, the user's next message) to the model that ran it.
3
+ //
4
+ // Normalized events produced by every reader:
5
+ // { type: 'prompt', t, text, key } a real human message
6
+ // { type: 'interrupt', t } the user stopped the agent
7
+ // { type: 'assistant', t, model, text, tools } one assistant message
8
+ // { type: 'tool', t, model, name, kind: 'shell'|'edit'|'other',
9
+ // status: 'ok'|'error'|'rejected'|'malformed', edits?: [{path, mode, removed, added}] }
10
+
11
+ const MAX_TEXT = 600;
12
+ const BULK_LINES = 500;
13
+
14
+ export function buildTurns(session) {
15
+ const turns = [];
16
+ let cur = null;
17
+ let lastModel = null;
18
+ const tracked = new Map(); // path -> Map(line -> [turnIndex, …])
19
+
20
+ const close = () => {
21
+ if (!cur) return;
22
+ // A prompt the agent never answered (the user sent two messages back to back) isn't a turn.
23
+ if (!cur.assistantMsgs && !cur.tools.calls && !cur.cancelled) {
24
+ cur = null;
25
+ return;
26
+ }
27
+ let best = null;
28
+ let bestN = 0;
29
+ for (const [m, n] of cur.modelCounts) if (n > bestN) [best, bestN] = [m, n];
30
+ cur.model = best || lastModel;
31
+ delete cur.modelCounts;
32
+ turns.push(cur);
33
+ };
34
+
35
+ for (const ev of session.events) {
36
+ if (ev.type === 'prompt') {
37
+ if (cur) cur.followUp = ev.text.slice(0, MAX_TEXT);
38
+ close();
39
+ cur = {
40
+ key: ev.key,
41
+ agent: session.agent,
42
+ session: session.id,
43
+ cwd: session.cwd,
44
+ start: ev.t,
45
+ end: ev.t,
46
+ prompt: ev.text.slice(0, 200),
47
+ followUp: null,
48
+ finalText: null,
49
+ endedOnTool: false,
50
+ cancelled: false,
51
+ modelCounts: new Map(),
52
+ assistantMsgs: 0,
53
+ tools: { calls: 0, shell: 0, shellErr: 0, edit: 0, editErr: 0, malformed: 0, rejected: 0 },
54
+ lines: { added: 0, sameTurn: 0, later: 0 },
55
+ };
56
+ continue;
57
+ }
58
+ if (!cur) continue; // activity before the first human prompt (e.g. a resumed tail)
59
+
60
+ if (ev.type === 'interrupt') {
61
+ cur.cancelled = true;
62
+ continue;
63
+ }
64
+ if (ev.model) {
65
+ cur.modelCounts.set(ev.model, (cur.modelCounts.get(ev.model) || 0) + 1);
66
+ lastModel = ev.model;
67
+ }
68
+ if (ev.t != null && (cur.end == null || ev.t > cur.end)) cur.end = ev.t;
69
+
70
+ if (ev.type === 'assistant') {
71
+ cur.assistantMsgs++;
72
+ // The reply the user saw last: text of the final assistant message ('' if empty/tool-only).
73
+ cur.finalText = (ev.text || '').trim().slice(-MAX_TEXT);
74
+ cur.endedOnTool = ev.tools > 0;
75
+ continue;
76
+ }
77
+ if (ev.type === 'tool') {
78
+ cur.endedOnTool = true;
79
+ const tl = cur.tools;
80
+ if (ev.status === 'malformed') {
81
+ tl.malformed++;
82
+ tl.calls++;
83
+ continue;
84
+ }
85
+ if (ev.status === 'rejected') {
86
+ tl.rejected++;
87
+ continue;
88
+ }
89
+ tl.calls++;
90
+ if (ev.kind === 'shell') {
91
+ tl.shell++;
92
+ if (ev.status === 'error') tl.shellErr++;
93
+ } else if (ev.kind === 'edit') {
94
+ tl.edit++;
95
+ if (ev.status === 'error') tl.editErr++;
96
+ }
97
+ if (ev.edits) for (const e of ev.edits) trackEdit(tracked, e, turns, turns.length, cur);
98
+ }
99
+ }
100
+ close();
101
+
102
+ const prompts = turns.length;
103
+ for (const t of turns) t.interactive = prompts >= 2;
104
+ return turns.filter((t) => t.model);
105
+ }
106
+
107
+ function trackEdit(tracked, edit, turns, curIndex, cur) {
108
+ if (!edit?.path) return;
109
+ let file = tracked.get(edit.path);
110
+ if (!file) tracked.set(edit.path, (file = new Map()));
111
+
112
+ let removed = edit.removed || [];
113
+ let added = edit.added || [];
114
+ if (edit.mode === 'delete') {
115
+ removed = [];
116
+ for (const [line, owners] of file) for (let i = 0; i < owners.length; i++) removed.push(line);
117
+ added = [];
118
+ } else if (edit.mode === 'write') {
119
+ // Whole-file write with unknown prior content: diff against what we tracked.
120
+ const next = new Map();
121
+ for (const l of added) next.set(l, (next.get(l) || 0) + 1);
122
+ const rm = [];
123
+ for (const [line, owners] of file) {
124
+ const keep = next.get(line) || 0;
125
+ for (let i = keep; i < owners.length; i++) rm.push(line);
126
+ }
127
+ const ad = [];
128
+ const have = new Map();
129
+ for (const [line, owners] of file) have.set(line, owners.length);
130
+ for (const l of added) {
131
+ const h = have.get(l) || 0;
132
+ if (h > 0) have.set(l, h - 1);
133
+ else ad.push(l);
134
+ }
135
+ removed = rm;
136
+ added = ad;
137
+ }
138
+
139
+ for (const line of removed) {
140
+ const owners = file.get(line);
141
+ if (!owners || !owners.length) continue;
142
+ const owner = owners.pop();
143
+ if (!owners.length) file.delete(line);
144
+ const target = owner === curIndex ? cur : turns[owner];
145
+ if (!target) continue;
146
+ if (owner === curIndex) target.lines.sameTurn++;
147
+ else target.lines.later++;
148
+ }
149
+ // Bulk writes (generated code, fixtures, data files) would swamp the ratio; don't track them.
150
+ if (added.length > BULK_LINES) return;
151
+ for (const line of added) {
152
+ let owners = file.get(line);
153
+ if (!owners) file.set(line, (owners = []));
154
+ owners.push(curIndex);
155
+ cur.lines.added++;
156
+ }
157
+ }