Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Claude Code's and Codex's adoption, activity and paging: declared data the kit applies in core (c5) (#1063)

Dee9f84355739c1
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 0596d058b..a52279387 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -184,6 +184,11 @@ const EDGE: RegExp[] = [
/^engines\/worker\/\w+Requests\.ts$/,
// The pilot reader implementations and their host are never loaded by supervised core.
/^engines\/(worker\/process|transcripts|(claude|codex)\/(transcript|\w+ReaderProcess))\.ts$/,
+ // Nor their transcripts' normalizers, Codex's rollout and sub-agent readers, or what replays their history: their
+ // readers' and live parsers', in their workers. Core reads only what they declare: adoption, activity and
+ // their stores (docs/design/2026-10-08-engine-launch.md, (c5)). Search's normalizer table is search's.
+ /^engines\/(claude|codex)\/(normalize|normalizer|subagent|subagentStats|rollout|lastTurn|live|attach)\.ts$/,
+ /^lib\/(normalize|transcriptReader)\.ts$/, /^lib\/sessionSearch\/externals\/(claude|codex)\.ts$/,
/^engines\/(runtime|(claude|codex)\/runtimeProfile)\.ts$/, /^lib\/runtimeProfile\.ts$/,
/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,
/^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,
@@ -212,6 +217,10 @@ const EDGE: RegExp[] = [
* list only shrinks: an entry no longer reached fails the test, so remove it with the move that ends it.
*/
const CORE_MAY_REACH: Record<string, string> = {
+ // Devin keeps its conversations in Claude Code's message format, and its search reader replays them with Claude
+ // Code's normalizer: core reaches both through Devin's reader until adoption loads it lazily.
+ 'engines/claude/normalize.ts': '(o5) Devin\'s search reader (lib/sessionSearch/externals/devin.ts → engines/devin/normalizer.ts)',
+ 'lib/normalize.ts': '(o5) Devin\'s search reader, as above',
}
/** The other twelve engines' own files: their folders but for the data they declare, their search readers, and the
@@ -232,21 +241,15 @@ const theirs = (file: string): boolean => THEIRS.some((pattern) => pattern.test(
const OTHER_ENGINES_CORE_MAY_REACH: Record<string, string> = {
'engines/cursor/pendingTasks.ts': '(o6) Cursor\'s pending tasks, read at the start and cleared on Stop and forget: a declared file, then a lazy load',
'lib/hermesHome.ts': '(o6) homes: which Hermes store a session\'s history is in',
- 'engines/agy/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
- 'engines/amp/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
- 'engines/commandcode/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
'engines/copilot/normalizer.ts': '(o5) adoption\'s readers',
- 'engines/cursor/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
'engines/devin/errorLog.ts': '(o5) adoption\'s readers',
'engines/devin/normalizer.ts': '(o5) adoption\'s readers',
'engines/devin/reader.ts': '(o5) adoption\'s readers',
- 'engines/grok/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
'engines/hermes/normalizer.ts': '(o5) adoption\'s readers',
'engines/kilo/normalizer.ts': '(o5) adoption\'s readers',
'engines/kilo/reader.ts': '(o5) adoption\'s readers',
'engines/opencode/normalizer.ts': '(o5) adoption\'s readers',
'engines/opencode/reader.ts': '(o5) adoption\'s readers',
- 'engines/pi/normalizer.ts': '(o5) adoption\'s readers, through lib/transcriptReader.ts',
'lib/sessionSearch/externals/agy.ts': '(o5) adoption\'s readers',
'lib/sessionSearch/externals/commandcode.ts': '(o5) adoption\'s readers',
'lib/sessionSearch/externals/copilot.ts': '(o5) adoption\'s readers',
@@ -362,30 +365,13 @@ describe('the daemon\'s shape', () => {
// control, with no engine worker and none of the two engines' code (docs/design/2026-10-08-engine-launch.md, (c4)).
const theirs = (entry: string): string[] => [...closureOf(entry).keys()]
.filter(file => /^engines\/(claude|codex)\//.test(file) && !DECLARED.has(file) && !LAUNCH_CONTRACTS.has(file))
+ // Pi's session reader, which session repair names Pi's folders with, streams lines (lib/transcriptLines.ts) and no
+ // longer loads the readers of the two engines' transcripts ((c5)).
for (const entry of ['lib/registry.ts', 'lib/handoffDiscovery.ts', 'lib/engineHomes.ts', 'engines/sessionFiles.ts',
- 'engines/sessionStoreContracts.ts', 'engines/kit/sessionRecords.ts', 'engines/kit/continuation.ts']) {
+ 'engines/sessionStoreContracts.ts', 'engines/kit/sessionRecords.ts', 'engines/kit/continuation.ts',
+ 'lib/sessionRepair.ts', 'lib/captureResumeIdentity.ts', 'engines/sessionStores.ts', 'core/agents/bind.ts']) {
expect(theirs(entry), entry).toEqual([])
}
- // Pi's session reader still loads the readers of the two engines' transcripts (lib/transcriptReader.ts), and
- // session repair names Pi's folders with it: the other engines' batch takes that out. Nothing else of session
- // repair, resume capture or binding reaches their code.
- const PI_READER = 'lib/sessionSearch/externals/pi.ts'
- const notThroughPi = (entry: string): string[] => {
- const seen = new Set<string>()
- const pending = [join(SRC, entry)]
- while (pending.length > 0) {
- const path = pending.pop()!
- const file = relative(SRC, path)
- if (seen.has(file) || file === PI_READER) continue
- seen.add(file)
- pending.push(...parsedFile(path).imports)
- }
- return [...seen].filter(file => /^engines\/(claude|codex)\//.test(file) && !DECLARED.has(file) && !LAUNCH_CONTRACTS.has(file))
- }
- for (const entry of ['lib/sessionRepair.ts', 'lib/captureResumeIdentity.ts', 'engines/sessionStores.ts', 'core/agents/bind.ts']) {
- expect(notThroughPi(entry), entry).toEqual([])
- }
- expect(closureOf('lib/sessionRepair.ts').has(PI_READER), 'Pi\'s reader is out of session repair: drop this exception').toBe(true)
// The stores alone, and what Codex's shares with its launch and hook contracts (the rollout layout, the child rule).
expect([...closureOf('engines/sessionStoreContracts.ts').keys()].filter(file => /^engines\/(claude|codex)\//.test(file)).sort())
.toEqual(['engines/claude/sessionStore.ts', 'engines/codex/hookContract.ts', 'engines/codex/launch.ts', 'engines/codex/sessionStore.ts'])
@@ -395,6 +381,31 @@ describe('the daemon\'s shape', () => {
}
})
+ it('adoption, activity, pages, history and the last turn load the engines\' declarations alone, never their normalizers', () => {
+ // Which conversations are on this machine and which process holds one (taking one over stops that process),
+ // an agent's latest activity, a thread's pages and line count, and core's history and recap reads
+ // (docs/design/2026-10-08-engine-launch.md, (c5)). Their replays are their readers', in their workers.
+ const adoption = new Set(['engines/claude/adoption.ts', 'engines/codex/adoption.ts'])
+ const declared = new Set([...DECLARED, ...LAUNCH_CONTRACTS, ...adoption])
+ const theirs = (entry: string): string[] => [...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file) && !declared.has(file))
+ for (const entry of ['engines/adoptions.ts', 'engines/kit/adoption.ts', 'lib/transcriptActivity.ts', 'lib/transcriptPages.ts',
+ 'lib/transcriptLines.ts', 'core/transcripts/history.ts', 'core/transcripts/lastTurn.ts', 'lib/agentFrame.ts',
+ 'lib/sessionSearch/external.ts']) {
+ expect(theirs(entry), entry).toEqual([])
+ }
+ // Adoption's composition reads the two declarations (and, through the process table, the discovery contracts).
+ expect([...closureOf('engines/adoptions.ts').keys()].filter(file => adoption.has(file)).sort()).toEqual([...adoption].sort())
+ // The pager, the line streamer and the paged history know no engine at all: each engine's reader hands the pager
+ // its rules. The kit's adoption names none either; it reads the process table (lib/tmux.ts) to match an owner.
+ for (const entry of ['lib/transcriptPages.ts', 'lib/transcriptLines.ts', 'engines/kit/history.ts']) {
+ expect([...closureOf(entry).keys()].filter(file => /^engines\/(?!kit\/|facets\/|types\.ts$)/.test(file)), entry).toEqual([])
+ }
+ expect(parsedFile(join(SRC, 'engines/kit/adoption.ts')).imports.map(path => relative(SRC, path)).filter(file => /^engines\/(?!kit\/|facets\/)/.test(file))).toEqual([])
+ // Core's adoption reaches the two engines' code only through Devin's reader (CORE_MAY_REACH, (o5)).
+ const viaDevin = new Set(closureOf('lib/sessionSearch/externals/devin.ts').keys())
+ expect(theirs('lib/sessionSearch/externals/index.ts').filter(file => !viaDevin.has(file))).toEqual([])
+ })
+
it('building a launch loads the engines\' declared launch contracts alone', () => {
const contracts = new Set(['engines/claude/launch.ts', 'engines/codex/launch.ts'])
// The builders: the argv and its script, a relaunch's overrides, a harness's flags. The homes they launch in
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 25b7c61ff..a2acf6390 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -25,7 +25,7 @@ import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'
import { GRID_FLEET_MAX_TIMEOUT_MS } from '../lib/gridFleetProtocol.js'
import type { GridLaunchOverride } from '../lib/gridLaunch.js'
import type { NewAgentModel } from '../lib/newAgentModel.js'
-import type { LastTurnText, LiveEvent } from '../lib/normalize.js'
+import type { LastTurnText, LiveEvent } from '../engines/kit/events.js'
import type { SessionRecaps } from '../lib/recapReads.js'
import type { SessionInputDelivery } from '../lib/sessionInput.js'
import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'
diff --git a/cli/src/core/deviceInput.ts b/cli/src/core/deviceInput.ts
index ad4de7cc2..792344aae 100644
--- a/cli/src/core/deviceInput.ts
+++ b/cli/src/core/deviceInput.ts
@@ -11,7 +11,7 @@
import { createHash } from 'node:crypto'
import type { RegisteredSession } from '../lib/registry.js'
import type { SessionInputDelivery } from '../lib/sessionInput.js'
-import type { LiveEvent } from '../lib/normalize.js'
+import type { LiveEvent } from '../engines/kit/events.js'
import { isMessageHold } from '../lib/messageHolds.js'
import { enterWithheldReason, type TerminalActionResult } from '../lib/terminalTypes.js'
import type { SubmissionReader } from '../lib/submissionReader.js'
diff --git a/cli/src/core/engines/cursorTasks.ts b/cli/src/core/engines/cursorTasks.ts
index 4a7809f4b..e933a1ea4 100644
--- a/cli/src/core/engines/cursorTasks.ts
+++ b/cli/src/core/engines/cursorTasks.ts
@@ -12,7 +12,7 @@ import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'
import { engineNow } from '../../engines/inProcess.js'
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent } from '../../engines/kit/events.js'
import type { registry } from '../../lib/registry.js'
import type { Watcher } from '../../watcher/watcher.js'
diff --git a/cli/src/core/engines/readers.ts b/cli/src/core/engines/readers.ts
index dafb508f7..2fa9eaa55 100644
--- a/cli/src/core/engines/readers.ts
+++ b/cli/src/core/engines/readers.ts
@@ -1,7 +1,7 @@
/** The core's reader port: bounded calls, no reader implementation and no fallback after a failure. */
import type { EngineTranscript, TranscriptSession } from '../../engines/facets/transcript.js'
import type { HistoryAnswer, HistoryAsk } from '../../engines/facets/transcript.js'
-import type { LastTurnText } from '../../lib/normalize.js'
+import type { LastTurnText } from '../../engines/kit/events.js'
import {
EngineReadError, historyAnswer, lastTurnAnswer, readerEngine, READER_ERRORS, READER_HISTORY,
READER_IN_FLIGHT, READER_LAST_TURN, READER_SERVICES, READER_VERSION, READER_WAIT_MS,
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index a9a7b343e..62310c0a2 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -15,7 +15,7 @@ import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js
import { deviceErrorText } from './cardText.js'
import { adaptSlashCommand } from '../lib/goalCommand.js'
import { sid } from '../lib/log.js'
-import type { LiveEvent } from '../lib/normalize.js'
+import type { LiveEvent } from '../engines/kit/events.js'
import type { RegisteredSession } from '../lib/registry.js'
import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'
import { passingHold } from '../lib/messageHolds.js'
diff --git a/cli/src/core/transcripts/databaseHistory.ts b/cli/src/core/transcripts/databaseHistory.ts
index fbe0ede54..88a44b73d 100644
--- a/cli/src/core/transcripts/databaseHistory.ts
+++ b/cli/src/core/transcripts/databaseHistory.ts
@@ -1,5 +1,5 @@
import { loadEngine } from '../../engines/inProcess.js'
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent } from '../../engines/kit/events.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { SQLITE_BACKED_ENGINES } from '../../lib/sqliteRead.js'
diff --git a/cli/src/core/transcripts/history.spec.ts b/cli/src/core/transcripts/history.spec.ts
index 325effc2a..d36fca1b4 100644
--- a/cli/src/core/transcripts/history.spec.ts
+++ b/cli/src/core/transcripts/history.spec.ts
@@ -19,7 +19,7 @@ import { lastActivityAt } from '../../lib/agentFrame.js'
import { sid } from '../../lib/log.js'
import { messagesToEvents, windowRawLines } from '../../lib/normalize.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import type { HistoryPage } from '../../lib/transcriptPages.js'
+import type { HistoryPage, ThreadPages } from '../../lib/transcriptPages.js'
import { tailFileCapped } from '../../lib/transcriptTail.js'
import { createHistory, wholeHistoryPage } from './history.js'
import { loadEngine } from '../../engines/inProcess.js'
@@ -118,9 +118,13 @@ function transcript(lines: string[], name = 'session.jsonl'): string {
}
function setup(s?: RegisteredSession, kept: RegisteredSession[] = [], readerFor = engineTranscriptFor) {
+ // The pager pages a thread by the rules its engine's reader hands it: a record's cursor (Claude Code's) or a
+ // line count (Codex's). Each kind is its own mock, so what each engine asked for is checked by kind.
+ const claude = vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null))
+ const codex = vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null))
const pages = {
- claude: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),
- codex: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),
+ claude, codex,
+ page: vi.fn(async (path: string, rules: ThreadPages, opts: { limit?: number; before?: string }) => rules.cursor === 'record' ? claude(path, opts) : codex(path, opts)),
lineCount: vi.fn(async (_path: string) => 0),
}
const deps = {
@@ -148,6 +152,19 @@ describe('an engine whose code could not be loaded', () => {
const file = session('grok', { transcriptPath: transcript(['g0']) })
expect(await setup(file).sessionGet({ sessionId: file.sessionId })).toStrictEqual({ ...about(file, MTIME), events: [], hasMore: false, oldestCursor: null })
})
+
+ // Core reads no engine's lines itself: Claude Code's and Codex's replays are their readers'. A shell keeps no
+ // transcript (registry.engineKeepsTranscriptFile), so this is only what a row that somehow had one would get.
+ it('so does an engine with neither a reader nor code of its own here', async () => {
+ const s = session('terminal', { transcriptPath: transcript(['l0', 'l1']) })
+ for (const ask of [{}, { limit: 2 }, { limit: 2, before: 'raw:1' }]) {
+ expect(await setup(s, [], () => undefined).sessionGet({ sessionId: s.sessionId, ...ask })).toStrictEqual({ ...about(s, MTIME), events: [], hasMore: false, oldestCursor: null })
+ }
+ const claude = session('claude', { transcriptPath: transcript(['c0']) })
+ expect(await setup(claude, [], () => undefined).sessionGet({ sessionId: claude.sessionId, limit: 2 })).toStrictEqual({ ...about(claude, MTIME), events: [], hasMore: false, oldestCursor: null })
+ expect(messagesToEvents).not.toHaveBeenCalled()
+ expect(windowRawLines).not.toHaveBeenCalled()
+ })
})
describe('what cannot be served', () => {
@@ -366,14 +383,14 @@ describe('sub-agent totals, joined from their own transcripts', () => {
])
})
- it('only Claude Code\'s replay is joined: the raw replay is, and an engine with its own replay is not', async () => {
+ it('only Claude Code\'s reader joins them: an engine with its own replay is not joined', async () => {
writeSubagent('agent7', subagent)
const lines = ['l0', 'l1']
- for (const [engine, replay, limit] of [['terminal', messagesToEvents, 5], ['terminal', messagesToEvents, undefined], ['pi', piMessagesToEvents, 5], ['pi', piMessagesToEvents, undefined]] as const) {
- const s = session(engine, { transcriptPath: transcript(lines) })
- vi.mocked(replay).mockReturnValueOnce([end({ agentId: 'agent7' })] as never)
+ for (const limit of [5, undefined]) {
+ const s = session('pi', { transcriptPath: transcript(lines) })
+ vi.mocked(piMessagesToEvents).mockReturnValueOnce([end({ agentId: 'agent7' })] as never)
const { events } = await setup(s).sessionGet({ sessionId: s.sessionId, limit }) as { events: Array<{ payload: { subagent?: Record<string, unknown> } }> }
- expect(events[0].payload.subagent?.totalToolUseCount, `${engine}, limit ${limit}`).toBe(engine === 'terminal' ? 3 : undefined)
+ expect(events[0].payload.subagent?.totalToolUseCount, `limit ${limit}`).toBeUndefined()
}
})
})
@@ -384,8 +401,6 @@ describe('the other file engines: read from the end, bounded', () => {
it.each([
['cursor', 'cursor'], ['muse', 'muse'], ['amp', 'amp'], ['grok', 'grok'], ['agy', 'agy'], ['copilot', 'copilot'],
['pi', 'pi'], ['commandcode', 'commandcode'],
- // An engine with no replay of its own is read as Claude Code's lines.
- ['terminal', 'claude'],
])('%s: the whole transcript, through its own replay', async (engine, from) => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const file = transcript(lines)
@@ -430,7 +445,6 @@ describe('the other file engines: read from the end, bounded', () => {
it.each([
['cursor', 'cursor', 'cursor'], ['pi', 'pi', 'pi'], ['commandcode', 'commandcode', 'commandcode'],
- ['terminal', 'raw', 'claude'],
])('%s: the newest page, the page before it, and a cursor it cannot find, through its own window', async (engine, window, from) => {
const s = session(engine, { transcriptPath: transcript(lines) })
const { sessionGet } = setup(s)
diff --git a/cli/src/core/transcripts/history.ts b/cli/src/core/transcripts/history.ts
index cd66ca7b8..b56794b49 100644
--- a/cli/src/core/transcripts/history.ts
+++ b/cli/src/core/transcripts/history.ts
@@ -17,11 +17,10 @@ import { stat } from 'node:fs/promises'
import type { EngineTranscript } from '../../engines/facets/transcript.js'
import { EngineReadError } from '../../engines/worker/protocol.js'
import { transcriptReadIdentity } from './readIdentity.js'
-import { enrichSubagentStats } from '../../engines/kit/history.js'
import { isOtherEngine, loadEngine, type InProcessModules, type OtherEngine } from '../../engines/inProcess.js'
import { sid } from '../../lib/log.js'
import { lastActivityAt } from '../../lib/agentFrame.js'
-import { messagesToEvents, windowRawLines, type SessionEvent } from '../../lib/normalize.js'
+import type { SessionEvent } from '../../engines/kit/events.js'
import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'
import type { TranscriptPager } from '../../lib/transcriptPages.js'
import { tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'
@@ -33,7 +32,7 @@ export interface HistoryDeps {
* and one a restart, a move or a restore had to leave for a new one. */
stopped: () => readonly RegisteredSession[]
/** Line counts, and the explicit inline compatibility path's pages. Isolated readers own their indexes. */
- pages: Pick<TranscriptPager, 'claude' | 'codex' | 'lineCount'>
+ pages: Pick<TranscriptPager, 'page' | 'lineCount'>
readerFor: (engine: string) => EngineTranscript | undefined
/** The database engines' stores. */
dbs: { opencode: string; kilo: string; devin: string }
@@ -176,8 +175,10 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb, readerFo
const st = await stat(s.transcriptPath).catch(() => null)
const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()
// The other file engines' replays and windows are their own code, loaded in this process: one that could
- // not load shows an empty conversation.
- const other = isOtherEngine(s.engine) ? await loadEngine(s.engine) : undefined
+ // not load shows an empty conversation, and so does an engine with no reader and no code of its own here.
+ // Claude Code and Codex always have a reader (core/engines/readers.ts), and a shell keeps no transcript
+ // (registry.engineKeepsTranscriptFile), so none reaches this: their replays are their readers', never core's.
+ const other = isOtherEngine(s.engine) ? await loadEngine(s.engine) : null
if (other === null) return { ...emptyPage(s, sessionId), timestamp }
const engine = <Name extends OtherEngine>(name: Name): InProcessModules[Name] => other as InProcessModules[Name]
@@ -196,10 +197,7 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb, readerFo
? wholeHistoryPage(engine('copilot').copilotMessagesToEvents(lines), false).events
: s.engine === 'pi'
? engine('pi').piMessagesToEvents(lines)
- : s.engine === 'commandcode'
- ? engine('commandcode').commandcodeMessagesToEvents(lines)
- : messagesToEvents(lines)
- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok' && s.engine !== 'agy' && s.engine !== 'copilot') await enrichSubagentStats(fullEvents, s.transcriptPath)
+ : engine('commandcode').commandcodeMessagesToEvents(lines)
return {
id: sessionId,
title: projectDisplayName(s),
@@ -244,9 +242,7 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb, readerFo
? engine('cursor').windowCursorLines(lines, { limit, before })
: s.engine === 'pi'
? engine('pi').windowPiLines(lines, { limit, before })
- : s.engine === 'commandcode'
- ? engine('commandcode').windowCommandCodeLines(lines, { limit, before })
- : windowRawLines(lines, { limit, before })
+ : engine('commandcode').windowCommandCodeLines(lines, { limit, before })
if (w.staleCursor) {
return { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true, ...truncated }
}
@@ -260,11 +256,8 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb, readerFo
)
: s.engine === 'pi'
? engine('pi').piMessagesToEvents(w.window)
- : s.engine === 'commandcode'
- ? engine('commandcode').commandcodeMessagesToEvents(w.window)
- : messagesToEvents(w.window)
+ : engine('commandcode').commandcodeMessagesToEvents(w.window)
// muse and amp are answered above and never reach here, so both are absent by design.
- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(events, s.transcriptPath)
// Older pages must not inject a spurious end-of-transcript marker mid-scroll.
if (before && events[events.length - 1]?.type === 'done') events.pop()
return {
diff --git a/cli/src/core/transcripts/lastTurn.spec.ts b/cli/src/core/transcripts/lastTurn.spec.ts
index b89670162..307f17d61 100644
--- a/cli/src/core/transcripts/lastTurn.spec.ts
+++ b/cli/src/core/transcripts/lastTurn.spec.ts
@@ -29,6 +29,7 @@ vi.mock('../../lib/transcriptTail.js', () => ({
vi.mock('../../engines/claude/normalize.js', () => ({
lastTurnTextFromRawLines: vi.fn((lines: string[]) => ({ text: `raw: ${lines[0]}` })),
selectClaudeRecapLine: vi.fn(),
+ claudePageLine: vi.fn(),
}))
vi.mock('../../engines/cursor/normalizer.js', () => ({ lastCursorTurnText: vi.fn((lines: string[]) => ({ text: `cursor: ${lines[0]}` })) }))
vi.mock('../../engines/muse/normalizer.js', () => ({ lastMuseTurnText: vi.fn((lines: string[]) => ({ text: `muse: ${lines[0]}` })) }))
@@ -88,8 +89,9 @@ describe('the last turn of each engine', () => {
for (const engine of engines) {
expect(await read(`${engine}-s`), engine).toEqual(text(`${engine}: /t/${engine}.jsonl capped`))
}
- // An engine with no reader of its own: its raw lines.
- expect(await read('terminal-s')).toEqual(text('raw: /t/shell.log capped'))
+ // An engine with no reader and no code of its own here has no last turn: core reads no engine's lines itself.
+ // (A shell keeps no transcript: registry.engineKeepsTranscriptFile.)
+ expect(await read('terminal-s')).toBeNull()
})
})
diff --git a/cli/src/core/transcripts/lastTurn.ts b/cli/src/core/transcripts/lastTurn.ts
index 829f5ff46..5095aa3b6 100644
--- a/cli/src/core/transcripts/lastTurn.ts
+++ b/cli/src/core/transcripts/lastTurn.ts
@@ -10,7 +10,7 @@
import type { EngineTranscript } from '../../engines/facets/transcript.js'
import { EngineReadError } from '../../engines/worker/protocol.js'
import { transcriptReadIdentity } from './readIdentity.js'
-import { lastTurnTextFromRawLines, type LastTurnText } from '../../lib/normalize.js'
+import type { LastTurnText } from '../../engines/kit/events.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { tailFileCapped } from '../../lib/transcriptTail.js'
import { loadEngine } from '../../engines/inProcess.js'
@@ -58,6 +58,8 @@ export function createLastTurnReader({ bySession, dbs, hermesDb, readerFor }: La
if (s.engine === 'copilot') return (await loadEngine('copilot'))?.lastCopilotTurnText(lines) ?? null
if (s.engine === 'pi') return (await loadEngine('pi'))?.lastPiTurnText(lines) ?? null
if (s.engine === 'commandcode') return (await loadEngine('commandcode'))?.lastCommandCodeTurnText(lines) ?? null
- return lastTurnTextFromRawLines(lines)
+ // No reader and no code of its own here: Claude Code and Codex always have a reader, and a shell keeps no
+ // transcript, so no engine reaches this. Their recaps are their readers', never core's.
+ return null
}
}
diff --git a/cli/src/core/turns/agyBackstop.ts b/cli/src/core/turns/agyBackstop.ts
index b98522d36..bae9028b3 100644
--- a/cli/src/core/turns/agyBackstop.ts
+++ b/cli/src/core/turns/agyBackstop.ts
@@ -15,7 +15,7 @@
import type { AgyNormalizer } from '../../engines/agy/normalizer.js'
import { engineNow } from '../../engines/inProcess.js'
import { sid } from '../../lib/log.js'
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent } from '../../engines/kit/events.js'
import type { RegisteredSession } from '../../lib/registry.js'
export interface AgyBackstopDeps {
diff --git a/cli/src/core/turns/recaps.ts b/cli/src/core/turns/recaps.ts
index f5b8f68e2..a18e9e537 100644
--- a/cli/src/core/turns/recaps.ts
+++ b/cli/src/core/turns/recaps.ts
@@ -10,7 +10,7 @@
* `mirror` keeps the calls the rest of the core made into the commander mirror when it ran here, so the
* funnel, the heartbeats, cancel, fork, binding and purge each say what happened in their own words.
*/
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent } from '../../engines/kit/events.js'
import { lastFullText, recentAsks, recentRecaps, type RecentRecap, type SessionRecaps } from '../../lib/recapReads.js'
import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'
import type { TurnActivity } from '../../lib/turnActivity.js'
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
index 2666ad48d..febd88420 100644
--- a/cli/src/core/turns/turnHooks.ts
+++ b/cli/src/core/turns/turnHooks.ts
@@ -14,7 +14,7 @@ import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
import type { TurnRecaps } from './recaps.js'
import { sid } from '../../lib/log.js'
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent } from '../../engines/kit/events.js'
import type { RegisteredSession } from '../../lib/registry.js'
import type { SessionNormalizers } from '../transcripts/normalizers.js'
diff --git a/cli/src/core/wifi.ts b/cli/src/core/wifi.ts
index c26bc6363..8ee9f38eb 100644
--- a/cli/src/core/wifi.ts
+++ b/cli/src/core/wifi.ts
@@ -22,7 +22,7 @@
* starting again) is held, in order, and handed on once the service has been resumed; a session, a
* request or a pairing asks for the process (core/devicesWake.ts).
*/
-import type { LiveEvent } from '../lib/normalize.js'
+import type { LiveEvent } from '../engines/kit/events.js'
import type { DeviceInputStatus } from './deviceInput.js'
import type { CoreApi, RemoteClient, WifiPort, WifiResume } from './api.js'
import type { AutonomousDeviceDelivery } from '../lib/autonomous-device/service.js'
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 35433e25e..99f4328d7 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -25,7 +25,10 @@ flags, folder trust and the resume repair, applied by `kit/launchStartup.ts`, `k
`kit/folderTrust.ts` and `kit/resumeRepair.ts`, and what discovery reads off their processes and transcripts
(`claude/discoveryContract.ts`, `codex/discoveryContract.ts`, `kit/processFacts.ts`, `kit/projectFolder.ts`), and
where they keep their sessions, which the registry, session repair, Stop's capture and the handoff read
-(`claude/sessionStore.ts`, `codex/sessionStore.ts`, `kit/sessionRecords.ts`, `kit/continuation.ts`) ([launch](../../../docs/design/2026-10-08-engine-launch.md)). Claude Code and Codex history/last-turn reads,
+(`claude/sessionStore.ts`, `codex/sessionStore.ts`, `kit/sessionRecords.ts`, `kit/continuation.ts`), with the activity
+an agent's frame shows, and how their conversations are adopted (`claude/adoption.ts`, `codex/adoption.ts`,
+`kit/adoption.ts`) ([launch](../../../docs/design/2026-10-08-engine-launch.md)). Their pages are paged by rules their
+readers hand the engine-neutral pager (`lib/transcriptPages.ts`). Claude Code and Codex history/last-turn reads,
live transcript parsing, runtime profiles/catalogs, screen interpretation, submission readings, model-control drivers, question navigation and Codex's app-server connection run on demand in supervised workers;
the other facets still run in core. Explicit inline mode and older masters retain inline implementations. See
[hooks](../../../docs/design/2026-10-08-engine-hooks.md),
diff --git a/cli/src/engines/__fixtures__/transcript-reads.golden.json b/cli/src/engines/__fixtures__/transcript-reads.golden.json
new file mode 100644
index 000000000..efc8781d1
--- /dev/null
+++ b/cli/src/engines/__fixtures__/transcript-reads.golden.json
@@ -0,0 +1,234 @@
+{
+"adoption": {
+ "scan · default homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"claude-app","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0008-4000-8000-000000000008","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0008-4000-8000-000000000008.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0009-4000-8000-000000000009","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0009-4000-8000-000000000009.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0013-4000-8000-000000000013","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/array.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0012-4000-8000-000000000012","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/linked.jsonl","mtime":true}],
+ "scan again · default homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"claude-app","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0008-4000-8000-000000000008","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0008-4000-8000-000000000008.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0009-4000-8000-000000000009","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0009-4000-8000-000000000009.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0013-4000-8000-000000000013","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/array.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0012-4000-8000-000000000012","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/linked.jsonl","mtime":true}],
+ "scan · default homes · codex": [{"sessionId":"cccccccc-0017-4000-8000-000000000017","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Archived one","transcriptPath":"<root>/codex/archived_sessions/rollout-2026-09-20T10-00-00-cccccccc-0017-4000-8000-000000000017.jsonl","archived":true,"mtime":true},{"sessionId":"cccccccc-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Retention cohorts","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"cccccccc-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"codex-app","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"cccccccc-0003-4000-8000-000000000003","cwd":"/work/dial","origin":"editor","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0003-4000-8000-000000000003.jsonl","mtime":true},{"sessionId":"cccccccc-0011-4000-8000-000000000011","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0011-4000-8000-000000000011.jsonl","mtime":true},{"sessionId":"cccccccc-0015-4000-8000-000000000015","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/rollout-2026-09-20T10-00-00-cccccccc-0015-4000-8000-000000000015.jsonl","mtime":true}],
+ "scan again · default homes · codex": [{"sessionId":"cccccccc-0017-4000-8000-000000000017","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Archived one","transcriptPath":"<root>/codex/archived_sessions/rollout-2026-09-20T10-00-00-cccccccc-0017-4000-8000-000000000017.jsonl","archived":true,"mtime":true},{"sessionId":"cccccccc-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Retention cohorts","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"cccccccc-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"codex-app","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"cccccccc-0003-4000-8000-000000000003","cwd":"/work/dial","origin":"editor","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0003-4000-8000-000000000003.jsonl","mtime":true},{"sessionId":"cccccccc-0011-4000-8000-000000000011","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0011-4000-8000-000000000011.jsonl","mtime":true},{"sessionId":"cccccccc-0015-4000-8000-000000000015","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/rollout-2026-09-20T10-00-00-cccccccc-0015-4000-8000-000000000015.jsonl","mtime":true}],
+ "scan · moved homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"claude-app","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0008-4000-8000-000000000008","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0008-4000-8000-000000000008.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0009-4000-8000-000000000009","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0009-4000-8000-000000000009.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0013-4000-8000-000000000013","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/array.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0012-4000-8000-000000000012","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/linked.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0016-4000-8000-000000000016","cwd":"/work/moved","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/moved-claude/projects/-work-moved/aaaaaaaa-0016-4000-8000-000000000016.jsonl","mtime":true}],
+ "scan again · moved homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"claude-app","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0008-4000-8000-000000000008","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0008-4000-8000-000000000008.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0009-4000-8000-000000000009","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0009-4000-8000-000000000009.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0013-4000-8000-000000000013","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/array.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0012-4000-8000-000000000012","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/linked.jsonl","mtime":true},{"sessionId":"aaaaaaaa-0016-4000-8000-000000000016","cwd":"/work/moved","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/moved-claude/projects/-work-moved/aaaaaaaa-0016-4000-8000-000000000016.jsonl","mtime":true}],
+ "scan · moved homes · codex": [{"sessionId":"cccccccc-0017-4000-8000-000000000017","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Archived one","transcriptPath":"<root>/codex/archived_sessions/rollout-2026-09-20T10-00-00-cccccccc-0017-4000-8000-000000000017.jsonl","archived":true,"mtime":true},{"sessionId":"cccccccc-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Retention cohorts","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"cccccccc-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"codex-app","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"cccccccc-0003-4000-8000-000000000003","cwd":"/work/dial","origin":"editor","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0003-4000-8000-000000000003.jsonl","mtime":true},{"sessionId":"cccccccc-0011-4000-8000-000000000011","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0011-4000-8000-000000000011.jsonl","mtime":true},{"sessionId":"cccccccc-0015-4000-8000-000000000015","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/rollout-2026-09-20T10-00-00-cccccccc-0015-4000-8000-000000000015.jsonl","mtime":true},{"sessionId":"cccccccc-0020-4000-8000-000000000020","cwd":"/work/moved","origin":"terminal","engine":"codex","title":"Moved home","transcriptPath":"<root>/moved-codex/sessions/2026/09/21/rollout-2026-09-20T10-00-00-cccccccc-0020-4000-8000-000000000020.jsonl","mtime":true}],
+ "scan again · moved homes · codex": [{"sessionId":"cccccccc-0017-4000-8000-000000000017","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Archived one","transcriptPath":"<root>/codex/archived_sessions/rollout-2026-09-20T10-00-00-cccccccc-0017-4000-8000-000000000017.jsonl","archived":true,"mtime":true},{"sessionId":"cccccccc-0001-4000-8000-000000000001","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"Retention cohorts","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0001-4000-8000-000000000001.jsonl","mtime":true},{"sessionId":"cccccccc-0002-4000-8000-000000000002","cwd":"/work/dial","origin":"codex-app","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0002-4000-8000-000000000002.jsonl","mtime":true},{"sessionId":"cccccccc-0003-4000-8000-000000000003","cwd":"/work/dial","origin":"editor","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0003-4000-8000-000000000003.jsonl","mtime":true},{"sessionId":"cccccccc-0011-4000-8000-000000000011","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0011-4000-8000-000000000011.jsonl","mtime":true},{"sessionId":"cccccccc-0015-4000-8000-000000000015","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/rollout-2026-09-20T10-00-00-cccccccc-0015-4000-8000-000000000015.jsonl","mtime":true},{"sessionId":"cccccccc-0020-4000-8000-000000000020","cwd":"/work/moved","origin":"terminal","engine":"codex","title":"Moved home","transcriptPath":"<root>/moved-codex/sessions/2026/09/21/rollout-2026-09-20T10-00-00-cccccccc-0020-4000-8000-000000000020.jsonl","mtime":true}],
+ "scan · written since · codex · past every window": [],
+ "scan · written since · claude": [{"sessionId":"aaaaaaaa-0006-4000-8000-000000000006","cwd":"/work/dial","origin":"terminal","engine":"claude","title":"","transcriptPath":"<root>/claude/projects/-work-dial/aaaaaaaa-0006-4000-8000-000000000006.jsonl","mtime":true}],
+ "scan · written since · codex": [{"sessionId":"cccccccc-0012-4000-8000-000000000012","cwd":"/work/dial","origin":"terminal","engine":"codex","title":"","transcriptPath":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0012-4000-8000-000000000012.jsonl","mtime":true}],
+ "owners · default homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","pid":101,"record":"<root>/claude/sessions/101.json"},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","pid":102,"record":"<root>/claude/sessions/102.json"},{"sessionId":"aaaaaaaa-0003-4000-8000-000000000003","pid":110,"record":"<root>/claude/sessions/110.json"},{"sessionId":"aaaaaaaa-0005-4000-8000-000000000005","pid":112,"record":"<root>/claude/sessions/112.json"}],
+ "owners · moved homes · claude": [{"sessionId":"aaaaaaaa-0001-4000-8000-000000000001","pid":101,"record":"<root>/claude/sessions/101.json"},{"sessionId":"aaaaaaaa-0002-4000-8000-000000000002","pid":102,"record":"<root>/claude/sessions/102.json"},{"sessionId":"aaaaaaaa-0003-4000-8000-000000000003","pid":110,"record":"<root>/claude/sessions/110.json"},{"sessionId":"aaaaaaaa-0005-4000-8000-000000000005","pid":112,"record":"<root>/claude/sessions/112.json"},{"sessionId":"aaaaaaaa-0016-4000-8000-000000000016","pid":201,"record":"<root>/moved-claude/sessions/201.json"}],
+ "owners · no records · claude": {"claims":[],"looked":false},
+ "busy · claude · 101.json": true,
+ "busy · claude · 102.json": false,
+ "busy · claude · 110.json": null,
+ "busy · claude · 104.json": false,
+ "busy · claude · gone.json": false,
+ "busy · claude · dir.json": false,
+ "owners · codex · asked for": ["codex","Codex"],
+ "owners · codex": [{"sessionId":"cccccccc-0001-4000-8000-000000000001","pid":301,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0001-4000-8000-000000000001.jsonl"},{"sessionId":"cccccccc-0002-4000-8000-000000000002","pid":303,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0002-4000-8000-000000000002.jsonl","app":true},{"sessionId":"cccccccc-0003-4000-8000-000000000003","pid":304,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0003-4000-8000-000000000003.jsonl","app":true},{"sessionId":"cccccccc-0004-4000-8000-000000000004","pid":305,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0004-4000-8000-000000000004.jsonl","app":true},{"sessionId":"cccccccc-0005-4000-8000-000000000005","pid":306,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0005-4000-8000-000000000005.jsonl","app":true},{"sessionId":"cccccccc-0006-4000-8000-000000000006","pid":307,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0006-4000-8000-000000000006.jsonl"},{"sessionId":"cccccccc-0007-4000-8000-000000000007","pid":308,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0007-4000-8000-000000000007.jsonl"},{"sessionId":"cccccccc-0008-4000-8000-000000000008","pid":309,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0008-4000-8000-000000000008.jsonl","app":true},{"sessionId":"cccccccc-0009-4000-8000-000000000009","pid":310,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0009-4000-8000-000000000009.jsonl","app":true},{"sessionId":"cccccccc-0010-4000-8000-000000000010","pid":310,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0010-4000-8000-000000000010.jsonl","app":true},{"sessionId":"cccccccc-0011-4000-8000-000000000011","pid":311,"record":"/x/rollout-2026-09-20T10-00-00-cccccccc-0011-4000-8000-000000000011.JSONL"},{"sessionId":"CCCCCCCC-0011-4000-8000-000000000011","pid":311,"record":"/x/rollout-CCCCCCCC-0011-4000-8000-000000000011.jsonl"},{"sessionId":"cccccccc-0015-4000-8000-000000000015","pid":312,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0015-4000-8000-000000000015.jsonl","app":true},{"sessionId":"cccccccc-0016-4000-8000-000000000016","pid":313,"record":"<root>/codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-cccccccc-0016-4000-8000-000000000016.jsonl"}],
+ "owners · nothing held · codex": {"claims":[],"listed":false},
+ "busy · codex · ended": false,
+ "busy · codex · aborted": false,
+ "busy · codex · working": true,
+ "busy · codex · other": true,
+ "busy · codex · unsaid": null,
+ "busy · codex · quoted": false,
+ "busy · codex · first line only": null,
+ "busy · codex · past the first window": false,
+ "busy · codex · past every window": null,
+ "busy · codex · gone": null
+},
+"activity": {
+ "claude · a prompt": 1789898460000,
+ "claude · a prompt · read again": 1789898460000,
+ "claude · an answer after a prompt": 1789898520000,
+ "claude · an answer after a prompt · read again": 1789898520000,
+ "claude · newest last, older after": 1789898700000,
+ "claude · newest last, older after · read again": 1789898700000,
+ "claude · a turn duration": 1789898640000,
+ "claude · a turn duration · read again": 1789898640000,
+ "claude · a stop hook summary": 1789898640000,
+ "claude · a stop hook summary · read again": 1789898640000,
+ "claude · a compact boundary": 1789898640000,
+ "claude · a compact boundary · read again": 1789898640000,
+ "claude · another system record": null,
+ "claude · another system record · read again": null,
+ "claude · a subtype that reads as a counted one": 1789898640000,
+ "claude · a subtype that reads as a counted one · read again": 1789898640000,
+ "claude · metadata only": null,
+ "claude · metadata only · read again": null,
+ "claude · a local time": 1789912800000,
+ "claude · a local time · read again": 1789912800000,
+ "claude · a bad time": null,
+ "claude · a bad time · read again": null,
+ "claude · a number for a time": null,
+ "claude · a number for a time · read again": null,
+ "claude · a record that is not an object": null,
+ "claude · a record that is not an object · read again": null,
+ "claude · a large last record": 1789898520000,
+ "claude · a large last record · read again": 1789898520000,
+ "claude · a large last record, not counted": 1789898460000,
+ "claude · a large last record, not counted · read again": 1789898460000,
+ "claude · activity past the bound": null,
+ "claude · activity past the bound · read again": null,
+ "claude · a codex rollout": null,
+ "claude · a codex rollout · read again": null,
+ "codex · each counted event": 1789898820000,
+ "codex · each counted event · read again": 1789898820000,
+ "codex · an uncounted event": null,
+ "codex · an uncounted event · read again": null,
+ "codex · each counted response": 1789898760000,
+ "codex · each counted response · read again": 1789898760000,
+ "codex · messages by role": 1789900260000,
+ "codex · messages by role · read again": 1789900260000,
+ "codex · a system message only": null,
+ "codex · a system message only · read again": null,
+ "codex · a type that reads as a message": null,
+ "codex · a type that reads as a message · read again": null,
+ "codex · a type that reads as a counted one": 1789900920000,
+ "codex · a type that reads as a counted one · read again": 1789900920000,
+ "codex · an item below the payload": 1789899120000,
+ "codex · an item below the payload · read again": 1789899120000,
+ "codex · an item below the payload, not counted": null,
+ "codex · an item below the payload, not counted · read again": null,
+ "codex · a compaction": 1789899180000,
+ "codex · a compaction · read again": 1789899180000,
+ "codex · metadata only": null,
+ "codex · metadata only · read again": null,
+ "codex · no payload": null,
+ "codex · no payload · read again": null,
+ "codex · a local time": 1789912800000,
+ "codex · a local time · read again": 1789912800000,
+ "codex · a claude transcript": null,
+ "codex · a claude transcript · read again": null,
+ "an empty file": null,
+ "a missing file": null,
+ "a folder": null,
+ "no path": null,
+ "another engine · pi": null,
+ "another engine · cursor": null,
+ "another engine · terminal": null,
+ "another engine · toString": null,
+ "grown since": 1789898820000
+},
+"pages": {
+ "claude · chain · limit 3": [{"lines":5,"sha":"4cb12132995090f2","first":"{\"type\":\"user\",\"uuid\":\"u-30\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-30","clipped":false},{"lines":4,"sha":"00f291384a5aba46","first":"{\"type\":\"user\",\"uuid\":\"u-29\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-29","clipped":false},{"lines":3,"sha":"f4c92c320b5c105d","first":"{\"type\":\"user\",\"uuid\":\"u-28\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-28","clipped":false},{"lines":4,"sha":"609d4f06334f09f5","first":"{\"type\":\"user\",\"uuid\":\"u-27\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-27","clipped":false},{"lines":4,"sha":"ca91148095c9ec8b","first":"{\"type\":\"user\",\"uuid\":\"u-26\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-26","clipped":false},{"lines":5,"sha":"0e6dbd80396b8e92","first":"{\"type\":\"user\",\"uuid\":\"u-25\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-25","clipped":false},{"lines":4,"sha":"0098a86d3a4e40d9","first":"{\"type\":\"user\",\"uuid\":\"u-24\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-24","clipped":false},{"lines":4,"sha":"b19124f2bb01d63a","first":"{\"type\":\"user\",\"uuid\":\"u-23\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-23","clipped":false},{"lines":4,"sha":"c27006b29a836e0f","first":"{\"type\":\"user\",\"uuid\":\"u-22\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-22","clipped":false},{"lines":3,"sha":"5d7f8c5ef8a293e6","first":"{\"type\":\"user\",\"uuid\":\"u-21\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-21","clipped":false},{"lines":5,"sha":"020abf3fa5cdf425","first":"{\"type\":\"user\",\"uuid\":\"u-20\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-20","clipped":false},{"lines":4,"sha":"a1e885b37bbe8f23","first":"{\"type\":\"user\",\"uuid\":\"u-19\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-19","clipped":false},{"lines":4,"sha":"1beb6ca86b0ad99c","first":"{\"type\":\"user\",\"uuid\":\"u-18\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-18","clipped":false},{"lines":8,"sha":"3efe8315a17cb8cf","first":"{\"type\":\"user\",\"uuid\":\"u-17\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-17","clipped":false},{"lines":4,"sha":"3d46438983b4558b","first":"{\"type\":\"user\",\"uuid\":\"u-16\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-16","clipped":false},{"lines":5,"sha":"8b0138ae16027f09","first":"{\"type\":\"user\",\"uuid\":\"u-15\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-15","clipped":false},{"lines":3,"sha":"ac592ae6c8bfc206","first":"{\"type\":\"user\",\"uuid\":\"u-14\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-14","clipped":false},{"lines":4,"sha":"8ddb986c5109047c","first":"{\"type\":\"user\",\"uuid\":\"u-13\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-13","clipped":false},{"lines":4,"sha":"824860ad1a92f449","first":"{\"type\":\"user\",\"uuid\":\"u-12\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-12","clipped":false},{"lines":56,"sha":"d66eaddba65caee4","first":"{\"type\":\"user\",\"uuid\":\"r-11-32\",\"message\":{\"role\":\"user\",\"co","hasMore":true,"oldestCursor":"r-11-32","clipped":true},{"lines":56,"sha":"4118e5e66c8c2b55","first":"{\"type\":\"user\",\"uuid\":\"r-11-4\",\"message\":{\"role\":\"user\",\"con","hasMore":true,"oldestCursor":"r-11-4","clipped":true},{"lines":10,"sha":"eb96b1d72433c221","first":"{\"type\":\"user\",\"uuid\":\"u-11\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-11","clipped":false},{"lines":5,"sha":"14df8d76ed1fc1b5","first":"{\"type\":\"user\",\"uuid\":\"u-10\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-10","clipped":false},{"lines":4,"sha":"d935f98c46e5574b","first":"{\"type\":\"user\",\"uuid\":\"u-9\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-9","clipped":false},{"lines":4,"sha":"25ca007df4542288","first":"{\"type\":\"user\",\"uuid\":\"u-8\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-8","clipped":false},{"lines":3,"sha":"5969ef7988259b75","first":"{\"type\":\"user\",\"uuid\":\"u-7\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-7","clipped":false},{"lines":4,"sha":"cb461ad838c83a0c","first":"{\"type\":\"user\",\"uuid\":\"u-6\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-6","clipped":false},{"lines":5,"sha":"0c9add5211b6e02c","first":"{\"type\":\"user\",\"uuid\":\"u-5\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-5","clipped":false},{"lines":4,"sha":"4d26937686ae0b5b","first":"{\"type\":\"user\",\"uuid\":\"u-4\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-4","clipped":false},{"lines":4,"sha":"153486dccc2e3117","first":"{\"type\":\"user\",\"uuid\":\"u-3\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-3","clipped":false},{"lines":4,"sha":"e1d2eef71aa6f180","first":"{\"type\":\"user\",\"uuid\":\"u-2\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-2","clipped":false},{"lines":4,"sha":"70ea0711323a976d","first":"{\"type\":\"user\",\"uuid\":\"u-1\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-1","clipped":false},{"lines":1,"sha":"d7f6d9375c79c707","first":"{\"type\":\"permission-mode\",\"permissionMode\":\"default\"}","hasMore":false,"oldestCursor":null,"clipped":false}],
+ "claude · chain · limit 10": [{"lines":12,"sha":"f8a6f30d59c06472","first":"{\"type\":\"user\",\"uuid\":\"u-28\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-28","clipped":false},{"lines":13,"sha":"c93d5b7c3cb69e43","first":"{\"type\":\"user\",\"uuid\":\"u-25\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-25","clipped":false},{"lines":12,"sha":"60afab189dd8f532","first":"{\"type\":\"user\",\"uuid\":\"u-22\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-22","clipped":false},{"lines":12,"sha":"9a79312799935f2d","first":"{\"type\":\"user\",\"uuid\":\"u-19\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-19","clipped":false},{"lines":12,"sha":"d6aa3b6a3d2ad920","first":"{\"type\":\"user\",\"uuid\":\"u-17\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-17","clipped":false},{"lines":12,"sha":"b5b752358d34d9a9","first":"{\"type\":\"user\",\"uuid\":\"u-14\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-14","clipped":false},{"lines":8,"sha":"cdcfb15dc2729aa7","first":"{\"type\":\"user\",\"uuid\":\"u-12\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-12","clipped":false},{"lines":56,"sha":"d66eaddba65caee4","first":"{\"type\":\"user\",\"uuid\":\"r-11-32\",\"message\":{\"role\":\"user\",\"co","hasMore":true,"oldestCursor":"r-11-32","clipped":true},{"lines":56,"sha":"4118e5e66c8c2b55","first":"{\"type\":\"user\",\"uuid\":\"r-11-4\",\"message\":{\"role\":\"user\",\"con","hasMore":true,"oldestCursor":"r-11-4","clipped":true},{"lines":10,"sha":"eb96b1d72433c221","first":"{\"type\":\"user\",\"uuid\":\"u-11\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-11","clipped":false},{"lines":13,"sha":"4b145758c7424d5e","first":"{\"type\":\"user\",\"uuid\":\"u-8\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-8","clipped":false},{"lines":12,"sha":"c6681f1d317d2025","first":"{\"type\":\"user\",\"uuid\":\"u-5\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-5","clipped":false},{"lines":12,"sha":"eb3d29454bf84e47","first":"{\"type\":\"user\",\"uuid\":\"u-2\",\"sessionId\":\"s\",\"timestamp\":\"202","hasMore":true,"oldestCursor":"u-2","clipped":false},{"lines":5,"sha":"dc9b44e35552f78a","first":"{\"type\":\"permission-mode\",\"permissionMode\":\"default\"}","hasMore":false,"oldestCursor":null,"clipped":false}],
+ "claude · chain · limit none": [{"lines":61,"sha":"84633db3716faa65","first":"{\"type\":\"user\",\"uuid\":\"u-17\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-17","clipped":false},{"lines":20,"sha":"6113a842945a13c4","first":"{\"type\":\"user\",\"uuid\":\"u-12\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-12","clipped":false},{"lines":56,"sha":"d66eaddba65caee4","first":"{\"type\":\"user\",\"uuid\":\"r-11-32\",\"message\":{\"role\":\"user\",\"co","hasMore":true,"oldestCursor":"r-11-32","clipped":true},{"lines":56,"sha":"4118e5e66c8c2b55","first":"{\"type\":\"user\",\"uuid\":\"r-11-4\",\"message\":{\"role\":\"user\",\"con","hasMore":true,"oldestCursor":"r-11-4","clipped":true},{"lines":52,"sha":"3147be52209fe9a8","first":"{\"type\":\"permission-mode\",\"permissionMode\":\"default\"}","hasMore":false,"oldestCursor":null,"clipped":false}],
+ "claude · lines": 249,
+ "codex · chain · limit 3": [{"lines":5,"sha":"553c50b682c531b6","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:268","clipped":false},{"lines":5,"sha":"c02b18664ce4e383","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:263","clipped":false},{"lines":4,"sha":"e43bfd3ec45796bd","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:258","clipped":false},{"lines":5,"sha":"8248bac8a5d96dbe","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:253","clipped":false},{"lines":5,"sha":"cd3152eb07bcf55f","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:248","clipped":false},{"lines":5,"sha":"bcde87a4cf753353","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:243","clipped":false},{"lines":5,"sha":"780eabf9b64c6d52","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:238","clipped":false},{"lines":5,"sha":"683dd9275d53662b","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:233","clipped":false},{"lines":5,"sha":"a63d57ca661203a4","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:228","clipped":false},{"lines":4,"sha":"7ee53ddefba0d43e","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:223","clipped":false},{"lines":5,"sha":"e8c175a27026a5db","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:218","clipped":false},{"lines":5,"sha":"b2df5386d0e8a474","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:213","clipped":false},{"lines":5,"sha":"a608edc01ad369ae","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:208","clipped":false},{"lines":9,"sha":"aa944ab6eeb96444","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:199","clipped":false},{"lines":5,"sha":"2a88d1d2acaf41ac","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:194","clipped":false},{"lines":5,"sha":"2527df4b8aa7890c","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:189","clipped":false},{"lines":4,"sha":"b3085d086b49e18d","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:184","clipped":false},{"lines":5,"sha":"351d6e6cc2a5f1ea","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:179","clipped":false},{"lines":5,"sha":"5c2132414ffd7231","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:174","clipped":false},{"lines":69,"sha":"07fd44f3398623d3","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"function_call_out","hasMore":true,"oldestCursor":"codex:105","clipped":true},{"lines":54,"sha":"b9e875648ceb210c","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:51","clipped":false},{"lines":5,"sha":"509cb7bd2a80f15c","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:46","clipped":false},{"lines":5,"sha":"d256fb0f2a125085","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:41","clipped":false},{"lines":5,"sha":"d03d3230b9dfe4a8","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:36","clipped":false},{"lines":4,"sha":"3e73a29866791a1f","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:31","clipped":false},{"lines":5,"sha":"572a153994cc6b86","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:26","clipped":false},{"lines":5,"sha":"9ee15ea1bed75275","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:21","clipped":false},{"lines":5,"sha":"fdcf77caf62f219f","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:16","clipped":false},{"lines":5,"sha":"a29a12c9c5505cd2","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:11","clipped":false},{"lines":5,"sha":"daede50180016906","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:6","clipped":false},{"lines":5,"sha":"2cabd1bd31f56bce","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:1","clipped":false},{"lines":1,"sha":"168eb7cda09bf266","first":"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s\",\"cwd\":\"/work/dial","hasMore":false,"oldestCursor":"codex:0","clipped":false}],
+ "codex · chain · limit 10": [{"lines":10,"sha":"b106db4b61d43516","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:263","clipped":false},{"lines":9,"sha":"377728f44ac9fd6a","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:253","clipped":false},{"lines":10,"sha":"8652b907dbad9bc0","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:243","clipped":false},{"lines":10,"sha":"c62459fea95c7b07","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:233","clipped":false},{"lines":9,"sha":"aa15befe90a1e1c0","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:223","clipped":false},{"lines":10,"sha":"3ac8cfafcb20f431","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:213","clipped":false},{"lines":14,"sha":"2c953a0451ad595e","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:199","clipped":false},{"lines":10,"sha":"010c603205db414a","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:189","clipped":false},{"lines":9,"sha":"fc89639cd542a8c7","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:179","clipped":false},{"lines":5,"sha":"5c2132414ffd7231","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:174","clipped":false},{"lines":69,"sha":"07fd44f3398623d3","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"function_call_out","hasMore":true,"oldestCursor":"codex:105","clipped":true},{"lines":54,"sha":"b9e875648ceb210c","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:51","clipped":false},{"lines":10,"sha":"ee7cc87b9345f562","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:41","clipped":false},{"lines":9,"sha":"dbbb4a1a62130ae5","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:31","clipped":false},{"lines":10,"sha":"4341be3a31380226","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:21","clipped":false},{"lines":10,"sha":"a6dfd7fbb0bdacc9","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:11","clipped":false},{"lines":10,"sha":"bb13bea749adfb54","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:1","clipped":false},{"lines":1,"sha":"168eb7cda09bf266","first":"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s\",\"cwd\":\"/work/dial","hasMore":false,"oldestCursor":"codex:0","clipped":false}],
+ "codex · chain · limit none": [{"lines":72,"sha":"f5aa5c8feaa8f1c7","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:199","clipped":false},{"lines":24,"sha":"be31ba4d0eae6d44","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:174","clipped":false},{"lines":69,"sha":"07fd44f3398623d3","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"function_call_out","hasMore":true,"oldestCursor":"codex:105","clipped":true},{"lines":69,"sha":"0a1052d1b8fbbef7","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:36","clipped":false},{"lines":35,"sha":"9ff80b48ffd71f49","first":"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s\",\"cwd\":\"/work/dial","hasMore":false,"oldestCursor":"codex:0","clipped":false}],
+ "codex · lines": 273,
+ "claude · before · a prompt": {"lines":4,"sha":"a1e885b37bbe8f23","first":"{\"type\":\"user\",\"uuid\":\"u-19\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-19","clipped":false},
+ "claude · before · a tool call": {"lines":5,"sha":"7198e7998ff3bd1b","first":"{\"type\":\"user\",\"uuid\":\"u-19\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-19","clipped":false},
+ "claude · before · the huge line": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · before · the first line": {"lines":1,"sha":"d7f6d9375c79c707","first":"{\"type\":\"permission-mode\",\"permissionMode\":\"default\"}","hasMore":false,"oldestCursor":null,"clipped":false},
+ "claude · before · unknown": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · before · empty": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · before · a quoted id": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · before · no limit, before a prompt": {"lines":64,"sha":"1fa8a34d2548552e","first":"{\"type\":\"user\",\"uuid\":\"u-14\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-14","clipped":false},
+ "codex · before · the start": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · before · a line": {"lines":4,"sha":"94dfb502075f9ee0","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:36","clipped":false},
+ "codex · before · a leading zero": {"lines":4,"sha":"94dfb502075f9ee0","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:36","clipped":false},
+ "codex · before · the end": {"lines":5,"sha":"553c50b682c531b6","first":"{\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"","hasMore":true,"oldestCursor":"codex:268","clipped":false},
+ "codex · before · past the end": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · before · negative": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · before · not a number": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · before · garbage": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · before · unsafe": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · before · no limit": {"lines":59,"sha":"92b8d05d9fb410c8","first":"{\"type\":\"session_meta\",\"payload\":{\"id\":\"s\",\"cwd\":\"/work/dial","hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "claude · missing · none": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"clipped":false},
+ "claude · missing · u-1": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · missing · codex:0": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · missing · codex:00": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · missing · codex:5": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · missing · garbage": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · missing · lines": 0,
+ "claude · unreadable · none": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"clipped":false},
+ "claude · unreadable · u-1": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · unreadable · codex:0": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · unreadable · codex:00": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · unreadable · codex:5": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · unreadable · garbage": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · missing · none": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · missing · u-1": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · missing · codex:0": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · missing · codex:00": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · missing · codex:5": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · missing · garbage": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · missing · lines": 0,
+ "codex · unreadable · none": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · unreadable · u-1": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · unreadable · codex:0": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · unreadable · codex:00": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":"codex:0","clipped":false},
+ "codex · unreadable · codex:5": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "codex · unreadable · garbage": {"lines":0,"sha":"e3b0c44298fc1c14","first":null,"hasMore":false,"oldestCursor":null,"staleCursor":true,"clipped":false},
+ "claude · grown · the remembered cursor": {"lines":4,"sha":"00f291384a5aba46","first":"{\"type\":\"user\",\"uuid\":\"u-29\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-29","clipped":false},
+ "claude · grown · the next": {"lines":3,"sha":"f4c92c320b5c105d","first":"{\"type\":\"user\",\"uuid\":\"u-28\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-28","clipped":false},
+ "claude · grown · from the end": {"lines":4,"sha":"b09b1927d5eaa2fb","first":"{\"type\":\"user\",\"uuid\":\"u-31\",\"sessionId\":\"s\",\"timestamp\":\"20","hasMore":true,"oldestCursor":"u-31","clipped":false},
+ "codex · grown · the old cursor": {"lines":5,"sha":"c02b18664ce4e383","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:263","clipped":false},
+ "codex · grown · from the end": {"lines":5,"sha":"46eb8d8ba768fac2","first":"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"messag","hasMore":true,"oldestCursor":"codex:273","clipped":false},
+ "codex · grown · lines": 278
+},
+"history": {
+ "reader · claude · fixture · whole": {"sha":"316f5e9cbdeba0d4","types":"user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,text_delta,text_delta,text_delta,done","timestamp":"string"},
+ "reader · claude · fixture · latest": {"sha":"316f5e9cbdeba0d4","types":"user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,text_delta,text_delta,text_delta,done","timestamp":"string","hasMore":false,"oldestCursor":"1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"},
+ "reader · claude · fixture · older": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":"1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"},
+ "reader · claude · fixture · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "reader · claude · fixture · last turn": {"userMessage":"Chạy 3 sub-agent SONG SONG (launch cả 3 cùng một lượt), mỗi agent một việc độc lập rồi báo cáo lại:\n- Agent 1: Report giá coin BTC\n- Agent 2: Report giá coin ETH\n- Agent 3: Report giá coin BNB","assistantText":"Đã spawn 3 sub-agent song song cho BTC, ETH, BNB. Sẽ báo kết quả khi cả ba hoàn thành.\n\nSub-agent ETH xong: **~$1,860–$1,870** (~$225.36 tỷ vốn hóa). Đang chờ BTC, BNB.\n\nSub-agent BNB xong: **~$590.04** (+0.72% 24h). Chỉ còn chờ BTC.\n\nCả 3 sub-agent đã hoàn thành. Tổng hợp giá coin:\n\n| Coin | Giá (USD) | Thay đổi 24h | Vốn hóa thị trường |\n|---|---|---|---|\n| **BTC** | ~$63,500–$63,900 | +2.1% | ~$1,281 tỷ (#1) |\n| **ETH** | ~$1,860–$1,870 | ~+0.5–1.2% (chênh lệch giữa sàn) | ~$225.36 tỷ (#2) |\n| **BNB** | ~$590.04 | +0.72% | ~$78.57 tỷ (#4) |"},
+ "reader · claude · corpus · whole": {"sha":"11a86e13d1b41748","types":"user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,done","timestamp":"string"},
+ "reader · claude · corpus · latest": {"sha":"313419b69dea5e32","types":"user_message,tool_start,tool_end,text_delta,done","timestamp":"string","hasMore":true,"oldestCursor":"u-31"},
+ "reader · claude · corpus · older": {"sha":"5290de351165723c","types":"user_message,tool_start,tool_end,text_delta","timestamp":"string","hasMore":true,"oldestCursor":"u-30"},
+ "reader · claude · corpus · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "reader · claude · corpus · last turn": {"userMessage":"ask 31","assistantText":"answer 31"},
+ "reader · codex · fixture · whole": {"sha":"72e8303d29cfef31","types":"tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,done","timestamp":"string"},
+ "reader · codex · fixture · latest": {"sha":"72e8303d29cfef31","types":"tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,done","timestamp":"string","hasMore":false,"oldestCursor":"codex:0"},
+ "reader · codex · fixture · older": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":"codex:0"},
+ "reader · codex · fixture · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "reader · codex · fixture · last turn": null,
+ "reader · codex · corpus · whole": {"sha":"b4cb4f48ddc96e5a","types":"user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,done","timestamp":"string"},
+ "reader · codex · corpus · latest": {"sha":"2a1f9418eef19e85","types":"user_message,tool_start,tool_end,text_delta,done","timestamp":"string","hasMore":true,"oldestCursor":"codex:273"},
+ "reader · codex · corpus · older": {"sha":"935d59da8ebbf8b5","types":"user_message,tool_start,tool_end,text_delta","timestamp":"string","hasMore":true,"oldestCursor":"codex:268"},
+ "reader · codex · corpus · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "reader · codex · corpus · last turn": {"userMessage":"ask 31","assistantText":"answer 31"},
+ "reader · claude · no transcript": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null},
+ "reader · claude · no transcript · last turn": null,
+ "reader · codex · no transcript": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","hasMore":false,"oldestCursor":null},
+ "reader · codex · no transcript · last turn": null,
+ "core · claude · fixture · whole": {"sha":"316f5e9cbdeba0d4","types":"user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,text_delta,text_delta,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"claude"},
+ "core · claude · fixture · latest": {"sha":"316f5e9cbdeba0d4","types":"user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,text_delta,text_delta,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":false,"oldestCursor":"1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"},
+ "core · claude · fixture · older": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":false,"oldestCursor":"1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"},
+ "core · claude · fixture · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "core · claude · fixture · list": [{"id":"session","title":"dial · sess","timestamp":"2026-10-07T12:00:00.000Z","messageCount":14,"participants":[],"lastActivity":"string"}],
+ "core · claude · fixture · last turn": {"userMessage":"Chạy 3 sub-agent SONG SONG (launch cả 3 cùng một lượt), mỗi agent một việc độc lập rồi báo cáo lại:\n- Agent 1: Report giá coin BTC\n- Agent 2: Report giá coin ETH\n- Agent 3: Report giá coin BNB","assistantText":"Đã spawn 3 sub-agent song song cho BTC, ETH, BNB. Sẽ báo kết quả khi cả ba hoàn thành.\n\nSub-agent ETH xong: **~$1,860–$1,870** (~$225.36 tỷ vốn hóa). Đang chờ BTC, BNB.\n\nSub-agent BNB xong: **~$590.04** (+0.72% 24h). Chỉ còn chờ BTC.\n\nCả 3 sub-agent đã hoàn thành. Tổng hợp giá coin:\n\n| Coin | Giá (USD) | Thay đổi 24h | Vốn hóa thị trường |\n|---|---|---|---|\n| **BTC** | ~$63,500–$63,900 | +2.1% | ~$1,281 tỷ (#1) |\n| **ETH** | ~$1,860–$1,870 | ~+0.5–1.2% (chênh lệch giữa sàn) | ~$225.36 tỷ (#2) |\n| **BNB** | ~$590.04 | +0.72% | ~$78.57 tỷ (#4) |"},
+ "core · claude · corpus · whole": {"sha":"11a86e13d1b41748","types":"user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"claude"},
+ "core · claude · corpus · latest": {"sha":"313419b69dea5e32","types":"user_message,tool_start,tool_end,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":true,"oldestCursor":"u-31"},
+ "core · claude · corpus · older": {"sha":"5290de351165723c","types":"user_message,tool_start,tool_end,text_delta","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":true,"oldestCursor":"u-30"},
+ "core · claude · corpus · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"claude","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "core · claude · corpus · list": [{"id":"session","title":"dial · sess","timestamp":"2026-10-07T12:00:00.000Z","messageCount":253,"participants":[],"lastActivity":"string"}],
+ "core · claude · corpus · last turn": {"userMessage":"ask 31","assistantText":"answer 31"},
+ "core · codex · fixture · whole": {"sha":"72e8303d29cfef31","types":"tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,done","timestamp":"string","id":"session","title":"dial · sess","engine":"codex"},
+ "core · codex · fixture · latest": {"sha":"72e8303d29cfef31","types":"tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,done","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":false,"oldestCursor":"codex:0"},
+ "core · codex · fixture · older": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":false,"oldestCursor":"codex:0"},
+ "core · codex · fixture · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "core · codex · fixture · list": [{"id":"session","title":"dial · sess","timestamp":"2026-10-07T12:00:00.000Z","messageCount":6,"participants":[],"lastActivity":"string"}],
+ "core · codex · fixture · last turn": null,
+ "core · codex · corpus · whole": {"sha":"b4cb4f48ddc96e5a","types":"user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,tool_start,tool_end,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,user_message,tool_start,tool_end,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"codex"},
+ "core · codex · corpus · latest": {"sha":"2a1f9418eef19e85","types":"user_message,tool_start,tool_end,text_delta,done","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":true,"oldestCursor":"codex:273"},
+ "core · codex · corpus · older": {"sha":"935d59da8ebbf8b5","types":"user_message,tool_start,tool_end,text_delta","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":true,"oldestCursor":"codex:268"},
+ "core · codex · corpus · stale": {"sha":"4f53cda18c2baa0c","types":"","timestamp":"string","id":"session","title":"dial · sess","engine":"codex","hasMore":false,"oldestCursor":null,"staleCursor":true},
+ "core · codex · corpus · list": [{"id":"session","title":"dial · sess","timestamp":"2026-10-07T12:00:00.000Z","messageCount":278,"participants":[],"lastActivity":"string"}],
+ "core · codex · corpus · last turn": {"userMessage":"ask 31","assistantText":"answer 31"}
+},
+"linux": {
+"adoption": {
+
+},
+"activity": {
+
+},
+"pages": {
+
+},
+"history": {
+
+}
+}
+}
diff --git a/cli/src/engines/adoptions.ts b/cli/src/engines/adoptions.ts
new file mode 100644
index 000000000..209e4b8cb
--- /dev/null
+++ b/cli/src/engines/adoptions.ts
@@ -0,0 +1,17 @@
+/**
+ * Claude Code's and Codex's adoption, composed from their declared contracts (engines/{claude,codex}/adoption.ts)
+ * and the kit's provider (kit/adoption.ts): what lib/sessionSearch/externals/index.ts builds for them, so core's
+ * adoption loads none of their code.
+ */
+import { adoption as claude } from './claude/adoption.js'
+import { adoption as codex } from './codex/adoption.js'
+import type { AdoptionContract } from './facets/adoption.js'
+import { adoptionProvider, type AdoptionPlaces } from './kit/adoption.js'
+import type { ExternalProvider } from '../lib/sessionSearch/externals/types.js'
+
+export const adoptionContracts = { claude, codex } satisfies Record<string, AdoptionContract>
+
+/** `engine`'s provider, looking where `places` says: Claude Code's sessions folders, Codex's homes. */
+export function adoptionProviderOf(engine: keyof typeof adoptionContracts, places: AdoptionPlaces): ExternalProvider {
+ return adoptionProvider(engine, adoptionContracts[engine], places)
+}
diff --git a/cli/src/engines/claude/adoption.ts b/cli/src/engines/claude/adoption.ts
new file mode 100644
index 000000000..cdb8957c6
--- /dev/null
+++ b/cli/src/engines/claude/adoption.ts
@@ -0,0 +1,29 @@
+import type { AdoptionContract } from '../facets/adoption.js'
+import { sessionStore } from './sessionStore.js'
+
+const record = 'record' in sessionStore.live ? sessionStore.live.record : null
+
+/**
+ * Claude Code's conversations, for adoption: data only, which core applies with the kit (kit/adoption.ts).
+ * Copied from the former lib/sessionSearch/externals/claude.ts. The layout and the process record are its
+ * session store's.
+ */
+export const adoption: AdoptionContract = {
+ // `<projects>/<folder>/<id>.jsonl`; a sub-agent's files live in a folder of their own beneath.
+ files: { layout: 'projects', suffix: '.jsonl' },
+ head: {
+ // The line that says who wrote it is usually the first prompt, which can carry a pasted image: a few hundred
+ // kilobytes, or megabytes.
+ windows: [256 * 1024, 4 * 1024 * 1024, 32 * 1024 * 1024],
+ line: { marked: '"entrypoint"' },
+ skip: { field: sessionStore.scan.from === 'head' ? sessionStore.scan.sidechain : 'isSidechain', is: true },
+ id: { field: 'sessionId', pattern: /^[A-Za-z0-9-]{8,80}$/ },
+ cwd: 'cwd',
+ // A terminal, or the Claude app. `sdk-cli` is a program driving Claude, Harness's own summaries among them.
+ origin: { field: 'entrypoint', values: { cli: 'terminal', 'claude-desktop': 'claude-app' } },
+ },
+ // A running Claude Code keeps `<home>/sessions/<pid>.json` naming its session and saying `idle` between turns:
+ // the owner and its state, exactly. `ps` gives a start to the second, and Claude stamps its record a moment after.
+ owners: { records: { folder: record!.folder, suffix: record!.suffix, pid: record!.pid, id: record!.id, started: 'startedAt', slackMs: 2_000 } },
+ busy: { record: { field: 'status', busy: 'busy', idle: 'idle' } },
+}
diff --git a/cli/src/engines/claude/sessionStore.ts b/cli/src/engines/claude/sessionStore.ts
index 140b74102..0cfaa6ebe 100644
--- a/cli/src/engines/claude/sessionStore.ts
+++ b/cli/src/engines/claude/sessionStore.ts
@@ -36,4 +36,12 @@ export const sessionStore: SessionStoreContract = {
* never a turn, so a continuation counts only once a turn is in it (or the file is too long to be those lines).
*/
continuation: { type: 'continued-in', field: 'continuedInSessionId', suffix: '.jsonl', tailBytes: 4 * 1024, turns: ['user', 'assistant'], headBytes: 256 * 1024 },
+ /** A prompt, an answer, and the system records a turn ends with: a title, a file snapshot or a mode is not work. */
+ activity: {
+ at: 'timestamp',
+ records: [
+ { type: 'user' }, { type: 'assistant' },
+ { type: 'system', fields: { subtype: { in: ['turn_duration', 'stop_hook_summary', 'compact_boundary'] } } },
+ ],
+ },
}
diff --git a/cli/src/engines/claude/subagentStats.ts b/cli/src/engines/claude/subagentStats.ts
new file mode 100644
index 000000000..b273a5d9c
--- /dev/null
+++ b/cli/src/engines/claude/subagentStats.ts
@@ -0,0 +1,33 @@
+/**
+ * Claude Code's background agents' totals, joined into its history. Moved from engines/kit/history.ts: the
+ * layout (`<session>/subagents/agent-<id>.jsonl`) and the counting (`SubagentStats`) are Claude Code's, and only
+ * its reader runs it (engines/claude/transcript.ts), in its worker or the inline compatibility path, never core.
+ */
+import { stat } from 'node:fs/promises'
+import { join } from 'node:path'
+import type { SessionEvent } from '../kit/events.js'
+import { streamRecords } from '../../lib/transcriptTail.js'
+import { SubagentStats } from './normalize.js'
+
+/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript
+ * (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record
+ * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation
+ * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */
+export async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {
+ const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')
+ for (const e of events) {
+ if (e.type !== 'tool_end') continue
+ const sub = e.payload.subagent
+ if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue
+ try {
+ // A line at a time: a long sub-agent's transcript is never held whole to count its calls.
+ const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)
+ const totals = new SubagentStats()
+ await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)
+ const stats = totals.result()
+ sub.totalToolUseCount = stats.totalToolUseCount
+ if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs
+ if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens
+ } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }
+ }
+}
diff --git a/cli/src/engines/claude/transcript.ts b/cli/src/engines/claude/transcript.ts
index 0e579ceea..2830cf0c6 100644
--- a/cli/src/engines/claude/transcript.ts
+++ b/cli/src/engines/claude/transcript.ts
@@ -1,11 +1,16 @@
-import { lastTurnTextFromRawLines, messagesToEvents, selectClaudeRecapLine } from './normalize.js'
+import { claudePageLine, lastTurnTextFromRawLines, messagesToEvents, selectClaudeRecapLine } from './normalize.js'
import { tailFileUntil } from '../../lib/transcriptTail.js'
+import type { ThreadPages } from '../../lib/transcriptPages.js'
import type { EngineTranscript } from '../facets/transcript.js'
import { pagedHistory } from '../kit/history.js'
+import { enrichSubagentStats } from './subagentStats.js'
+
+/** A cursor is the id a record carries; a page starts at a real prompt, so a turn is never split. */
+export const pages: ThreadPages = { cursor: 'record', line: claudePageLine }
export const transcript: EngineTranscript = {
async lastTurnText(session) {
return session.transcriptPath ? lastTurnTextFromRawLines(await tailFileUntil(session.transcriptPath, selectClaudeRecapLine)) : null
},
- historyPage: (session, ask, pages) => pagedHistory(session, ask, (path, options) => pages.claude(path, options), messagesToEvents),
+ historyPage: (session, ask, pager) => pagedHistory(session, ask, (path, options) => pager.page(path, pages, options), messagesToEvents, enrichSubagentStats),
}
diff --git a/cli/src/engines/codex/adoption.ts b/cli/src/engines/codex/adoption.ts
new file mode 100644
index 000000000..d8e8b9496
--- /dev/null
+++ b/cli/src/engines/codex/adoption.ts
@@ -0,0 +1,37 @@
+import type { AdoptionContract } from '../facets/adoption.js'
+import { sessionStore } from './sessionStore.js'
+
+const first = sessionStore.first!
+
+/**
+ * Codex's conversations, for adoption: data only, which core applies with the kit (kit/adoption.ts). Copied from
+ * the former lib/sessionSearch/externals/codex.ts. The folders and the first record are its session store's.
+ */
+export const adoption: AdoptionContract = {
+ // `<home>/sessions/YYYY/MM/DD/rollout-*.jsonl`, and the same below `archived_sessions/`: found, to read, but
+ // Codex resumes one only once `codex unarchive` puts it back.
+ files: { layout: 'walk', prefix: 'rollout-', suffix: '.jsonl', depth: 4, folders: { sessions: sessionStore.sessions.own.folder!, archived: sessionStore.sessions.archived } },
+ head: {
+ // A little first; `session_meta` can carry long base instructions, so up to a megabyte when it has to.
+ windows: [16 * 1024, 1024 * 1024],
+ line: 'first',
+ type: first.type,
+ at: first.id.slice(0, -1),
+ id: { field: first.id[first.id.length - 1], pattern: /^[A-Za-z0-9-]{8,80}$/ },
+ cwd: first.cwd[first.cwd.length - 1],
+ // A terminal, or the Codex app (`vscode` from "Codex Desktop") and the editor extensions. `exec` is a script,
+ // and a sub-agent's source is another thread's helper.
+ origin: { field: 'source', values: { cli: 'terminal', vscode: { field: 'originator', is: 'Codex Desktop', then: 'codex-app', otherwise: 'editor' } } },
+ },
+ titles: { file: 'session_index.jsonl', id: 'id', title: 'thread_name' },
+ // Codex keeps no process record, but holds its rollout open while it runs, so `lsof` names the owner. A server
+ // Codex runs for other clients (the app, an editor, MCP) holds their threads.
+ owners: {
+ open: {
+ commands: ['codex', 'Codex'], id: /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i, contains: 'rollout-',
+ servers: { executable: /codex-acp$/, args: /(?:^|\/)codex-acp(?:\s|$)/, subcommands: ['app-server', 'mcp-server', 'mcp', 'proto'] },
+ },
+ },
+ // The rollout's last turn event says whether a turn is running; a file that cannot say is busy.
+ busy: { tail: { windows: [256 * 1024, 4 * 1024 * 1024], marker: '"event_msg"', at: ['payload', 'type'], open: 'task_started', closed: ['task_complete', 'turn_aborted'] } },
+}
diff --git a/cli/src/engines/codex/sessionStore.ts b/cli/src/engines/codex/sessionStore.ts
index b8fd48788..d109dc839 100644
--- a/cli/src/engines/codex/sessionStore.ts
+++ b/cli/src/engines/codex/sessionStore.ts
@@ -41,4 +41,18 @@ export const sessionStore: SessionStoreContract = {
live: { open: { file: /rollout-[^/]*\.jsonl$/, launcher: /^node(?:js)?$/ } },
// A sub-agent's hooks run from its parent's pane, and an older daemon let them overwrite the parent's binding.
repairsOverwrittenParent: true,
+ /**
+ * The events and items of a conversation, and a compaction; never `session_meta`, `turn_context`, a token count
+ * or a rate-limit reading. An item is the payload's, or the one nested in it.
+ */
+ activity: {
+ at: 'timestamp',
+ item: [['payload', 'item'], ['payload']],
+ records: [
+ { type: 'event_msg', item: { type: { in: ['user_message', 'UserMessage', 'agent_message', 'AgentMessage', 'task_started', 'task_complete', 'turn_aborted', 'context_compacted'] } } },
+ { type: 'response_item', item: { type: { in: ['reasoning', 'function_call', 'custom_tool_call', 'tool_search_call', 'function_call_output', 'custom_tool_call_output', 'tool_search_output'] } } },
+ { type: 'response_item', item: { type: { is: ['message'] }, role: { is: ['user', 'assistant'] } } },
+ { type: 'compacted' },
+ ],
+ },
}
diff --git a/cli/src/engines/codex/transcript.ts b/cli/src/engines/codex/transcript.ts
index b5f30f7eb..b8cab6cf5 100644
--- a/cli/src/engines/codex/transcript.ts
+++ b/cli/src/engines/codex/transcript.ts
@@ -1,11 +1,15 @@
import { readLastCodexTurnText } from './lastTurn.js'
-import { codexMessagesToEvents } from './normalizer.js'
+import { codexMessagesToEvents, codexPageStart } from './normalizer.js'
import { codexSubagentResolverFor } from './subagent.js'
+import type { ThreadPages } from '../../lib/transcriptPages.js'
import type { EngineTranscript } from '../facets/transcript.js'
import { pagedHistory } from '../kit/history.js'
+/** A cursor is `codex:<lines before it>`; a page starts at a user's message or a goal's injected context. */
+export const pages: ThreadPages = { cursor: 'line', prefix: 'codex', startsPage: codexPageStart }
+
export const transcript: EngineTranscript = {
async lastTurnText(session) { return session.transcriptPath ? readLastCodexTurnText(session.transcriptPath) : null },
- historyPage: (session, ask, pages) => pagedHistory(session, ask, (path, options) => pages.codex(path, options),
+ historyPage: (session, ask, pager) => pagedHistory(session, ask, (path, options) => pager.page(path, pages, options),
lines => codexMessagesToEvents(lines, codexSubagentResolverFor(session.codexHome))),
}
diff --git a/cli/src/engines/facets/adoption.ts b/cli/src/engines/facets/adoption.ts
new file mode 100644
index 000000000..7323187af
--- /dev/null
+++ b/cli/src/engines/facets/adoption.ts
@@ -0,0 +1,58 @@
+import type { ExternalOrigin } from '../../lib/sessionSearch/externals/types.js'
+
+/**
+ * How core finds an engine's conversations on this machine that Harness did not start, which process holds one
+ * open, and whether a turn is running there: adoption (Cmd-P, opening one here, and stopping its owner first).
+ * Declared data, applied in core by the kit (kit/adoption.ts): taking a conversation over stops a process, so it
+ * never waits on an engine worker (docs/design/2026-10-08-engine-launch.md, (c5)).
+ */
+export interface AdoptionContract {
+ /**
+ * Which files hold conversations. `projects`: `<root>/<folder>/<name><suffix>`, a folder's own files, never a
+ * sub-agent's folder beneath it; a root is a sessions folder. `walk`: files named `<prefix>…<suffix>` below a
+ * home's `folders.sessions` (and `folders.archived`, found to read but marked archived), `depth` folders down.
+ */
+ files:
+ | { layout: 'projects'; suffix: string }
+ | { layout: 'walk'; prefix: string; suffix: string; depth: number; folders: { sessions: string; archived?: string } }
+ /** How a file's head says whose conversation it is. */
+ head: {
+ /** Read a window at a time, each wider than the last; a file shorter than a window is read whole. */
+ windows: readonly number[]
+ /**
+ * `marked`: the first whole line naming `marker` that parses to an object, which then decides; `first`: the
+ * file's first line, once it has ended. A file read whole with no such line is still being written.
+ */
+ line: { marked: string } | 'first'
+ /** The record's `type`, when one is required, and where its fields are (the record itself, else `at`). */
+ type?: string
+ at?: readonly string[]
+ /** A conversation another one delegated to: never offered. */
+ skip?: { field: string; is: unknown }
+ id: { field: string; pattern: RegExp }
+ /** An absolute folder: where it ran, and so where it resumes. */
+ cwd: string
+ /** Who wrote it, by a field's value; one value may need a second field to say. No match is not a person's. */
+ origin: { field: string; values: Readonly<Record<string, ExternalOrigin | { field: string; is: string; then: ExternalOrigin; otherwise: ExternalOrigin }>> }
+ }
+ /** The engine's own names for its conversations: one `{id, title}` record a line, the last one winning. */
+ titles?: { file: string; id: string; title: string }
+ /**
+ * Which process holds a conversation. `records`: a record the process keeps of itself, beside each sessions
+ * folder, naming its pid and conversation; a record whose pid now runs another engine, or a process that started
+ * after the record says (past `slackMs`), is someone else's. `open`: the session file a process of these
+ * `commands` holds open, its conversation the id the file's name holds; a server's (an app's or an editor's) is
+ * never stopped from here.
+ */
+ owners:
+ | { records: { folder: string; suffix: string; pid: string; id: string; started: string; slackMs: number } }
+ | { open: { commands: readonly string[]; id: RegExp; contains: string; servers: { executable: RegExp; args: RegExp; subcommands: readonly string[] } } }
+ /**
+ * Whether the owner is mid-turn. `record`: its record's `field` says (no record: it ended, so not). `tail`: the
+ * last turn event near the file's end, read in widening windows, says; `marker` is on every such line, and only
+ * the event's type at `at` counts, never what was said.
+ */
+ busy:
+ | { record: { field: string; busy: string; idle: string } }
+ | { tail: { windows: readonly number[]; marker: string; at: readonly string[]; open: string; closed: readonly string[] } }
+}
diff --git a/cli/src/engines/facets/sessionStore.ts b/cli/src/engines/facets/sessionStore.ts
index bd4f32a7f..a3b3540ab 100644
--- a/cli/src/engines/facets/sessionStore.ts
+++ b/cli/src/engines/facets/sessionStore.ts
@@ -55,4 +55,23 @@ export interface SessionStoreContract {
continuation?: { type: string; field: string; suffix: string; tailBytes: number; turns: readonly string[]; headBytes: number }
/** A parent's binding, overwritten by its delegated session's hook, is put back as the registry loads. */
repairsOverwrittenParent?: boolean
+ /**
+ * What counts as conversation activity in a transcript, for an agent's frame (lib/transcriptActivity.ts): a
+ * record whose `at` field is a time, of one of `records`' kinds. Metadata rewritten when an idle session is
+ * discovered or resumed never counts. A kind names the record's `type`, and may require fields of the record,
+ * or of its item (the first object at one of `item`'s paths), to be one of the values listed: `in` compares a
+ * field as text, `is` as it is.
+ */
+ activity?: {
+ at: string
+ item?: readonly (readonly string[])[]
+ records: readonly ActivityRecord[]
+ }
+}
+
+export type ActivityMatch = { in: readonly string[] } | { is: readonly string[] }
+export interface ActivityRecord {
+ type: string
+ fields?: Readonly<Record<string, ActivityMatch>>
+ item?: Readonly<Record<string, ActivityMatch>>
}
diff --git a/cli/src/engines/facets/transcript.ts b/cli/src/engines/facets/transcript.ts
index 3e145f75d..c0271c51f 100644
--- a/cli/src/engines/facets/transcript.ts
+++ b/cli/src/engines/facets/transcript.ts
@@ -14,5 +14,6 @@ export interface HistoryAnswer {
}
export interface EngineTranscript {
lastTurnText(session: TranscriptSession): Promise<LastTurnText | null>
- historyPage(session: TranscriptSession, ask: HistoryAsk, pages: Pick<TranscriptPager, 'claude' | 'codex'>): Promise<HistoryAnswer>
+ /** `pages` is the pager of the process the reader runs in; the reader hands it its own rules (`ThreadPages`). */
+ historyPage(session: TranscriptSession, ask: HistoryAsk, pages: Pick<TranscriptPager, 'page'>): Promise<HistoryAnswer>
}
diff --git a/cli/src/engines/kit/adoption.ts b/cli/src/engines/kit/adoption.ts
new file mode 100644
index 000000000..86b40ebd2
--- /dev/null
+++ b/cli/src/engines/kit/adoption.ts
@@ -0,0 +1,247 @@
+/**
+ * Adoption as an engine's contract declares it (facets/adoption.ts): its conversations on disk, the process that
+ * holds each, and whether a turn is running there. Moved from lib/sessionSearch/externals/{claude,codex}.ts, whose
+ * every answer this reproduces (engines/transcriptReads.golden.spec.ts). A provider reads the engine's own store and
+ * nothing else: it never writes, never starts the engine, and never logs a process's arguments (they can carry a key).
+ */
+import { join } from 'node:path'
+
+import { agentCommandOwnershipSnapshot } from '../../lib/engineBin.js'
+import { absoluteFolder, entries, fileStamp, firstLine, parseLine, readHead, readJson, readTail, readText, record, text } from '../../lib/sessionSearch/externals/support.js'
+import { argvTokens, engineProcessMatch } from '../../lib/tmux.js'
+import {
+ type ExternalEngine, type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView,
+ type RunningProcess, type ScanContext, UNSETTLED,
+} from '../../lib/sessionSearch/externals/types.js'
+import type { AdoptionContract } from '../facets/adoption.js'
+
+type Head = AdoptionContract['head']
+type Owners = AdoptionContract['owners']
+type Tail = Extract<AdoptionContract['busy'], { tail: unknown }>['tail']
+
+export interface AdoptedHead { sessionId: string; cwd: string; origin: ExternalOrigin }
+
+/** Where a provider looks: each root its layout lists (a sessions folder, or a home), and where an engine that
+ * keeps process records keeps them (beside each root, unless given). Asked on every scan: a home the person moves
+ * is adopted while the daemon runs. */
+export interface AdoptionPlaces {
+ roots(): string[]
+ records?(): string[]
+}
+
+/** The value at `path` below `row`, each step an object. */
+function at(row: Record<string, unknown> | null, path: readonly string[]): unknown {
+ let value: unknown = row
+ for (const key of path) value = record(value)?.[key]
+ return value
+}
+
+/** Who wrote it, from the record's fields; null for anyone but a person at a terminal, an app or an editor. */
+function originOf(fields: Record<string, unknown>, origin: Head['origin']): ExternalOrigin | null {
+ const value = fields[origin.field]
+ if (typeof value !== 'string' || !Object.hasOwn(origin.values, value)) return null
+ const rule = origin.values[value]
+ return typeof rule === 'string' ? rule : fields[rule.field] === rule.is ? rule.then : rule.otherwise
+}
+
+/** What a head record says: its conversation, folder and author, or null when it is not a person's. */
+function judge(row: Record<string, unknown> | null, head: Head): AdoptedHead | null {
+ const fields = head.at ? record(at(row, head.at)) : row
+ if ((head.type !== undefined && row?.type !== head.type) || !fields) return null
+ if (head.skip && fields[head.skip.field] === head.skip.is) return null
+ const origin = originOf(fields, head.origin)
+ const cwd = absoluteFolder(fields[head.cwd])
+ if (!origin || !head.id.pattern.test(text(fields[head.id.field])) || !cwd) return null
+ return { sessionId: text(fields[head.id.field]), cwd, origin }
+}
+
+/**
+ * A file's conversation, folder and author, from its head. UNSETTLED while the engine is still writing the line
+ * that would say: a file read whole without one.
+ */
+export async function readAdoptedHead(path: string, head: Head): Promise<AdoptedHead | null | typeof UNSETTLED> {
+ if (head.line === 'first') {
+ let line: string | null = null
+ for (const bytes of head.windows) {
+ line = await firstLine(path, bytes)
+ if (line !== null) break
+ // The whole file was read and it has no line yet: the engine is still writing it.
+ if (Buffer.byteLength(await readHead(path, bytes)) < bytes) return UNSETTLED
+ }
+ return line === null ? null : judge(record(parseLine(line)), head)
+ }
+ const marker = head.line.marked
+ for (const bytes of head.windows) {
+ const read = await readHead(path, bytes)
+ const whole = Buffer.byteLength(read) < bytes
+ // A window that ends mid-file ends mid-line: that line is read whole by the next, wider one.
+ const lines = read.split('\n')
+ if (!whole) lines.pop()
+ for (const line of lines) {
+ if (!line.includes(marker)) continue
+ let row: Record<string, unknown> | null
+ try { row = record(JSON.parse(line)) } catch { continue }
+ if (!row) continue
+ return judge(row, head)
+ }
+ if (whole) return UNSETTLED
+ }
+ return null
+}
+
+/** The engine's own names for its conversations, the last one winning, read again only when the file changes. */
+export async function adoptedTitles(engine: string, path: string, titles: NonNullable<AdoptionContract['titles']>, ctx: ScanContext): Promise<Map<string, string>> {
+ const stamp = await fileStamp(path)
+ if (!stamp) return new Map()
+ return ctx.memo(`${engine}:titles:${path}`, stamp.stamp, async () => {
+ const found = new Map<string, string>()
+ for (const line of (await readText(path)).split('\n')) {
+ const row = record(parseLine(line))
+ const name = text(row?.[titles.title]).trim()
+ if (text(row?.[titles.id]) && name) found.set(text(row?.[titles.id]), name)
+ }
+ return found
+ })
+}
+
+/** Every file a walk layout lists below `dir`, at any depth up to its limit. */
+export async function walkFiles(dir: string, files: Extract<AdoptionContract['files'], { layout: 'walk' }>): Promise<string[]> {
+ const out: string[] = []
+ const walk = async (from: string, depth: number): Promise<void> => {
+ for (const entry of await entries(from)) {
+ const path = join(from, entry.name)
+ if (entry.isDirectory() && depth < files.depth) await walk(path, depth + 1)
+ // A file or a link to one; the scan's stat drops a broken link.
+ else if (!entry.isDirectory() && entry.name.startsWith(files.prefix) && entry.name.endsWith(files.suffix)) out.push(path)
+ }
+ }
+ await walk(dir, 0)
+ return out
+}
+
+/** Whether a process serves other clients rather than a person's terminal. */
+export function servesOthers(row: RunningProcess | undefined, servers: Extract<Owners, { open: unknown }>['open']['servers']): boolean {
+ if (!row) return false
+ if (servers.executable.test(row.executable) || servers.args.test(row.args)) return true
+ // The subcommand: the first argument that is not an option.
+ const subcommand = argvTokens(row.args).slice(1).find((token) => !token.startsWith('-'))
+ return !!subcommand && servers.subcommands.includes(subcommand)
+}
+
+/**
+ * Whether a file's last turn is still running: the last turn event near its end says. What was said can name the
+ * events; only events count. A file that cannot say answers `unknown`.
+ */
+export async function turnOpen(path: string, tail: Tail, unknown: boolean | null): Promise<boolean | null> {
+ const mark = new RegExp(`"(${[tail.open, ...tail.closed].join('|')})"`)
+ for (const bytes of tail.windows) {
+ const lines = (await readTail(path, bytes)).split('\n')
+ for (let i = lines.length - 1; i > 0; i--) {
+ const line = lines[i]
+ if (!line.includes(tail.marker) || !mark.test(line)) continue
+ const kind = at(record(parseLine(line)), tail.at)
+ if (kind === tail.open) return true
+ if (typeof kind === 'string' && tail.closed.includes(kind)) return false
+ }
+ }
+ return unknown
+}
+
+async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { records: unknown }>['records'], dirs: string[], view: ProcessView): Promise<OwnerClaim[]> {
+ const claims: OwnerClaim[] = []
+ for (const dir of dirs) {
+ const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith(owners.suffix))
+ if (!records.length) continue
+ const processes = new Map((await view.list()).map((process): [number, RunningProcess] => [process.pid, process]))
+ const ownership = agentCommandOwnershipSnapshot()
+ for (const file of records) {
+ const path = join(dir, file.name)
+ const row = record(await readJson(path))
+ const pid = row?.[owners.pid]
+ if (typeof pid !== 'number' || !text(row?.[owners.id]) || !view.alive(pid)) continue
+ // A record outlives a crash, and its pid can be handed to anything after — a shell in another tab. Only a
+ // process of this engine already running when the record says it started still has it.
+ const process = processes.get(pid)
+ if (!process || engineProcessMatch(process, engine as never, ownership).score <= 0) continue
+ const started = row?.[owners.started]
+ if (process.started !== undefined && typeof started === 'number' && process.started > started + owners.slackMs) continue
+ claims.push({ sessionId: text(row?.[owners.id]), pid, record: path })
+ }
+ }
+ return claims
+}
+
+async function openFileOwners(open: Extract<Owners, { open: unknown }>['open'], view: ProcessView): Promise<OwnerClaim[]> {
+ const claims: OwnerClaim[] = []
+ const held = await view.openFilesOf(open.commands)
+ if (!held.size) return claims
+ const processes = new Map((await view.list()).map((row): [number, RunningProcess] => [row.pid, row]))
+ for (const [pid, files] of held) {
+ // A server holding a thread is never stopped from here, even when a terminal started it.
+ const app = servesOthers(processes.get(pid), open.servers)
+ for (const path of files) {
+ const id = open.id.exec(path)?.[1]
+ if (id && path.includes(open.contains)) claims.push({ sessionId: id, pid, record: path, ...(app ? { app: true } : {}) })
+ }
+ }
+ return claims
+}
+
+/** One engine's provider, from its contract, looking where `places` says. */
+export function adoptionProvider(engine: ExternalEngine, contract: AdoptionContract, places: AdoptionPlaces): ExternalProvider {
+ const { files, head } = contract
+ const sessionAt = async (path: string, ctx: ScanContext): Promise<{ head: AdoptedHead; mtime: number } | null> => {
+ // A file, or a link to one; not a folder, not a broken link.
+ const stamp = await fileStamp(path)
+ if (!stamp) return null
+ // A head never changes: read once, however the file grows.
+ const found = await ctx.head(`${engine}:${path}`, stamp.stamp, () => readAdoptedHead(path, head))
+ await ctx.pace()
+ return found && !ctx.excluded(found.cwd) ? { head: found, mtime: stamp.mtime } : null
+ }
+ const owners = contract.owners
+ const busy = contract.busy
+ return {
+ engine,
+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {
+ const found: ExternalSession[] = []
+ for (const root of places.roots()) {
+ if (files.layout === 'projects') {
+ for (const project of await entries(root)) {
+ if (!project.isDirectory()) continue
+ const folder = join(root, project.name)
+ // Only the project's own files: a sub-agent's are in a folder beneath it.
+ for (const file of await entries(folder)) {
+ if (!file.name.endsWith(files.suffix)) continue
+ const path = join(folder, file.name)
+ const session = await sessionAt(path, ctx)
+ if (session) found.push({ ...session.head, engine, title: '', mtime: session.mtime, transcriptPath: path })
+ }
+ }
+ continue
+ }
+ const titles = contract.titles ? await adoptedTitles(engine, join(root, contract.titles.file), contract.titles, ctx) : new Map<string, string>()
+ const archived = new Set(files.folders.archived ? await walkFiles(join(root, files.folders.archived), files) : [])
+ for (const path of [...await walkFiles(join(root, files.folders.sessions), files), ...archived]) {
+ const session = await sessionAt(path, ctx)
+ if (!session) continue
+ found.push({
+ ...session.head, engine, title: titles.get(session.head.sessionId) ?? '', mtime: session.mtime, transcriptPath: path,
+ ...(archived.has(path) ? { archived: true as const } : {}),
+ })
+ }
+ }
+ return found
+ },
+ owners: (view: ProcessView) => 'records' in owners
+ ? recordOwners(engine, owners.records, places.records?.() ?? places.roots().map((root) => join(root, '..', owners.records.folder)), view)
+ : openFileOwners(owners.open, view),
+ async busy(owner): Promise<boolean | null> {
+ if ('tail' in busy) return turnOpen(owner.record, busy.tail, null)
+ const row = record(await readJson(owner.record))
+ // No record: the process ended with it, so it is not mid-turn.
+ if (!row) return false
+ return row[busy.record.field] === busy.record.busy ? true : row[busy.record.field] === busy.record.idle ? false : null
+ },
+ }
+}
diff --git a/cli/src/engines/kit/history.ts b/cli/src/engines/kit/history.ts
index 0c203cf13..e4fd9423e 100644
--- a/cli/src/engines/kit/history.ts
+++ b/cli/src/engines/kit/history.ts
@@ -1,43 +1,20 @@
import { stat } from 'node:fs/promises'
-import { join } from 'node:path'
-import { SubagentStats, type SessionEvent } from '../../lib/normalize.js'
-import { streamRecords } from '../../lib/transcriptTail.js'
+import type { SessionEvent } from './events.js'
import type { HistoryPage } from '../../lib/transcriptPages.js'
import type { HistoryAsk, HistoryAnswer, TranscriptSession } from '../facets/transcript.js'
-/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript
- * (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record
- * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation
- * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */
-export async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {
- const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')
- for (const e of events) {
- if (e.type !== 'tool_end') continue
- const sub = e.payload.subagent
- if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue
- try {
- // A line at a time: a long sub-agent's transcript is never held whole to count its calls.
- const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)
- const totals = new SubagentStats()
- await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)
- const stats = totals.result()
- sub.totalToolUseCount = stats.totalToolUseCount
- if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs
- if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens
- } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }
- }
-}
-
-/** Bounded paging is shared machinery; each engine supplies its pager and replay rules. */
+/** Bounded paging is shared machinery; each engine supplies its pager and replay rules, and what it adds to the
+ * replayed events from files beside the transcript (Claude Code's background agents' totals). */
export async function pagedHistory(session: TranscriptSession, { limit, before }: HistoryAsk,
- page: (path: string, options: HistoryAsk) => Promise<HistoryPage>, replay: (lines: string[]) => SessionEvent[]): Promise<HistoryAnswer> {
+ page: (path: string, options: HistoryAsk) => Promise<HistoryPage>, replay: (lines: string[]) => SessionEvent[],
+ enrich?: (events: SessionEvent[], transcriptPath: string) => Promise<void>): Promise<HistoryAnswer> {
if (!session.transcriptPath) return { events: [], timestamp: new Date(session.touchedAt).toISOString(), hasMore: false, oldestCursor: null }
const found = await page(session.transcriptPath, limit ? { limit, before } : {})
const st = await stat(session.transcriptPath).catch(() => null)
const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()
if (found.staleCursor) return { events: [], timestamp, hasMore: false, oldestCursor: null, staleCursor: true }
const events = replay(found.lines)
- await enrichSubagentStats(events, session.transcriptPath)
+ await enrich?.(events, session.transcriptPath)
if (limit && before && events[events.length - 1]?.type === 'done') events.pop()
return { events, timestamp, ...(limit || found.hasMore ? { hasMore: found.hasMore, oldestCursor: found.oldestCursor } : {}) }
}
diff --git a/cli/src/engines/transcriptReads.golden.spec.ts b/cli/src/engines/transcriptReads.golden.spec.ts
new file mode 100644
index 000000000..fbe093753
--- /dev/null
+++ b/cli/src/engines/transcriptReads.golden.spec.ts
@@ -0,0 +1,600 @@
+/**
+ * What core and the readers make of Claude Code's and Codex's conversations on disk, answer for answer: recorded
+ * from the code as it stood before their adoption, activity and paging rules became declared data the kit applies,
+ * and before the core stopped loading their normalizers (docs/design/2026-10-08-engine-launch.md, (c5)). It covers:
+ *
+ * - adoption: the conversations each engine's provider finds in every home (heads read in widening windows, files
+ * still being written, sub-agents, programs and Harness's own left out, thread names), which process holds
+ * each, and whether it is mid-turn;
+ * - the latest conversation activity an agent's frame shows, from a transcript's tail;
+ * - pages of a thread, followed cursor by cursor, with turns too long for a page and lines too long for any;
+ * - history and the last turn, through each engine's reader and through core's `session_get`.
+ *
+ * Each case runs with `process.platform` pinned to darwin and to linux, and linux's are stored where they
+ * differ. Local time is pinned (`TZ`): a timestamp written without a zone is read in it. Sizes in a case never
+ * depend on the temporary folder's path.
+ *
+ * `RECORD_TRANSCRIPT_READS_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter what
+ * core reads, and say so in that change.
+ */
+import { createHash } from 'node:crypto'
+import { appendFileSync, chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { ProcessView, RunningProcess } from '../lib/sessionSearch/externals/types.js'
+
+process.env.TZ = 'America/New_York'
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/transcript-reads.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_TRANSCRIPT_READS_GOLDEN === '1'
+
+let root = ''
+const saved: Record<string, string | undefined> = {}
+const VARS = ['ADAPTER_DATA_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR'] as const
+type Modules = {
+ index: typeof import('../lib/sessionSearch/externals/index.js')
+ support: typeof import('../lib/sessionSearch/externals/support.js')
+ homes: typeof import('../lib/engineHomes.js')
+ activity: typeof import('../lib/transcriptActivity.js')
+ pages: typeof import('../lib/transcriptPages.js')
+ transcripts: typeof import('./transcripts.js')
+ history: typeof import('../core/transcripts/history.js')
+ lastTurn: typeof import('../core/transcripts/lastTurn.js')
+}
+let m: Modules
+
+const write = (path: string, lines: unknown[], end = '\n'): string => {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + end)
+ chmodSync(path, 0o644)
+ return path
+}
+const norm = (value: unknown): unknown => value === undefined ? '<undefined>' : JSON.parse(JSON.stringify(value).split(root).join('<root>'))
+const sha = (text: string): string => createHash('sha256').update(text).digest('hex').slice(0, 16)
+async function attempt<T>(run: () => T | Promise<T>): Promise<unknown> {
+ try { return norm(await run()) } catch (error) { return { threw: norm(error instanceof Error ? error.message : String(error)) } }
+}
+const uuid = (n: number, tag = 'a') => `${tag.repeat(8).slice(0, 8)}-${String(n).padStart(4, '0')}-4000-8000-${String(n).padStart(12, '0')}`
+
+beforeAll(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'transcript-reads-golden-')))
+ for (const name of VARS) saved[name] = process.env[name]
+ process.env.ADAPTER_DATA_DIR = join(root, 'data')
+ process.env.CLAUDE_PROJECTS_DIR = join(root, 'claude', 'projects')
+ process.env.CODEX_HOME = join(root, 'codex')
+ delete process.env.CLAUDE_CONFIG_DIR
+ mkdirSync(join(root, 'data'), { recursive: true })
+ chmodSync(join(root, 'data'), 0o700)
+ vi.resetModules()
+ m = {
+ index: await import('../lib/sessionSearch/externals/index.js'),
+ support: await import('../lib/sessionSearch/externals/support.js'),
+ homes: await import('../lib/engineHomes.js'),
+ activity: await import('../lib/transcriptActivity.js'),
+ pages: await import('../lib/transcriptPages.js'),
+ transcripts: await import('./transcripts.js'),
+ history: await import('../core/transcripts/history.js'),
+ lastTurn: await import('../core/transcripts/lastTurn.js'),
+ }
+})
+
+afterAll(() => {
+ for (const name of VARS) {
+ if (saved[name] === undefined) delete process.env[name]
+ else process.env[name] = saved[name]
+ }
+ m?.homes.resetEngineHomes()
+ rmSync(root, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+function adoptMoved(): void {
+ m.homes.resetEngineHomes()
+ rmSync(join(root, 'data', 'engine-homes.json'), { force: true })
+ m.homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(root, 'moved-claude'), CODEX_HOME: join(root, 'moved-codex') },
+ { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })
+}
+function forgetMoved(): void {
+ m.homes.resetEngineHomes()
+ rmSync(join(root, 'data', 'engine-homes.json'), { force: true })
+}
+
+// --------------------------------------------------------------------------------------------- adoption
+
+const WORK = '/work/dial'
+const claudeLine = (sessionId: unknown, entrypoint: string, extra: Record<string, unknown> = {}) => ({
+ type: 'user', sessionId, cwd: WORK, entrypoint, timestamp: '2026-09-20T10:00:00Z',
+ message: { role: 'user', content: 'fix the dial scroll' }, ...extra,
+})
+const codexMeta = (id: string, source: unknown, originator = 'codex-tui', cwd: unknown = WORK, instructions = 40_000) => ({
+ timestamp: '2026-09-20T10:00:00Z', type: 'session_meta',
+ payload: { id, cwd, originator, source, base_instructions: 'x'.repeat(instructions) },
+})
+const codexEvent = (type: string) => ({ type: 'event_msg', payload: { type } })
+const rolloutName = (id: string) => `rollout-2026-09-20T10-00-00-${id}.jsonl`
+
+/** A provider's sessions, in an order of their own, with nothing that depends on when the files were written. */
+const sessions = (found: Array<Record<string, unknown>>) => norm(found.map(({ mtime, ...rest }) => ({ ...rest, mtime: typeof mtime === 'number' && mtime > 0 }) as Record<string, unknown>)
+ .sort((a, b) => `${a.engine}:${a.transcriptPath}`.localeCompare(`${b.engine}:${b.transcriptPath}`)))
+
+async function adoptionCases(): Promise<Record<string, unknown>> {
+ const cases: Record<string, unknown> = {}
+ const projects = join(root, 'claude', 'projects')
+ const folder = join(projects, '-work-dial')
+ const claude = (name: string, lines: unknown[]) => write(join(folder, `${name}.jsonl`), lines)
+ claude(uuid(1), [{ type: 'permission-mode' }, '{"entrypoint": half', claudeLine(uuid(1), 'cli')])
+ claude(uuid(2), [claudeLine(uuid(2), 'claude-desktop')])
+ claude(uuid(3), [claudeLine(uuid(3), 'sdk-cli')])
+ claude(uuid(4), [claudeLine(uuid(4), 'cli', { isSidechain: true })])
+ claude(uuid(5), [claudeLine(uuid(5), 'cli', { cwd: 'relative/path' })])
+ claude('short', [claudeLine('short', 'cli')])
+ claude('number-id', [claudeLine(7, 'cli')])
+ const unsettled = claude(uuid(6), ['["entrypoint"]'])
+ claude(uuid(7), [{ type: 'summary', summary: 'nothing else' }])
+ claude(uuid(8), [{ type: 'permission-mode' }, claudeLine(uuid(8), 'cli', { message: { role: 'user', content: [{ type: 'image', source: { data: 'i'.repeat(300 * 1024) } }] } })])
+ claude(uuid(9), [{ type: 'summary', summary: 'x'.repeat(4 * 1024 * 1024 + 100) }, claudeLine(uuid(9), 'cli')])
+ claude(uuid(10), [claudeLine(uuid(10), 'cli', { cwd: join(root, 'data', 'recap-scratch') })])
+ claude('array', ['["entrypoint", 1]', claudeLine(uuid(13), 'cli')])
+ claude('later-line', [claudeLine(uuid(14), 'cli', { cwd: 7 }), claudeLine(uuid(15), 'cli')])
+ write(join(folder, uuid(11), 'subagents', 'agent-1.jsonl'), [claudeLine(uuid(11), 'cli')])
+ write(join(folder, 'notes.txt'), ['not a transcript'])
+ writeFileSync(join(projects, 'stray-file'), '')
+ mkdirSync(join(folder, 'odd.jsonl'), { recursive: true })
+ symlinkSync(join(root, 'nowhere.jsonl'), join(folder, 'broken.jsonl'))
+ write(join(root, 'elsewhere', `${uuid(12)}.jsonl`), [claudeLine(uuid(12), 'cli')])
+ symlinkSync(join(root, 'elsewhere', `${uuid(12)}.jsonl`), join(folder, 'linked.jsonl'))
+ write(join(root, 'moved-claude', 'projects', '-work-moved', `${uuid(16)}.jsonl`), [claudeLine(uuid(16), 'cli', { cwd: '/work/moved' })])
+
+ const home = join(root, 'codex')
+ const day = join(home, 'sessions', '2026', '09', '20')
+ const codex = (id: string, lines: unknown[], dir = day) => write(join(dir, rolloutName(id)), lines)
+ const C = (n: number) => uuid(n, 'c')
+ codex(C(1), [codexMeta(C(1), 'cli'), codexEvent('x')])
+ codex(C(2), [codexMeta(C(2), 'vscode', 'Codex Desktop'), codexEvent('x')])
+ codex(C(3), [codexMeta(C(3), 'vscode', 'codex_vscode'), codexEvent('x')])
+ codex(C(4), [codexMeta(C(4), 'exec', 'codex_exec')])
+ codex(C(5), [codexMeta(C(5), { subagent: { other: 'guardian' } })])
+ codex(C(6), [codexMeta(C(6), 'cli', 'codex-tui', 'relative')])
+ codex(C(7), [{ ...codexMeta('x', 'cli') }])
+ codex(C(8), [{ type: 'other', payload: {} }])
+ codex(C(9), [{ type: 'session_meta' }])
+ codex(C(10), ['not json'])
+ codex(C(11), [codexMeta(C(11), 'cli', 'codex-tui', WORK, 1)])
+ const partial = join(day, rolloutName(C(12)))
+ writeFileSync(partial, JSON.stringify(codexMeta(C(12), 'cli')))
+ writeFileSync(join(day, rolloutName(C(13))), 'x'.repeat(1024 * 1024 + 10))
+ codex(C(14), [codexMeta(C(14), 'cli')], join(home, 'sessions', 'a', 'b', 'c', 'd', 'e'))
+ codex(C(15), [codexMeta(C(15), 'cli')], join(home, 'sessions', '2026', '09'))
+ write(join(day, 'notes.jsonl'), ['x'])
+ write(join(day, `rolling-${C(21)}.jsonl`), [codexMeta(C(21), 'cli')])
+ mkdirSync(join(day, rolloutName(C(16))), { recursive: true })
+ codex(C(17), [codexMeta(C(17), 'cli')], join(home, 'archived_sessions'))
+ symlinkSync(join(root, 'nowhere.jsonl'), join(home, 'archived_sessions', rolloutName(C(18))))
+ codex(C(19), [codexMeta(C(19), 'cli', 'codex-tui', join(root, 'data', 'recap'))])
+ utimesSync(join(day, rolloutName(C(1))), new Date('2026-09-25T00:00:00Z'), new Date('2026-09-25T00:00:00Z'))
+ write(join(home, 'session_index.jsonl'), [
+ { id: C(1), thread_name: 'Old name' }, { id: C(1), thread_name: 'Retention cohorts' }, { id: C(2), thread_name: ' ' },
+ { thread_name: 'no id' }, 'half a line', { id: C(17), thread_name: 'Archived one' },
+ ])
+ codex(C(20), [codexMeta(C(20), 'cli', 'codex-tui', '/work/moved')], join(root, 'moved-codex', 'sessions', '2026', '09', '21'))
+ write(join(root, 'moved-codex', 'session_index.jsonl'), [{ id: C(20), thread_name: 'Moved home' }])
+
+ const paths = { ...m.index.externalPaths(), claudeProjectsDir: projects, codexHome: home }
+ const providerOf = (engine: string, from = paths) => m.index.externalProviders(from).find((provider) => provider.engine === engine)!
+ for (const moved of [false, true]) {
+ if (moved) adoptMoved(); else forgetMoved()
+ const label = moved ? 'moved homes' : 'default homes'
+ for (const engine of ['claude', 'codex']) {
+ const memo = m.support.scanMemo({ excluded: [join(root, 'data')] })
+ cases[`scan · ${label} · ${engine}`] = sessions(await providerOf(engine).scan(memo.context()) as unknown as Array<Record<string, unknown>>)
+ // Again, from what the first scan kept: the same answer, read only where something changed.
+ cases[`scan again · ${label} · ${engine}`] = sessions(await providerOf(engine).scan(memo.context()) as unknown as Array<Record<string, unknown>>)
+ }
+ }
+ forgetMoved()
+ // The two files still being written, once their first lines are: found by the same scan's memory.
+ const memo = m.support.scanMemo({ excluded: [join(root, 'data')] })
+ await providerOf('claude').scan(memo.context())
+ await providerOf('codex').scan(memo.context())
+ write(unsettled, ['["entrypoint"]', claudeLine(uuid(6), 'cli')])
+ writeFileSync(partial, JSON.stringify(codexMeta(C(12), 'cli')) + '\n')
+ // A first line longer than any window is judged for good: written whole since, it is still not read again.
+ writeFileSync(join(day, rolloutName(C(13))), JSON.stringify(codexMeta(C(13), 'cli', 'codex-tui', WORK, 1024 * 1024 + 10)) + '\n')
+ cases['scan · written since · codex · past every window'] = sessions((await providerOf('codex').scan(memo.context())).filter((s) => s.sessionId === C(13)) as unknown as Array<Record<string, unknown>>)
+ cases['scan · written since · claude'] = sessions((await providerOf('claude').scan(memo.context())).filter((s) => s.sessionId === uuid(6)) as unknown as Array<Record<string, unknown>>)
+ cases['scan · written since · codex'] = sessions((await providerOf('codex').scan(memo.context())).filter((s) => s.sessionId === C(12)) as unknown as Array<Record<string, unknown>>)
+
+ // Owners: Claude's process records, in its own home and a moved one.
+ const started = Date.parse('2026-09-27T10:00:00Z')
+ const records = join(root, 'claude', 'sessions')
+ const record = (dir: string, name: string, lines: unknown[]) => write(join(dir, name), lines)
+ record(records, '101.json', [{ pid: 101, sessionId: uuid(1), status: 'busy', startedAt: started + 400 }])
+ record(records, '102.json', [{ pid: 102, sessionId: uuid(2), status: 'idle' }])
+ record(records, '103.json', [{ pid: 103, sessionId: uuid(2) }])
+ record(records, '104.json', ['{ being written'])
+ record(records, '105.json', [{ pid: '105', sessionId: uuid(2) }])
+ record(records, '106.json', [{ pid: 106 }])
+ record(records, '107.json', [{ pid: 107, sessionId: 'reused-by-a-shell', startedAt: started }])
+ record(records, '108.json', [{ pid: 108, sessionId: 'reused-by-claude', startedAt: started }])
+ record(records, '109.json', [{ pid: 109, sessionId: 'unlisted' }])
+ record(records, '110.json', [{ pid: 110, sessionId: uuid(3), status: 'thinking', startedAt: started + 2_000 }])
+ record(records, '111.json', [{ pid: 111, sessionId: uuid(4), startedAt: started - 2_001 }])
+ record(records, '112.json', [{ pid: 112, sessionId: uuid(5), startedAt: started - 1_500 }])
+ record(records, '113.json', [{ pid: 113, sessionId: uuid(7), startedAt: started - 2_500 }])
+ record(records, 'notes.txt', ['x'])
+ mkdirSync(join(records, 'dir.json'), { recursive: true })
+ record(join(root, 'moved-claude', 'sessions'), '201.json', [{ pid: 201, sessionId: uuid(16), status: 'idle' }])
+ const running: RunningProcess[] = [
+ { pid: 101, ppid: 1, executable: 'claude', args: 'claude --resume x', started },
+ { pid: 102, ppid: 1, executable: 'claude', args: 'claude' },
+ { pid: 106, ppid: 1, executable: 'claude', args: 'claude', started },
+ { pid: 107, ppid: 1, executable: '-zsh', args: '-zsh', started: started + 60_000 },
+ { pid: 108, ppid: 1, executable: 'claude', args: 'claude', started: started + 60_000 },
+ { pid: 110, ppid: 1, executable: 'claude', args: 'claude', started },
+ { pid: 111, ppid: 1, executable: 'node', args: 'node /opt/claude/cli.js', started },
+ { pid: 112, ppid: 1, executable: 'claude', args: 'claude', started },
+ { pid: 113, ppid: 1, executable: 'claude', args: 'claude', started },
+ { pid: 201, ppid: 1, executable: 'claude', args: 'claude' },
+ ]
+ const alive = new Set([101, 102, 106, 107, 108, 109, 110, 111, 112, 113, 201])
+ const claudeView: ProcessView = { list: async () => running, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: (pid) => alive.has(pid) }
+ for (const moved of [false, true]) {
+ if (moved) adoptMoved(); else forgetMoved()
+ const claims = await providerOf('claude').owners!(claudeView)
+ cases[`owners · ${moved ? 'moved homes' : 'default homes'} · claude`] = norm(claims.sort((a, b) => a.pid - b.pid))
+ }
+ forgetMoved()
+ let looked = false
+ cases['owners · no records · claude'] = norm({
+ claims: await providerOf('claude', { ...paths, claudeProjectsDir: join(root, 'none', 'projects') }).owners!({ ...claudeView, list: async () => { looked = true; return [] } }),
+ looked,
+ })
+ for (const name of ['101.json', '102.json', '110.json', '104.json', 'gone.json', 'dir.json']) {
+ cases[`busy · claude · ${name}`] = await attempt(() => providerOf('claude').busy!({ pid: 1, record: join(records, name) }))
+ }
+
+ // Owners: the rollouts Codex processes hold open; a server's are an app's.
+ const held = (pid: number, files: string[]) => [pid, files] as [number, string[]]
+ const C1 = join(day, rolloutName(C(1)))
+ const codexView: ProcessView = {
+ list: async () => [
+ { pid: 301, ppid: 1, executable: 'codex', args: '/opt/codex/bin/codex resume x' },
+ { pid: 303, ppid: 1, executable: 'codex', args: '/opt/codex/bin/codex app-server --listen stdio' },
+ { pid: 304, ppid: 1, executable: '/opt/bin/codex-acp', args: '/opt/bin/codex-acp' },
+ { pid: 305, ppid: 1, executable: 'node', args: 'node /opt/lib/codex-acp --stdio' },
+ { pid: 306, ppid: 1, executable: 'codex', args: 'codex --verbose mcp' },
+ { pid: 307, ppid: 1, executable: 'codex', args: 'codex -m o3 "run the mcp tests"' },
+ { pid: 309, ppid: 1, executable: 'codex', args: 'codex proto' },
+ { pid: 310, ppid: 1, executable: 'codex', args: 'codex mcp-server' },
+ { pid: 312, ppid: 1, executable: '/opt/bin/codex-acp', args: 'codex-acp-wrapper --stdio' },
+ { pid: 313, ppid: 1, executable: 'codex-acp-wrapper', args: 'codex-acp-wrapper --stdio' },
+ ],
+ openFiles: async () => new Map(), alive: () => true,
+ openFilesOf: async (commands) => {
+ cases['owners · codex · asked for'] = commands
+ return new Map([
+ held(301, [C1, '/dev/ttys003', join(root, 'tmp', 'rollout-notes.txt')]), held(302, ['/x/rollout-2026-not-an-id.jsonl']),
+ held(303, [join(day, rolloutName(C(2)))]), held(304, [join(day, rolloutName(C(3)))]), held(305, [join(day, rolloutName(C(4)))]),
+ held(306, [join(day, rolloutName(C(5)))]), held(307, [join(day, rolloutName(C(6)))]), held(308, [join(day, rolloutName(C(7)))]),
+ held(309, [join(day, rolloutName(C(8)))]), held(310, [join(day, rolloutName(C(9))), join(day, rolloutName(C(10)))]),
+ held(311, [`/x/${rolloutName(C(11)).replace('.jsonl', '.JSONL')}`, `/x/ROLLOUT-${C(11)}.jsonl`, `/x/rollout-${C(11).toUpperCase()}.jsonl`]),
+ held(312, [join(day, rolloutName(C(15)))]), held(313, [join(day, rolloutName(C(16)))]),
+ ])
+ },
+ }
+ cases['owners · codex'] = norm(await providerOf('codex').owners!(codexView))
+ let listed = false
+ cases['owners · nothing held · codex'] = norm({ claims: await providerOf('codex').owners!({ ...codexView, openFilesOf: async () => new Map(), list: async () => { listed = true; return [] } }), listed })
+ const turns = join(root, 'turns')
+ const talk = { type: 'response_item', payload: { type: 'message', content: [{ text: 'then "task_complete" arrives' }] } }
+ const turnFile = (name: string, lines: unknown[]) => write(join(turns, `${name}.jsonl`), [codexMeta(C(1), 'cli'), ...lines])
+ const turnCases: Record<string, string> = {
+ ended: turnFile('ended', [codexEvent('task_started'), talk, codexEvent('task_complete'), talk]),
+ aborted: turnFile('aborted', [codexEvent('task_started'), codexEvent('turn_aborted')]),
+ working: turnFile('working', [codexEvent('task_complete'), codexEvent('task_started'), talk]),
+ other: turnFile('other', [codexEvent('task_started'), { type: 'event_msg', payload: { type: 'task_complete_ish' } }]),
+ unsaid: turnFile('unsaid', []),
+ quoted: turnFile('quoted', [codexEvent('task_complete'), { type: 'event_msg', payload: { type: 'agent_message', phase: 'task_started' } }]),
+ 'first line only': write(join(turns, 'first.jsonl'), [codexEvent('task_started')]),
+ 'past the first window': turnFile('mid', [codexEvent('task_complete'), { type: 'response_item', payload: { big: 'x'.repeat(300 * 1024) } }]),
+ 'past every window': turnFile('long', [codexEvent('task_complete'), { type: 'response_item', payload: { big: 'x'.repeat(5 * 1024 * 1024) } }]),
+ gone: join(turns, 'gone.jsonl'),
+ }
+ for (const [name, path] of Object.entries(turnCases)) cases[`busy · codex · ${name}`] = await attempt(() => providerOf('codex').busy!({ pid: 1, record: path }))
+ return cases
+}
+
+// --------------------------------------------------------------------------------------------- activity
+
+async function activityCases(): Promise<Record<string, unknown>> {
+ const cases: Record<string, unknown> = {}
+ const dir = join(root, 'activity')
+ const at = (minute: number, zone = 'Z') => `2026-09-20T10:${String(minute).padStart(2, '0')}:00${zone === 'Z' ? '.000Z' : zone}`
+ const claudeFiles: Record<string, unknown[]> = {
+ 'a prompt': [{ type: 'user', timestamp: at(1) }],
+ 'an answer after a prompt': [{ type: 'user', timestamp: at(1) }, { type: 'assistant', timestamp: at(2) }],
+ 'newest last, older after': [{ type: 'assistant', timestamp: at(5) }, { type: 'user', timestamp: at(3) }],
+ 'a turn duration': [{ type: 'system', subtype: 'turn_duration', timestamp: at(4) }],
+ 'a stop hook summary': [{ type: 'system', subtype: 'stop_hook_summary', timestamp: at(4) }],
+ 'a compact boundary': [{ type: 'system', subtype: 'compact_boundary', timestamp: at(4) }],
+ 'another system record': [{ type: 'system', subtype: 'informational', timestamp: at(4) }],
+ 'a subtype that reads as a counted one': [{ type: 'system', subtype: ['turn_duration'], timestamp: at(4) }],
+ 'metadata only': [{ type: 'summary', timestamp: at(1) }, { type: 'file-history-snapshot', timestamp: at(2) }, { type: 'custom-title', timestamp: at(3) }],
+ 'a local time': [{ type: 'user', timestamp: '2026-09-20T10:00:00' }],
+ 'a bad time': [{ type: 'user', timestamp: 'yesterday' }],
+ 'a number for a time': [{ type: 'user', timestamp: 1_790_000_000_000 }],
+ 'a record that is not an object': ['["user"]', '7', 'not json'],
+ 'a large last record': [{ type: 'user', timestamp: at(1) }, { type: 'assistant', timestamp: at(2), pad: 'p'.repeat(150 * 1024) }],
+ 'a large last record, not counted': [{ type: 'user', timestamp: at(1) }, { type: 'summary', timestamp: at(2), pad: 'p'.repeat(150 * 1024) }],
+ 'activity past the bound': [{ type: 'user', timestamp: at(1) }, ...Array.from({ length: 300 }, () => ({ type: 'summary', pad: 'p'.repeat(8 * 1024) }))],
+ 'a codex rollout': [{ type: 'event_msg', timestamp: at(1), payload: { type: 'user_message' } }],
+ }
+ const codexFiles: Record<string, unknown[]> = {
+ 'each counted event': ['user_message', 'UserMessage', 'agent_message', 'AgentMessage', 'task_started', 'task_complete', 'turn_aborted', 'context_compacted']
+ .map((type, minute) => ({ type: 'event_msg', timestamp: at(minute), payload: { type } })),
+ 'an uncounted event': [{ type: 'event_msg', timestamp: at(9), payload: { type: 'token_count' } }],
+ 'each counted response': ['reasoning', 'function_call', 'custom_tool_call', 'tool_search_call', 'function_call_output', 'custom_tool_call_output', 'tool_search_output']
+ .map((type, minute) => ({ type: 'response_item', timestamp: at(minute), payload: { type } })),
+ 'messages by role': ['user', 'assistant', 'system', 'developer'].map((role, minute) => ({ type: 'response_item', timestamp: at(30 + minute), payload: { type: 'message', role } })),
+ 'a system message only': [{ type: 'response_item', timestamp: at(40), payload: { type: 'message', role: 'system' } }],
+ 'a type that reads as a message': [{ type: 'response_item', timestamp: at(41), payload: { type: ['message'], role: 'user' } }],
+ 'a type that reads as a counted one': [{ type: 'event_msg', timestamp: at(42), payload: { type: ['user_message'] } }],
+ 'an item below the payload': [{ type: 'response_item', timestamp: at(12), payload: { item: { type: 'reasoning' } } }],
+ 'an item below the payload, not counted': [{ type: 'response_item', timestamp: at(12), payload: { item: { type: 'web_search' }, type: 'reasoning' } }],
+ 'a compaction': [{ type: 'compacted', timestamp: at(13) }],
+ 'metadata only': [{ type: 'session_meta', timestamp: at(1), payload: { id: 'x' } }, { type: 'turn_context', timestamp: at(2) }],
+ 'no payload': [{ type: 'event_msg', timestamp: at(1) }, { type: 'response_item', timestamp: at(2) }],
+ 'a local time': [{ type: 'compacted', timestamp: '2026-09-20T10:00:00' }],
+ 'a claude transcript': [{ type: 'user', timestamp: at(1) }],
+ }
+ for (const [engine, files] of [['claude', claudeFiles], ['codex', codexFiles]] as const) {
+ for (const [name, lines] of Object.entries(files)) {
+ const path = write(join(dir, engine, `${name.replace(/\W+/g, '-')}.jsonl`), lines)
+ cases[`${engine} · ${name}`] = await attempt(() => m.activity.transcriptActivityAt(path, engine))
+ cases[`${engine} · ${name} · read again`] = await attempt(() => m.activity.transcriptActivityAt(path, engine))
+ }
+ }
+ const one = write(join(dir, 'one.jsonl'), [{ type: 'user', timestamp: at(1) }])
+ writeFileSync(join(dir, 'empty.jsonl'), '')
+ cases['an empty file'] = await attempt(() => m.activity.transcriptActivityAt(join(dir, 'empty.jsonl'), 'claude'))
+ cases['a missing file'] = await attempt(() => m.activity.transcriptActivityAt(join(dir, 'missing.jsonl'), 'codex'))
+ cases['a folder'] = await attempt(() => m.activity.transcriptActivityAt(dir, 'claude'))
+ cases['no path'] = await attempt(() => m.activity.transcriptActivityAt(null, 'claude'))
+ for (const engine of ['pi', 'cursor', 'terminal', 'toString']) cases[`another engine · ${engine}`] = await attempt(() => m.activity.transcriptActivityAt(one, engine))
+ // A file that grew is read again; one that did not is the same answer.
+ appendFileSync(one, JSON.stringify({ type: 'assistant', timestamp: at(7) }) + '\n')
+ cases['grown since'] = await attempt(() => m.activity.transcriptActivityAt(one, 'claude'))
+ return cases
+}
+
+// ------------------------------------------------------------------------------------------------ pages
+
+const claudeTurn = (k: number, opts: { huge?: boolean; tools?: number; crlf?: boolean } = {}): string[] => {
+ const lines: unknown[] = [
+ { type: 'user', uuid: `u-${k}`, sessionId: 's', timestamp: '2026-09-20T10:00:00Z', message: { role: 'user', content: `ask ${k}` } },
+ ]
+ for (let t = 0; t < (opts.tools ?? 1); t++) {
+ lines.push({ type: 'assistant', uuid: `a-${k}-${t}`, message: { role: 'assistant', content: [{ type: 'tool_use', id: `t-${k}-${t}`, name: 'Bash', input: { command: `ls ${t}` } }] } })
+ lines.push({ type: 'user', uuid: `r-${k}-${t}`, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: `t-${k}-${t}`, content: opts.huge && t === 0 ? 'y'.repeat(10 * 1024) : `out ${t}` }] } })
+ }
+ lines.push({ type: 'assistant', uuid: `a-${k}-z`, message: { role: 'assistant', content: [{ type: 'text', text: `answer ${k}` }] } })
+ if (k % 5 === 0) lines.push({ type: 'summary', summary: `turn ${k}` })
+ const text = lines.map((line) => JSON.stringify(line))
+ if (opts.crlf) text[0] += '\r'
+ if (k % 4 === 0) text.push(' ')
+ return text
+}
+const codexTurn = (k: number, opts: { huge?: boolean; tools?: number; goal?: boolean } = {}): string[] => {
+ const lines: unknown[] = [opts.goal
+ ? { type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: `<codex_internal_context source="goal"><objective>goal ${k}</objective></codex_internal_context>` }] } }
+ : { type: 'event_msg', payload: { type: 'user_message', message: `ask ${k}` } }]
+ for (let t = 0; t < (opts.tools ?? 1); t++) {
+ lines.push({ type: 'response_item', payload: { type: 'function_call', name: 'shell', call_id: `c-${k}-${t}`, arguments: '{"command":["ls"]}' } })
+ lines.push({ type: 'response_item', payload: { type: 'function_call_output', call_id: `c-${k}-${t}`, output: opts.huge && t === 0 ? 'y'.repeat(10 * 1024) : `out ${t}` } })
+ }
+ lines.push({ type: 'event_msg', payload: { type: 'agent_message', message: `answer ${k}` } })
+ lines.push({ type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: `answer ${k}` }] } })
+ return lines.map((line) => JSON.stringify(line))
+}
+
+/** A page as the golden keeps it: its lines by count and digest, and what it says of the page before. */
+const pageView = (page: Record<string, unknown>) => {
+ const { lines, ...rest } = page as { lines: string[] } & Record<string, unknown>
+ return norm({ lines: lines.length, sha: sha(lines.join('\n')), first: lines[0]?.slice(0, 60) ?? null, ...rest })
+}
+
+async function pageCases(): Promise<Record<string, unknown>> {
+ const cases: Record<string, unknown> = {}
+ const dir = join(root, 'pages')
+ const claudeFile = join(dir, 'claude.jsonl')
+ const codexFile = join(dir, 'codex.jsonl')
+ const claudeLines: string[] = [JSON.stringify({ type: 'permission-mode', permissionMode: 'default' })]
+ const codexLines: string[] = [JSON.stringify({ type: 'session_meta', payload: { id: 's', cwd: WORK } })]
+ for (let k = 1; k <= 30; k++) {
+ const opts = { huge: k % 7 === 0, tools: k === 11 ? 60 : k === 17 ? 3 : 1, crlf: k === 13, goal: k % 6 === 0 }
+ claudeLines.push(...claudeTurn(k, opts))
+ codexLines.push(...codexTurn(k, opts))
+ }
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(claudeFile, claudeLines.join('\n') + '\n')
+ writeFileSync(codexFile, codexLines.join('\n'))
+ const pager = () => new m.pages.TranscriptPager({ maxBytes: 8 * 1024, stride: { lines: 7, bytes: 2048 } })
+ for (const engine of ['claude', 'codex'] as const) {
+ const file = engine === 'claude' ? claudeFile : codexFile
+ for (const limit of [3, 10, undefined]) {
+ const pages = pager()
+ const chain: unknown[] = []
+ let before: string | undefined
+ for (let n = 0; n < 60; n++) {
+ const page = await m.transcripts.pageOf(pages, engine, file, { ...(limit ? { limit } : {}), ...(before !== undefined ? { before } : {}) })
+ chain.push(pageView(page as unknown as Record<string, unknown>))
+ if (!page.hasMore || !page.oldestCursor || page.staleCursor) break
+ before = page.oldestCursor
+ }
+ cases[`${engine} · chain · limit ${limit ?? 'none'}`] = chain
+ }
+ cases[`${engine} · lines`] = await pager().lineCount(file)
+ }
+ const claudeAsks: Record<string, { limit?: number; before?: string }> = {
+ 'a prompt': { limit: 4, before: 'u-20' }, 'a tool call': { limit: 4, before: 'a-20-0' }, 'the huge line': { limit: 2, before: 'r-14-0' },
+ 'the first line': { limit: 4, before: 'u-1' }, 'unknown': { limit: 4, before: 'missing' }, 'empty': { limit: 4, before: '' },
+ 'a quoted id': { limit: 4, before: 'a "quoted" id' }, 'no limit, before a prompt': { before: 'u-29' },
+ }
+ for (const [name, ask] of Object.entries(claudeAsks)) cases[`claude · before · ${name}`] = pageView(await m.transcripts.pageOf(pager(), 'claude', claudeFile, ask) as unknown as Record<string, unknown>)
+ const codexCount = await pager().lineCount(codexFile)
+ const codexAsks: Record<string, { limit?: number; before?: string }> = {
+ 'the start': { limit: 4, before: 'codex:0' }, 'a line': { limit: 4, before: 'codex:40' }, 'a leading zero': { limit: 4, before: 'codex:040' },
+ 'the end': { limit: 4, before: `codex:${codexCount}` }, 'past the end': { limit: 4, before: `codex:${codexCount + 1}` },
+ 'negative': { limit: 4, before: 'codex:-1' }, 'not a number': { limit: 4, before: 'codex:x' }, 'garbage': { limit: 4, before: 'u-20' },
+ 'unsafe': { limit: 4, before: 'codex:9007199254740993' }, 'no limit': { before: 'codex:60' },
+ }
+ for (const [name, ask] of Object.entries(codexAsks)) cases[`codex · before · ${name}`] = pageView(await m.transcripts.pageOf(pager(), 'codex', codexFile, ask) as unknown as Record<string, unknown>)
+ // A file that cannot be read is an empty one, with the cursor an empty file has.
+ for (const engine of ['claude', 'codex'] as const) {
+ for (const before of [undefined, 'u-1', 'codex:0', 'codex:00', 'codex:5', 'garbage']) {
+ cases[`${engine} · missing · ${before ?? 'none'}`] = pageView(await m.transcripts.pageOf(pager(), engine, join(dir, 'missing.jsonl'), { limit: 4, ...(before !== undefined ? { before } : {}) }) as unknown as Record<string, unknown>)
+ }
+ cases[`${engine} · missing · lines`] = await pager().lineCount(join(dir, 'missing.jsonl'))
+ // A folder cannot be read as a file at all.
+ mkdirSync(join(dir, 'folder.jsonl'), { recursive: true })
+ for (const before of [undefined, 'u-1', 'codex:0', 'codex:00', 'codex:5', 'garbage']) {
+ cases[`${engine} · unreadable · ${before ?? 'none'}`] = pageView(await m.transcripts.pageOf(pager(), engine, join(dir, 'folder.jsonl'), { limit: 4, ...(before !== undefined ? { before } : {}) }) as unknown as Record<string, unknown>)
+ }
+ }
+ // The same pager again after the file grew: the cursors it remembers still name their lines.
+ const grown = pager()
+ const first = await m.transcripts.pageOf(grown, 'claude', claudeFile, { limit: 3 })
+ const second = await m.transcripts.pageOf(grown, 'claude', claudeFile, { limit: 3, before: first.oldestCursor! })
+ appendFileSync(claudeFile, claudeTurn(31).join('\n') + '\n')
+ cases['claude · grown · the remembered cursor'] = pageView(await m.transcripts.pageOf(grown, 'claude', claudeFile, { limit: 3, before: first.oldestCursor! }) as unknown as Record<string, unknown>)
+ cases['claude · grown · the next'] = pageView(await m.transcripts.pageOf(grown, 'claude', claudeFile, { limit: 3, before: second.oldestCursor! }) as unknown as Record<string, unknown>)
+ cases['claude · grown · from the end'] = pageView(await m.transcripts.pageOf(grown, 'claude', claudeFile, { limit: 3 }) as unknown as Record<string, unknown>)
+ const codexPages = pager()
+ const latest = await m.transcripts.pageOf(codexPages, 'codex', codexFile, { limit: 3 })
+ appendFileSync(codexFile, '\n' + codexTurn(31).join('\n'))
+ cases['codex · grown · the old cursor'] = pageView(await m.transcripts.pageOf(codexPages, 'codex', codexFile, { limit: 3, before: latest.oldestCursor! }) as unknown as Record<string, unknown>)
+ cases['codex · grown · from the end'] = pageView(await m.transcripts.pageOf(codexPages, 'codex', codexFile, { limit: 3 }) as unknown as Record<string, unknown>)
+ cases['codex · grown · lines'] = await codexPages.lineCount(codexFile)
+ return cases
+}
+
+// ---------------------------------------------------------------------------------------------- history
+
+const eventsView = (answer: Record<string, unknown>) => {
+ const { timestamp, events, ...rest } = answer as { timestamp: unknown; events: Array<{ type: string }> } & Record<string, unknown>
+ return norm({ sha: sha(JSON.stringify(events)), types: events.map((event) => event.type).join(','), timestamp: typeof timestamp, ...rest })
+}
+
+async function historyCases(): Promise<Record<string, unknown>> {
+ const cases: Record<string, unknown> = {}
+ const dir = join(root, 'history')
+ const claudePath = join(dir, 'claude', 'session-a.jsonl')
+ mkdirSync(join(dir, 'claude'), { recursive: true })
+ copyFileSync(fileURLToPath(new URL('../lib/__fixtures__/transcript-async-subagents.jsonl', import.meta.url)), claudePath)
+ // Two of its three background agents have transcripts of their own: their cards take their totals.
+ const subagent = (id: string, lines: unknown[]) => write(join(dir, 'claude', 'session-a', 'subagents', `agent-${id}.jsonl`), lines)
+ subagent('a523fae36e503c7a1', [
+ { type: 'user', timestamp: '2026-09-20T10:00:00Z' },
+ { type: 'assistant', timestamp: '2026-09-20T10:00:05Z', message: { content: [{ type: 'tool_use' }, { type: 'tool_use' }], usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 2 } } },
+ { type: 'assistant', timestamp: '2026-09-20T10:01:00Z', message: { content: [{ type: 'text' }], usage: { output_tokens: 3 } } },
+ ])
+ subagent('a316a821c79b054b9', [{ type: 'assistant', timestamp: '2026-09-20T10:00:00', message: { content: [{ type: 'tool_use' }] } }, 'not json'])
+ const claudeCorpus = join(dir, 'claude', 'corpus.jsonl')
+ copyFileSync(join(root, 'pages', 'claude.jsonl'), claudeCorpus)
+ const codexPath = join(dir, 'codex', 'rollout-session.jsonl')
+ mkdirSync(join(dir, 'codex'), { recursive: true })
+ copyFileSync(fileURLToPath(new URL('../lib/fixtures/session-work-codex.jsonl', import.meta.url)), codexPath)
+ const codexCorpus = join(dir, 'codex', 'corpus.jsonl')
+ copyFileSync(join(root, 'pages', 'codex.jsonl'), codexCorpus)
+ const session = (engine: string, transcriptPath: string | null, sessionId = 'session') => ({
+ agentId: `agent-${engine}`, sessionId, engine, transcriptPath, touchedAt: 1_791_374_400_000, registeredAt: 1_791_374_400_000, cwd: WORK,
+ codexHome: join(root, 'codex'),
+ }) as unknown as RegisteredSession
+ const files: Array<[string, string, string]> = [['claude', 'fixture', claudePath], ['claude', 'corpus', claudeCorpus], ['codex', 'fixture', codexPath], ['codex', 'corpus', codexCorpus]]
+ for (const [engine, name, path] of files) {
+ const reader = m.transcripts.engineTranscriptFor(engine)!
+ const pages = new m.pages.TranscriptPager()
+ const s = session(engine, path)
+ cases[`reader · ${engine} · ${name} · whole`] = eventsView(await reader.historyPage(s, {}, pages) as unknown as Record<string, unknown>)
+ const latest = await reader.historyPage(s, { limit: 3 }, pages)
+ cases[`reader · ${engine} · ${name} · latest`] = eventsView(latest as unknown as Record<string, unknown>)
+ if (latest.oldestCursor) cases[`reader · ${engine} · ${name} · older`] = eventsView(await reader.historyPage(s, { limit: 3, before: latest.oldestCursor }, pages) as unknown as Record<string, unknown>)
+ cases[`reader · ${engine} · ${name} · stale`] = eventsView(await reader.historyPage(s, { limit: 3, before: 'missing-cursor' }, pages) as unknown as Record<string, unknown>)
+ cases[`reader · ${engine} · ${name} · last turn`] = await attempt(() => reader.lastTurnText(s))
+ }
+ for (const engine of ['claude', 'codex']) {
+ const reader = m.transcripts.engineTranscriptFor(engine)!
+ cases[`reader · ${engine} · no transcript`] = eventsView(await reader.historyPage(session(engine, null), { limit: 3 }, new m.pages.TranscriptPager()) as unknown as Record<string, unknown>)
+ cases[`reader · ${engine} · no transcript · last turn`] = await attempt(() => reader.lastTurnText(session(engine, null)))
+ }
+
+ // Through core: `session_get`, `sessions_list` and the recap's last turn, with the readers core is handed.
+ for (const [engine, name, path] of files) {
+ const s = session(engine, path)
+ const deps = {
+ readerFor: m.transcripts.engineTranscriptFor, resolve: (id: string) => id === 'session' || id === s.agentId ? s : undefined,
+ stopped: () => [], pages: new m.pages.TranscriptPager(), dbs: { opencode: '', kilo: '', devin: '' }, hermesDb: async () => '',
+ }
+ const history = m.history.createHistory(deps as unknown as Parameters<typeof m.history.createHistory>[0])
+ const whole = await history.sessionGet({ sessionId: 'session' })
+ cases[`core · ${engine} · ${name} · whole`] = eventsView(whole)
+ const latest = await history.sessionGet({ sessionId: 'session', limit: 3 })
+ cases[`core · ${engine} · ${name} · latest`] = eventsView(latest)
+ if (latest.oldestCursor) cases[`core · ${engine} · ${name} · older`] = eventsView(await history.sessionGet({ sessionId: 'session', limit: 3, before: latest.oldestCursor as string }))
+ cases[`core · ${engine} · ${name} · stale`] = eventsView(await history.sessionGet({ sessionId: 'session', limit: 3, before: 'missing-cursor' }))
+ const listed = await history.sessionsList({ agentId: s.agentId }) as { sessions: Array<Record<string, unknown>> }
+ cases[`core · ${engine} · ${name} · list`] = norm(listed.sessions.map(({ lastActivity, ...rest }) => ({ ...rest, lastActivity: typeof lastActivity })))
+ const readLast = m.lastTurn.createLastTurnReader({ ...deps, bySession: () => s } as unknown as Parameters<typeof m.lastTurn.createLastTurnReader>[0])
+ cases[`core · ${engine} · ${name} · last turn`] = await attempt(() => readLast('session'))
+ }
+ return cases
+}
+
+type Sections = Record<string, Record<string, unknown>>
+const PLATFORMS = ['darwin', 'linux'] as const
+
+async function sectionsOn(platform: (typeof PLATFORMS)[number]): Promise<Sections> {
+ const real = Object.getOwnPropertyDescriptor(process, 'platform')!
+ Object.defineProperty(process, 'platform', { ...real, value: platform })
+ // Each platform reads files of its own: nothing either one wrote or remembered is the other's.
+ for (const name of ['claude', 'codex', 'moved-claude', 'moved-codex', 'elsewhere', 'turns', 'activity', 'pages', 'history', 'none', 'tmp']) rmSync(join(root, name), { recursive: true, force: true })
+ try {
+ return { adoption: await adoptionCases(), activity: await activityCases(), pages: await pageCases(), history: await historyCases() }
+ } finally { Object.defineProperty(process, 'platform', real) }
+}
+
+describe('core reads Claude Code\'s and Codex\'s conversations as it did before their reading rules were declared', () => {
+ it('adoption, activity, pages, history and the last turn match the record, on darwin and linux', async () => {
+ const darwin = await sectionsOn('darwin')
+ const linux = await sectionsOn('linux')
+ const linuxDiffers = Object.fromEntries(Object.entries(linux).map(([section, cases]) => [section,
+ Object.fromEntries(Object.entries(cases).filter(([key, value]) => JSON.stringify(value) !== JSON.stringify(darwin[section]![key])))]))
+ if (RECORD) {
+ const block = (cases: Record<string, unknown>): string => Object.entries(cases).map(([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`).join(',\n')
+ const sections = (all: Sections): string => Object.entries(all).map(([section, cases]) => `${JSON.stringify(section)}: {\n${block(cases)}\n}`).join(',\n')
+ writeFileSync(GOLDEN, `{\n${sections(darwin)},\n"linux": {\n${sections(linuxDiffers)}\n}\n}\n`)
+ return
+ }
+ const { linux: linuxGolden, ...darwinGolden } = JSON.parse(readFileSync(GOLDEN, 'utf8')) as Sections & { linux: Sections }
+ for (const [platform, actual, golden] of [
+ ['darwin', darwin, darwinGolden],
+ ['linux', linux, Object.fromEntries(Object.entries(darwinGolden).map(([section, cases]) => [section, { ...cases, ...linuxGolden[section] }]))],
+ ] as const) {
+ expect(Object.keys(actual), platform).toEqual(Object.keys(golden))
+ for (const [section, cases] of Object.entries(golden)) {
+ expect(Object.keys(actual[section]!).sort(), `${platform} · ${section}`).toEqual(Object.keys(cases).sort())
+ for (const [key, value] of Object.entries(cases)) expect(actual[section]![key], `${platform} · ${section} · ${key}`).toEqual(value)
+ }
+ }
+ }, 240_000)
+
+ it('records no machine-specific path', () => {
+ const text = readFileSync(GOLDEN, 'utf8')
+ expect(text).not.toContain('transcript-reads-golden-')
+ expect(text).not.toContain(root)
+ expect(text).not.toMatch(/\/Users\/|\/home\/runner/)
+ })
+})
diff --git a/cli/src/engines/transcripts.ts b/cli/src/engines/transcripts.ts
index e386d3386..f9057dfb6 100644
--- a/cli/src/engines/transcripts.ts
+++ b/cli/src/engines/transcripts.ts
@@ -1,9 +1,15 @@
-import type { EngineTranscript } from './facets/transcript.js'
-import { transcript as claude } from './claude/transcript.js'
-import { transcript as codex } from './codex/transcript.js'
+import type { EngineTranscript, HistoryAsk } from './facets/transcript.js'
+import type { HistoryPage, TranscriptPager } from '../lib/transcriptPages.js'
+import { pages as claudePages, transcript as claude } from './claude/transcript.js'
+import { pages as codexPages, transcript as codex } from './codex/transcript.js'
/** Only for explicit inline compatibility and tests. Supervised core uses the reader port. */
export function engineTranscriptFor(engine: string): EngineTranscript | undefined {
const transcripts = { claude, codex }
return Object.hasOwn(transcripts, engine) ? transcripts[engine as keyof typeof transcripts] : undefined
}
+
+/** One page of `engine`'s transcript at `path`, as that engine's reader asks the pager for it. */
+export function pageOf(pager: TranscriptPager, engine: 'claude' | 'codex', path: string, ask: HistoryAsk): Promise<HistoryPage> {
+ return pager.page(path, engine === 'claude' ? claudePages : codexPages, ask)
+}
diff --git a/cli/src/lib/sessionSearch/externals/claude.ts b/cli/src/lib/sessionSearch/externals/claude.ts
index d66910e22..06dce5e7d 100644
--- a/cli/src/lib/sessionSearch/externals/claude.ts
+++ b/cli/src/lib/sessionSearch/externals/claude.ts
@@ -5,108 +5,30 @@
*
* A running Claude Code keeps `~/.claude/sessions/<pid>.json` naming its session and saying `idle`
* between turns: the owner and its state, exactly.
+ *
+ * Declared in engines/claude/adoption.ts and read by the kit (engines/kit/adoption.ts); these are the names its
+ * specs have always used. Core builds the provider from the declaration (engines/adoptions.ts), never from here.
*/
-
import { join } from 'node:path'
-import { agentCommandOwnershipSnapshot } from '../../engineBin.js'
-import { engineProcessMatch } from '../../tmux.js'
-import { absoluteFolder, entries, fileStamp, readHead, readJson, record, text } from './support.js'
-import { type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'
-
-/**
- * How much of a transcript is read to classify it, a window at a time. The line that says who wrote it
- * is usually the first prompt, which can carry a pasted image: a few hundred kilobytes, or megabytes.
- */
-const HEAD_BYTES = [256 * 1024, 4 * 1024 * 1024, 32 * 1024 * 1024]
-const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/
-/** `ps` gives a start to the second; Claude stamps its record a moment after it starts. */
-const START_SLACK_MS = 2_000
+import { adoption } from '../../../engines/claude/adoption.js'
+import { adoptionProvider, readAdoptedHead, type AdoptedHead } from '../../../engines/kit/adoption.js'
+import type { ExternalProvider, UNSETTLED } from './types.js'
-export interface ClaudeHead { sessionId: string; cwd: string; origin: ExternalOrigin }
+export type ClaudeHead = AdoptedHead
/**
* A transcript's session, folder and entrypoint, from the first line that has them. UNSETTLED when no
* such line is there yet in a file shorter than what is read: Claude may still be writing it.
*/
-export async function readClaudeHead(path: string, windows: readonly number[] = HEAD_BYTES): Promise<ClaudeHead | null | typeof UNSETTLED> {
- for (const bytes of windows) {
- const head = await readHead(path, bytes)
- const whole = Buffer.byteLength(head) < bytes
- // A window that ends mid-file ends mid-line: that line is read whole by the next, wider one.
- const lines = head.split('\n')
- if (!whole) lines.pop()
- for (const line of lines) {
- if (!line.includes('"entrypoint"')) continue
- let row: Record<string, unknown> | null
- try { row = record(JSON.parse(line)) } catch { continue }
- if (!row) continue
- if (row.isSidechain === true) return null
- const origin: ExternalOrigin | null = row.entrypoint === 'cli' ? 'terminal' : row.entrypoint === 'claude-desktop' ? 'claude-app' : null
- const cwd = absoluteFolder(row.cwd)
- if (!origin || !SESSION_ID.test(text(row.sessionId)) || !cwd) return null
- return { sessionId: text(row.sessionId), cwd, origin }
- }
- // The whole file, and no line says yet: Claude may still be writing it.
- if (whole) return UNSETTLED
- }
- return null
+export function readClaudeHead(path: string, windows: readonly number[] = adoption.head.windows): Promise<ClaudeHead | null | typeof UNSETTLED> {
+ return readAdoptedHead(path, { ...adoption.head, windows })
}
export function claudeProvider(options: { projectsDir: string; home: string; roots?: () => string[] }): ExternalProvider {
- return {
- engine: 'claude',
- async scan(ctx: ScanContext): Promise<ExternalSession[]> {
- const found: ExternalSession[] = []
- for (const projectsDir of options.roots?.() ?? [options.projectsDir]) {
- for (const project of await entries(projectsDir)) {
- if (!project.isDirectory()) continue
- const folder = join(projectsDir, project.name)
- // Only the project's own files: a sub-agent's are in a folder beneath it.
- for (const file of await entries(folder)) {
- if (!file.name.endsWith('.jsonl')) continue
- const path = join(folder, file.name)
- // A file, or a link to one; not a folder, not a broken link.
- const stamp = await fileStamp(path)
- if (!stamp) continue
- // A transcript's first lines never change: its head is read once, however it grows.
- const head = await ctx.head(`claude:${path}`, stamp.stamp, () => readClaudeHead(path))
- await ctx.pace()
- if (!head || ctx.excluded(head.cwd)) continue
- found.push({ ...head, engine: 'claude', title: '', mtime: stamp.mtime, transcriptPath: path })
- }
- }
- }
- return found
- },
- async owners(view: ProcessView): Promise<OwnerClaim[]> {
- const claims: OwnerClaim[] = []
- const dirs = options.roots?.().map(root => join(root, '..', 'sessions')) ?? [join(options.home, 'sessions')]
- for (const dir of dirs) {
- const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith('.json'))
- if (!records.length) continue
- const processes = new Map((await view.list()).map((process): [number, RunningProcess] => [process.pid, process]))
- const ownership = agentCommandOwnershipSnapshot()
- for (const file of records) {
- const path = join(dir, file.name)
- const row = record(await readJson(path))
- const pid = row?.pid
- if (typeof pid !== 'number' || !text(row?.sessionId) || !view.alive(pid)) continue
- // A record outlives a crash, and its pid can be handed to anything after — a shell in another
- // tab. Only a Claude process already running when the record says Claude started still has it.
- const process = processes.get(pid)
- if (!process || engineProcessMatch(process, 'claude', ownership).score <= 0) continue
- if (process.started !== undefined && typeof row?.startedAt === 'number' && process.started > row.startedAt + START_SLACK_MS) continue
- claims.push({ sessionId: text(row?.sessionId), pid, record: path })
- }
- }
- return claims
- },
- async busy(owner): Promise<boolean | null> {
- const row = record(await readJson(owner.record))
- // No record: the process ended with it, so it is not mid-turn.
- if (!row) return false
- return row.status === 'busy' ? true : row.status === 'idle' ? false : null
- },
- }
+ const records = 'records' in adoption.owners ? adoption.owners.records.folder : 'sessions'
+ return adoptionProvider('claude', adoption, {
+ roots: options.roots ?? (() => [options.projectsDir]),
+ ...(options.roots ? {} : { records: () => [join(options.home, records)] }),
+ })
}
diff --git a/cli/src/lib/sessionSearch/externals/codex.ts b/cli/src/lib/sessionSearch/externals/codex.ts
index e4f89109d..915d4be52 100644
--- a/cli/src/lib/sessionSearch/externals/codex.ts
+++ b/cli/src/lib/sessionSearch/externals/codex.ts
@@ -7,87 +7,41 @@
*
* Codex keeps no process record, but holds its rollout open while it runs, so `lsof` names the
* owner; the rollout's last turn event says whether a turn is running.
+ *
+ * Declared in engines/codex/adoption.ts and read by the kit (engines/kit/adoption.ts); these are the names its
+ * specs have always used. Core builds the provider from the declaration (engines/adoptions.ts), never from here.
*/
+import { adoption } from '../../../engines/codex/adoption.js'
+import { adoptedTitles, adoptionProvider, readAdoptedHead, servesOthers, turnOpen, walkFiles, type AdoptedHead } from '../../../engines/kit/adoption.js'
+import type { ExternalProvider, RunningProcess, ScanContext, UNSETTLED } from './types.js'
-import { join } from 'node:path'
-
-import { absoluteFolder, entries, fileStamp, firstLine, parseLine, readHead, readTail, readText, record, text } from './support.js'
-import { argvTokens } from '../../tmux.js'
-import { type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'
-
-/** How much of a rollout is read for its first line: a little first; `session_meta` can carry long
- * base instructions, so up to a megabyte when it has to. */
-const HEAD_BYTES = [16 * 1024, 1024 * 1024]
-const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/
-const ROLLOUT_ID = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i
+export type CodexHead = AdoptedHead
-export interface CodexHead { sessionId: string; cwd: string; origin: ExternalOrigin }
+const files = adoption.files.layout === 'walk' ? adoption.files : null
+const open = 'open' in adoption.owners ? adoption.owners.open : null
+const tail = 'tail' in adoption.busy ? adoption.busy.tail : null
/**
* A rollout's session, folder and source, from its first line. UNSETTLED while that line has no end
* yet in a file shorter than what is read: Codex is still writing it.
*/
-export async function readCodexHead(path: string): Promise<CodexHead | null | typeof UNSETTLED> {
- let line: string | null = null
- for (const bytes of HEAD_BYTES) {
- line = await firstLine(path, bytes)
- if (line !== null) break
- // The whole file was read and it has no line yet: Codex is still writing it.
- if (Buffer.byteLength(await readHead(path, bytes)) < bytes) return UNSETTLED
- }
- if (line === null) return null
- const row = record(parseLine(line))
- const meta = record(row?.payload)
- if (row?.type !== 'session_meta' || !meta) return null
- const origin: ExternalOrigin | null = meta.source === 'cli' ? 'terminal'
- : meta.source === 'vscode' ? (meta.originator === 'Codex Desktop' ? 'codex-app' : 'editor')
- : null
- const cwd = absoluteFolder(meta.cwd)
- if (!origin || !SESSION_ID.test(text(meta.id)) || !cwd) return null
- return { sessionId: text(meta.id), cwd, origin }
+export function readCodexHead(path: string): Promise<CodexHead | null | typeof UNSETTLED> {
+ return readAdoptedHead(path, adoption.head)
}
/** Thread names: `session_index.jsonl`, one `{id, thread_name}` a line, the last one winning. */
-export async function codexTitles(path: string, ctx: ScanContext): Promise<Map<string, string>> {
- const stamp = await fileStamp(path)
- if (!stamp) return new Map()
- return ctx.memo(`codex:titles:${path}`, stamp.stamp, async () => {
- const titles = new Map<string, string>()
- for (const line of (await readText(path)).split('\n')) {
- const row = record(parseLine(line))
- const name = text(row?.thread_name).trim()
- if (text(row?.id) && name) titles.set(text(row?.id), name)
- }
- return titles
- })
+export function codexTitles(path: string, ctx: ScanContext): Promise<Map<string, string>> {
+ return adoptedTitles('codex', path, adoption.titles!, ctx)
}
/** Every rollout file under a sessions folder (`YYYY/MM/DD/rollout-*.jsonl`), at any depth up to 4. */
-export async function rollouts(dir: string): Promise<string[]> {
- const out: string[] = []
- const walk = async (at: string, depth: number): Promise<void> => {
- for (const entry of await entries(at)) {
- const path = join(at, entry.name)
- if (entry.isDirectory() && depth < 4) await walk(path, depth + 1)
- // A file or a link to one; the scan's stat drops a broken link.
- else if (!entry.isDirectory() && entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) out.push(path)
- }
- }
- await walk(dir, 0)
- return out
+export function rollouts(dir: string): Promise<string[]> {
+ return walkFiles(dir, files!)
}
-const TURN_MARK = /"(task_started|task_complete|turn_aborted)"/
-
-const SERVER_COMMANDS = new Set(['app-server', 'mcp-server', 'mcp', 'proto'])
-
/** Whether a Codex process serves other clients rather than a person's terminal. */
export function codexServer(row: RunningProcess | undefined): boolean {
- if (!row) return false
- if (/codex-acp$/.test(row.executable) || /(?:^|\/)codex-acp(?:\s|$)/.test(row.args)) return true
- // The subcommand: the first argument that is not an option.
- const subcommand = argvTokens(row.args).slice(1).find((token) => !token.startsWith('-'))
- return !!subcommand && SERVER_COMMANDS.has(subcommand)
+ return servesOthers(row, open!.servers)
}
/**
@@ -95,59 +49,10 @@ export function codexServer(row: RunningProcess | undefined): boolean {
* `turn_aborted` event near its end says. What was said can name the events; only events count.
* A file that cannot say counts as busy.
*/
-export async function codexTurnOpen(path: string, unknown: boolean | null = true): Promise<boolean | null> {
- for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {
- const lines = (await readTail(path, bytes)).split('\n')
- for (let i = lines.length - 1; i > 0; i--) {
- const line = lines[i]
- if (!line.includes('"event_msg"') || !TURN_MARK.test(line)) continue
- const kind = record(record(parseLine(line))?.payload)?.type
- if (kind === 'task_started') return true
- if (kind === 'task_complete' || kind === 'turn_aborted') return false
- }
- }
- return unknown
+export function codexTurnOpen(path: string, unknown: boolean | null = true): Promise<boolean | null> {
+ return turnOpen(path, tail!, unknown)
}
export function codexProvider(options: { home: string; roots?: () => string[] }): ExternalProvider {
- return {
- engine: 'codex',
- async scan(ctx: ScanContext): Promise<ExternalSession[]> {
- const found: ExternalSession[] = []
- for (const home of options.roots?.() ?? [options.home]) {
- const titles = await codexTitles(join(home, 'session_index.jsonl'), ctx)
- const archived = new Set(await rollouts(join(home, 'archived_sessions')))
- for (const path of [...await rollouts(join(home, 'sessions')), ...archived]) {
- const stamp = await fileStamp(path)
- if (!stamp) continue
- // A rollout's first line never changes: read once, however the file grows.
- const head = await ctx.head(`codex:${path}`, stamp.stamp, () => readCodexHead(path))
- await ctx.pace()
- if (!head || ctx.excluded(head.cwd)) continue
- found.push({
- ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path,
- ...(archived.has(path) ? { archived: true as const } : {}),
- })
- }
- }
- return found
- },
- async owners(view: ProcessView): Promise<OwnerClaim[]> {
- const claims: OwnerClaim[] = []
- const held = await view.openFilesOf(['codex', 'Codex'])
- if (!held.size) return claims
- const processes = new Map((await view.list()).map((row): [number, RunningProcess] => [row.pid, row]))
- for (const [pid, files] of held) {
- // A server Codex runs for other clients (the app, an editor, MCP) holds their threads: never
- // stopped from here, even when a terminal started it.
- const app = codexServer(processes.get(pid))
- for (const path of files) {
- const id = ROLLOUT_ID.exec(path)?.[1]
- if (id && path.includes('rollout-')) claims.push({ sessionId: id, pid, record: path, ...(app ? { app: true } : {}) })
- }
- }
- return claims
- },
- busy: (owner) => codexTurnOpen(owner.record, null),
- }
+ return adoptionProvider('codex', adoption, { roots: options.roots ?? (() => [options.home]) })
}
diff --git a/cli/src/lib/sessionSearch/externals/copilot.ts b/cli/src/lib/sessionSearch/externals/copilot.ts
index 813398c7e..17ec077f4 100644
--- a/cli/src/lib/sessionSearch/externals/copilot.ts
+++ b/cli/src/lib/sessionSearch/externals/copilot.ts
@@ -18,7 +18,7 @@ import { basename, join } from 'node:path'
import { copilotHistoryTurnOpen } from '../../../engines/copilot/normalizer.js'
import { agentCommandOwnershipSnapshot } from '../../engineBin.js'
import { argvTokens, engineProcessMatch } from '../../tmux.js'
-import { forEachLine } from '../../transcriptReader.js'
+import { forEachLine } from '../../transcriptLines.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readTail, record, text, UUID } from './support.js'
import type { ExternalOrigin, ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/grok.ts b/cli/src/lib/sessionSearch/externals/grok.ts
index a8ddee570..1ecf0160b 100644
--- a/cli/src/lib/sessionSearch/externals/grok.ts
+++ b/cli/src/lib/sessionSearch/externals/grok.ts
@@ -18,7 +18,7 @@ import { basename, join } from 'node:path'
import { agentCommandOwnershipSnapshot } from '../../engineBin.js'
import { argvTokens, engineProcessMatch } from '../../tmux.js'
-import { forEachLine } from '../../transcriptReader.js'
+import { forEachLine } from '../../transcriptLines.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readJson, readTail, record, text, UUID } from './support.js'
import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/index.ts b/cli/src/lib/sessionSearch/externals/index.ts
index 7f00c1d61..d16cfd955 100644
--- a/cli/src/lib/sessionSearch/externals/index.ts
+++ b/cli/src/lib/sessionSearch/externals/index.ts
@@ -7,10 +7,9 @@ import { isAbsolute, join } from 'node:path'
import { cursorConfigDir, cursorDataDir } from '../../../engines/cursor/home.js'
import { env } from '../../../config/env.js'
+import { adoptionProviderOf } from '../../../engines/adoptions.js'
import { claudeProjectsRoots, codexHomeRoots } from '../../engineHomes.js'
import { agyProvider } from './agy.js'
-import { claudeProvider } from './claude.js'
-import { codexProvider } from './codex.js'
import { commandcodeProvider } from './commandcode.js'
import { copilotProvider } from './copilot.js'
import { cursorProvider } from './cursor.js'
@@ -75,8 +74,10 @@ export function externalProviders(paths: ExternalPaths = externalPaths()): Exter
return [
// QA found search's separate process started before the core adopted the shell's homes.
// Resolve roots on each scan, retaining the default and previously adopted conversations.
- claudeProvider({ projectsDir: paths.claudeProjectsDir, home: join(paths.claudeProjectsDir, '..'), roots: () => claudeProjectsRoots(paths.claudeProjectsDir) }),
- codexProvider({ home: paths.codexHome, roots: () => codexHomeRoots(paths.codexHome) }),
+ // Claude Code's and Codex's are declared (engines/adoptions.ts): Claude Code's listed from each sessions
+ // folder, its process records beside each; Codex's from each home.
+ adoptionProviderOf('claude', { roots: () => claudeProjectsRoots(paths.claudeProjectsDir) }),
+ adoptionProviderOf('codex', { roots: () => codexHomeRoots(paths.codexHome) }),
cursorProvider({ configDir: paths.cursorConfigDir, dataDir: paths.cursorDataDir }),
grokProvider({ home: paths.grokHome }),
copilotProvider({ home: paths.copilotHome }),
diff --git a/cli/src/lib/sessionSearch/externals/muse.ts b/cli/src/lib/sessionSearch/externals/muse.ts
index 8453f6237..90643e883 100644
--- a/cli/src/lib/sessionSearch/externals/muse.ts
+++ b/cli/src/lib/sessionSearch/externals/muse.ts
@@ -18,7 +18,7 @@ import { basename, dirname, join } from 'node:path'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch, resumeSessionId } from '../../tmux.js'
-import { forEachLine } from '../../transcriptReader.js'
+import { forEachLine } from '../../transcriptLines.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readHead, readTail, record, text, UUID } from './support.js'
import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/pi.ts b/cli/src/lib/sessionSearch/externals/pi.ts
index ad2bbf198..d6991e921 100644
--- a/cli/src/lib/sessionSearch/externals/pi.ts
+++ b/cli/src/lib/sessionSearch/externals/pi.ts
@@ -22,7 +22,7 @@ import { isAbsolute, join, resolve } from 'node:path'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch, resumeSessionId } from '../../tmux.js'
-import { forEachLine } from '../../transcriptReader.js'
+import { forEachLine } from '../../transcriptLines.js'
import { absoluteFolder, entries, fileStamp, parseLine, readHead, readJson, readTail, record, text } from './support.js'
import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'
diff --git a/cli/src/lib/transcriptActivity.ts b/cli/src/lib/transcriptActivity.ts
index 9fa4014c9..1af59b6d2 100644
--- a/cli/src/lib/transcriptActivity.ts
+++ b/cli/src/lib/transcriptActivity.ts
@@ -1,4 +1,8 @@
import { open, stat } from 'node:fs/promises'
+import type { ActivityMatch, SessionStoreContract } from '../engines/facets/sessionStore.js'
+import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
+
+type Activity = NonNullable<SessionStoreContract['activity']>
const CHUNK_BYTES = 64 * 1024
const MAX_TAIL_BYTES = 2 * 1024 * 1024
@@ -11,39 +15,38 @@ function object(value: unknown): Record<string, unknown> | null {
? value as Record<string, unknown> : null
}
-const codexEvents = new Set([
- 'user_message', 'UserMessage', 'agent_message', 'AgentMessage',
- 'task_started', 'task_complete', 'turn_aborted', 'context_compacted',
-])
-const codexResponses = new Set([
- 'reasoning', 'function_call', 'custom_tool_call', 'tool_search_call',
- 'function_call_output', 'custom_tool_call_output', 'tool_search_output',
-])
+/** The first object at one of `paths` in `row`. */
+function itemOf(row: Record<string, unknown>, paths: readonly (readonly string[])[]): Record<string, unknown> | null {
+ for (const path of paths) {
+ let at: unknown = row
+ for (const key of path) at = object(at)?.[key]
+ const found = object(at)
+ if (found) return found
+ }
+ return null
+}
+
+function matches(value: unknown, match: ActivityMatch): boolean {
+ return 'in' in match ? match.in.includes(String(value)) : match.is.some((one) => value === one)
+}
/** Metadata can be rewritten when an idle harness is discovered or resumed. Only conversation
- * records count; a fresh file mtime, title, context snapshot, or rate-limit reading does not. */
-function activity(line: string, engine: string): number | null {
+ * records count, as the engine's session store declares them (`activity`); a fresh file mtime, title,
+ * context snapshot, or rate-limit reading does not. */
+function activity(line: string, rule: Activity): number | null {
let row: Record<string, unknown> | null
try { row = object(JSON.parse(line)) } catch { return null }
- if (!row || typeof row.timestamp !== 'string') return null
- const at = Date.parse(row.timestamp)
+ if (!row || typeof row[rule.at] !== 'string') return null
+ const at = Date.parse(row[rule.at] as string)
if (!Number.isFinite(at)) return null
- if (engine === 'claude') {
- return row.type === 'user' || row.type === 'assistant'
- || row.type === 'system' && ['turn_duration', 'stop_hook_summary', 'compact_boundary'].includes(String(row.subtype))
- ? at : null
- }
- const direct = object(row.payload)
- const item = object(direct?.item) ?? direct
- if (row.type === 'event_msg' && codexEvents.has(String(item?.type))) return at
- if (row.type === 'response_item' && item) {
- if (codexResponses.has(String(item.type))) return at
- if (item.type === 'message' && (item.role === 'user' || item.role === 'assistant')) return at
- }
- return row.type === 'compacted' ? at : null
+ const item = rule.item ? itemOf(row, rule.item) : null
+ const counted = rule.records.some((kind) => row!.type === kind.type
+ && Object.entries(kind.fields ?? {}).every(([field, match]) => matches(row![field], match))
+ && (!kind.item || (!!item && Object.entries(kind.item).every(([field, match]) => matches(item[field], match)))))
+ return counted ? at : null
}
-async function readActivity(path: string, size: number, engine: string): Promise<number | null> {
+async function readActivity(path: string, size: number, rule: Activity): Promise<number | null> {
if (reading >= 4) await new Promise<void>(resolve => waiting.push(resolve))
else reading++
try {
@@ -65,7 +68,7 @@ async function readActivity(path: string, size: number, engine: string): Promise
const complete = start === 0 ? chunk : chunk.subarray(newline + 1)
let latest: number | null = null
for (const line of complete.toString('utf8').split('\n')) {
- const at = activity(line, engine)
+ const at = activity(line, rule)
if (at !== null) latest = Math.max(latest ?? at, at)
}
if (latest !== null) return latest
@@ -90,11 +93,13 @@ async function readActivity(path: string, size: number, engine: string): Promise
}
}
-/** Read the latest dated work from known JSONL formats. Bounded tail reads are shared by list/push
- * frames and cached until the file changes; no transcript text is retained. Other engines use the
- * caller's last hook instead of pretending their database/file modification time is activity. */
+/** Read the latest dated work from the JSONL formats whose engines declare it (their session store's
+ * `activity`). Bounded tail reads are shared by list/push frames and cached until the file changes; no
+ * transcript text is retained. Other engines use the caller's last hook instead of pretending their
+ * database/file modification time is activity. */
export async function transcriptActivityAt(path: string | null, engine: string): Promise<number | null> {
- if (!path || (engine !== 'claude' && engine !== 'codex')) return null
+ const rule = sessionStoreOf(engine)?.activity
+ if (!path || !rule) return null
const info = await stat(path).catch(() => null)
if (!info?.isFile() || !info.size) return null
const key = `${engine}:${path}`
@@ -102,7 +107,7 @@ export async function transcriptActivityAt(path: string | null, engine: string):
const found = cache.get(key)
if (found?.signature === signature) return found.value
if (cache.size >= 512) cache.delete(cache.keys().next().value!)
- const value = readActivity(path, info.size, engine)
+ const value = readActivity(path, info.size, rule)
cache.set(key, { signature, value })
return value
}
diff --git a/cli/src/lib/transcriptLines.ts b/cli/src/lib/transcriptLines.ts
new file mode 100644
index 000000000..07607bda5
--- /dev/null
+++ b/cli/src/lib/transcriptLines.ts
@@ -0,0 +1,87 @@
+/**
+ * A transcript read line by line from a byte offset, never more than one line in memory, the lines a caller
+ * names by their first bytes dropped before they are decoded. Engine-neutral: moved out of lib/transcriptReader.ts,
+ * which re-exports it, so the adoption readers that only stream lines load none of the engines' normalizers that
+ * file holds for search.
+ */
+import { open } from 'node:fs/promises'
+
+/** How much of a line is read before deciding whether to skip it. */
+const HEAD_BYTES = 1024
+/** A longer line is not a prompt or an answer anyone wrote; it is dropped unread. */
+const MAX_LINE_BYTES = 16 * 1024 * 1024
+const CHUNK_BYTES = 1024 * 1024
+
+export interface LineVisit {
+ text: string
+ /** Byte offset of the line's first byte. */
+ offset: number
+}
+
+/**
+ * Calls `visit` for every complete line from `start`, and resolves with the offset just past the last
+ * complete line. A final line without its newline is left for the next pass: the engine may still be
+ * writing it. `visit` may return a promise to pace the reader.
+ */
+export async function forEachLine(
+ path: string,
+ start: number,
+ visit: (line: LineVisit) => void | Promise<void>,
+ options: { skip?: ((head: string) => boolean) | null; shouldStop?: () => boolean } = {},
+): Promise<{ end: number }> {
+ const handle = await open(path, 'r')
+ try {
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES)
+ let position = start
+ let lineStart = start
+ let parts: Buffer[] = []
+ let length = 0
+ let decided = false
+ let dropping = false
+ for (;;) {
+ if (options.shouldStop?.()) return { end: lineStart }
+ const { bytesRead } = await handle.read(buffer, 0, CHUNK_BYTES, position)
+ if (bytesRead === 0) return { end: lineStart }
+ let cursor = 0
+ while (cursor < bytesRead) {
+ const newline = buffer.indexOf(10, cursor)
+ const stop = newline === -1 || newline >= bytesRead ? bytesRead : newline
+ if (!dropping) {
+ const piece = buffer.subarray(cursor, stop)
+ if (length + piece.length > MAX_LINE_BYTES) {
+ dropping = true
+ parts = []
+ length = 0
+ } else {
+ parts.push(Buffer.from(piece))
+ length += piece.length
+ if (!decided && options.skip && (length >= HEAD_BYTES || stop < bytesRead)) {
+ decided = true
+ const head = Buffer.concat(parts, length).subarray(0, HEAD_BYTES).toString('utf8')
+ if (options.skip(head)) {
+ dropping = true
+ parts = []
+ length = 0
+ }
+ }
+ }
+ }
+ if (stop === bytesRead) break
+ // A complete line.
+ if (!dropping && length > 0) {
+ const text = Buffer.concat(parts, length).toString('utf8')
+ await visit({ text, offset: lineStart })
+ }
+ lineStart = position + stop + 1
+ parts = []
+ length = 0
+ decided = false
+ dropping = false
+ cursor = stop + 1
+ }
+ position += bytesRead
+ }
+ } finally {
+ await handle.close()
+ }
+}
diff --git a/cli/src/lib/transcriptPages.spec.ts b/cli/src/lib/transcriptPages.spec.ts
index 024362965..fb3701b76 100644
--- a/cli/src/lib/transcriptPages.spec.ts
+++ b/cli/src/lib/transcriptPages.spec.ts
@@ -8,6 +8,7 @@ import { claude, claudeScenario, codex, codexScenario } from '../testing/transcr
import { claudePageLine, windowRawLines } from './normalize.js'
import { tailFile } from './transcriptTail.js'
import { LineIndex, pageBefore, TranscriptPager, type HistoryPage, type OpenFile } from './transcriptPages.js'
+import { pageOf } from '../engines/transcripts.js'
let dir: string
let files = 0
@@ -31,7 +32,7 @@ async function pageThrough(engine: Engine, file: string, limit: number): Promise
let before: string | undefined
for (let pages = 1; ; pages++) {
const old = window(engine, lines, { limit, before })
- const now = await pager[engine](file, { limit, before })
+ const now = await pageOf(pager, engine, file, { limit, before })
expect(asOld(now), `${engine} page ${pages}, limit ${limit}, before ${before}`).toEqual(old)
expect(now.clipped).toBe(false)
if (!old.hasMore || old.staleCursor || old.oldestCursor === null) return pages
@@ -74,13 +75,13 @@ describe('history pages equal the windows cut from the whole file', { timeout: F
const lines = await tailFile(file, Infinity)
const pager = new TranscriptPager()
for (const before of ['nothing-like-it', 'codex:x', `codex:${lines.length + 1}`, 'codex:99999999999999999999']) {
- expect(asOld(await pager[engine](file, { limit: 5, before }))).toEqual(window(engine, lines, { limit: 5, before }))
+ expect(asOld(await pageOf(pager, engine, file, { limit: 5, before }))).toEqual(window(engine, lines, { limit: 5, before }))
}
})
it('gives every line, oldest first, when asked for no page at all', async () => {
const file = fresh(records.join('\n') + '\n')
- const page = await new TranscriptPager()[engine](file, {})
+ const page = await pageOf(new TranscriptPager(), engine, file, {})
expect(page.lines).toEqual(await tailFile(file, Infinity))
expect(page.hasMore).toBe(false)
})
@@ -90,17 +91,17 @@ describe('history pages equal the windows cut from the whole file', { timeout: F
const pager = new TranscriptPager()
const missing = join(dir, 'gone.jsonl')
for (const before of [undefined, 'u1']) {
- expect(asOld(await pager.claude(missing, { limit: 5, before }))).toEqual(windowRawLines([], { limit: 5, before }))
+ expect(asOld(await pageOf(pager, 'claude', missing, { limit: 5, before }))).toEqual(windowRawLines([], { limit: 5, before }))
}
for (const before of [undefined, 'codex:0', 'codex:1']) {
- expect(asOld(await pager.codex(missing, { limit: 5, before }))).toEqual(windowCodexLines([], { limit: 5, before }))
+ expect(asOld(await pageOf(pager, 'codex', missing, { limit: 5, before }))).toEqual(windowCodexLines([], { limit: 5, before }))
}
expect(await pager.lineCount(missing)).toBe(0)
const locked = fresh(claudeScenario().join('\n') + '\n')
chmodSync(locked, 0o000)
try {
- expect(asOld(await pager.claude(locked, { limit: 5 }))).toEqual(windowRawLines([], { limit: 5 }))
- expect((await pager.claude(locked, { limit: 5, before: 'u1' })).staleCursor).toBe(true)
+ expect(asOld(await pageOf(pager, 'claude', locked, { limit: 5 }))).toEqual(windowRawLines([], { limit: 5 }))
+ expect((await pageOf(pager, 'claude', locked, { limit: 5, before: 'u1' })).staleCursor).toBe(true)
expect(await pageBefore(locked, 100, 5, { startsPage: () => true })).toEqual({ lines: [], count: 0, start: 0, hasMore: false, clipped: false })
} finally { chmodSync(locked, 0o600) }
})
@@ -112,11 +113,11 @@ describe('history pages equal the windows cut from the whole file', { timeout: F
const lines = await tailFile(file, Infinity)
const pager = new TranscriptPager()
// Paging back from the second line leaves only the first, which has no id of its own.
- expect(asOld(await pager.claude(file, { limit: 5, before: first }))).toEqual(windowRawLines(lines, { limit: 5, before: first }))
+ expect(asOld(await pageOf(pager, 'claude', file, { limit: 5, before: first }))).toEqual(windowRawLines(lines, { limit: 5, before: first }))
const top = claudePageLine(records[0]).cursor
expect(top).toBeNull()
const withId = fresh(records.slice(1).join('\n') + '\n')
- const page = await pager.claude(withId, { limit: 5, before: first })
+ const page = await pageOf(pager, 'claude', withId, { limit: 5, before: first })
expect(asOld(page)).toEqual(windowRawLines(await tailFile(withId, Infinity), { limit: 5, before: first }))
expect(page.oldestCursor).toBe(first)
})
@@ -128,7 +129,7 @@ describe('a Claude cursor', () => {
const records = [claude.user('one'), twice, claude.user('two'), twice, claude.user('three')]
const file = fresh(records.join('\n') + '\n')
const before = claudePageLine(twice).cursor!
- const page = await new TranscriptPager().claude(file, { limit: 1, before })
+ const page = await pageOf(new TranscriptPager(), 'claude', file, { limit: 1, before })
expect(page.lines).toEqual([records[2]])
expect(windowRawLines(await tailFile(file, Infinity), { limit: 1, before }).window).toEqual([records[0]])
})
@@ -137,16 +138,16 @@ describe('a Claude cursor', () => {
const records = claudeScenario()
const file = fresh(records.join('\n') + '\n')
const pager = new TranscriptPager()
- const first = await pager.claude(file, { limit: 3 })
- const again = await pager.claude(file, { limit: 3, before: first.oldestCursor! })
- expect(again).toEqual(await new TranscriptPager().claude(file, { limit: 3, before: first.oldestCursor! }))
+ const first = await pageOf(pager, 'claude', file, { limit: 3 })
+ const again = await pageOf(pager, 'claude', file, { limit: 3, before: first.oldestCursor! })
+ expect(again).toEqual(await pageOf(new TranscriptPager(), 'claude', file, { limit: 3, before: first.oldestCursor! }))
// Rewritten so the byte remembered for that cursor now starts another line.
writeFileSync(file, [claude.user('a new first line, longer than before'), ...records].join('\n') + '\n')
- expect(await pager.claude(file, { limit: 3, before: first.oldestCursor! }))
- .toEqual(await new TranscriptPager().claude(file, { limit: 3, before: first.oldestCursor! }))
+ expect(await pageOf(pager, 'claude', file, { limit: 3, before: first.oldestCursor! }))
+ .toEqual(await pageOf(new TranscriptPager(), 'claude', file, { limit: 3, before: first.oldestCursor! }))
// And when the file shrank past it.
writeFileSync(file, records.slice(0, 2).join('\n') + '\n')
- expect((await pager.claude(file, { limit: 3, before: first.oldestCursor! })).staleCursor).toBe(true)
+ expect((await pageOf(pager, 'claude', file, { limit: 3, before: first.oldestCursor! })).staleCursor).toBe(true)
})
it('is matched as a whole id, and an id with characters JSON may escape is read the slow way', async () => {
@@ -155,9 +156,9 @@ describe('a Claude cursor', () => {
const file = fresh(records.join('\n') + '\n')
const lines = await tailFile(file, Infinity)
const pager = new TranscriptPager()
- expect(asOld(await pager.claude(file, { limit: 1, before: odd }))).toEqual(windowRawLines(lines, { limit: 1, before: odd }))
+ expect(asOld(await pageOf(pager, 'claude', file, { limit: 1, before: odd }))).toEqual(windowRawLines(lines, { limit: 1, before: odd }))
const prefix = claudePageLine(records[2]).cursor!.slice(0, -1)
- expect((await pager.claude(file, { limit: 1, before: prefix })).staleCursor).toBe(true)
+ expect((await pageOf(pager, 'claude', file, { limit: 1, before: prefix })).staleCursor).toBe(true)
})
it('remembers a bounded number of cursors and files', async () => {
@@ -165,9 +166,9 @@ describe('a Claude cursor', () => {
const records = Array.from({ length: 80 }, (_, i) => claude.user(`prompt ${i}`))
const file = fresh(records.join('\n') + '\n')
let before: string | undefined
- for (let i = 0; i < 70; i++) before = (await pager.claude(file, { limit: 1, before })).oldestCursor!
- for (let i = 0; i < 3; i++) await pager.claude(fresh(records.join('\n') + '\n'), { limit: 1 })
- expect(await pager.claude(file, { limit: 1, before })).toEqual(await new TranscriptPager().claude(file, { limit: 1, before }))
+ for (let i = 0; i < 70; i++) before = (await pageOf(pager, 'claude', file, { limit: 1, before })).oldestCursor!
+ for (let i = 0; i < 3; i++) await pageOf(pager, 'claude', fresh(records.join('\n') + '\n'), { limit: 1 })
+ expect(await pageOf(pager, 'claude', file, { limit: 1, before })).toEqual(await pageOf(new TranscriptPager(), 'claude', file, { limit: 1, before }))
})
})
@@ -218,7 +219,7 @@ describe('a page held to its size', () => {
let before: string | undefined
let endIndex = records.length
for (;;) {
- const page = await pager.codex(file, { limit: 4, before })
+ const page = await pageOf(pager, 'codex', file, { limit: 4, before })
seen.unshift(...page.lines)
const start = Number(page.oldestCursor!.slice('codex:'.length))
expect(start).toBeLessThan(endIndex)
@@ -383,17 +384,17 @@ describe('LineIndex', { timeout: FILE_WORK_TIMEOUT_MS }, () => {
expect(gone.count()).toBe(0)
const pager = new TranscriptPager()
expect(await pager.lineCount(dir)).toBe(0)
- expect(asOld(await pager.codex(dir, { limit: 2 }))).toEqual(windowCodexLines([], { limit: 2 }))
- expect(asOld(await pager.codex(dir, { limit: 2, before: 'codex:3' }))).toEqual(windowCodexLines([], { limit: 2, before: 'codex:3' }))
- expect(asOld(await pager.codex(dir, {}))).toEqual(windowCodexLines([], { limit: Infinity }))
+ expect(asOld(await pageOf(pager, 'codex', dir, { limit: 2 }))).toEqual(windowCodexLines([], { limit: 2 }))
+ expect(asOld(await pageOf(pager, 'codex', dir, { limit: 2, before: 'codex:3' }))).toEqual(windowCodexLines([], { limit: 2, before: 'codex:3' }))
+ expect(asOld(await pageOf(pager, 'codex', dir, {}))).toEqual(windowCodexLines([], { limit: Infinity }))
})
})
describe('the pager', () => {
it('says a page is stale when the file shrank under its walk', async () => {
const pager = new TranscriptPager({ walk: async () => false })
- expect((await pager.claude(fresh(claudeScenario().join('\n') + '\n'), { limit: 2 })).staleCursor).toBe(true)
- expect((await pager.codex(fresh(codexScenario().join('\n') + '\n'), { limit: 2 })).staleCursor).toBe(true)
+ expect((await pageOf(pager, 'claude', fresh(claudeScenario().join('\n') + '\n'), { limit: 2 })).staleCursor).toBe(true)
+ expect((await pageOf(pager, 'codex', fresh(codexScenario().join('\n') + '\n'), { limit: 2 })).staleCursor).toBe(true)
})
it('keeps a bounded number of indexes', async () => {
@@ -407,14 +408,14 @@ describe('the pager', () => {
const records = [claude.user('one'), claude.assistant([claude.text('a')], 'end_turn'), claude.user('two, still being written')]
const file = fresh(records.join('\n'))
const pager = new TranscriptPager()
- const first = await pager.claude(file, { limit: 1 })
+ const first = await pageOf(pager, 'claude', file, { limit: 1 })
expect(first.lines).toEqual([records[2]])
appendFileSync(file, '\n' + claude.user('three'))
const lines = await tailFile(file, Infinity)
- expect(asOld(await pager.claude(file, { limit: 1, before: first.oldestCursor! }))).toEqual(windowRawLines(lines, { limit: 1, before: first.oldestCursor! }))
+ expect(asOld(await pageOf(pager, 'claude', file, { limit: 1, before: first.oldestCursor! }))).toEqual(windowRawLines(lines, { limit: 1, before: first.oldestCursor! }))
const unended = fresh(records.join('\n'))
- const page = await pager.claude(unended, { limit: 1 })
- expect(asOld(await pager.claude(unended, { limit: 1, before: page.oldestCursor! })))
+ const page = await pageOf(pager, 'claude', unended, { limit: 1 })
+ expect(asOld(await pageOf(pager, 'claude', unended, { limit: 1, before: page.oldestCursor! })))
.toEqual(windowRawLines(await tailFile(unended, Infinity), { limit: 1, before: page.oldestCursor! }))
})
})
diff --git a/cli/src/lib/transcriptPages.ts b/cli/src/lib/transcriptPages.ts
index 16757a6dd..455e8152e 100644
--- a/cli/src/lib/transcriptPages.ts
+++ b/cli/src/lib/transcriptPages.ts
@@ -7,16 +7,18 @@
*
* Lines are `tailFile(path, Infinity)`'s, the reader every page came from: LF, CR and CRLF end a line,
* a line that is only whitespace is no line, and a last line with no ending yet is one. Pages are the
- * windows `windowRawLines` and `windowCodexLines` cut from those lines, with the same cursors, except:
+ * windows an engine's whole-file windower cuts from those lines (Claude Code's `windowRawLines`, Codex's
+ * `windowCodexLines`), with the same cursors, except:
* - a page holds at most `PAGE_MAX_BYTES` (see `pageBefore`), and a line longer than that is counted
* but left out — the old window held whatever its turn did, a whole file at worst;
- * - a Claude cursor names the newest line with that id, where the old window took the oldest. Ids are
+ * - a cursor a record names is the newest line with that id, where the old window took the oldest. Ids are
* unique in practice, and finding the oldest would mean reading back to the start every time.
+ *
+ * The rules are the engine's, handed in by its reader (`ThreadPages`): this file knows no engine, so the pager
+ * the core keeps for line counts loads none of their code.
*/
import { open, stat } from 'node:fs/promises'
import { StringDecoder } from 'node:string_decoder'
-import { codexPageStart, windowCodexLines } from '../engines/codex/normalizer.js'
-import { claudePageLine } from './normalize.js'
import { scanRecordsBackward, streamRecords } from './transcriptTail.js'
/** The most a page holds. A page used to be however long its turn was, and a turn can be gigabytes. */
@@ -240,6 +242,15 @@ export interface PageRules {
startsPage(line: string): boolean
}
+/**
+ * How an engine's thread is paged, as its reader declares it. `record`: a cursor is the id a line's record
+ * carries (`line` says which, and whether a page may start there), the page before names the newest line with
+ * that id. `line`: a cursor is `<prefix>:<n>`, the number of lines before it, kept in an index as the file grows.
+ */
+export type ThreadPages =
+ | { cursor: 'record'; line(line: string): { cursor: string | null; startsPage: boolean } }
+ | { cursor: 'line'; prefix: string; startsPage(line: string): boolean }
+
export interface Page {
/** Oldest first. */
lines: string[]
@@ -354,44 +365,48 @@ export class TranscriptPager {
try { return (await this.index(filePath)).count() } catch { return 0 }
}
- /** `windowRawLines` over the whole file, without it. No `limit` asks for every line, as far as fits. */
- async claude(filePath: string, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
+ /** The page of a thread before `opts.before` (else its end), as `rules` page it: the engine's whole-file window,
+ * without the whole file. No `limit` asks for every line, as far as fits. */
+ page(filePath: string, rules: ThreadPages, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
+ return rules.cursor === 'record' ? this.byRecord(filePath, rules, opts) : this.byLine(filePath, rules, opts)
+ }
+
+ private async byRecord(filePath: string, rules: Extract<ThreadPages, { cursor: 'record' }>, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
let end = await length(filePath)
if (opts.before !== undefined) {
- const at = await this.findClaude(filePath, end, opts.before)
+ const at = await this.findRecord(filePath, end, opts.before, rules)
if (at === null) return STALE
end = at
}
- const page = await pageBefore(filePath, end, opts.limit ?? Infinity, { startsPage: (line) => claudePageLine(line).startsPage }, this.maxBytes, this.options.walk)
+ const page = await pageBefore(filePath, end, opts.limit ?? Infinity, { startsPage: (line) => rules.line(line).startsPage }, this.maxBytes, this.options.walk)
if (!page) return STALE
// An empty window before a cursor still names that cursor's line, as the old one did.
- const oldestCursor = page.lines.length ? claudePageLine(page.lines[0]).cursor : opts.before ?? null
+ const oldestCursor = page.lines.length ? rules.line(page.lines[0]).cursor : opts.before ?? null
if (page.lines.length && oldestCursor !== null) this.remember(filePath, oldestCursor, page.start)
return { lines: page.lines, hasMore: page.hasMore, oldestCursor, clipped: page.clipped }
}
- /** `windowCodexLines` over the whole file, without it. No `limit` asks for every line, as far as fits.
- * A file that cannot be read is an empty one, as it was to the whole-file reader. */
- async codex(filePath: string, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
- try { return await this.codexPage(filePath, opts) } catch {
- const old = windowCodexLines([], { limit: opts.limit ?? Infinity, before: opts.before })
- return old.staleCursor ? STALE : { lines: [], hasMore: false, oldestCursor: old.oldestCursor, clipped: false }
+ /** A file that cannot be read is an empty one, as it was to the whole-file reader: its only cursor is the
+ * start, `<prefix>:0`, and any other is stale. */
+ private async byLine(filePath: string, rules: Extract<ThreadPages, { cursor: 'line' }>, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
+ try { return await this.linePage(filePath, rules, opts) } catch {
+ const at = opts.before === undefined ? 0 : lineCursor(rules.prefix, opts.before)
+ return at === 0 ? { lines: [], hasMore: false, oldestCursor: `${rules.prefix}:0`, clipped: false } : STALE
}
}
- private async codexPage(filePath: string, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
+ private async linePage(filePath: string, rules: Extract<ThreadPages, { cursor: 'line' }>, opts: { limit?: number; before?: string }): Promise<HistoryPage> {
const index = await this.index(filePath)
const count = index.count()
let endIndex = count
if (opts.before !== undefined) {
- const match = /^codex:(\d+)$/.exec(opts.before)
- if (!match) return STALE
- endIndex = Number(match[1])
- if (!Number.isSafeInteger(endIndex) || endIndex > count) return STALE
+ const at = lineCursor(rules.prefix, opts.before)
+ if (at === null || at > count) return STALE
+ endIndex = at
}
- const page = await pageBefore(filePath, await index.endOf(endIndex), opts.limit ?? Infinity, { startsPage: codexPageStart }, this.maxBytes, this.options.walk)
+ const page = await pageBefore(filePath, await index.endOf(endIndex), opts.limit ?? Infinity, { startsPage: rules.startsPage }, this.maxBytes, this.options.walk)
if (!page) return STALE
- return { lines: page.lines, hasMore: page.hasMore, oldestCursor: `codex:${endIndex - page.count}`, clipped: page.clipped }
+ return { lines: page.lines, hasMore: page.hasMore, oldestCursor: `${rules.prefix}:${endIndex - page.count}`, clipped: page.clipped }
}
private async index(filePath: string): Promise<LineIndex> {
@@ -416,8 +431,8 @@ export class TranscriptPager {
}
/** Where the newest line with this cursor starts, or null. A remembered byte is checked first. */
- private async findClaude(filePath: string, end: number, cursor: string): Promise<number | null> {
- const names = (line: string): boolean => claudePageLine(line).cursor === cursor
+ private async findRecord(filePath: string, end: number, cursor: string, rules: Extract<ThreadPages, { cursor: 'record' }>): Promise<number | null> {
+ const names = (line: string): boolean => rules.line(line).cursor === cursor
const known = this.cursors.get(filePath)?.get(cursor)
if (known !== undefined && known < end) {
let line: string | null = null
@@ -441,3 +456,11 @@ export class TranscriptPager {
async function length(filePath: string): Promise<number> {
try { return (await stat(filePath)).size } catch { return 0 }
}
+
+/** The line a `<prefix>:<n>` cursor names, or null for one that names none. */
+function lineCursor(prefix: string, cursor: string): number | null {
+ if (!cursor.startsWith(`${prefix}:`)) return null
+ const digits = cursor.slice(prefix.length + 1)
+ const at = /^\d+$/.test(digits) ? Number(digits) : NaN
+ return Number.isSafeInteger(at) && at >= 0 ? at : null
+}
diff --git a/cli/src/lib/transcriptReader.ts b/cli/src/lib/transcriptReader.ts
index c8ba41286..5eaba2cbd 100644
--- a/cli/src/lib/transcriptReader.ts
+++ b/cli/src/lib/transcriptReader.ts
@@ -8,8 +8,6 @@
* seek, not a parse.
*/
-import { open } from 'node:fs/promises'
-
import type { LiveEvent } from './normalize.js'
import { lineToEvents, newTurnState } from './normalize.js'
import { AgyNormalizer } from '../engines/agy/normalizer.js'
@@ -147,11 +145,6 @@ const SKIP_HEAD: Record<string, RegExp> = {
claude: /^\{[^]*?"type":"user"[^]*?"content":\[\{"tool_use_id"|^\{[^]*?"type":"user"[^]*?"content":\[\{"type":"tool_result"/,
}
-/** How much of a line is read before deciding whether to skip it. */
-const HEAD_BYTES = 1024
-/** A longer line is not a prompt or an answer anyone wrote; it is dropped unread. */
-const MAX_LINE_BYTES = 16 * 1024 * 1024
-const CHUNK_BYTES = 1024 * 1024
export function skipPredicate(engine: string): ((head: string) => boolean) | null {
const pattern = SKIP_HEAD[engine]
@@ -181,76 +174,4 @@ export function lineTime(line: string): number | null {
return null
}
-export interface LineVisit {
- text: string
- /** Byte offset of the line's first byte. */
- offset: number
-}
-
-/**
- * Calls `visit` for every complete line from `start`, and resolves with the offset just past the last
- * complete line. A final line without its newline is left for the next pass: the engine may still be
- * writing it. `visit` may return a promise to pace the reader.
- */
-export async function forEachLine(
- path: string,
- start: number,
- visit: (line: LineVisit) => void | Promise<void>,
- options: { skip?: ((head: string) => boolean) | null; shouldStop?: () => boolean } = {},
-): Promise<{ end: number }> {
- const handle = await open(path, 'r')
- try {
- const buffer = Buffer.allocUnsafe(CHUNK_BYTES)
- let position = start
- let lineStart = start
- let parts: Buffer[] = []
- let length = 0
- let decided = false
- let dropping = false
- for (;;) {
- if (options.shouldStop?.()) return { end: lineStart }
- const { bytesRead } = await handle.read(buffer, 0, CHUNK_BYTES, position)
- if (bytesRead === 0) return { end: lineStart }
- let cursor = 0
- while (cursor < bytesRead) {
- const newline = buffer.indexOf(10, cursor)
- const stop = newline === -1 || newline >= bytesRead ? bytesRead : newline
- if (!dropping) {
- const piece = buffer.subarray(cursor, stop)
- if (length + piece.length > MAX_LINE_BYTES) {
- dropping = true
- parts = []
- length = 0
- } else {
- parts.push(Buffer.from(piece))
- length += piece.length
- if (!decided && options.skip && (length >= HEAD_BYTES || stop < bytesRead)) {
- decided = true
- const head = Buffer.concat(parts, length).subarray(0, HEAD_BYTES).toString('utf8')
- if (options.skip(head)) {
- dropping = true
- parts = []
- length = 0
- }
- }
- }
- }
- if (stop === bytesRead) break
- // A complete line.
- if (!dropping && length > 0) {
- const text = Buffer.concat(parts, length).toString('utf8')
- await visit({ text, offset: lineStart })
- }
- lineStart = position + stop + 1
- parts = []
- length = 0
- decided = false
- dropping = false
- cursor = stop + 1
- }
- position += bytesRead
- }
- } finally {
- await handle.close()
- }
-}
+export { forEachLine, type LineVisit } from './transcriptLines.js'
diff --git a/docs/design/2026-10-08-engine-launch.md b/docs/design/2026-10-08-engine-launch.md
index 20fa44154..c6be992de 100644
--- a/docs/design/2026-10-08-engine-launch.md
+++ b/docs/design/2026-10-08-engine-launch.md
@@ -7,7 +7,7 @@ declares what it needs as data on its launch contract (`Engine.launch`, `engines
Shared mechanics in `engines/kit` read that data, and core runs them in line.
(c) is too large to land as one change. It is split into five sub-batches, each green on its own. This
-document records (c1) to (c4), which are done, and plans the last.
+document records all five, which are done.
## (c1) Launch argv and the pane script: done
@@ -356,14 +356,121 @@ from the declared files and adds a closure test:
The launch builders' closure test now admits the session stores too, since `lib/engineHomes.ts` reads them.
-## The plan for the rest of (c)
+## (c5) Adoption, activity, pages and the normalizers: done
-The sub-batches are ordered by risk: pure functions first, then async writes, then the hot and synchronous
-paths. Each one records today's behavior in a golden spec first, in its own commit. One is left.
+What core reads of Claude Code's and Codex's conversations, besides binding them: which ones are on this machine
+and which process holds one (adoption: Cmd-P, opening one here, and stopping its owner first), an agent's latest
+activity, and a thread's pages and line count. Taking a conversation over stops a process, so adoption stays in
+core, declared: a new facet, `AdoptionContract` (`engines/facets/adoption.ts`), declared in
+`engines/{claude,codex}/adoption.ts`, which reuse their session stores' layout, process record, first record and
+archive, and applied by `engines/kit/adoption.ts`. The replays stay their readers', in their workers.
-| | Scope | Why it is in this place | Golden proof |
-| --- | --- | --- | --- |
-| **(c5) Adoption readers and shared normalizers** | `lib/sessionSearch/externals/{claude,codex}.ts`, `lib/transcriptPages.ts`, `lib/transcriptReader.ts` and `lib/transcriptActivity.ts`. Also splitting the functions `engines/claude/normalize.ts` and `engines/codex/{normalizer,subagent}.ts` share with other engines into `engines/kit`. | The largest (1,000 to 2,000 lines) but async. Listing and paging sessions for adoption is not session control. Those readers may run in a worker, as long as adoption fails safe when it is down: refused with a reason, never a wrong session. | The adoption and paging specs, unchanged, plus a recorded corpus of transcripts → pages. |
+| Was | Now |
+| --- | --- |
+| `lib/sessionSearch/externals/claude.ts`: projects scanned, heads read in widening windows for the first line naming `"entrypoint"`, sub-agents and programs left out; owners from `<home>/sessions/<pid>.json`, checked against the process table and their start; busy from the record's `status` | `files` (`projects`), `head` (windows, `marked`, the sidechain flag, id, folder, origin by `entrypoint`), `owners.records` (the store's record, `startedAt` and its slack) and `busy.record`. The file is a wrapper its spec still uses; core builds the provider from the declaration (`engines/adoptions.ts`). |
+| `lib/sessionSearch/externals/codex.ts`: rollouts walked four folders down in `sessions` and `archived_sessions`, the first line read in two windows, thread names from `session_index.jsonl`; owners from the rollouts `codex` holds open, a server's an app's; busy from the last turn event near the end | `files` (`walk`: prefix, suffix, depth, the store's folders), `head` (`first`, the store's first record, origin by `source` and `originator`), `titles`, `owners.open` (commands, the id in the name, servers by executable, arguments and subcommand) and `busy.tail`. A wrapper as above. |
+| `lib/transcriptActivity.ts`: the record types each of the two counts as work, by name | `activity` on the session store: the time field, the item paths, and the kinds of record, each field compared as text (`in`) or as it is (`is`), exactly as the former code compared it. |
+| `lib/transcriptPages.ts` `claude()` and `codex()`, with Claude Code's `claudePageLine` and Codex's `codexPageStart` and `windowCodexLines` imported | `page(path, rules, ask)`: the rules are the reader's (`ThreadPages`: a record's cursor, or a `<prefix>:<n>` line cursor). Claude Code's and Codex's readers hand theirs in (`engines/{claude,codex}/transcript.ts`). An unreadable file still answers as an empty one. |
+| `engines/kit/history.ts` `enrichSubagentStats` (Claude Code's background agents' totals, with its `SubagentStats`) | `engines/claude/subagentStats.ts`, which Claude Code's reader passes to `pagedHistory`. Codex's never needed it: its cards carry their totals. |
+| `core/transcripts/{history,lastTurn}.ts`: Claude Code's replay, window and recap as the fallback for an engine with no reader | An empty page and no recap, as for an engine whose code could not load. No engine reaches it: Claude Code and Codex always have a reader (`core/engines/readers.ts`), and a shell keeps no transcript (`registry.engineKeepsTranscriptFile`). Core reads no engine's lines itself. |
+| `lib/transcriptReader.ts` `forEachLine`, which four other engines' adoption readers stream lines with | `lib/transcriptLines.ts`, which `transcriptReader.ts` re-exports for search. Search's table of every engine's normalizer stays where it was, out of core. |
+| `core/**` imports of `lib/normalize.ts` | `engines/kit/events.ts`. `lib/normalize.ts` remains for the engines that write Claude Code's message format (Devin, Command Code). |
+
+The functions Claude Code's normalizer shares with other engines are that message format, and Codex's share
+nothing. Neither moved into `engines/kit`: moving them would only have relabelled 978 lines as core's. They leave
+the core instead, with what read them.
+
+### The same answers
+
+**Golden record.** `engines/transcriptReads.golden.spec.ts` was recorded in its own commit, from the former code. It
+reads the pager through `engines/transcripts.ts` `pageOf`, the call each reader makes, and everything else through
+the public entries: the providers `externals/index.ts` builds, `transcriptActivityAt`, the readers, and core's
+`session_get`, `sessions_list` and recap reader. It holds 210 cases:
+
+- **33 for adoption.** Each provider's scan in its own and moved homes, scanned again from what the first scan kept.
+ The heads cover widening windows, a pasted image, a first line past every window, and files still being written
+ and then written. They also cover what is left out: sub-agents, programs, relative folders, bad ids, Harness's
+ own folder, links and folders that are not files, archived rollouts, and thread names. Owners cover reused pids,
+ late and early starts within and past the slack, servers by executable, arguments and subcommand, and ids in
+ file names. Busy covers each record status and each turn event near and past the windows.
+- **71 for activity.** Each counted and uncounted record of both engines, a zone-less time (local time is pinned),
+ bad times, records that are not objects, values that read as counted ones, large last records, activity past
+ the bound, missing, empty and folder paths, other engines, and a file that grew.
+- **58 pages.** A 30-turn corpus per engine, followed cursor by cursor at three page sizes. It includes a turn too
+ long for a page (clipped), lines too long for any, CR endings and blank lines. Cursors cover a prompt, a tool
+ call, the huge line, quoted, empty, leading-zero, unsafe and out-of-range cursors, a missing file and a folder,
+ and a file that grew while its pager remembered cursors.
+- **48 for history.** Both readers on the recorded fixtures and on the corpora, with Claude Code's background
+ agents' totals joined from their files. Core's `session_get` (whole, latest, older, stale), `sessions_list` and
+ last turn for each.
+
+Every case runs on darwin and on linux (no differences), and it also passes with `TZ=UTC TMPDIR=/tmp`. It passes
+unchanged against the declarations and the kit. Of 41 one-line mutations, 38 fail it:
+
+- adoption: windows, marker, sidechain flag, id shape, folder, origins, the record's start field and slack, busy,
+ prefix, depth, archive, titles, commands, the id in a name, servers, the tail's windows, marker and events;
+- activity: each list, an item path, `is` against `in`, and each kind;
+- pages: the line cursor's prefix, and the unreadable file's answer;
+- the kit: a whole file is still being written, the first line is never a whole one, and Claude Code's agents' totals.
+
+The three that pass change nothing anyone can observe:
+
+- the size of Claude Code's first head window, while the last one is unchanged;
+- dropping a window's partial last line, which never parses;
+- skipping a file where a project folder should be, which lists nothing either way.
+
+### Time
+
+Each measure is the median of six runs of each side, alternated on the same machine, over fixed inputs built
+once per run. The normalizers' code did not change; they were timed because they run per line.
+
+| | Before (the record commit) | After |
+| --- | --- | --- |
+| Claude Code's normalizer, lines a millisecond (28,000 lines) | 591 (565 – 655) | 592 (550 – 605) |
+| Codex's normalizer, lines a millisecond (28,000 lines) | 1,072 (1,043 – 1,156) | 1,075 (1,038 – 1,131) |
+| A whole Claude Code thread, 50 lines a page | 168 ms (142 – 194) | 162 ms (148 – 171) |
+| A whole Codex thread, 50 lines a page | 995 ms (918 – 1,043) | 961 ms (909 – 1,036) |
+| Activity, one uncached tail read | 0.25 ms (0.24 – 0.28) | 0.25 ms (0.23 – 0.36) |
+| Adoption scan, 1,500 Claude Code conversations | 127 ms (110 – 142) | 128 ms (106 – 144) |
+| Adoption scan, 1,500 Codex rollouts | 308 ms (282 – 339) | 326 ms (307 – 343) |
+
+Every difference is within the runs' spread.
+
+### Core closure
+
+| | Lines | Files |
+| --- | --- | --- |
+| Before (the record commit, on main with (o4)) | 70,288 | 378 |
+| After | 66,955 | 370 |
+
+**Left, 3,801 lines in all:**
+
+- Codex's normalizer, sub-agent reader and rollout wrapper (1,062);
+- `lib/transcriptReader.ts` (257), and with it the six other engines' normalizers reached only through it (2,171);
+- the two adoption providers (267);
+- `kit/history.ts` (44).
+
+**Came in, 422 lines:** the kit's adoption (248), the two declarations and their composition (86), and the line
+streamer (88). The pager grew by 23 lines and the stores by 22, and `history.ts` lost 7.
+
+Claude Code's normalizer (978) and `lib/normalize.ts` remain, reached only through Devin's adoption reader. Devin
+replays its store with Claude Code's message format. `architecture.spec.ts` now treats the two engines' normalizers,
+readers, `lib/normalize.ts` and `lib/transcriptReader.ts` as edge files. It lists Claude Code's normalizer and
+`lib/normalize.ts` in `CORE_MAY_REACH` for (o5), and drops the six normalizer entries (o5) no longer needs. A new
+closure test checks adoption, activity, the pager, the line streamer, history, the last turn, the agent frame and
+`external.ts`: they reach none of the two engines' code but their declarations. The pager, the line streamer and
+the paged history know no engine at all. Session repair's exception for Pi's reader is gone: Pi's reader streams
+lines and loads no normalizer.
+
+### For (o5)
+
+- **`lib/transcriptReader.ts` is out of the core.** The adoption readers of Pi, Copilot, Muse and Grok stream lines
+ with `lib/transcriptLines.ts`, and search keeps its table.
+- **`externals/index.ts` builds Claude Code's and Codex's providers from their declarations** (`engines/adoptions.ts`),
+ statically: those stay. The other ten are (o5)'s to load lazily.
+- **Devin's reader is the last road to Claude Code's normalizer.** Making it lazy ends the two `CORE_MAY_REACH`
+ entries, which the ratchet then asks to remove.
+- **`external.ts` is unchanged.**
**Out of (c).** These stay as they are, as tables over every engine:
diff --git a/docs/design/2026-10-08-engine-remaining-facets.md b/docs/design/2026-10-08-engine-remaining-facets.md
index 48fdd41eb..b7eb77704 100644
--- a/docs/design/2026-10-08-engine-remaining-facets.md
+++ b/docs/design/2026-10-08-engine-remaining-facets.md
@@ -119,7 +119,7 @@ About 220 lines would leave, and with them core's only native child process and
4. **(c) Launch, discovery and resume.** The largest. It has the most synchronous call sites (registry
load, discovery tables, argv). It is split by risk into (c1) launch argv and the pane script (done),
(c2) launch preparation (trust writes and the resume repair, done), (c3) discovery and process matching (done),
- (c4) registry load and session identity (done), and (c5) adoption readers and the shared normalizers
+ (c4) registry load and session identity (done), and (c5) adoption readers and the shared normalizers (done)
([engine launch](2026-10-08-engine-launch.md)). Session control stays worker-free throughout, as in (b).
This puts (d) before (b) and (c), unlike the order the owner listed. The reason: async work that is