Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## [Unreleased]

### Added

- **Codex compaction parity with Claude.** Codex passive ingest now detects `compacted` session-log records, persists them as ledger compaction events, and anchors them to the preceding Codex turn so compaction-loss analysis can cover Codex sessions instead of only Claude Code.

## [0.34.0] - 2026-04-27

### Changed
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Codex ingest persists compaction events.** The Codex passive ingest path now appends parser-emitted compactions through the existing ledger compaction writer, so `burn waste --kind compaction` can see Codex context compactions with the same event shape Claude uses.

## [0.34.0] - 2026-04-27

### Added
Expand Down
108 changes: 108 additions & 0 deletions packages/cli/src/ingest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,28 @@ describe('ingestCodexSessions execution graph passthrough (#87)', () => {
seen.add(key);
}
});

it('persists codex compaction events, no duplicates on re-ingest', async () => {
await writeCodexSession(tmpHome, 'rollout-compact-1', codexCompactionSession());
await ingestCodexSessions();
await ingestCodexSessions();

const ledger = await readFile(path.join(tmpRelay, 'ledger.jsonl'), 'utf8');
const lines = ledger
.split('\n')
.map((l) => l.trim())
.filter((l) => l.length > 0)
.map((l) => JSON.parse(l) as { kind: string; record: Record<string, unknown> });

const compactions = lines
.filter((l) => l.kind === 'compaction' && l.record['source'] === 'codex')
.map((l) => l.record);

assert.equal(compactions.length, 1, 'exactly one codex compaction row appended');
assert.equal(compactions[0]!['sessionId'], 'sess_codex_compact_ingest');
assert.equal(compactions[0]!['precedingMessageId'], 'turn_compact_ingest_1');
assert.equal(compactions[0]!['tokensBeforeCompact'], 1000);
});
});

// ---------- helpers ----------
Expand Down Expand Up @@ -668,6 +690,92 @@ function codexCommittedSession(sessionId: string, turnId: string, cwd: string):
return lines.map((line) => JSON.stringify(line)).join('\n') + '\n';
}

function codexCompactionSession(): string {
const lines = [
{
timestamp: '2026-04-20T03:00:00.000Z',
type: 'session_meta',
payload: {
id: 'sess_codex_compact_ingest',
cwd: '/tmp/project',
timestamp: '2026-04-20T03:00:00.000Z',
},
},
{
timestamp: '2026-04-20T03:00:00.100Z',
type: 'turn_context',
payload: { turn_id: 'turn_compact_ingest_1', cwd: '/tmp/project', model: 'gpt-5.4' },
},
{
timestamp: '2026-04-20T03:00:00.200Z',
type: 'event_msg',
payload: { type: 'task_started', turn_id: 'turn_compact_ingest_1' },
},
{
timestamp: '2026-04-20T03:00:01.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
total_token_usage: {
input_tokens: 3000,
cached_input_tokens: 1000,
output_tokens: 200,
reasoning_output_tokens: 50,
},
},
},
},
{
timestamp: '2026-04-20T03:00:02.000Z',
type: 'event_msg',
payload: { type: 'task_complete', turn_id: 'turn_compact_ingest_1' },
},
{
timestamp: '2026-04-20T03:00:03.000Z',
type: 'compacted',
payload: {
message: '',
replacement_history: [
{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'start' }] },
{ type: 'compaction', encrypted_content: 'opaque' },
],
},
},
{
timestamp: '2026-04-20T03:00:04.000Z',
type: 'turn_context',
payload: { turn_id: 'turn_compact_ingest_2', cwd: '/tmp/project', model: 'gpt-5.4' },
},
{
timestamp: '2026-04-20T03:00:04.100Z',
type: 'event_msg',
payload: { type: 'task_started', turn_id: 'turn_compact_ingest_2' },
},
{
timestamp: '2026-04-20T03:00:05.000Z',
type: 'event_msg',
payload: {
type: 'token_count',
info: {
total_token_usage: {
input_tokens: 6500,
cached_input_tokens: 1500,
output_tokens: 450,
reasoning_output_tokens: 90,
},
},
},
},
{
timestamp: '2026-04-20T03:00:06.000Z',
type: 'event_msg',
payload: { type: 'task_complete', turn_id: 'turn_compact_ingest_2' },
},
];
return lines.map((line) => JSON.stringify(line)).join('\n') + '\n';
}

// A codex session that spawns one subagent (call_spawn_eg → agent_eg_xyz),
// receives the spawn function_call_output, and commits the turn — exercising
// the execution-graph passthrough path in `ingestCodexInto`.
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/ingest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,9 @@ async function ingestCodexInto(
rootSessionEmitted: priorCodex.rootSessionEmitted === true,
nextEventIndex: priorCodex.nextEventIndex ?? 0,
toolResultCounters: { ...(priorCodex.toolResultCounters ?? {}) },
...(priorCodex.lastCompletedTurn !== undefined
? { lastCompletedTurn: priorCodex.lastCompletedTurn }
: {}),
};

