@oathe/oathe 0.0.1 → 0.2.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.
Files changed (70) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +7 -0
  3. package/README.md +99 -12
  4. package/assets/oathe-hero.svg +92 -0
  5. package/bin/oathe.mjs +376 -0
  6. package/docs/PRIVACY.md +45 -0
  7. package/package.json +32 -23
  8. package/plugin/.claude-plugin/plugin.json +10 -0
  9. package/plugin/.mcp.json +13 -0
  10. package/plugin/hooks/frame-note.mjs +24 -0
  11. package/plugin/hooks/heartbeat.mjs +49 -0
  12. package/plugin/hooks/hooks.json +39 -0
  13. package/plugin/hooks/lib.mjs +83 -0
  14. package/plugin/hooks/render-board.mjs +11 -0
  15. package/plugin/skills/oathe-work/SKILL.md +33 -0
  16. package/src/atif.mjs +633 -0
  17. package/src/blocks.mjs +192 -0
  18. package/src/board-render.mjs +106 -0
  19. package/src/config.mjs +169 -0
  20. package/src/context.mjs +35 -0
  21. package/src/doctor.mjs +108 -0
  22. package/src/harness.mjs +271 -0
  23. package/src/init.mjs +92 -0
  24. package/src/launch-env.mjs +25 -0
  25. package/src/launch.mjs +259 -0
  26. package/src/manifest.mjs +89 -0
  27. package/src/mcp/oathe-tools.mjs +517 -0
  28. package/src/paths.mjs +49 -0
  29. package/src/plans.mjs +50 -0
  30. package/src/runtime/discharge.mjs +57 -0
  31. package/src/runtime/provider.mjs +154 -0
  32. package/src/runtime/simple-cage.mjs +67 -0
  33. package/src/runtime/sql-acceptance-lane.mjs +89 -0
  34. package/src/session-host.mjs +81 -0
  35. package/src/substrate.mjs +337 -0
  36. package/src/successor.mjs +31 -0
  37. package/src/traces.mjs +242 -0
  38. package/src/uninstall.mjs +45 -0
  39. package/src/verifier.mjs +322 -0
  40. package/src/workspace.mjs +47 -0
  41. package/vendor/ddl/001_core.sql +312 -0
  42. package/vendor/ddl/002_claim.sql +438 -0
  43. package/vendor/ddl/003_verification.sql +480 -0
  44. package/vendor/ddl/004_delegation.sql +397 -0
  45. package/vendor/ddl/005_escalation.sql +303 -0
  46. package/vendor/ddl/006_dependency.sql +384 -0
  47. package/vendor/ddl/007_assignment.sql +502 -0
  48. package/vendor/ddl/008_effect_receipt.sql +290 -0
  49. package/vendor/ddl/009_verified_edge.sql +452 -0
  50. package/vendor/ddl/010_parent_child_verification.sql +320 -0
  51. package/vendor/ddl/011_confirm.sql +288 -0
  52. package/vendor/ddl/012_evaluator_lane.sql +444 -0
  53. package/vendor/ddl/013_claim_terminal.sql +279 -0
  54. package/vendor/ddl/014_claim_settlement.sql +327 -0
  55. package/vendor/ddl/015_claim_yield.sql +213 -0
  56. package/vendor/ddl/016_reopened_reclaim.sql +285 -0
  57. package/vendor/ddl/017_claim_yield_causes.sql +357 -0
  58. package/vendor/ddl/018_receiptless_unknown.sql +249 -0
  59. package/vendor/ddl/019_verification_contract_freeze.sql +335 -0
  60. package/vendor/ddl/020_context_compilation.sql +105 -0
  61. package/vendor/ddl/021_execution_attempt_closure.sql +95 -0
  62. package/vendor/ddl/022_verification_clause.sql +106 -0
  63. package/vendor/ddl/023_executor_role.sql +66 -0
  64. package/vendor/ddl/024_executor_role_hardening.sql +439 -0
  65. package/vendor/ddl/025_running_attempt_uniqueness.sql +102 -0
  66. package/vendor/ddl/026_acceptance_authority.sql +230 -0
  67. package/vendor/ddl/027_ownership_return.sql +836 -0
  68. package/vendor/ddl/028_attempt_bind_ownership.sql +173 -0
  69. package/vendor/ddl/manifest.json +183 -0
  70. package/index.js +0 -33
