@oathe/oathe 0.3.2 → 0.4.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.
Files changed (56) hide show
  1. package/README.md +42 -12
  2. package/assets/oathe-hero.png +0 -0
  3. package/bin/node-floor.mjs +16 -0
  4. package/bin/oathe.mjs +78 -134
  5. package/docs/PRIVACY.md +7 -6
  6. package/notch/Oathe Notch.app/Contents/Info.plist +1 -1
  7. package/notch/Oathe Notch.app/Contents/MacOS/OatheNotch +0 -0
  8. package/notch/README.md +33 -18
  9. package/package.json +9 -5
  10. package/plugin/.claude-plugin/plugin.json +2 -2
  11. package/plugin/.cursor-plugin/plugin.json +2 -2
  12. package/plugin/commands/verify.md +6 -5
  13. package/plugin/hooks/heartbeat.mjs +14 -5
  14. package/plugin/hooks/hooks.json +1 -1
  15. package/plugin/hooks/lib.mjs +7 -5
  16. package/plugin/hooks/render-board.mjs +3 -3
  17. package/plugin/skills/oathe-work/SKILL.md +4 -1
  18. package/src/activation.mjs +3 -0
  19. package/src/atif.mjs +182 -348
  20. package/src/board-render.mjs +46 -42
  21. package/src/breach-digest.mjs +183 -0
  22. package/src/config.mjs +15 -3
  23. package/src/context.mjs +1 -1
  24. package/src/doctor.mjs +30 -8
  25. package/src/evidence.mjs +153 -0
  26. package/src/harnesses/catalog.mjs +12 -1
  27. package/src/harnesses/claude-roster.mjs +49 -0
  28. package/src/harnesses/claude-transcript.mjs +174 -0
  29. package/src/harnesses/claude.mjs +35 -2
  30. package/src/harnesses/codex-rollout.mjs +610 -0
  31. package/src/harnesses/codex-roster.mjs +88 -0
  32. package/src/harnesses/codex.mjs +72 -2
  33. package/src/harnesses/cursor.mjs +10 -8
  34. package/src/harnesses/fidelity.mjs +123 -0
  35. package/src/init.mjs +5 -1
  36. package/src/launch-env.mjs +5 -5
  37. package/src/launch.mjs +5 -6
  38. package/src/manifest.mjs +35 -0
  39. package/src/mcp/connection.mjs +9 -7
  40. package/src/mcp/oathe-tools.mjs +135 -75
  41. package/src/node-floor.mjs +44 -0
  42. package/src/notch-frame.mjs +152 -0
  43. package/src/oathe-annotator.mjs +113 -0
  44. package/src/pager.mjs +75 -37
  45. package/src/runtime/provider.mjs +2 -2
  46. package/src/session-host.mjs +1 -1
  47. package/src/sessions.mjs +8 -1
  48. package/src/speaker.mjs +54 -26
  49. package/src/statements.mjs +120 -2
  50. package/src/substrate.mjs +3 -3
  51. package/src/successor.mjs +2 -3
  52. package/src/trace-census.mjs +96 -0
  53. package/src/traces.mjs +98 -6
  54. package/src/uninstall.mjs +4 -1
  55. package/src/verifier.mjs +37 -19
  56. package/assets/oathe-hero.svg +0 -92
