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.

feat: emit history events for pre-existing transcript lines and ignore replays in turn counts

0xken152461de859f58
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index f970f134b..12b97c255 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -426,7 +426,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// Hub tap (mirrors managerWs): keep `machine_agents` in sync from the adapter's agent
// lifecycle frames. Needed so the device voice path's agent-ownership check
// (deviceWs: `machineAgent.findFirst`) recognizes remote tmux sessions.
- const f = env.frame as { type?: string; agentId?: unknown; payload?: { agent?: unknown; agentId?: unknown; machineId?: unknown } }
+ const f = env.frame as { type?: string; agentId?: unknown; replay?: unknown; payload?: { agent?: unknown; agentId?: unknown; machineId?: unknown } }
if (f.type === 'agent_synced') {
void recordCreatedAgent(machineId, f.payload?.agent as { id?: unknown; name?: unknown } | undefined)
} else if (f.type === 'agent_deleted' && typeof f.payload?.agentId === 'string') {
@@ -434,14 +434,16 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// Reading `machineId` here meant no deletion was EVER recorded, so machine_agents grew a row per
// agent forever — and that table is what the plan cap counts.
void recordDeletedAgent(machineId, f.payload.agentId)
- } else if (f.type === 'turn_started') {
- // Usage signal for machine_daily_presence / agent_daily_presence. Only the plaintext `type`
- // and top-level `agentId` (set by the CLI's correlateAgentEvent) are read — the payload is
- // E2EE ciphertext (cli e2ee/core.ts ENCRYPTED_UP_TYPES) and stays opaque here. The CLI already
- // dedupes engines that re-announce one turn (cursor/agy/copilot, cli.ts), so one frame == one
- // turn; the one known over-count is a daemon restarting mid-turn, which re-emits the open
- // turn's start on attach (cli.ts `resumed`) — rare, and invisible from here. A frame with no
- // (or a malformed) agentId has nothing to attribute the turn to and is not counted.
+ } else if (f.type === 'turn_started' && f.replay !== true) {
+ // Usage signal for machine_daily_presence / agent_daily_presence. Only the plaintext `type`,
+ // top-level `agentId` and `replay` (set by the CLI's correlateAgentEvent / emitSessionEvents)
+ // are read — the payload is E2EE ciphertext (cli e2ee/core.ts ENCRYPTED_UP_TYPES) and stays
+ // opaque here. The CLI already dedupes engines that re-announce one turn (cursor/agy/copilot,
+ // cli.ts), so one frame == one turn. `replay: true` is the CLI saying this one did NOT start
+ // now — a turn resumed at attach, or a prompt re-read from a transcript already on disk
+ // (measured 2026-09-17: 42 such frames in one second credited to one agent). It still relays,
+ // it is just not a turn today. A frame with no (or a malformed) agentId has nothing to
+ // attribute the turn to and is not counted.
const now = new Date()
const agentId = typeof f.agentId === 'string' && TURN_AGENT_ID_RE.test(f.agentId) ? f.agentId : undefined
if (agentId && allowTurnWrite(now.getTime())) {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b6c7d3f39..9649679b7 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -117,7 +117,7 @@ import {
type TmuxRuntimeRef,
} from './lib/terminalTypes.js'
import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'
-import { Watcher, type LineEvent } from './watcher/watcher.js'
+import { Watcher, type HistoryEvent, type LineEvent } from './watcher/watcher.js'
import { chooseHookAgent, startHookServer } from './hookServer.js'
import { BackendSocket, isLocalClientId } from './backendSocket.js'
import { AutonomousDeviceService } from './lib/autonomous-device/service.js'
@@ -1618,19 +1618,37 @@ async function runForeground(session: AuthSession): Promise<void> {
const hermesReaders = new Map<string, HermesReader>()
const devinReaders = new Map<string, DevinReader>()
const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()
+ /** Whether this session's engine state says a turn is open right now, whichever engine it is. */
+ const sessionTurnOpen = (sessionId: string): boolean =>
+ turnStates.get(sessionId)?.turnOpen
+ ?? codexNormalizers.get(sessionId)?.turnOpen
+ ?? cursorNormalizers.get(sessionId)?.turnOpen
+ ?? opencodeReaders.get(sessionId)?.turnOpen
+ ?? kiloReaders.get(sessionId)?.turnOpen
+ ?? piNormalizers.get(sessionId)?.turnOpen
+ ?? museNormalizers.get(sessionId)?.turnOpen
+ ?? ampNormalizers.get(sessionId)?.turnOpen
+ ?? grokNormalizers.get(sessionId)?.turnOpen
+ ?? agyNormalizers.get(sessionId)?.turnOpen
+ ?? copilotNormalizers.get(sessionId)?.turnOpen
+ ?? hermesReaders.get(sessionId)?.turnOpen
+ ?? devinReaders.get(sessionId)?.turnOpen
+ ?? commandcodeNormalizers.get(sessionId)?.turnOpen
+ ?? false
const watcher = new Watcher()
const queuedSessionEvents: Array<{
sessionId: string
events: ReturnType<CursorNormalizer['ingest']>
+ opts?: { resumed?: boolean; replay?: boolean }
}> = []
// Hook registration can race the rest of daemon initialization immediately after the localhost
// server binds. Queue those first records until input/mirror/heartbeat dependencies are ready.
let emitSessionEvents = (
sessionId: string,
events: ReturnType<CursorNormalizer['ingest']>,
- _opts?: { resumed?: boolean },
+ opts?: { resumed?: boolean; replay?: boolean },
): void => {
- if (events.length) queuedSessionEvents.push({ sessionId, events })
+ if (events.length) queuedSessionEvents.push({ sessionId, events, opts })
}
/**
* A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure
@@ -2258,21 +2276,7 @@ async function runForeground(session: AuthSession): Promise<void> {
stopHeartbeat(sessionId) // restart → guarantee a single timer per session
const timer = setInterval(() => {
if (!registry.has(sessionId)) { stopHeartbeat(sessionId); return }
- const turnOpen =
- turnStates.get(sessionId)?.turnOpen
- ?? codexNormalizers.get(sessionId)?.turnOpen
- ?? cursorNormalizers.get(sessionId)?.turnOpen
- ?? opencodeReaders.get(sessionId)?.turnOpen
- ?? kiloReaders.get(sessionId)?.turnOpen
- ?? piNormalizers.get(sessionId)?.turnOpen
- ?? museNormalizers.get(sessionId)?.turnOpen
- ?? ampNormalizers.get(sessionId)?.turnOpen
- ?? grokNormalizers.get(sessionId)?.turnOpen
- ?? agyNormalizers.get(sessionId)?.turnOpen
- ?? copilotNormalizers.get(sessionId)?.turnOpen
- ?? hermesReaders.get(sessionId)?.turnOpen
- ?? devinReaders.get(sessionId)?.turnOpen
- ?? commandcodeNormalizers.get(sessionId)?.turnOpen
+ const turnOpen = sessionTurnOpen(sessionId)
// A TURN THAT IS OPEN GETS ITS TRANSCRIPT RE-READ, every beat.
//
// The engines whose turn ends in a FILE — codex writes `task_complete`,
@@ -2301,11 +2305,18 @@ async function runForeground(session: AuthSession): Promise<void> {
heartbeats.set(sessionId, timer)
}
- emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>, opts?: { resumed?: boolean }): void => {
+ emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>, opts?: { resumed?: boolean; replay?: boolean }): void => {
if (!events.length || !registry.bySession(sessionId)?.active) return
for (const event of events) {
const agentId = agentIdFor(sessionId)
- backend.send(correlateAgentEvent(event, sessionId, agentId))
+ const frame = correlateAgentEvent(event, sessionId, agentId)
+ // A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt
+ // re-read from a transcript that was already on disk — says so in the clear, beside `agentId`
+ // (the payload is E2EE; the backend can only read the envelope). The backend's daily turn count
+ // skips these; every other consumer ignores an unknown field. Measured before this existed: one
+ // agent credited with 42 turns in a single second, all re-reads.
+ if (event.type === 'turn_started' && (opts?.resumed || opts?.replay)) frame.replay = true
+ backend.send(frame)
if (event.type === 'turn_started') {
turnStartedAt.set(sessionId, Date.now())
console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)
@@ -2340,7 +2351,7 @@ async function runForeground(session: AuthSession): Promise<void> {
}
mirror.ingest(events, sessionId)
}
- for (const queued of queuedSessionEvents.splice(0)) emitSessionEvents(queued.sessionId, queued.events)
+ for (const queued of queuedSessionEvents.splice(0)) emitSessionEvents(queued.sessionId, queued.events, queued.opts)
const cursorSubagents = new CursorSubagentManager(env.CURSOR_HOME, emitSessionEvents)
const cursorTaskHooks = new CursorTaskHookQueue({
drainTranscript: (sessionId) => watcher.pollSession(sessionId),
@@ -3495,76 +3506,113 @@ async function runForeground(session: AuthSession): Promise<void> {
// JSONL watcher → normalize each appended line → stream up. ONE lineToEvents pass feeds BOTH
// audiences: web (send, ServerEvents) and device (mirror.ingest → curated commander_event cards).
+ /** One transcript line through its engine's normalizer. The events, not yet emitted — the two
+ * callers below differ only in what they know about the line's age. */
+ const ingestLine = (evt: LineEvent): ReturnType<CursorNormalizer['ingest']> | null => {
+ if (!registry.has(evt.sessionId)) return null // scope to terminal-registered sessions
+ const session = registry.bySession(evt.sessionId)
+ if (!session || session.engine !== evt.engine) return null
+ runtimeProfiles.ingest(session, evt.text)
+ let events
+ if (session.engine === 'codex') {
+ let normalizer = codexNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and
+ // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the
+ // turn_ended that `events` carries.
+ const taskError = codexTaskError(evt.text)
+ if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)
+ } else if (session.engine === 'cursor') {
+ let normalizer = cursorNormalizers.get(evt.sessionId)
+ if (!normalizer) {
+ normalizer = new CursorNormalizer('live', evt.sessionId)
+ cursorNormalizers.set(evt.sessionId, normalizer)
+ }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'muse') {
+ let normalizer = museNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new MuseNormalizer(); museNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'amp') {
+ let normalizer = ampNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'grok') {
+ let normalizer = grokNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'agy') {
+ let normalizer = agyNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new AgyNormalizer(); agyNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'copilot') {
+ let normalizer = copilotNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CopilotNormalizer(); copilotNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'pi') {
+ let normalizer = piNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'commandcode') {
+ let normalizer = commandcodeNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CommandCodeNormalizer('live'); commandcodeNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Command Code fires no Stop hook for a failed turn: this record IS the notification. `ingest`
+ // already closed the turn (its turn_ended is in `events`, emitted just below) — announce the
+ // reason first so the web/device show the error ahead of the turn closing.
+ const runError = commandCodeRunError(evt.text)
+ if (runError !== null) {
+ announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))
+ }
+ } else {
+ let st = turnStates.get(evt.sessionId)
+ if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }
+ events = lineToEvents(evt.text, st)
+ }
+ return events
+ return events
+ }
watcher.on('line', (evt: LineEvent) => {
// This runs from a void-discarded async read, so a throw here would be an unhandledRejection. A
// single malformed line must never take the daemon down — contain it per line and move on.
try {
- if (!registry.has(evt.sessionId)) return // scope to terminal-registered sessions
- const session = registry.bySession(evt.sessionId)
- if (!session || session.engine !== evt.engine) return
- runtimeProfiles.ingest(session, evt.text)
- let events
- if (session.engine === 'codex') {
- let normalizer = codexNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and
- // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the
- // turn_ended that `events` carries.
- const taskError = codexTaskError(evt.text)
- if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)
- } else if (session.engine === 'cursor') {
- let normalizer = cursorNormalizers.get(evt.sessionId)
- if (!normalizer) {
- normalizer = new CursorNormalizer('live', evt.sessionId)
- cursorNormalizers.set(evt.sessionId, normalizer)
- }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'muse') {
- let normalizer = museNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new MuseNormalizer(); museNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'amp') {
- let normalizer = ampNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'grok') {
- let normalizer = grokNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'agy') {
- let normalizer = agyNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new AgyNormalizer(); agyNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'copilot') {
- let normalizer = copilotNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CopilotNormalizer(); copilotNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'pi') {
- let normalizer = piNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'commandcode') {
- let normalizer = commandcodeNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CommandCodeNormalizer('live'); commandcodeNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- // Command Code fires no Stop hook for a failed turn: this record IS the notification. `ingest`
- // already closed the turn (its turn_ended is in `events`, emitted just below) — announce the
- // reason first so the web/device show the error ahead of the turn closing.
- const runError = commandCodeRunError(evt.text)
- if (runError !== null) {
- announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))
- }
- } else {
- let st = turnStates.get(evt.sessionId)
- if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }
- events = lineToEvents(evt.text, st)
- }
- emitSessionEvents(evt.sessionId, events)
+ const events = ingestLine(evt)
+ if (events) emitSessionEvents(evt.sessionId, events)
} catch (err) {
console.error(`[cli] line handler error (session ${evt.sessionId}):`, err instanceof Error ? err.message : err)
}
})
+ // Lines that were on disk before the tail began (watcher.ts `HistoryEvent`). They still stream — the
+ // clients render them the way they always have — but every `turn_started` among them is a prompt
+ // already answered, except the last one if the batch ends inside a turn: that turn is running now,
+ // and it is the one an `unseen` re-attach exists to catch (its first prompt landed before the path
+ // was known). Everything else is marked `replay` so the backend does not count it as a turn today.
+ watcher.on('history', (batch: HistoryEvent) => {
+ try {
+ type Events = ReturnType<CursorNormalizer['ingest']>
+ const all: Events = []
+ for (const evt of batch.lines) {
+ const events = ingestLine(evt)
+ if (events) all.push(...events)
+ }
+ if (!all.length) return
+ const liveTail = sessionTurnOpen(batch.sessionId)
+ ? all.map((e) => e.type).lastIndexOf('turn_started')
+ : -1
+ const starts = all.filter((e, i) => e.type === 'turn_started' && i !== liveTail).length
+ if (starts) console.log(`[watcher] ${sid(batch.sessionId)} re-read ${batch.lines.length} lines already on disk · ${starts} past turn_started marked replay${liveTail >= 0 ? ' · last turn still open, kept live' : ''}`)
+ // Order is preserved: the live tail (if any) is emitted in place, between what surrounds it.
+ if (liveTail < 0) { emitSessionEvents(batch.sessionId, all, { replay: true }); return }
+ const before = all.slice(0, liveTail)
+ const after = all.slice(liveTail + 1)
+ if (before.length) emitSessionEvents(batch.sessionId, before, { replay: true })
+ emitSessionEvents(batch.sessionId, [all[liveTail]])
+ if (after.length) emitSessionEvents(batch.sessionId, after, { replay: true })
+ } catch (err) {
+ console.error(`[cli] history handler error (session ${batch.sessionId}):`, err instanceof Error ? err.message : err)
+ }
+ })
for (const session of registry.list()) {
// An UNBOUND process agent has no transcript to attach to yet. Discovery keeps it visible and the
// hook/store repair path binds it as soon as the engine reports a session. Attaching an
@@ -3573,24 +3621,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!session.active || !session.sessionId) continue
if (!await attachSession(session)) registry.setActive(session.agentId, false)
else {
- input.setTurnOpen(
- session.agentId,
- turnStates.get(session.sessionId)?.turnOpen
- ?? codexNormalizers.get(session.sessionId)?.turnOpen
- ?? cursorNormalizers.get(session.sessionId)?.turnOpen
- ?? opencodeReaders.get(session.sessionId)?.turnOpen
- ?? kiloReaders.get(session.sessionId)?.turnOpen
- ?? piNormalizers.get(session.sessionId)?.turnOpen
- ?? museNormalizers.get(session.sessionId)?.turnOpen
- ?? ampNormalizers.get(session.sessionId)?.turnOpen
- ?? grokNormalizers.get(session.sessionId)?.turnOpen
- ?? agyNormalizers.get(session.sessionId)?.turnOpen
- ?? copilotNormalizers.get(session.sessionId)?.turnOpen
- ?? hermesReaders.get(session.sessionId)?.turnOpen
- ?? devinReaders.get(session.sessionId)?.turnOpen
- ?? commandcodeNormalizers.get(session.sessionId)?.turnOpen
- ?? false,
- )
+ input.setTurnOpen(session.agentId, sessionTurnOpen(session.sessionId))
}
}
/**
diff --git a/cli/src/watcher/watcher.spec.ts b/cli/src/watcher/watcher.spec.ts
index e82ebc961..21834499c 100644
--- a/cli/src/watcher/watcher.spec.ts
+++ b/cli/src/watcher/watcher.spec.ts
@@ -2,7 +2,7 @@ import { appendFile, mkdtemp, rm, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
-import { Watcher, type LineEvent } from './watcher.js'
+import { Watcher, type HistoryEvent, type LineEvent } from './watcher.js'
const cleanup: string[] = []
@@ -81,12 +81,75 @@ describe('Watcher.pollAll', () => {
await writeFile(transcriptPath, '{"a":1}\n{"a":2}\n{"a":3}\n')
const watcher = new Watcher()
const lines: string[] = []
+ const history: string[][] = []
watcher.on('line', (event: LineEvent) => lines.push(event.text))
+ watcher.on('history', (batch: HistoryEvent) => history.push(batch.lines.map((l) => l.text)))
await watcher.addSession({ sessionId: 'p1', engine: 'pi', transcriptPath }, { fromStart: true })
await watcher.pollSession('p1')
- expect(lines).toEqual(['{"a":1}', '{"a":2}', '{"a":3}'])
+ // Everything that was on disk when the tail was placed arrives as ONE history batch, so the
+ // consumer can tell a prompt already answered from the one turn that may still be running; what
+ // is appended afterwards is live, line by line.
+ expect(history).toEqual([['{"a":1}', '{"a":2}', '{"a":3}']])
+ expect(lines).toEqual([])
+ await appendFile(transcriptPath, '{"a":4}\n')
+ await watcher.pollSession('p1')
+ expect(lines).toEqual(['{"a":4}'])
+ expect(history).toHaveLength(1)
+ await watcher.stop()
+ })
+
+ it('reads a file that shrank under it as history, not as a conversation happening now', async () => {
+ // The untrusted-producer version of the repair case below: a transcript rewritten in place by
+ // something that never called setTail. The old behaviour re-emitted the whole file as live — on
+ // prod that was one agent credited with 42 turns in a single second.
+ const dir = await mkdtemp(join(tmpdir(), 'machine-shrink-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"t":1}\n{"t":2}\n{"t":3}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ const history: string[][] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+ watcher.on('history', (batch: HistoryEvent) => history.push(batch.lines.map((l) => l.text)))
+
+ await watcher.addSession({ sessionId: 'x1', engine: 'pi', transcriptPath })
+ await watcher.pollSession('x1')
+ expect(lines).toEqual([])
+
+ await writeFile(transcriptPath, '{"t":1}\n{"t":2}\n') // shorter than the tail's cursor
+ await watcher.pollSession('x1')
+ expect(history).toEqual([['{"t":1}', '{"t":2}']])
+ expect(lines).toEqual([])
+
+ await appendFile(transcriptPath, '{"t":4}\n')
+ await watcher.pollSession('x1')
+ expect(lines).toEqual(['{"t":4}'])
+ expect(history).toHaveLength(1)
+ await watcher.stop()
+ })
+
+ it('splits one chunk into its historical prefix and its live rest', async () => {
+ // A `fromStart` tail placed on a file that grows before the first read: the bytes below the
+ // cursor's placement are history, the bytes appended since are not, and they arrive in the
+ // same read. The split is by byte position, so a multi-byte line cannot shift it.
+ const dir = await mkdtemp(join(tmpdir(), 'machine-split-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"h":"xin chào"}\n{"h":2}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ const history: string[][] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+ watcher.on('history', (batch: HistoryEvent) => history.push(batch.lines.map((l) => l.text)))
+
+ await watcher.addSession({ sessionId: 's1', engine: 'pi', transcriptPath }, { fromStart: true })
+ await appendFile(transcriptPath, '{"live":3}\n')
+ await watcher.pollSession('s1')
+
+ expect(history).toEqual([['{"h":"xin chào"}', '{"h":2}']])
+ expect(lines).toEqual(['{"live":3}'])
await watcher.stop()
})
diff --git a/cli/src/watcher/watcher.ts b/cli/src/watcher/watcher.ts
index 47bdd1c15..6b913260d 100644
--- a/cli/src/watcher/watcher.ts
+++ b/cli/src/watcher/watcher.ts
@@ -22,8 +22,24 @@ export interface LineEvent {
ts: number
}
+/**
+ * Lines that were ALREADY ON DISK when this tail started reading them — a `fromStart` attach of a file
+ * with content, or a re-read after the file shrank under us. They are emitted as one batch, on
+ * `'history'` rather than `'line'`, because the consumer has to know where the batch ENDS: everything in
+ * it is the past except a turn still open at its last line, and only the whole batch can say which.
+ * Measured on prod (2026-09-17): one agent's 42 turns landed in the same second, all of them re-reads of
+ * prompts already answered — counted as 42 turns started that day.
+ */
+export interface HistoryEvent {
+ sessionId: string
+ engine: AgentEngine
+ lines: LineEvent[]
+}
+
interface FileState extends WatchedSession {
offset: number
+ /** Bytes below this were on disk before the current read cursor was placed — history, not live. */
+ historicalUntil: number
partial: string
seq: number
debounce: NodeJS.Timeout | null
@@ -60,8 +76,10 @@ export class Watcher extends EventEmitter {
let offset = 0
let cursorLines: string[] = []
+ let size = 0
+ try { size = (await stat(session.transcriptPath)).size } catch { size = 0 }
if (!opts.fromStart) {
- try { offset = (await stat(session.transcriptPath)).size } catch { offset = 0 }
+ offset = size
if (session.engine === 'cursor') {
try { cursorLines = completeLines(await readFile(session.transcriptPath, 'utf8')) } catch { cursorLines = [] }
}
@@ -79,6 +97,8 @@ export class Watcher extends EventEmitter {
this.files.set(session.transcriptPath, {
...session,
offset,
+ // A `fromStart` tail of a file that already has content reads that content as history.
+ historicalUntil: opts.fromStart ? size : 0,
partial: '',
seq: 0,
debounce: null,
@@ -187,8 +207,11 @@ export class Watcher extends EventEmitter {
let size: number
try { size = (await stat(filePath)).size } catch { return }
if (size < state.offset) {
+ // The file shrank: rewritten in place (or recreated). Whatever it holds now is read from byte 0,
+ // and none of it is new to the world — it is history until the write that grows it past this.
state.offset = 0
state.partial = ''
+ state.historicalUntil = size
}
if (size <= state.offset) return
@@ -209,21 +232,36 @@ export class Watcher extends EventEmitter {
return
}
+ // Byte position of each line, to tell the historical prefix of this chunk from the live rest: a
+ // file appended to between the cursor being placed and this read has both in the same chunk. The
+ // carried partial line began that many bytes before `start`.
+ let pos = start - Buffer.byteLength(state.partial, 'utf8')
const combined = state.partial + chunk
const lines = combined.split('\n')
state.partial = combined.endsWith('\n') ? '' : (lines.pop() ?? '')
+ const history: LineEvent[] = []
for (const raw of lines) {
+ const linePos = pos
+ pos += Buffer.byteLength(raw, 'utf8') + 1
const text = raw.replace(/\r$/, '')
if (!text.trim()) continue
- this.emit('line', {
+ const evt: LineEvent = {
sessionId: state.sessionId,
engine: state.engine,
projectDir: basename(dirname(filePath)),
text,
seq: state.seq++,
ts: Date.now(),
- } satisfies LineEvent)
+ }
+ if (linePos < state.historicalUntil) { history.push(evt); continue }
+ if (history.length) this.flushHistory(state, history)
+ this.emit('line', evt)
}
+ if (history.length) this.flushHistory(state, history)
+ }
+
+ private flushHistory(state: FileState, lines: LineEvent[]): void {
+ this.emit('history', { sessionId: state.sessionId, engine: state.engine, lines: lines.splice(0) } satisfies HistoryEvent)
}
private async readCursor(filePath: string, state: FileState): Promise<void> {
@@ -234,6 +272,7 @@ export class Watcher extends EventEmitter {
state.cursorLines = next
state.offset = 0
state.partial = ''
+ state.historicalUntil = 0
for (const text of next.slice(common)) {
if (!text.trim()) continue
this.emit('line', {