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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: implement automated Claude session migration tracking by following continuation markers in transcript tails
0xken158125cd621980
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 92bdd17c7..4e99c1bda 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -57,7 +57,7 @@ import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'import { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'-import { findLiveSession } from './lib/sessionRepair.js'+import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { createAndRegisterPane } from './lib/createAgentPane.js'import { basename } from 'node:path'@@ -2228,23 +2228,51 @@ async function runForeground(session: AuthSession): Promise<void> {// The switch leaves exactly one trace — the `inuse.<pid>.lock` Copilot takes on the new session// directory. It writes nothing to the transcript and fires no hook until the next prompt.if (agent.sessionId) {- if (observed.engine !== 'copilot') return- const current = await copilotSessionForPid(env.COPILOT_HOME, observed.processIdentity.pid)- if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return- const transcript = await findCopilotTranscript(env.COPILOT_HOME, current)- console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)- const rotated = registry.register({- engine: 'copilot',- sessionId: current,- transcriptPath: transcript ?? undefined,- cwd: observed.cwd,- source: 'copilot-resume',- runtimes: observed.runtimes,- primaryRuntimeKey: observed.primaryRuntimeKey,- processIdentity: observed.processIdentity,- hookEvent: 'CopilotResume',- })- if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ if (observed.engine === 'copilot') {+ const current = await copilotSessionForPid(env.COPILOT_HOME, observed.processIdentity.pid)+ if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return+ const transcript = await findCopilotTranscript(env.COPILOT_HOME, current)+ console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)+ const rotated = registry.register({+ engine: 'copilot',+ sessionId: current,+ transcriptPath: transcript ?? undefined,+ cwd: observed.cwd,+ source: 'copilot-resume',+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: 'CopilotResume',+ })+ if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ return+ }+ // Claude can also change session WITHOUT any hook firing: a long conversation's transcript+ // rolls over to a new file on its own (compaction/a resume chain), and if the turn that follows+ // lands on a pooled/"spare" worker process rather than one spawned fresh in the pane, no+ // SessionStart/UserPromptSubmit ever reaches us for it — the agent is left bound to a transcript+ // that has gone quiet forever while the real conversation continues one file over. Checked on+ // the same cadence this reconciler already re-observes every live process, so it costs nothing+ // extra to ask.+ if (observed.engine === 'claude' && agent.transcriptPath) {+ const continuation = await claudeContinuation(agent.transcriptPath)+ if (!continuation || continuation.sessionId === agent.sessionId+ || registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return+ console.log(`[discovery] ${sid(agent.agentId)} claude session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)+ const rotated = registry.register({+ engine: 'claude',+ sessionId: continuation.sessionId,+ transcriptPath: continuation.transcriptPath,+ cwd: observed.cwd,+ source: 'claude-continuation',+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: 'ClaudeContinuation',+ })+ if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ return+ }return}diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex c92660a6f..c99013939 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'+import { claudeContinuation } from './sessionRepair.js'/*** Repair binds a live launcher back to a session the daemon lost track of. The danger is not failing to@@ -321,3 +322,61 @@ describe('session repair — Codex profiles', () => {}})})++describe('claudeContinuation', () => {+ it('follows a continued-in marker to the new session file', async () => {+ const dir = tempRoot()+ const oldPath = join(dir, 'old-session.jsonl')+ const newId = 'b6758945-6852-4214-8a42-2b448d8ad391'+ writeFileSync(+ oldPath,+ [+ JSON.stringify({ type: 'session', cwd: CWD, id: 'old-session' }),+ JSON.stringify({ type: 'continued-in', sessionId: 'old-session', continuedInSessionId: newId }),+ ].join('\n') + '\n',+ )+ writeFileSync(join(dir, `${newId}.jsonl`), `${JSON.stringify({ type: 'session', cwd: CWD, id: newId })}\n`)++ await expect(claudeContinuation(oldPath)).resolves.toEqual({+ sessionId: newId,+ transcriptPath: join(dir, `${newId}.jsonl`),+ })+ })++ it('returns null when the transcript has not rotated', async () => {+ const dir = tempRoot()+ const path = join(dir, 'session.jsonl')+ writeFileSync(path, `${JSON.stringify({ type: 'session', cwd: CWD, id: 'session' })}\n`)+ await expect(claudeContinuation(path)).resolves.toBeNull()+ })++ it('returns null when the continued-in target file does not exist yet', async () => {+ const dir = tempRoot()+ const oldPath = join(dir, 'old-session.jsonl')+ writeFileSync(+ oldPath,+ `${JSON.stringify({ type: 'continued-in', continuedInSessionId: 'not-written-yet' })}\n`,+ )+ await expect(claudeContinuation(oldPath)).resolves.toBeNull()+ })++ it('finds the marker even past a large tail (bounded read)', async () => {+ const dir = tempRoot()+ const oldPath = join(dir, 'old-session.jsonl')+ const newId = 'b6758945-6852-4214-8a42-2b448d8ad391'+ const filler = JSON.stringify({ type: 'assistant', text: 'x'.repeat(200) })+ const lines = Array.from({ length: 50 }, () => filler)+ lines.push(JSON.stringify({ type: 'continued-in', continuedInSessionId: newId }))+ writeFileSync(oldPath, lines.join('\n') + '\n')+ writeFileSync(join(dir, `${newId}.jsonl`), `${JSON.stringify({ type: 'session', cwd: CWD, id: newId })}\n`)++ await expect(claudeContinuation(oldPath)).resolves.toEqual({+ sessionId: newId,+ transcriptPath: join(dir, `${newId}.jsonl`),+ })+ })++ it('returns null for a missing file', async () => {+ await expect(claudeContinuation('/nonexistent/path/session.jsonl')).resolves.toBeNull()+ })+})diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 3f804983b..d69a4140d 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -15,7 +15,7 @@*/import { execFile } from 'child_process'-import { readdir, readFile, realpath, stat } from 'fs/promises'+import { open, readdir, readFile, realpath, stat } from 'fs/promises'import { basename, dirname, join, sep } from 'path'import { promisify } from 'util'import { env } from '../config/env.js'@@ -377,3 +377,59 @@ async function agySession(pid: number): Promise<RepairedSession | null> {// path anyway, so bind it and let the watcher pick the file up when it appears.return { sessionId: conversationId, transcriptPath: transcriptPath ?? undefined }}++/** The last `maxBytes` of a file, as text. Bounded so a multi-MB transcript costs nothing to check. */+async function tailBytes(path: string, maxBytes: number): Promise<string> {+ const handle = await open(path, 'r')+ try {+ const info = await handle.stat()+ const start = Math.max(0, info.size - maxBytes)+ const length = info.size - start+ if (length <= 0) return ''+ const buffer = Buffer.alloc(length)+ await handle.read(buffer, 0, length, start)+ return buffer.toString('utf-8')+ } finally {+ await handle.close()+ }+}++const CLAUDE_CONTINUATION_TAIL_BYTES = 4 * 1024++/**+ * Claude rolls a long conversation's transcript over to a NEW file on its own (compaction, a resume+ * chain) — the old file's last line names the new session and Claude simply starts writing there. No+ * fresh SessionStart/UserPromptSubmit fires for it on its own if the actual turn that follows is+ * served by a pooled/"spare" worker process rather than one spawned directly in the pane — so a+ * hook-only bind can be left pointed at a transcript that has gone permanently quiet while the real+ * conversation continues one file over. This is a cheap, bounded check for exactly that marker, read+ * from the tail since it is always the very last line and tiny.+ */+export async function claudeContinuation(transcriptPath: string): Promise<RepairedSession | null> {+ let tail: string+ try {+ tail = await tailBytes(transcriptPath, CLAUDE_CONTINUATION_TAIL_BYTES)+ } catch {+ return null+ }+ const lines = tail.split('\n').map((line) => line.trim()).filter(Boolean)+ const lastLine = lines[lines.length - 1]+ if (!lastLine) return null+ let record: Record<string, unknown>+ try {+ record = JSON.parse(lastLine) as Record<string, unknown>+ } catch {+ return null+ }+ const nextId = record.type === 'continued-in' && typeof record.continuedInSessionId === 'string'+ ? record.continuedInSessionId+ : ''+ if (!nextId) return null+ const nextPath = join(dirname(transcriptPath), `${nextId}.jsonl`)+ try {+ if (!(await stat(nextPath)).isFile()) return null+ } catch {+ return null+ }+ return { sessionId: nextId, transcriptPath: nextPath }+}