@@ -0,0 +1,610 @@
1
+ // The codex rollout projection — ALL codex trace-format knowledge lives here, beside its
2
+ // adapter (R-HARNESS-TOUCHPOINTS), routed by the declared roster in codex-roster.mjs.
3
+ // Format facts, measured on live rollouts (codex CLI 0.149–0.150, 2026-08-31/09-01):
4
+ // - custom_tool_call carries the command as a STRING OF JS SOURCE in payload.input
5
+ // (`const r = await tools.exec_command({cmd:"…"})`, bare object keys) — the raw source
6
+ // is ground truth; projection recovers the inner tool and its arguments, and falls back
7
+ // to the raw source itself, never to `{}` and never to a refusal on readable content.
8
+ // - token_count nests under payload.info.last_token_usage (the per-turn delta;
9
+ // total_token_usage is cumulative and summing it would double-count). A token_count
10
+ // CLOSES one model API call — the reference converter's partition (Harbor codex.py,
11
+ // finish_api_call) — so it is the step boundary wherever the file carries one with
12
+ // usage; `info: null` is a documented vendor state (Harbor #970): the call happened,
13
+ // its usage is unknown — counted, never zeros, never a refusal.
14
+ // - reasoning rows are encrypted — no readable text. In a file with no usage-bearing
15
+ // token_count they mark an LLM response and stay the boundary (a user-message-only
16
+ // boundary would merge 18 calls into one step). ONE boundary per file, chosen
17
+ // by the file's own evidence and declared in extra.record.step_boundary.
18
+ // - the item stream (event_msg item_completed, row order call → item → output →
19
+ // token_count) is the vendor's own decode of what the exec source wraps: an item's id is
20
+ // its own (exec-<uuid>), so a CommandExecution/McpToolCall/FileChange completes the call
21
+ // in the current turn still awaiting its output whose arguments agree; SubAgentActivity's
22
+ // id IS the spawn call's; Extension (web.search) has no response_item counterpart at all.
23
+ // Items ENRICH — a structural exit code, a recovered MCP call, the files a patch changed,
24
+ // the thread a spawn started — and never make a step of their own except Extension.
25
+ // - role 'developer' rows are INJECTED instructions (permissions, board text) — system
26
+ // voice, never the agent's own words.
27
+ // - the inter-agent bus: an ADDRESSED agent_message (author/recipient agent paths, a typed
28
+ // first line) is never this agent's SAID. From an ancestor (the delegated brief — its
29
+ // payload encrypted; the plaintext brief is the child's own first user row) it is a USER
30
+ // step, the harness converters' shape for a delegated prompt; otherwise (a child's answer)
31
+ // a SYSTEM step, llm_call_count 0, whose observation carries the message and a ref to the
32
+ // embedded child — resolved by the author's agent_path through the spawn items or the
33
+ // thread index; unresolvable → counted in extra.record.unresolved_inbound, never invented.
34
+ // - function_call may carry a namespace (`collaboration` + `spawn_agent`, MCP forms with a
35
+ // leading-underscore name) that composes into the function name.
36
+
37
+ import { AtifProjector, AtifError, textOf } from '../atif.mjs';
38
+ import { TraceContractError } from '../traces.mjs';
39
+ import { CODEX_ROLLOUT_ROSTER, CODEX_ROOT_AGENT_PATH, INTER_AGENT_MESSAGE_TYPE, codexKindOf } from './codex-roster.mjs';
40
+
41
+ /**
42
+ * Reads the inner `tools.<name>(…)` calls out of a custom_tool_call's JS source. A balanced
43
+ * scanner (string-aware), never a bare regex over the argument text — real commands contain
44
+ * quotes, parens, and escapes. Argument literals use bare object keys; parsing quotes them
45
+ * outside strings and falls back to null (the caller keeps the raw source) when the literal
46
+ * is not data.
47
+ */
48
+ export class ExecCallReader {
49
+ /** @returns {Array<{tool: string, args: object|null}>} */
50
+ read(source) {
51
+ const src = String(source);
52
+ const calls = [];
53
+ const opener = /tools\.([A-Za-z_$][\w$]*)\s*\(/g;
54
+ let match;
55
+ while ((match = opener.exec(src))) {
56
+ const argText = this.#balanced(src, opener.lastIndex - 1);
57
+ if (argText === null) continue;
58
+ calls.push({ tool: match[1], args: this.#parseArgs(argText) });
59
+ }
60
+ return calls;
61
+ }
62
+
63
+ /** The text between the paren at `openAt` and its balanced closer — string-aware. */
64
+ #balanced(src, openAt) {
65
+ let depth = 0;
66
+ let inString = null;
67
+ for (let i = openAt; i < src.length; i += 1) {
68
+ const ch = src[i];
69
+ if (inString) {
70
+ if (ch === '\\') i += 1;
71
+ else if (ch === inString) inString = null;
72
+ continue;
73
+ }
74
+ if (ch === '"' || ch === "'" || ch === '`') inString = ch;
75
+ else if (ch === '(') depth += 1;
76
+ else if (ch === ')') {
77
+ depth -= 1;
78
+ if (depth === 0) return src.slice(openAt + 1, i);
79
+ }
80
+ }
81
+ return null;
82
+ }
83
+
84
+ #parseArgs(argText) {
85
+ const text = argText.trim();
86
+ if (text === '') return null;
87
+ try { return JSON.parse(text); } catch { /* bare-keyed object literal next */ }
88
+ try { return JSON.parse(this.#quoteBareKeys(text)); } catch { return null; }
89
+ }
90
+
91
+ /** Quote bare identifier keys outside string literals — the live literals use them. */
92
+ #quoteBareKeys(text) {
93
+ let out = '';
94
+ let inString = null;
95
+ for (let i = 0; i < text.length; i += 1) {
96
+ const ch = text[i];
97
+ if (inString) {
98
+ out += ch;
99
+ if (ch === '\\') { out += text[i + 1] ?? ''; i += 1; } else if (ch === inString) inString = null;
100
+ continue;
101
+ }
102
+ if (ch === '"' || ch === "'") { inString = ch; out += ch; continue; }
103
+ if (/[A-Za-z_$]/.test(ch)) {
104
+ let end = i;
105
+ while (end < text.length && /[\w$]/.test(text[end])) end += 1;
106
+ let after = end;
107
+ while (after < text.length && /\s/.test(text[after])) after += 1;
108
+ if (text[after] === ':') {
109
+ out += `"${text.slice(i, end)}"`;
110
+ i = end - 1;
111
+ continue;
112
+ }
113
+ }
114
+ out += ch;
115
+ }
116
+ return out;
117
+ }
118
+ }
119
+
120
+ export class CodexAtifProjector extends AtifProjector {
121
+ #execReader = new ExecCallReader();
122
+
123
+ map(rows, file) {
124
+ const head = rows[0];
125
+ if (head?.type !== 'session_meta') {
126
+ throw new AtifError('ATIF_UNMAPPABLE',
127
+ `${file}: first rollout line is '${head?.type}', expected session_meta`, { file });
128
+ }
129
+ const meta = head.payload ?? {};
130
+ this.sessionId = meta.id ?? meta.session_id;
131
+ this.agentInfo.version = meta.cli_version ?? null;
132
+ // The model is the turn's, not the session's: session_meta names only the provider
133
+ // (measured 2026-09-01: no rollout carries a model there), and "openai" is not a model.
134
+ // The first turn_context's model is the agent's — Harbor codex.py reads the same; none
135
+ // means null, never something invented.
136
+ this.agentInfo.model_name = rows.find((r) => r.type === 'turn_context' && typeof r.payload?.model === 'string')?.payload.model ?? null;
137
+ // Who this thread is on the inter-agent bus: a child knows its path from its spawn; the root is /root.
138
+ this.selfPath = meta.source?.subagent?.thread_spawn?.agent_path ?? CODEX_ROOT_AGENT_PATH;
139
+ this.agentThreads = new Map(); // agent_path → agent_thread_id, from the spawn items (the index is the fallback)
140
+ this.indexedThreads = null; // the thread index's children, read once when an author needs resolving
141
+ this.breakAgent = false;
142
+ this.callOpen = false; // an agent row landed since the last token_count — a call a count can close
143
+ this.turnId = null;
144
+ this.awaiting = []; // calls pushed and not yet answered — what an item can complete
145
+ this.completed = []; // calls answered, with their result — a command can outlive its call
146
+ this.callsById = new Map(); // every call, for the items whose id IS a call id
147
+ this.spawnThreads = new Map(); // agent_thread_id → the call that started it (completed items key by thread)
148
+ this.filesTouched = new Set();
149
+ // Every response_item id this record holds — what a forked child (fork_turns:"all")
150
+ // begins with under the same ids, and therefore inherited rather than did.
151
+ this.rowIds = new Set(rows.filter((r) => r.type === 'response_item' && r.payload?.id).map((r) => r.payload.id));
152
+ // ONE boundary per file, from the file's own evidence (measured row order: call → item →
153
+ // output → token_count): a usage-bearing token_count anywhere means the model's API calls
154
+ // partition the steps; none means the reasoning rows do.
155
+ this.record.step_boundary = rows.some((r) => r.type === 'event_msg' && r.payload?.type === 'token_count' && r.payload.info?.last_token_usage)
156
+ ? 'token_count' : 'reasoning';
157
+
158
+ for (const row of rows.slice(1)) {
159
+ const { channel, type } = codexKindOf(row);
160
+ if (channel === 'item' && type === undefined) {
161
+ throw new AtifError('ATIF_CODEX_ITEM_SHAPE',
162
+ `${file}: item_completed carries no item — the typed stream this projector relies on is unreadable, not empty`, { file });
163
+ }
164
+ const lane = CODEX_ROLLOUT_ROSTER[channel];
165
+ if (lane.ignored[type] !== undefined) continue; // seen, judged non-evidence — the roster says why
166
+ if (!lane.handled.includes(type)) {
167
+ // An addition codex made that we have not reviewed: quarantine VISIBLY (counted here,
168
+ // announced in the evidence view, DRIFT in the census lane) — never a refusal, never silence.
169
+ this.noteUnrecognized(channel === 'line' ? type : `${channel}.${type}`);
170
+ continue;
171
+ }
172
+ if (channel === 'response_item') this.#mapResponseItem(row, file);
173
+ else if (channel === 'item') this.#mapItem(row, file);
174
+ else if (channel === 'event_msg' && type === 'token_count') this.#mapTokenCount(row.payload ?? {}, file);
175
+ else if (type === 'turn_context') {
176
+ this.breakAgent = true; // turns are step boundaries
177
+ this.turnId = row.payload?.turn_id ?? null;
178
+ } else if (type === 'compacted') {
179
+ // A synthetic step: no model was called to produce it (llm_call_count 0, the RFC's
180
+ // deterministic-dispatch reading), stamped with the row's own clock.
181
+ this.pushStep({ source: 'system', message: '[context compacted]', ...(row.timestamp ? { timestamp: row.timestamp } : {}), llm_call_count: 0 });
182
+ }
183
+ // a resume-appended mid-file session_meta changes nothing — identity is the head's
184
+ }
185
+ if (this.filesTouched.size > 0) this.record.files_touched = [...this.filesTouched];
186
+
187
+ for (const child of this.#children()) this.addSubagent(child);
188
+ }
189
+
190
+ /** The thread index's children of this thread — none when this machine keeps no index. */
191
+ #childThreads() {
192
+ if (this.indexedThreads === null) {
193
+ try {
194
+ this.indexedThreads = this.store.childThreads(this.sessionId);
195
+ } catch (e) {
196
+ if (!(e instanceof TraceContractError && e.code === 'TRACE_CODEX_STATE_ABSENT')) throw e;
197
+ this.indexedThreads = [];
198
+ }
199
+ }
200
+ return this.indexedThreads;
201
+ }
202
+
203
+ #children() {
204
+ const projected = [];
205
+ const children = this.#childThreads();
206
+ for (const child of children) {
207
+ if (!child.rollout_path) {
208
+ throw new AtifError('ATIF_UNMAPPABLE',
209
+ `codex child thread ${child.thread_id} has no rollout path — a fan-out member cannot `
210
+ + 'be silently dropped from the evidence', { child });
211
+ }
212
+ const projectedChild = new CodexAtifProjector({ store: this.store, copiedIds: this.rowIds }).project(child.rollout_path);
213
+ projectedChild.trajectory_id = child.thread_id;
214
+ // Who this child was and how its spawn ended, in the record's own words — parity with
215
+ // Claude's subagent_meta. parent_thread_id is redundant (the embedding IS the parent).
216
+ const spawnMeta = { ...(child.spawn ?? {}) };
217
+ delete spawnMeta.parent_thread_id;
218
+ projectedChild.extra.record.subagent_meta = { kind: 'thread_spawn', status: child.status ?? null, ...spawnMeta };
219
+ projected.push(projectedChild);
220
+ // The ref on the spawn call's receipt: the call SubAgentActivity(started) tied to this
221
+ // thread, else the spawn call whose task_name is the child's nickname (the index's).
222
+ const call = this.spawnThreads.get(child.thread_id) ?? this.#spawnCallFor(child.spawn);
223
+ if (call) {
224
+ const agentPath = call.extra?.record?.agent_path ?? child.spawn?.agent_path ?? null;
225
+ this.attachRef(call.tool_call_id, { trajectory_id: child.thread_id, ...(agentPath ? { extra: { agent_path: agentPath } } : {}) }, { file: child.rollout_path });
226
+ }
227
+ }
228
+ return projected;
229
+ }
230
+
231
+ /** The spawn call that named this child by task_name, when no item tied the thread to a call. */
232
+ #spawnCallFor(spawn) {
233
+ const nickname = spawn?.agent_nickname ?? spawn?.agent_path?.split('/').at(-1);
234
+ if (!nickname) return null;
235
+ return [...this.callsById.values()].find((call) => /spawn_agent$/.test(call.function_name)
236
+ && call.arguments?.task_name === nickname && !call.extra?.record?.agent_thread_id) ?? null;
237
+ }
238
+
239
+ /**
240
+ * The open agent step — or a fresh one when a boundary (a turn, a closed API call, a
241
+ * reasoning row under that boundary) closed the last; a fresh step wears the clock of the
242
+ * row that opened it.
243
+ */
244
+ #agentStep(row) {
245
+ this.callOpen = true;
246
+ const open = this.breakAgent ? null : this.currentAgentStep();
247
+ this.breakAgent = false;
248
+ if (open) return open;
249
+ const step = this.pushStep({ source: 'agent', message: '' });
250
+ if (row?.timestamp) step.timestamp = row.timestamp;
251
+ return step;
252
+ }
253
+
254
+ /** The last agent step in the record — where a model API call's accounting lands. */
255
+ #lastAgentStep() {
256
+ return [...this.steps].reverse().find((s) => s.source === 'agent') ?? null;
257
+ }
258
+
259
+ /**
260
+ * A model API call ended: count it on its step (llm_call_count) and, under the token_count
261
+ * boundary, close the step. A count with no call to close — no agent row since the last
262
+ * count: nothing at all yet, or a compaction's turn-start re-emission (measured 2026-09-02:
263
+ * the same last_token_usage again, right after turn_context) — is an orphan: counted in the
264
+ * record, never attributed to anyone, never a second call on a step already closed.
265
+ */
266
+ #closeCall(step) {
267
+ this.callOpen = false;
268
+ if (!step) {
269
+ this.record.orphan_token_counts = (this.record.orphan_token_counts ?? 0) + 1;
270
+ return;
271
+ }
272
+ step.llm_call_count = (step.llm_call_count ?? 0) + 1;
273
+ if (this.record.step_boundary === 'token_count') this.breakAgent = true;
274
+ }
275
+
276
+ /** The per-call delta, accumulated — a missing shape refuses, zeros would be a lie. */
277
+ #mapTokenCount(payload, file) {
278
+ const open = this.callOpen ? this.#lastAgentStep() : null;
279
+ if (payload.info === null) {
280
+ // A documented vendor state (Harbor #970; 2 local occurrences): the call happened,
281
+ // its usage is unknown — the call counts and closes, the metrics stay absent.
282
+ this.#closeCall(open);
283
+ return;
284
+ }
285
+ const last = payload.info?.last_token_usage;
286
+ if (!last || typeof last !== 'object') {
287
+ throw new AtifError('ATIF_CODEX_TOKEN_SHAPE',
288
+ `${file}: token_count carries no info.last_token_usage — the shape this projector `
289
+ + `relies on is gone (saw keys: ${Object.keys(payload).join(', ')}); metrics must `
290
+ + 'never silently become zeros', { file, payload_keys: Object.keys(payload) });
291
+ }
292
+ // A count whose last usage is all zero closed no call either: a context-size report
293
+ // (measured 2026-09-02, after a compaction: input 0, output 0, total = the new window).
294
+ const step = (last.input_tokens || last.output_tokens) ? open : null;
295
+ if (step) {
296
+ this.addMetrics(step, {
297
+ prompt_tokens: last.input_tokens ?? 0,
298
+ completion_tokens: last.output_tokens ?? 0,
299
+ cached_tokens: last.cached_input_tokens ?? 0,
300
+ });
301
+ }
302
+ this.#closeCall(step);
303
+ }
304
+
305
+ /**
306
+ * A call lands on a step and waits for its output — and for the items that decode it.
307
+ * `inner` is how many calls an exec source names (the reader's count): one may be recovered
308
+ * from its item, several stay one exec whose record lists what ran inside.
309
+ */
310
+ #pushCall(step, call, { inner = 1 } = {}) {
311
+ step.tool_calls = [...(step.tool_calls ?? []), call];
312
+ this.awaiting.push({ call, turn: this.turnId, inner, enrich: null, executions: [] });
313
+ this.callsById.set(call.tool_call_id, call);
314
+ }
315
+
316
+ /**
317
+ * The output answers the call; whatever the items decoded meanwhile rides the result
318
+ * (extra.record), and the call stays reachable for a command that outlives it.
319
+ */
320
+ attachResult(callId, content, { file, rowId = null }) {
321
+ const result = super.attachResult(callId, content, { file });
322
+ this.landed(this.ownerOf.get(result), rowId);
323
+ const at = this.awaiting.findIndex((e) => e.call.tool_call_id === callId);
324
+ if (at >= 0) {
325
+ const [entry] = this.awaiting.splice(at, 1);
326
+ entry.result = result;
327
+ this.completed.push(entry);
328
+ this.#stampResult(entry);
329
+ }
330
+ return result;
331
+ }
332
+
333
+ /**
334
+ * What the items decoded for a call, on its result: exactly one command → its exit_code;
335
+ * several (one exec source can run many — measured up to 9) → the executions, each with
336
+ * its command and exit code; plus whatever else an item enriched (files_changed).
337
+ * Rebuilt whole each time, so a late completion never leaves a stale single exit code.
338
+ */
339
+ #stampResult(entry) {
340
+ const record = { ...(entry.enrich ?? {}) };
341
+ const [only] = entry.executions;
342
+ if (entry.executions.length === 1 && 'command' in only) {
343
+ if (Number.isInteger(only.exit_code)) record.exit_code = only.exit_code;
344
+ } else if (entry.executions.length > 0) {
345
+ record.executions = entry.executions;
346
+ }
347
+ if (Object.keys(record).length > 0) entry.result.extra = { ...(entry.result.extra ?? {}), record };
348
+ }
349
+
350
+ /** The most recent call in the current turn still awaiting its output that `matches`. */
351
+ #completing(matches) {
352
+ for (let i = this.awaiting.length - 1; i >= 0; i -= 1) {
353
+ const entry = this.awaiting[i];
354
+ if (entry.turn === this.turnId && matches(entry.call)) return entry;
355
+ }
356
+ return null;
357
+ }
358
+
359
+ /**
360
+ * The call a decoded command belongs to. A parsed call names its command — match it
361
+ * exactly, awaiting first. A raw exec source (a variable, a template, several calls in one
362
+ * Promise.all) is the OLDEST such call still running: commands run in dispatch order. A
363
+ * command can outlive its call (exec_command yields after yield_time_ms; write_stdin
364
+ * continues it; the CommandExecution completes after the output row): then it is the
365
+ * completed call in this turn that named it, else the most recent completed raw exec that
366
+ * has no command yet, else the most recent completed raw exec. Nothing → null.
367
+ */
368
+ #commandHome(tail) {
369
+ const parsed = (e) => tail !== undefined && e.call.arguments?.cmd === tail;
370
+ const raw = (e) => typeof e.call.arguments?.input === 'string';
371
+ const awaiting = this.awaiting.filter((e) => e.turn === this.turnId);
372
+ const completed = this.completed.filter((e) => e.turn === this.turnId);
373
+ return [...awaiting].reverse().find(parsed)
374
+ ?? awaiting.find(raw)
375
+ ?? [...completed].reverse().find(parsed)
376
+ ?? [...completed].reverse().find((e) => raw(e) && e.executions.length === 0)
377
+ ?? [...completed].reverse().find(raw)
378
+ ?? null;
379
+ }
380
+
381
+ /** An item that completes no call is counted in the record — visible, never lost, never invented onto a call. */
382
+ #uncorrelated(item) {
383
+ this.record.uncorrelated_items ??= {};
384
+ this.record.uncorrelated_items[item.type] = (this.record.uncorrelated_items[item.type] ?? 0) + 1;
385
+ }
386
+
387
+ #mapItem(row, file) {
388
+ const item = row.payload.item;
389
+ switch (item.type) {
390
+ case 'CommandExecution': {
391
+ const tail = Array.isArray(item.command) ? item.command.at(-1) : undefined;
392
+ const entry = this.#commandHome(tail);
393
+ if (!entry) return this.#uncorrelated(item);
394
+ entry.executions.push({ command: tail, ...(Number.isInteger(item.exit_code) ? { exit_code: item.exit_code } : {}) });
395
+ if (entry.result) this.#stampResult(entry); // a late completion lands on the answered call
396
+ return;
397
+ }
398
+ case 'McpToolCall': {
399
+ const name = `mcp__${item.server}__${item.tool}`;
400
+ const names = (call) => call.function_name === name
401
+ || (typeof call.arguments?.input === 'string' && call.arguments.input.includes(`tools.${name}`));
402
+ // Awaiting first; an item can also complete after the output row (measured) — then it
403
+ // belongs to the most recent answered call in this turn that names the act.
404
+ const entry = this.#completing(names)
405
+ ?? [...this.completed].reverse().find((e) => e.turn === this.turnId && names(e.call))
406
+ ?? null;
407
+ if (!entry) return this.#uncorrelated(item);
408
+ if (entry.call.function_name === name) return; // the parsed call already IS this act
409
+ if (entry.inner === 1) {
410
+ // One inner call whose source could not be parsed into arguments: the record knows
411
+ // the server, the tool and the arguments — never {input: raw} when it knows better.
412
+ entry.call.function_name = name;
413
+ entry.call.arguments = item.arguments ?? {};
414
+ } else {
415
+ // Several inner calls: the exec stays one call; the record lists what ran inside.
416
+ entry.executions.push({ tool: name, arguments: item.arguments ?? {} });
417
+ if (entry.result) this.#stampResult(entry);
418
+ }
419
+ return;
420
+ }
421
+ case 'FileChange': {
422
+ const files = Object.keys(item.changes ?? {});
423
+ for (const changed of files) this.filesTouched.add(changed);
424
+ const entry = this.#completing(() => true);
425
+ if (!entry) return this.#uncorrelated(item);
426
+ entry.enrich = { ...(entry.enrich ?? {}), files_changed: files };
427
+ return;
428
+ }
429
+ case 'SubAgentActivity': {
430
+ // Measured: started and interacted carry the CALL's id (spawn_agent, send_message);
431
+ // completed carries its own and keys by the thread the spawn started.
432
+ if (item.kind === 'completed') {
433
+ if (!this.spawnThreads.has(item.agent_thread_id)) this.#uncorrelated(item);
434
+ return;
435
+ }
436
+ const call = this.callsById.get(item.id);
437
+ if (!call) return this.#uncorrelated(item);
438
+ if (item.kind === 'started') {
439
+ if (!item.agent_thread_id) {
440
+ throw new AtifError('ATIF_CODEX_ITEM_SHAPE',
441
+ `${file}: SubAgentActivity(started) for '${item.id}' names no agent_thread_id — the spawn `
442
+ + 'linkage this projector relies on is unreadable', { file, call_id: item.id });
443
+ }
444
+ call.extra = { ...(call.extra ?? {}), record: { agent_thread_id: item.agent_thread_id, ...(item.agent_path ? { agent_path: item.agent_path } : {}) } };
445
+ this.spawnThreads.set(item.agent_thread_id, call);
446
+ if (item.agent_path) this.agentThreads.set(item.agent_path, item.agent_thread_id);
447
+ }
448
+ return;
449
+ }
450
+ case 'Extension': {
451
+ // An action with no response_item counterpart (web.search): the item is the call and
452
+ // its results are the observation.
453
+ const step = this.#agentStep(row);
454
+ const call = this.buildToolCall({ id: item.id, name: item.kind, args: { query: item.query, action: item.action } });
455
+ this.#pushCall(step, call);
456
+ this.attachResult(item.id, JSON.stringify(item.results ?? []), { file });
457
+ return;
458
+ }
459
+ default:
460
+ throw new AtifError('ATIF_UNMAPPABLE',
461
+ `${file}: roster-handled item '${item.type}' has no mapping — the roster and the projector drifted apart`, { file });
462
+ }
463
+ }
464
+
465
+ /** The thread an agent path names — the spawn item's word first, else the index's. */
466
+ #threadFor(agentPath) {
467
+ return this.agentThreads.get(agentPath)
468
+ ?? this.#childThreads().find((child) => child.spawn?.agent_path === agentPath)?.thread_id
469
+ ?? null;
470
+ }
471
+
472
+ /**
473
+ * An addressed agent_message — the inter-agent bus. Never this agent's SAID: from an ancestor
474
+ * it is the delegated brief (a USER step, the address on the record); otherwise a child's
475
+ * answer (a SYSTEM step, llm_call_count 0, the message as an observation with a ref to the
476
+ * embedded child). An encrypted payload is said so; an author no spawn names is counted.
477
+ */
478
+ #inbound(row) {
479
+ const { author, recipient, content } = row.payload;
480
+ const parts = Array.isArray(content) ? content : [];
481
+ const text = textOf(parts) + (parts.some((p) => p?.type === 'encrypted_content') ? '\n[payload encrypted]' : '');
482
+ const messageType = INTER_AGENT_MESSAGE_TYPE.exec(text)?.[1] ?? null;
483
+ const inbound = { author, recipient, ...(messageType ? { message_type: messageType } : {}) };
484
+ const stamp = row.timestamp ? { timestamp: row.timestamp } : {};
485
+ if (recipient === this.selfPath && this.selfPath.startsWith(`${author}/`)) {
486
+ this.landed(this.pushStep({ source: 'user', message: text, ...stamp, extra: { record: { inbound } } }), row.payload.id);
487
+ return;
488
+ }
489
+ // A ref must RESOLVE (the RFC's rule): only a child this record embeds — one the thread
490
+ // index carries — gets one. A thread the spawn item names but the index does not carry
491
+ // (no state db, a child written elsewhere) rides the record as agent_thread_id, counted
492
+ // unresolved: nothing is lost, nothing is pointed at that is not there.
493
+ const threadId = recipient === this.selfPath ? this.#threadFor(author) : null;
494
+ const embedded = threadId !== null && this.#childThreads().some((child) => child.thread_id === threadId);
495
+ if (threadId !== null && !embedded) inbound.agent_thread_id = threadId;
496
+ if (!embedded) this.record.unresolved_inbound = (this.record.unresolved_inbound ?? 0) + 1;
497
+ this.landed(this.pushStep({
498
+ source: 'system',
499
+ message: `[inbound ${messageType ?? 'message'} from ${author}]`,
500
+ ...stamp,
501
+ llm_call_count: 0,
502
+ observation: { results: [{ content: text, ...(embedded ? { subagent_trajectory_ref: [{ trajectory_id: threadId }] } : {}) }] },
503
+ extra: { record: { inbound } },
504
+ }), row.payload.id);
505
+ }
506
+
507
+ #mapResponseItem(row, file) {
508
+ const payload = row.payload ?? {};
509
+ switch (payload.type) {
510
+ case 'message':
511
+ case 'agent_message': {
512
+ if (payload.type === 'agent_message' && payload.recipient) {
513
+ this.#inbound(row);
514
+ break;
515
+ }
516
+ const text = textOf(payload.content);
517
+ if (payload.role === 'user') {
518
+ this.landed(this.pushStep({ source: 'user', message: text }), payload.id);
519
+ } else if (payload.role === 'developer') {
520
+ // Injected instructions (permissions, board text) — never the agent's own words.
521
+ this.landed(this.pushStep({ source: 'system', message: text }), payload.id);
522
+ } else {
523
+ const step = this.#agentStep(row);
524
+ step.message = [step.message, text].filter((t) => t !== '').join('\n');
525
+ this.landed(step, payload.id);
526
+ }
527
+ break;
528
+ }
529
+ case 'reasoning': {
530
+ // Under the reasoning boundary (no usage-bearing token_count in this file) a reasoning
531
+ // row marks an LLM response: if the open step already carries content, this is the
532
+ // NEXT response — close it. Under the token_count boundary the count closes the call.
533
+ // The content itself is usually encrypted; the boundary is the evidence even then.
534
+ const open = this.currentAgentStep();
535
+ if (this.record.step_boundary === 'reasoning' && open
536
+ && (open.tool_calls?.length || open.message !== '' || open.reasoning_content)) {
537
+ this.breakAgent = true;
538
+ }
539
+ const text = textOf(payload.content ?? payload.summary);
540
+ if (text) {
541
+ const step = this.#agentStep(row);
542
+ step.reasoning_content = [step.reasoning_content, text].filter(Boolean).join('\n');
543
+ this.landed(step, payload.id);
544
+ }
545
+ break;
546
+ }
547
+ case 'custom_tool_call': {
548
+ if (typeof payload.input !== 'string' || !payload.name) {
549
+ throw new AtifError('ATIF_CODEX_CALL_SHAPE',
550
+ `${file}: custom_tool_call '${payload.call_id}' carries no input source — the `
551
+ + 'action this projector relies on is unreadable, not empty', { file, call_id: payload.call_id });
552
+ }
553
+ const inner = this.#execReader.read(payload.input);
554
+ // Exactly one inner call with data arguments → that call IS the action (and oathe
555
+ // speech acts surface by their real names); anything else keeps the raw source.
556
+ const single = inner.length === 1 && inner[0].args !== null ? inner[0] : null;
557
+ const execStep = this.#agentStep(row);
558
+ this.#pushCall(execStep, this.buildToolCall({
559
+ id: payload.call_id,
560
+ name: single ? single.tool : (payload.name ?? payload.type),
561
+ args: single ? single.args : { input: payload.input },
562
+ }), { inner: inner.length });
563
+ this.landed(execStep, payload.id);
564
+ break;
565
+ }
566
+ case 'function_call':
567
+ case 'local_shell_call': {
568
+ let args = payload.arguments ?? payload.action ?? {};
569
+ if (typeof args === 'string') {
570
+ try {
571
+ args = JSON.parse(args);
572
+ } catch {
573
+ throw new AtifError('ATIF_UNMAPPABLE',
574
+ `${file}: tool call '${payload.call_id}' carries arguments that are not JSON`, { file });
575
+ }
576
+ }
577
+ const name = payload.namespace
578
+ ? `${payload.namespace}__${String(payload.name ?? '').replace(/^_/, '')}`
579
+ : (payload.name ?? payload.type);
580
+ const callStep = this.#agentStep(row);
581
+ this.#pushCall(callStep, this.buildToolCall({ id: payload.call_id, name, args }));
582
+ this.landed(callStep, payload.id);
583
+ break;
584
+ }
585
+ case 'tool_search_call': {
586
+ const searchStep = this.#agentStep(row);
587
+ this.#pushCall(searchStep, this.buildToolCall({ id: payload.call_id, name: 'tool_search', args: payload.arguments ?? {} }));
588
+ this.landed(searchStep, payload.id);
589
+ break;
590
+ }
591
+ case 'function_call_output':
592
+ case 'custom_tool_call_output':
593
+ this.attachResult(payload.call_id, payload.output ?? payload.content, { file, rowId: payload.id });
594
+ break;
595
+ case 'tool_search_output':
596
+ this.attachResult(payload.call_id,
597
+ payload.tools !== undefined ? JSON.stringify(payload.tools) : (payload.output ?? payload.content), { file, rowId: payload.id });
598
+ break;
599
+ case 'compaction':
600
+ // codex 0.150-alpha writes the compaction summary as an (encrypted) response item with
601
+ // no `compacted` line row beside it — the same synthetic system step, the same clock.
602
+ this.pushStep({ source: 'system', message: '[context compacted]', ...(row.timestamp ? { timestamp: row.timestamp } : {}), llm_call_count: 0 });
603
+ break;
604
+ default:
605
+ // unreachable: the roster routed here — a handled type without a case is a bug
606
+ throw new AtifError('ATIF_UNMAPPABLE',
607
+ `${file}: roster-handled response_item '${payload.type}' has no mapping — the roster and the projector drifted apart`, { file });
608
+ }
609
+ }
610
+ }