package/src/atif.mjs ADDED
@@ -0,0 +1,633 @@
1
+ // oathe — ATIF projection: both harnesses' raw traces, derived at read time into Harbor's
2
+ // Agent Trajectory Interchange Format (v1.7), with oathe's claims-vs-actions layer riding the
3
+ // spec's ONE sanctioned extension point (`extra`) as the documented `extra.oathe` convention
4
+ // (docs/atif-oathe.md). Raw stores stay ground truth; a projector never emits an invalid
5
+ // trajectory (finalize() validates); anything unmappable is a typed refusal, never a silent
6
+ // drop. The reference models forbid unknown fields outside `extra` — so does our validator.
7
+
8
+ import path from 'node:path';
9
+
10
+ import { ClaudeTraceStore, CodexTraceStore, TraceContractError, harnessForTracePath } from './traces.mjs';
11
+ import { makeToolDefs } from './mcp/oathe-tools.mjs';
12
+
13
+ export const ATIF_SCHEMA_VERSION = 'ATIF-v1.7';
14
+ export const OATHE_CONVENTION_VERSION = 1;
15
+
16
+ /** Accepted by the reference models (Literal v1.0..v1.7). */
17
+ const KNOWN_SCHEMA_VERSIONS = Object.freeze(
18
+ Array.from({ length: 8 }, (_, i) => `ATIF-v1.${i}`),
19
+ );
20
+
21
+ /** The oathe speech-act verbs — derived from the server's own tool defs, never retyped. */
22
+ const OATHE_VERBS = Object.freeze(makeToolDefs().map((t) => t.name));
23
+
24
+ const EXIT_CODE_PATTERN = /[Ee]xit code:?\s+(\d+)/;
25
+
26
+ export class AtifError extends Error {
27
+ constructor(code, message, details = {}) {
28
+ super(message);
29
+ this.name = 'AtifError';
30
+ this.code = code;
31
+ this.details = details;
32
+ }
33
+ }
34
+
35
+ // --------------------------------------------------------------------------- shared assembly
36
+
37
+ /** Text of a content part list (Claude tool_result content may itself be a part array). */
38
+ function textOf(content) {
39
+ if (typeof content === 'string') return content;
40
+ if (!Array.isArray(content)) return content == null ? '' : JSON.stringify(content);
41
+ return content
42
+ .map((part) => part?.text ?? part?.thinking ?? '')
43
+ .filter((t) => t !== '')
44
+ .join('\n');
45
+ }
46
+
47
+ /** The conservative observed-facts parse: only what the output text actually states. */
48
+ function observedFacts(resultText) {
49
+ const match = String(resultText).match(EXIT_CODE_PATTERN);
50
+ return match ? { exit_code: Number(match[1]) } : null;
51
+ }
52
+
53
+ /** oathe verb name for a tool call, when the call IS an oathe speech act (MCP-prefixed). */
54
+ function oatheVerbFor(functionName) {
55
+ return OATHE_VERBS.find((verb) => functionName === verb || functionName.endsWith(`__${verb}`)) ?? null;
56
+ }
57
+
58
+ /**
59
+ * The projector family's shared trajectory assembly. Subclasses implement `map(rows, file)`
60
+ * by driving the step/observation helpers; the base owns numbering, metrics accumulation,
61
+ * the extra.oathe stamp, and validation-before-return.
62
+ */
63
+ export class AtifProjector {
64
+ constructor({ store }) {
65
+ if (!store) throw new AtifError('ATIF_STORE_REQUIRED', 'a projector needs its trace store');
66
+ this.store = store;
67
+ }
68
+
69
+ /** @returns {object} a VALID ATIF trajectory (validator-asserted) */
70
+ project(file) {
71
+ this.steps = [];
72
+ this.agentInfo = { name: this.harness, version: null, model_name: null };
73
+ this.oatheRoot = {
74
+ oathe_convention: OATHE_CONVENTION_VERSION,
75
+ harness: this.harness,
76
+ source_path: file,
77
+ };
78
+ this.subagents = [];
79
+ this.map(this.store.entries(file), file);
80
+ if (this.steps.length === 0) {
81
+ throw new AtifError('ATIF_UNMAPPABLE',
82
+ `${file}: no mappable steps — a trajectory with nothing in it is not evidence`, { file });
83
+ }
84
+ return this.#finalize(file);
85
+ }
86
+
87
+ // ---- step helpers for subclasses
88
+
89
+ pushStep(step) {
90
+ this.steps.push({ step_id: this.steps.length + 1, ...step });
91
+ return this.steps.at(-1);
92
+ }
93
+
94
+ /** The open agent step to attach observations/content to — or null. */
95
+ currentAgentStep() {
96
+ const last = this.steps.at(-1);
97
+ return last?.source === 'agent' ? last : null;
98
+ }
99
+
100
+ /** Attach a tool result to the step owning `callId`; refuses when nobody owns it. */
101
+ attachResult(callId, content, { file }) {
102
+ const owner = [...this.steps].reverse()
103
+ .find((s) => s.tool_calls?.some((c) => c.tool_call_id === callId));
104
+ if (!owner) {
105
+ throw new AtifError('ATIF_UNMAPPABLE',
106
+ `${file}: tool result for '${callId}' has no matching tool call — the trace is not `
107
+ + 'internally consistent and the projection will not paper over it', { file, callId });
108
+ }
109
+ owner.observation ??= { results: [] };
110
+ const text = textOf(content);
111
+ const result = { source_call_id: callId, content: text };
112
+ const observed = observedFacts(text);
113
+ if (observed) result.extra = { oathe: { observed } };
114
+ owner.observation.results.push(result);
115
+ return result;
116
+ }
117
+
118
+ /** A tool_call object with the oathe extras (files touched, speech-act marking). */
119
+ buildToolCall({ id, name, args }) {
120
+ const call = { tool_call_id: id, function_name: name, arguments: args ?? {} };
121
+ if (typeof call.arguments?.file_path === 'string') {
122
+ call.extra = { oathe: { files: [call.arguments.file_path] } };
123
+ }
124
+ return call;
125
+ }
126
+
127
+ /** Mark a step's oathe speech acts (claim/statement/done/…) from its tool calls. */
128
+ markClaimEvents(step) {
129
+ const events = (step.tool_calls ?? [])
130
+ .map((call) => {
131
+ const verb = oatheVerbFor(call.function_name);
132
+ return verb ? { verb, task_id: call.arguments?.task_id } : null;
133
+ })
134
+ .filter(Boolean);
135
+ if (events.length > 0) {
136
+ step.extra = { ...(step.extra ?? {}), oathe: { ...(step.extra?.oathe ?? {}), claim_events: events } };
137
+ }
138
+ }
139
+
140
+ addSubagent(trajectory) {
141
+ this.subagents.push(trajectory);
142
+ }
143
+
144
+ #finalize(file) {
145
+ const totals = { total_prompt_tokens: 0, total_completion_tokens: 0, total_cached_tokens: 0, total_steps: this.steps.length };
146
+ for (const step of this.steps) {
147
+ if (!step.metrics) continue;
148
+ totals.total_prompt_tokens += step.metrics.prompt_tokens ?? 0;
149
+ totals.total_completion_tokens += step.metrics.completion_tokens ?? 0;
150
+ totals.total_cached_tokens += step.metrics.cached_tokens ?? 0;
151
+ }
152
+ const trajectory = {
153
+ schema_version: ATIF_SCHEMA_VERSION,
154
+ session_id: this.oatheRoot.session_id ?? null,
155
+ agent: this.agentInfo,
156
+ steps: this.steps,
157
+ final_metrics: totals,
158
+ extra: { oathe: this.oatheRoot },
159
+ ...(this.subagents.length > 0 ? { subagent_trajectories: this.subagents } : {}),
160
+ };
161
+ new AtifValidator().assert(trajectory, { file });
162
+ return trajectory;
163
+ }
164
+ }
165
+
166
+ // --------------------------------------------------------------------------- Claude
167
+
168
+ const CLAUDE_NOISE_TYPES = new Set([
169
+ 'last-prompt', 'mode', 'permission-mode', 'atis-latch', 'bridge-session', 'attachment',
170
+ 'queue-operation', 'file-history-snapshot', 'ai-title',
171
+ ]);
172
+
173
+ export class ClaudeAtifProjector extends AtifProjector {
174
+ harness = 'claude';
175
+
176
+ map(rows, file) {
177
+ let lastMessageId = null;
178
+ this.turnBroken = false;
179
+ const filesTouched = new Set();
180
+ for (const row of rows) {
181
+ if (row.type === 'ai-title') {
182
+ this.oatheRoot.session_title = row.aiTitle;
183
+ continue;
184
+ }
185
+ if (row.type === 'file-history-snapshot') {
186
+ for (const touched of Object.keys(row.snapshot?.trackedFileBackups ?? {})) filesTouched.add(touched);
187
+ continue;
188
+ }
189
+ if (CLAUDE_NOISE_TYPES.has(row.type)) continue;
190
+ if (row.sessionId && !this.oatheRoot.session_id) this.oatheRoot.session_id = row.sessionId;
191
+ if (row.version && !this.agentInfo.version) this.agentInfo.version = row.version;
192
+
193
+ if (row.type === 'assistant') {
194
+ this.#mapAssistant(row, lastMessageId);
195
+ lastMessageId = row.message?.id ?? null;
196
+ } else if (row.type === 'user') {
197
+ this.#mapUser(row, file);
198
+ } else if (row.type === 'system') {
199
+ this.pushStep({ source: 'system', message: textOf(row.message?.content ?? row.content ?? '') });
200
+ }
201
+ }
202
+ if (filesTouched.size > 0) this.oatheRoot.files_touched = [...filesTouched];
203
+
204
+ for (const sub of this.store.subagentsFor(file)) {
205
+ const child = new ClaudeAtifProjector({ store: this.store }).project(sub.path);
206
+ child.trajectory_id = sub.agent_id;
207
+ if (sub.meta) child.extra.oathe.subagent_meta = sub.meta;
208
+ this.addSubagent(child);
209
+ }
210
+ }
211
+
212
+ #mapAssistant(row, lastMessageId) {
213
+ const parts = Array.isArray(row.message?.content) ? row.message.content : [];
214
+ const texts = parts.filter((p) => p.type === 'text').map((p) => p.text);
215
+ const thinking = parts.filter((p) => p.type === 'thinking').map((p) => p.thinking);
216
+ const calls = parts.filter((p) => p.type === 'tool_use')
217
+ .map((p) => this.buildToolCall({ id: p.id, name: p.name, args: p.input }));
218
+ if (row.message?.model && !this.agentInfo.model_name) this.agentInfo.model_name = row.message.model;
219
+
220
+ // Consecutive assistant rows are one TURN (streamed content blocks): merge into the open
221
+ // agent step — but any intervening user row (a tool result included) ENDS the turn.
222
+ // Usage repeats per API response id, so it is added once per message id.
223
+ let step = this.turnBroken ? null : this.currentAgentStep();
224
+ this.turnBroken = false;
225
+ if (!step) {
226
+ step = this.pushStep({ source: 'agent', message: '' });
227
+ if (row.timestamp) step.timestamp = row.timestamp;
228
+ }
229
+ if (texts.length > 0) step.message = [step.message, ...texts].filter((t) => t !== '').join('\n');
230
+ if (thinking.length > 0) {
231
+ step.reasoning_content = [step.reasoning_content, ...thinking].filter(Boolean).join('\n');
232
+ }
233
+ if (calls.length > 0) step.tool_calls = [...(step.tool_calls ?? []), ...calls];
234
+
235
+ const usage = row.message?.usage;
236
+ const messageId = row.message?.id ?? null;
237
+ // Dedupe usage only when an API response id actually REPEATS — absent ids never match.
238
+ if (usage && (messageId === null || messageId !== lastMessageId)) {
239
+ const cached = usage.cache_read_input_tokens ?? 0;
240
+ const creation = usage.cache_creation_input_tokens ?? 0;
241
+ const prior = step.metrics ?? { prompt_tokens: 0, completion_tokens: 0, cached_tokens: 0 };
242
+ step.metrics = {
243
+ prompt_tokens: prior.prompt_tokens + (usage.input_tokens ?? 0) + cached + creation,
244
+ completion_tokens: prior.completion_tokens + (usage.output_tokens ?? 0),
245
+ cached_tokens: prior.cached_tokens + cached,
246
+ ...(creation > 0 ? { extra: { cache_creation_input_tokens: creation } } : {}),
247
+ };
248
+ }
249
+ this.markClaimEvents(step);
250
+ }
251
+
252
+ #mapUser(row, file) {
253
+ this.turnBroken = true;
254
+ const content = row.message?.content;
255
+ if (Array.isArray(content)) {
256
+ const results = content.filter((p) => p.type === 'tool_result');
257
+ const texts = content.filter((p) => p.type === 'text').map((p) => p.text);
258
+ for (const result of results) this.attachResult(result.tool_use_id, result.content, { file });
259
+ if (texts.length > 0) this.pushStep({ source: 'user', message: texts.join('\n') });
260
+ } else {
261
+ this.pushStep({ source: 'user', message: textOf(content) });
262
+ }
263
+ }
264
+ }
265
+
266
+ // --------------------------------------------------------------------------- Codex
267
+
268
+ export class CodexAtifProjector extends AtifProjector {
269
+ harness = 'codex';
270
+
271
+ map(rows, file) {
272
+ const head = rows[0];
273
+ if (head?.type !== 'session_meta') {
274
+ throw new AtifError('ATIF_UNMAPPABLE',
275
+ `${file}: first rollout line is '${head?.type}', expected session_meta`, { file });
276
+ }
277
+ const meta = head.payload ?? {};
278
+ this.oatheRoot.session_id = meta.id ?? meta.session_id;
279
+ this.agentInfo.version = meta.cli_version ?? null;
280
+ const modelName = meta.model ?? meta.model_provider;
281
+ if (!modelName) {
282
+ throw new AtifError('ATIF_UNMAPPABLE',
283
+ `${file}: session_meta names neither model nor model_provider — the agent identity `
284
+ + 'cannot be stated without being invented', { file });
285
+ }
286
+ this.agentInfo.model_name = modelName;
287
+
288
+ for (const row of rows.slice(1)) {
289
+ if (row.type === 'response_item') this.#mapResponseItem(row.payload ?? {}, file);
290
+ else if (row.type === 'event_msg' && row.payload?.type === 'token_count') {
291
+ const step = this.currentAgentStep() ?? this.steps.at(-1);
292
+ if (step && step.source === 'agent') {
293
+ step.metrics = {
294
+ prompt_tokens: row.payload.input_tokens ?? 0,
295
+ completion_tokens: row.payload.output_tokens ?? 0,
296
+ cached_tokens: row.payload.cached_tokens ?? 0,
297
+ };
298
+ }
299
+ }
300
+ }
301
+
302
+ for (const child of this.#children()) this.addSubagent(child);
303
+ }
304
+
305
+ #children() {
306
+ const projected = [];
307
+ let children = [];
308
+ try {
309
+ children = this.store.childThreads(this.oatheRoot.session_id);
310
+ } catch (e) {
311
+ if (e instanceof TraceContractError && e.code === 'TRACE_CODEX_STATE_ABSENT') return projected;
312
+ throw e;
313
+ }
314
+ for (const child of children) {
315
+ if (!child.rollout_path) {
316
+ throw new AtifError('ATIF_UNMAPPABLE',
317
+ `codex child thread ${child.thread_id} has no rollout path — a fan-out member cannot `
318
+ + 'be silently dropped from the evidence', { child });
319
+ }
320
+ const projectedChild = new CodexAtifProjector({ store: this.store }).project(child.rollout_path);
321
+ projectedChild.trajectory_id = child.thread_id;
322
+ projected.push(projectedChild);
323
+ }
324
+ return projected;
325
+ }
326
+
327
+ #agentStep() {
328
+ return this.currentAgentStep() ?? this.pushStep({ source: 'agent', message: '' });
329
+ }
330
+
331
+ #mapResponseItem(payload, file) {
332
+ switch (payload.type) {
333
+ case 'message':
334
+ case 'agent_message': {
335
+ const text = textOf(payload.content);
336
+ if (payload.role === 'user') {
337
+ this.pushStep({ source: 'user', message: text });
338
+ } else {
339
+ const step = this.#agentStep();
340
+ step.message = [step.message, text].filter((t) => t !== '').join('\n');
341
+ }
342
+ break;
343
+ }
344
+ case 'reasoning': {
345
+ const step = this.#agentStep();
346
+ const text = textOf(payload.content ?? payload.summary);
347
+ if (text) step.reasoning_content = [step.reasoning_content, text].filter(Boolean).join('\n');
348
+ break;
349
+ }
350
+ case 'function_call':
351
+ case 'local_shell_call':
352
+ case 'custom_tool_call': {
353
+ const step = this.#agentStep();
354
+ let args = payload.arguments ?? payload.action ?? {};
355
+ if (typeof args === 'string') {
356
+ try {
357
+ args = JSON.parse(args);
358
+ } catch {
359
+ throw new AtifError('ATIF_UNMAPPABLE',
360
+ `${file}: tool call '${payload.call_id}' carries arguments that are not JSON`, { file });
361
+ }
362
+ }
363
+ step.tool_calls = [...(step.tool_calls ?? []),
364
+ this.buildToolCall({ id: payload.call_id, name: payload.name ?? payload.type, args })];
365
+ this.markClaimEvents(step);
366
+ break;
367
+ }
368
+ case 'function_call_output':
369
+ case 'custom_tool_call_output':
370
+ this.attachResult(payload.call_id, payload.output ?? payload.content, { file });
371
+ break;
372
+ default:
373
+ break; // compaction/additional_tools/… — context machinery, not evidence steps
374
+ }
375
+ }
376
+ }
377
+
378
+ // --------------------------------------------------------------------------- factory
379
+
380
+ export function projectorFor(file, { claudeHome, codexHome } = {}) {
381
+ return harnessForTracePath(file) === 'codex'
382
+ ? new CodexAtifProjector({ store: new CodexTraceStore({ home: codexHome }) })
383
+ : new ClaudeAtifProjector({ store: new ClaudeTraceStore({ home: claudeHome }) });
384
+ }
385
+
386
+ // --------------------------------------------------------------------------- claim intervals
387
+
388
+ const FOCUS_CLOSERS = new Set(['oathe_done', 'oathe_yield']);
389
+
390
+ /**
391
+ * Claim-focused intervals of a trajectory (correction packet §5.4): a session becomes
392
+ * attributable to a task only from the step where it ACTS on that task through an oathe
393
+ * speech act (claim, pickup, statement, done, yield — the projector's claim_events), and
394
+ * stops being attributable when the act names a different task (a switch), when done/yield
395
+ * closes the work, or when the session ends. Steps before the first act — planning, board
396
+ * reading, repository discussion — belong to no interval and are context, not evidence.
397
+ *
398
+ * @returns {Array<{task_id: string, start_index: number, end_index: number}>}
399
+ */
400
+ export function claimIntervals(trajectory) {
401
+ const intervals = [];
402
+ let open = null;
403
+ const close = (endIndex) => {
404
+ if (open && endIndex >= open.start_index) intervals.push({ ...open, end_index: endIndex });
405
+ open = null;
406
+ };
407
+ (trajectory.steps ?? []).forEach((step, index) => {
408
+ for (const event of step.extra?.oathe?.claim_events ?? []) {
409
+ const task = event.task_id;
410
+ if (!task) continue; // board reads and other task-less acts focus nothing
411
+ if (open && open.task_id !== task) close(index - 1); // explicit switch
412
+ if (!open) open = { task_id: task, start_index: index };
413
+ if (FOCUS_CLOSERS.has(event.verb)) close(index); // done/yield include their own step
414
+ }
415
+ });
416
+ close((trajectory.steps ?? []).length - 1); // session end closes what remains open
417
+ return intervals;
418
+ }
419
+
420
+ /**
421
+ * The trajectory reduced to the steps attributable to ONE task — what a verifier may treat
422
+ * as that task's execution evidence. When the trajectory carries no interval for the task
423
+ * (a pre-interval trace, or CLI-only work), the WHOLE trajectory is returned: whole-session
424
+ * evidence is then the only honest option and slicing to nothing would fabricate absence.
425
+ */
426
+ export function sliceForTask(trajectory, taskId) {
427
+ const mine = claimIntervals(trajectory).filter((i) => i.task_id === taskId);
428
+ if (mine.length === 0) return trajectory;
429
+ const keep = new Set();
430
+ for (const { start_index, end_index } of mine) {
431
+ for (let i = start_index; i <= end_index; i++) keep.add(i);
432
+ }
433
+ return { ...trajectory, steps: trajectory.steps.filter((_, i) => keep.has(i)) };
434
+ }
435
+
436
+ // --------------------------------------------------------------------------- evidence view
437
+
438
+ const CLIP = { message: 300, args: 140, result: 200, user: 200 };
439
+ const SUBAGENT_BUDGET_SHARE = 0.3;
440
+
441
+ function clip(text, max) {
442
+ const flat = String(text).replaceAll('\n', ' ⏎ ');
443
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
444
+ }
445
+
446
+ /** One step → its aligned lines: SAID (the claims), CLAIM (speech acts), DID (actions), GOT (outcomes). */
447
+ function stepLines(step) {
448
+ const lines = [];
449
+ if (step.source === 'user') return [`USER: ${clip(step.message, CLIP.user)}`];
450
+ if (step.source === 'system') return [`SYSTEM: ${clip(step.message, CLIP.user)}`];
451
+ if (step.message) lines.push(`SAID: ${clip(step.message, CLIP.message)}`);
452
+ for (const event of step.extra?.oathe?.claim_events ?? []) {
453
+ lines.push(`CLAIM(${event.verb}${event.task_id ? ` ${event.task_id}` : ''})`);
454
+ }
455
+ for (const call of step.tool_calls ?? []) {
456
+ lines.push(`DID: ${call.function_name}(${clip(JSON.stringify(call.arguments), CLIP.args)})`);
457
+ }
458
+ for (const result of step.observation?.results ?? []) {
459
+ const exit = result.extra?.oathe?.observed?.exit_code;
460
+ lines.push(`GOT${exit !== undefined ? ` [exit ${exit}]` : ''}: ${clip(result.content, CLIP.result)}`);
461
+ }
462
+ return lines;
463
+ }
464
+
465
+ function plural(n, word) {
466
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
467
+ }
468
+
469
+ /**
470
+ * The deterministic human/engine-facing rendering of a trajectory: aligned SAID/DID/GOT per
471
+ * step under a character budget. Truncation is TAIL-PRIORITIZED (the most recent steps
472
+ * survive whole) and ANNOUNCED — an elision the reader cannot see is evidence silently lost.
473
+ */
474
+ export function renderEvidenceView(trajectory, { budget }) {
475
+ const oathe = trajectory.extra?.oathe ?? {};
476
+ const header = [
477
+ `TRACE ${trajectory.session_id} (${oathe.harness ?? trajectory.agent?.name}`
478
+ + `${oathe.session_title ? ` — "${oathe.session_title}"` : ''})`,
479
+ ...(oathe.files_touched?.length ? [`files touched: ${oathe.files_touched.join(', ')}`] : []),
480
+ ];
481
+ const subagents = trajectory.subagent_trajectories ?? [];
482
+ const mainBudget = subagents.length > 0 ? Math.floor(budget * (1 - SUBAGENT_BUDGET_SHARE)) : budget;
483
+
484
+ const blocks = trajectory.steps.map((step) => stepLines(step).map((l) => ` ${l}`).join('\n'));
485
+ const kept = [];
486
+ let spent = 0;
487
+ for (let at = blocks.length - 1; at >= 0; at -= 1) {
488
+ if (spent + blocks[at].length > mainBudget && kept.length > 0) break;
489
+ kept.unshift(at);
490
+ spent += blocks[at].length;
491
+ if (spent > mainBudget) break;
492
+ }
493
+ const elidedSteps = trajectory.steps.slice(0, kept[0] ?? 0);
494
+ const body = [];
495
+ if (elidedSteps.length > 0) {
496
+ const toolCalls = elidedSteps.reduce((n, s) => n + (s.tool_calls?.length ?? 0), 0);
497
+ const claims = elidedSteps.reduce((n, s) => n + (s.extra?.oathe?.claim_events?.length ?? 0), 0);
498
+ body.push(` [${plural(elidedSteps.length, 'earlier step')} elided: `
499
+ + `${plural(toolCalls, 'tool call')}, ${plural(claims, 'claim')}]`);
500
+ }
501
+ for (const at of kept) body.push(blocks[at]);
502
+
503
+ const out = [...header, ...body];
504
+ if (subagents.length > 0) {
505
+ const each = Math.floor((budget * SUBAGENT_BUDGET_SHARE) / subagents.length);
506
+ for (const child of subagents) {
507
+ const meta = child.extra?.oathe?.subagent_meta;
508
+ out.push(`SUBAGENT ${child.trajectory_id}${meta?.agentType ? ` (${meta.agentType})` : ''}`);
509
+ out.push(renderEvidenceView(child, { budget: each }));
510
+ }
511
+ }
512
+ return out.join('\n');
513
+ }
514
+
515
+ // --------------------------------------------------------------------------- validator
516
+
517
+ /** Known fields per object — the reference models' extra:'forbid' posture, re-implemented. */
518
+ const KNOWN_FIELDS = Object.freeze({
519
+ trajectory: ['schema_version', 'session_id', 'trajectory_id', 'agent', 'steps', 'notes',
520
+ 'final_metrics', 'continued_trajectory_ref', 'extra', 'subagent_trajectories'],
521
+ agent: ['name', 'version', 'model_name', 'tool_definitions', 'extra'],
522
+ step: ['step_id', 'timestamp', 'source', 'model_name', 'reasoning_effort', 'message',
523
+ 'reasoning_content', 'tool_calls', 'observation', 'metrics', 'is_copied_context',
524
+ 'llm_call_count', 'extra'],
525
+ tool_call: ['tool_call_id', 'function_name', 'arguments', 'extra'],
526
+ observation: ['results', 'extra'],
527
+ observation_result: ['source_call_id', 'content', 'subagent_trajectory_ref', 'extra'],
528
+ metrics: ['prompt_tokens', 'completion_tokens', 'cached_tokens', 'cost_usd',
529
+ 'prompt_token_ids', 'completion_token_ids', 'logprobs', 'extra'],
530
+ final_metrics: ['total_prompt_tokens', 'total_completion_tokens', 'total_cached_tokens',
531
+ 'total_cost_usd', 'total_steps', 'extra'],
532
+ });
533
+
534
+ const STEP_SOURCES = new Set(['system', 'user', 'agent']);
535
+ const AGENT_ONLY_STEP_FIELDS = ['tool_calls', 'metrics', 'reasoning_content'];
536
+
537
+ export class AtifValidator {
538
+ /** @returns {{ok: boolean, detail: string|null}} */
539
+ validate(trajectory) {
540
+ try {
541
+ this.#trajectory(trajectory, 'trajectory');
542
+ return { ok: true, detail: null };
543
+ } catch (e) {
544
+ if (e instanceof AtifError) return { ok: false, detail: e.message };
545
+ throw e;
546
+ }
547
+ }
548
+
549
+ assert(trajectory, { file } = {}) {
550
+ const seen = this.validate(trajectory);
551
+ if (!seen.ok) {
552
+ throw new AtifError('ATIF_INVALID', `${file ? `${file}: ` : ''}${seen.detail}`, { file });
553
+ }
554
+ }
555
+
556
+ #fail(message) {
557
+ throw new AtifError('ATIF_INVALID', message);
558
+ }
559
+
560
+ #knownFields(obj, kind, where) {
561
+ for (const key of Object.keys(obj)) {
562
+ if (!KNOWN_FIELDS[kind].includes(key)) {
563
+ this.#fail(`${where}: unknown field '${key}' on ${kind} — the reference models forbid `
564
+ + "fields outside 'extra'");
565
+ }
566
+ }
567
+ }
568
+
569
+ #trajectory(t, where) {
570
+ if (t === null || typeof t !== 'object') this.#fail(`${where}: not an object`);
571
+ this.#knownFields(t, 'trajectory', where);
572
+ if (!KNOWN_SCHEMA_VERSIONS.includes(t.schema_version)) {
573
+ this.#fail(`${where}: schema_version '${t.schema_version}' is not an accepted ATIF version`);
574
+ }
575
+ if (!t.agent || typeof t.agent !== 'object') this.#fail(`${where}: agent required`);
576
+ this.#knownFields(t.agent, 'agent', `${where}.agent`);
577
+ if (!t.agent.name) this.#fail(`${where}.agent: name required`);
578
+ if (!Array.isArray(t.steps) || t.steps.length === 0) this.#fail(`${where}: steps must be a non-empty array`);
579
+ t.steps.forEach((step, at) => this.#step(step, at, `${where}.steps[${at}]`));
580
+ if (t.final_metrics) this.#knownFields(t.final_metrics, 'final_metrics', `${where}.final_metrics`);
581
+ if (t.subagent_trajectories !== undefined) {
582
+ const ids = new Set();
583
+ for (const [at, child] of t.subagent_trajectories.entries()) {
584
+ if (!child.trajectory_id) {
585
+ this.#fail(`${where}.subagent_trajectories[${at}]: embedded trajectories require a non-null trajectory_id`);
586
+ }
587
+ if (ids.has(child.trajectory_id)) {
588
+ this.#fail(`${where}.subagent_trajectories[${at}]: duplicate trajectory_id '${child.trajectory_id}'`);
589
+ }
590
+ ids.add(child.trajectory_id);
591
+ this.#trajectory(child, `${where}.subagent_trajectories[${at}]`);
592
+ }
593
+ }
594
+ }
595
+
596
+ #step(step, at, where) {
597
+ this.#knownFields(step, 'step', where);
598
+ if (step.step_id !== at + 1) {
599
+ this.#fail(`${where}: step_id ${step.step_id} breaks the sequential-from-1 rule (expected ${at + 1})`);
600
+ }
601
+ if (!STEP_SOURCES.has(step.source)) this.#fail(`${where}: source '${step.source}' invalid`);
602
+ if (typeof step.message !== 'string' && !Array.isArray(step.message)) {
603
+ this.#fail(`${where}: message is required (string or content parts)`);
604
+ }
605
+ if (step.source !== 'agent') {
606
+ for (const field of AGENT_ONLY_STEP_FIELDS) {
607
+ if (step[field] !== undefined) this.#fail(`${where}: '${field}' is agent-only`);
608
+ }
609
+ }
610
+ const callIds = new Set();
611
+ for (const [ci, call] of (step.tool_calls ?? []).entries()) {
612
+ this.#knownFields(call, 'tool_call', `${where}.tool_calls[${ci}]`);
613
+ if (!call.tool_call_id || !call.function_name || call.arguments === undefined) {
614
+ this.#fail(`${where}.tool_calls[${ci}]: tool_call_id, function_name and arguments are required`);
615
+ }
616
+ callIds.add(call.tool_call_id);
617
+ }
618
+ if (step.observation !== undefined) {
619
+ this.#knownFields(step.observation, 'observation', `${where}.observation`);
620
+ for (const [ri, result] of (step.observation.results ?? []).entries()) {
621
+ this.#knownFields(result, 'observation_result', `${where}.observation.results[${ri}]`);
622
+ // source_call_id is OPTIONAL (free-form environment observations — proven by Harbor's
623
+ // own golden fixture); when present it must resolve.
624
+ if (result.source_call_id !== undefined && result.source_call_id !== null
625
+ && !callIds.has(result.source_call_id)) {
626
+ this.#fail(`${where}.observation.results[${ri}]: source_call_id '${result.source_call_id}' `
627
+ + 'matches no tool call on its step');
628
+ }
629
+ }
630
+ }
631
+ if (step.metrics !== undefined) this.#knownFields(step.metrics, 'metrics', `${where}.metrics`);
632
+ }
633
+ }