if (!rotated && startOffset >= st.size) {
Expand All @@ -374,6 +377,7 @@ async function ingestCodexInto(
const {
turns,
content,
events,
userTurns,
relationships,
toolResultEvents,
Expand Down Expand Up @@ -407,6 +411,9 @@ async function ingestCodexInto(
if (content.length > 0) {
await appendContent(content);
}
if (events.length > 0) {
await appendCompactions(events);
}
if (relationships.length > 0) {
await appendRelationships(relationships);
}
Expand All @@ -432,6 +439,9 @@ async function ingestCodexInto(
if (nextResume.toolResultCounters && Object.keys(nextResume.toolResultCounters).length > 0) {
next.toolResultCounters = nextResume.toolResultCounters;
}
if (nextResume.lastCompletedTurn !== undefined) {
next.lastCompletedTurn = nextResume.lastCompletedTurn;
}
cursors[file] = next;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
Expand Down
4 changes: 4 additions & 0 deletions packages/ledger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- **Codex cursors remember the last committed turn.** `CodexCursor` now carries the reader's last completed Codex turn snapshot so incremental ingest can anchor a later compaction marker to the preceding turn without re-reading the whole session.

## [0.33.0] - 2026-04-27

### Dependencies
Expand Down
3 changes: 2 additions & 1 deletion packages/ledger/src/cursors.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import * as path from 'node:path';

import type { PersistedUserTurnSlot } from '@relayburn/reader';
import type { CodexLastCompletedTurn, PersistedUserTurnSlot } from '@relayburn/reader';

import { withLock } from './lock.js';
import { cursorsPath } from './paths.js';
Expand Down Expand Up @@ -30,6 +30,7 @@ export interface CodexCursor {
rootSessionEmitted?: boolean;
nextEventIndex?: number;
toolResultCounters?: Record<string, number>;
lastCompletedTurn?: CodexLastCompletedTurn;
}

export interface OpencodeCursor {
Expand Down
4 changes: 4 additions & 0 deletions packages/reader/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Codex compaction markers emit `CompactionEvent`s.** `parseCodexSession` and `parseCodexSessionIncremental` now return an `events` array for Codex, matching Claude's compaction event surface. The reader detects Codex `type: "compacted"` records, anchors each event to the most recent committed Codex turn, and carries that turn through `CodexResumeState` so incremental parses preserve `precedingMessageId` and `tokensBeforeCompact` across cursor boundaries.

## [0.33.0] - 2026-04-27

### Dependencies
Expand Down
55 changes: 55 additions & 0 deletions packages/reader/src/codex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ describe('parseCodexSession', () => {
assert.equal(t2!.toolCalls[0]!.target, 'ls');
});

it('emits a CompactionEvent anchored to the preceding committed turn', async () => {
const { turns, events } = await parseCodexSession(path.join(FIXTURES, 'compaction.jsonl'));

assert.equal(turns.length, 2);
assert.equal(events.length, 1);

const ev = events[0]!;
assert.equal(ev.source, 'codex');
assert.equal(ev.sessionId, 'sess_codex_compact');
assert.equal(ev.ts, '2026-04-20T03:00:03.000Z');
assert.equal(ev.precedingMessageId, 'turn_compact_1');

const preceding = turns.find((t) => t.messageId === 'turn_compact_1')!;
assert.equal(ev.tokensBeforeCompact, preceding.usage.cacheRead);
assert.equal(ev.tokensBeforeCompact, 1000);
});

it('produces stable argsHash for identical tool inputs', async () => {
const a = await parseCodexSession(path.join(FIXTURES, 'with-tool-call.jsonl'));
const b = await parseCodexSession(path.join(FIXTURES, 'with-tool-call.jsonl'));
Expand Down Expand Up @@ -331,6 +348,44 @@ describe('parseCodexSessionIncremental', () => {
}
});

it('anchors a resumed compaction event to the previous cursor turn', async () => {
const file = path.join(FIXTURES, 'compaction.jsonl');
const raw = await readFile(file, 'utf8');
const lines = raw.split('\n');
// Offset right after the first task_complete line (line index 4, 0-based).
const cutoff = Buffer.byteLength(lines.slice(0, 5).join('\n') + '\n', 'utf8');

const { mkdtemp, writeFile, rm } = await import('node:fs/promises');
const { tmpdir } = await import('node:os');
const tmp = await mkdtemp(path.join(tmpdir(), 'burn-codex-compact-inc-'));
try {
const partialPath = path.join(tmp, 'partial.jsonl');
await writeFile(partialPath, raw.slice(0, cutoff), 'utf8');
const partial = await parseCodexSessionIncremental(partialPath);
assert.equal(partial.turns.length, 1);
assert.equal(partial.events.length, 0);
assert.deepEqual(partial.resume.lastCompletedTurn, {
messageId: 'turn_compact_1',
cacheRead: 1000,
});

const fullPath = path.join(tmp, 'full.jsonl');
await writeFile(fullPath, raw, 'utf8');
const resumed = await parseCodexSessionIncremental(fullPath, {
startOffset: partial.endOffset,
resume: partial.resume,
});

assert.equal(resumed.turns.length, 1);
assert.equal(resumed.turns[0]!.messageId, 'turn_compact_2');
assert.equal(resumed.events.length, 1);
assert.equal(resumed.events[0]!.precedingMessageId, 'turn_compact_1');
assert.equal(resumed.events[0]!.tokensBeforeCompact, 1000);
} finally {
await rm(tmp, { recursive: true, force: true });
}
});

it('does not advance endOffset if no task_complete seen in the tail', async () => {
const file = path.join(FIXTURES, 'simple-turn.jsonl');
const raw = await readFile(file, 'utf8');
Expand Down
Loading