| 1 | import test from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import { importTrace } from '../dist/core/ingest.js'; |
| 4 | import { compilePetTelemetry } from '../dist/core/pet-telemetry.js'; |
| 5 | |
| 6 | const session = entries => JSON.stringify({ metadata: { id: 'session-1' }, journal: { entries } }); |
| 7 | const at = seconds => new Date(Date.UTC(2026, 0, 1, 0, 0, seconds)).toISOString(); |
| 8 | |
| 9 | test('Codewhale session import bounds emitted events, keeps call identities and never ends a call before it starts', () => { |
| 10 | // One entry, many blocks: the limit applies per event, not per entry. |
| 11 | const blocks = Array.from({ length: 5 }, (_, i) => ({ type: 'text', text: `block ${i}` })); |
| 12 | assert.throws(() => importTrace(session([{ id: 'e1', message: { role: 'assistant', content: blocks } }]), 's', { maxEvents: 3 }), |
| 13 | /3 event limit/); |
| 14 | // A repeated tool call id would otherwise silently replace the first call. |
| 15 | const call = id => ({ id, message: { role: 'assistant', content: [{ type: 'tool_use', id: 'call-1', name: 'read_file', input: {} }] } }); |
| 16 | assert.throws(() => importTrace(session([call('e1'), call('e2')]), 's'), /Duplicate event identity \(session-1, call-1\)/); |
| 17 | // A result timestamped before its call is clamped, reported, and still compiles. |
| 18 | const [trace] = importTrace(session([ |
| 19 | { id: 'e1', created_at: at(10), message: { role: 'assistant', content: [{ type: 'tool_use', id: 'call-1', name: 'read_file', input: {} }] } }, |
| 20 | { id: 'e2', created_at: at(4), message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'call-1', content: 'ok' }] } }, |
| 21 | ]), 's'); |
| 22 | const tool = trace.events.find(e => e.id === 'call-1'); |
| 23 | assert.equal(tool.openEnded, false); |
| 24 | assert.ok(tool.endTime >= tool.startTime); |
| 25 | assert.ok(trace.warnings.some(w => w.includes('timestamped before its call'))); |
| 26 | assert.ok(compilePetTelemetry(trace.events, trace.duration).length > 0); |
| 27 | }); |
| 28 | |
| 29 | test('Codewhale runtime import never ends a turn before its kept start', () => { |
| 30 | // turn.completed carries wall times earlier than the turn.started record that fixed the start. |
| 31 | const rec = (seq, event, s, turn) => ({ seq, event, thread_id: 'th', turn_id: 't1', timestamp: at(s), payload: { turn } }); |
| 32 | const [trace] = importTrace([rec(0, 'turn.started', 10, {}), |
| 33 | rec(1, 'turn.completed', 12, { started_at: at(0), ended_at: at(5), status: 'completed' })].map(r => JSON.stringify(r)).join('\n'), 'r'); |
| 34 | const turn = trace.events.find(e => e.id === 'turn:t1'); |
| 35 | assert.equal(turn.openEnded, false); |
| 36 | assert.ok(turn.endTime >= turn.startTime, `${turn.startTime} > ${turn.endTime}`); |
| 37 | assert.ok(compilePetTelemetry(trace.events, trace.duration).length > 0); |
| 38 | }); |
| 39 |