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: resolve Claude project working directories from transcripts to prevent drift
0xken15bb062c6d6794
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex efd9c278e..56b342136 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -1290,7 +1290,12 @@ async function fallbackRegister(input, engine, tmuxPane) {: transcriptPath? basename(dirname(transcriptPath)): basename(typeof input.cwd === 'string' ? input.cwd : '') || sessionId,- cwd: typeof input.cwd === 'string' ? input.cwd : (existing?.cwd ?? null),+ // The row's folder outranks the hook's for the session the row already holds: Claude reports+ // its tracked shell directory, which follows every Bash `cd`, and a resume or restore `cd`s+ // wherever this says. Same rule as `registry.register()`.+ cwd: existing && existing.sessionId === sessionId && typeof existing.cwd === 'string' && existing.cwd+ ? existing.cwd+ : typeof input.cwd === 'string' ? input.cwd : (existing?.cwd ?? null),runtimes,primaryRuntimeKey: existing?.primaryRuntimeKey && runtimes.some((runtime) => runtimeRouteKey(runtime) === existing.primaryRuntimeKey)? existing.primaryRuntimeKeydiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 06563c6c9..0bdb7ecf1 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -86,6 +86,7 @@ import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } fromimport { createAndRegisterPane } from './lib/createAgentPane.js'import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'+import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { createStopAgentService } from './lib/stopAgentService.js'import { createResumeAgentService } from './lib/resumeAgentService.js'@@ -4024,6 +4025,17 @@ async function runForeground(session: AuthSession): Promise<void> {}}+ // Rows that drifted out of their project folder while `register` still took the hook's cwd on+ // every prompt are put back BEFORE anything relaunches them: restore below `cd`s into `entry.cwd`,+ // and what it archives on the way is copied from the row. See cwdRepair.ts.+ // Best effort: an archive directory that cannot be listed, or a row that cannot be rewritten, is a+ // line in the log, never a daemon that does not come up.+ try {+ const repaired = await repairClaudeCwd({ registry, stoppedAgents, log: (message) => console.log(message) })+ if (repaired.registry || repaired.archived) console.log(`[repair] cwd · ${repaired.registry} live · ${repaired.archived} saved`)+ } catch (error) {+ console.warn(`[repair] cwd repair skipped · ${error instanceof Error ? error.message : error}`)+ }watcher.start()await cursorDiscovery.start()// Panes that died while the daemon was down (a reboot takes the whole tmux server with it) arediff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 87ec34b7a..4569b1c40 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -895,6 +895,44 @@ describe('hook notify terminal scope', () => {expect(registry[0]).not.toHaveProperty('launch')})+ it('an offline re-register of the session a row already holds keeps the row\'s folder', async () => {+ // Claude's UserPromptSubmit carries the tracked shell directory — wherever the agent last+ // `cd`'d — and a daemon-down rebuild must not move the row there any more than the daemon does.+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cwd-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-1.jsonl')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ writeFileSync(transcriptPath, '{}\n')+ const row = {+ schemaVersion: 2, active: true, agentId: 'agent-bound', sessionId: 'session-1', boundAt: 1, engine: 'claude',+ gateway: null, grid: null, codexHome: null, transcriptPath, projectDir: 'demo', cwd: '/tmp/demo',+ runtimes: [{ backend: 'tmux', paneId: '%7' }], primaryRuntimeKey: 'tmux\u0000%7', tmuxPane: '%7',+ source: null, title: null, model: null, cliVersion: null,+ processIdentity: { pid: 7001, executable: 'claude', startMarker: 'Mon Aug 10 10:00:01 2026' },+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,+ }+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([row]))++ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: 'UserPromptSubmit', session_id: 'session-1', transcript_path: transcriptPath, cwd: '/tmp/demo/cli' },+ })+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({ agentId: 'agent-bound', sessionId: 'session-1', cwd: '/tmp/demo' })++ // A rotation is a new session and takes the folder it reports.+ const rotated = join(claudeProjectsDir, 'demo', 'session-2.jsonl')+ writeFileSync(rotated, '{}\n')+ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: 'SessionStart', session_id: 'session-2', transcript_path: rotated, cwd: '/tmp/demo/cli' },+ })+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({ agentId: 'agent-bound', sessionId: 'session-2', cwd: '/tmp/demo/cli' })+ })+it('drops stale registry entries when boot marker predates this boot', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-reboot-'))tmpDirs.push(dir)diff --git a/cli/src/lib/claudeProject.spec.ts b/cli/src/lib/claudeProject.spec.tsnew file mode 100644index 000000000..9c76e4bde--- /dev/null+++ b/cli/src/lib/claudeProject.spec.ts@@ -0,0 +1,98 @@+import { describe, it, expect, afterEach } from 'vitest'+import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, realpathSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { claudeProjectMatches, claudeTranscriptCwd, isClaudeProjectTranscript, mangleClaudeProjectDir } from './claudeProject.js'++const dirs: string[] = []+const scratch = (): string => { const d = mkdtempSync(join(tmpdir(), 'claude-project-')); dirs.push(d); return d }+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })++const transcriptFor = (root: string, cwd: string, lines: Array<Record<string, unknown> | string>): string => {+ const dir = join(root, mangleClaudeProjectDir(cwd))+ mkdirSync(dir, { recursive: true })+ const path = join(dir, 'session.jsonl')+ writeFileSync(path, lines.map((l) => typeof l === 'string' ? l : JSON.stringify(l)).join('\n') + '\n')+ return path+}++describe('mangleClaudeProjectDir', () => {+ it('replaces every non-alphanumeric character with a dash, as Claude names its project dirs', () => {+ expect(mangleClaudeProjectDir('/Users/x/go/src/github.com/autonomous-ai/openharness')).toBe('-Users-x-go-src-github-com-autonomous-ai-openharness')+ expect(mangleClaudeProjectDir('/Users/x/.fleets/ws_1')).toBe('-Users-x--fleets-ws-1')+ expect(mangleClaudeProjectDir('/private/tmp/claude-502/-Users-x/probe')).toBe('-private-tmp-claude-502--Users-x-probe')+ })+})++describe('isClaudeProjectTranscript', () => {+ it('only a transcript inside a mangled project dir counts', () => {+ expect(isClaudeProjectTranscript('/home/u/.claude/projects/-home-u-repo/abc.jsonl')).toBe(true)+ expect(isClaudeProjectTranscript('/tmp/adapter-registry-XYZ/s1.jsonl')).toBe(false)+ })+})++describe('claudeProjectMatches', () => {+ it('accepts the folder itself and refuses a subfolder the shell moved into', () => {+ const t = '/home/u/.claude/projects/-home-u-repo/abc.jsonl'+ expect(claudeProjectMatches('/home/u/repo', t)).toBe(true)+ expect(claudeProjectMatches('/home/u/repo/cli', t)).toBe(false)+ expect(claudeProjectMatches('/home/u/other', t)).toBe(false)+ })+ it('accepts a path that only differs from the transcript by a symlink', () => {+ const root = scratch()+ const real = join(root, 'real'); mkdirSync(real)+ const link = join(root, 'link'); symlinkSync(real, link)+ const t = join(root, mangleClaudeProjectDir(realpathSync(real)), 'abc.jsonl')+ expect(claudeProjectMatches(link, t)).toBe(true)+ })+})++describe('claudeTranscriptCwd', () => {+ it('skips lines whose cwd drifted and returns the first one that is the project folder', () => {+ const root = scratch()+ const project = join(root, 'repo')+ const t = transcriptFor(root, project, [+ { type: 'mode', sessionId: 's' },+ 'not json at all',+ { type: 'user', cwd: join(project, 'cli') },+ { type: 'user', cwd: join(root, 'elsewhere') },+ { type: 'user', cwd: project },+ { type: 'user', cwd: join(project, 'desktop') },+ ])+ expect(claudeTranscriptCwd(t)).toBe(project)+ })+ it('is null when no line names the folder, the file is missing, or it is not a Claude project transcript', () => {+ const root = scratch()+ const project = join(root, 'repo')+ const renamed = transcriptFor(root, project, [{ type: 'user', cwd: join(root, 'old-name') }])+ expect(claudeTranscriptCwd(renamed)).toBeNull()+ expect(claudeTranscriptCwd(join(root, mangleClaudeProjectDir(project), 'missing.jsonl'))).toBeNull()+ const plain = join(root, 'plain'); mkdirSync(plain)+ const notProject = join(plain, 's.jsonl'); writeFileSync(notProject, JSON.stringify({ cwd: project }) + '\n')+ expect(claudeTranscriptCwd(notProject)).toBeNull()+ })+ it('matches a folder whose name has multi-byte characters even when a chunk boundary splits one', () => {+ const root = scratch()+ const project = join(root, 'dự-án-thử')+ // The mangled name keeps only ASCII alphanumerics, so the folder still has a project dir of its own.+ const dir = join(root, mangleClaudeProjectDir(project)); mkdirSync(dir, { recursive: true })+ const t = join(dir, 's.jsonl')+ // Pad so the cwd line starts a few bytes before the 64 KiB chunk boundary.+ const pad = JSON.stringify({ type: 'assistant', text: 'y'.repeat(64 * 1024 - 60) })+ writeFileSync(t, pad + '\n' + JSON.stringify({ type: 'user', cwd: project }) + '\n')+ expect(claudeTranscriptCwd(t)).toBe(project)+ })++ it('stops at the scan cap and handles a match on the last, unterminated line', () => {+ const root = scratch()+ const project = join(root, 'repo')+ const filler = { type: 'assistant', text: 'x'.repeat(4000) }+ const t = transcriptFor(root, project, [...Array.from({ length: 10 }, () => filler), { type: 'user', cwd: project }])+ expect(claudeTranscriptCwd(t, 8 * 1024)).toBeNull()+ expect(claudeTranscriptCwd(t)).toBe(project)+ const dir = join(root, mangleClaudeProjectDir(project))+ const tail = join(dir, 'tail.jsonl')+ writeFileSync(tail, JSON.stringify({ type: 'user', cwd: project })) // no trailing newline+ expect(claudeTranscriptCwd(tail)).toBe(project)+ })+})diff --git a/cli/src/lib/claudeProject.ts b/cli/src/lib/claudeProject.tsnew file mode 100644index 000000000..f9614a51c--- /dev/null+++ b/cli/src/lib/claudeProject.ts@@ -0,0 +1,91 @@+/**+ * Which folder a Claude Code transcript belongs to.+ *+ * Claude writes `{CLAUDE_PROJECTS_DIR}/<mangled launch dir>/<sessionId>.jsonl` (see paths.ts) and never+ * moves the file: a session resumed or forked from elsewhere still lives, and keeps writing, under the+ * folder it was first started in. The `cwd` on each transcript LINE is something else — the session's+ * tracked shell directory, which follows every Bash `cd` — so a line's cwd can name a subfolder, a+ * sibling repo or a temp dir while the file's own directory still says where the project is.+ *+ * The registry's `cwd` is where a resume, restore or restart `cd`s before exec'ing the engine, so it+ * must be the folder the transcript belongs to, not wherever the shell last went. These helpers answer+ * that from the transcript's location alone: the mangling is lossy, but exact in one direction, so a+ * cwd either round-trips to the directory name or it does not.+ */+import { closeSync, openSync, readSync, realpathSync } from 'node:fs'+import { basename, dirname } from 'node:path'+import { StringDecoder } from 'node:string_decoder'++/** Claude's project directory name for a folder: every non-alphanumeric character becomes `-`. */+export function mangleClaudeProjectDir(cwd: string): string {+ return cwd.replace(/[^A-Za-z0-9]/g, '-')+}++/** Whether the transcript sits in a Claude project directory at all. A mangled absolute path always+ * starts with `-`; a spec's temp dir or another engine's layout does not, and is never read. */+export function isClaudeProjectTranscript(transcriptPath: string): boolean {+ return basename(dirname(transcriptPath)).startsWith('-')+}++/** Whether `cwd` is the folder this transcript belongs to. Checked as given and as its real path: the+ * transcript carries `process.cwd()` (physical, `/private/tmp/…`) while a row written from a picker+ * may say `/tmp/…`. */+export function claudeProjectMatches(cwd: string, transcriptPath: string): boolean {+ const project = basename(dirname(transcriptPath))+ if (mangleClaudeProjectDir(cwd) === project) return true+ try { return mangleClaudeProjectDir(realpathSync(cwd)) === project } catch { return false }+}++/** How much of a transcript is read looking for its folder. The matching line is on the first few lines+ * of every file seen so far; the cap is for the pathological one, since this can run while an engine+ * is blocked on its startup hook. */+export const CLAUDE_TRANSCRIPT_SCAN_BYTES = 2 * 1024 * 1024++/**+ * The folder a transcript belongs to, read from the transcript: the first line whose `cwd` mangles to+ * the file's own directory name. Null when no line does within the scan cap (an old transcript whose+ * folder was renamed since), when the file cannot be read, or when it is not in a Claude project+ * directory. Exact by construction — a fork copies its source's history, and a `/clear` rotation can+ * open on a drifted line, and both still resolve to the directory the file lives in.+ */+export function claudeTranscriptCwd(transcriptPath: string, limit = CLAUDE_TRANSCRIPT_SCAN_BYTES): string | null {+ if (!isClaudeProjectTranscript(transcriptPath)) return null+ const project = basename(dirname(transcriptPath))+ let fd: number+ try { fd = openSync(transcriptPath, 'r') } catch { return null }+ try {+ const chunk = Buffer.allocUnsafe(64 * 1024)+ // A multi-byte character split across two chunks must not become U+FFFD: a cwd with one in it+ // would then fail to match on exactly the line that named the folder.+ const decoder = new StringDecoder('utf8')+ let carry = ''+ let read = 0+ while (read < limit) {+ let n: number+ try { n = readSync(fd, chunk, 0, Math.min(chunk.length, limit - read), read) } catch { return null }+ if (n <= 0) break+ read += n+ const text = carry + decoder.write(chunk.subarray(0, n))+ const lines = text.split('\n')+ carry = lines.pop() ?? ''+ for (const line of lines) {+ const cwd = lineCwd(line, project)+ if (cwd) return cwd+ }+ }+ carry += decoder.end()+ return carry ? lineCwd(carry, project) : null+ } finally {+ closeSync(fd)+ }+}++function lineCwd(line: string, project: string): string | null {+ // Cheap reject before parsing: most lines (tool results, assistant text) are large and carry a cwd+ // only as one field among many; the ones without the key never need JSON.parse.+ if (!line.includes('"cwd"')) return null+ let record: unknown+ try { record = JSON.parse(line) } catch { return null }+ const cwd = (record as { cwd?: unknown } | null)?.cwd+ return typeof cwd === 'string' && cwd && mangleClaudeProjectDir(cwd) === project ? cwd : null+}diff --git a/cli/src/lib/cwdRepair.spec.ts b/cli/src/lib/cwdRepair.spec.tsnew file mode 100644index 000000000..51a4a3765--- /dev/null+++ b/cli/src/lib/cwdRepair.spec.ts@@ -0,0 +1,106 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import type { RegisteredSession } from './registry.js'++let directory = ''+let projects = ''+beforeEach(() => {+ vi.resetModules()+ directory = mkdtempSync(join(tmpdir(), 'harness-cwd-repair-'))+ projects = join(directory, 'projects')+ vi.stubEnv('ADAPTER_DATA_DIR', directory)+ vi.stubEnv('CLAUDE_PROJECTS_DIR', projects)+})+afterEach(() => {+ vi.unstubAllEnvs()+ rmSync(directory, { recursive: true, force: true })+})++const mangle = (p: string): string => p.replace(/[^A-Za-z0-9]/g, '-')+function transcript(project: string, sessionId: string, cwds: string[]): string {+ const dir = join(projects, mangle(project))+ mkdirSync(dir, { recursive: true })+ const path = join(dir, `${sessionId}.jsonl`)+ writeFileSync(path, [JSON.stringify({ type: 'mode' }), ...cwds.map((cwd) => JSON.stringify({ type: 'user', cwd }))].join('\n') + '\n')+ return path+}++async function fixture() {+ const { registry } = await import('./registry.js')+ const { StoppedAgentStore } = await import('./stoppedAgents.js')+ const { repairClaudeCwd } = await import('./cwdRepair.js')+ const store = new StoppedAgentStore(join(directory, 'stopped-agents'))+ const project = join(directory, 'repo')+ mkdirSync(join(project, 'cli'), { recursive: true })+ const open = (id: string, pane: string, cwd: string, extra: Partial<RegisteredSession> = {}): RegisteredSession => {+ const row = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: pane }], cwd, defaultName: `Agent ${id}` })!+ Object.assign(row, extra)+ return row+ }+ const bind = (row: RegisteredSession, sessionId: string, cwds: string[], under = project): RegisteredSession => {+ const cwd = row.cwd!+ const path = transcript(under, sessionId, cwds)+ return registry.register({ sessionId, transcriptPath: path, cwd, engine: 'claude', runtimes: row.runtimes, processIdentity: { pid: 100 + Number(row.tmuxPane.slice(1)), executable: 'claude', startMarker: 'm' } })!.entry+ }+ const logs: string[] = []+ return { registry, store, repairClaudeCwd, project, open, bind, logs, log: (m: string) => { logs.push(m) } }+}++describe('repairClaudeCwd', () => {+ it('moves drifted live and archived rows to their transcript folder, leaves the rest alone, and is idempotent', async () => {+ const { registry, store, repairClaudeCwd, project, open, bind, logs, log } = await fixture()+ // Drifted: the row says the subfolder, the transcript lives under the project and names it on line 3.+ const drifted = bind(open('a', '%1', project), 'sess-a', [join(project, 'cli'), project])+ registry.setCwd(drifted.agentId, join(project, 'cli')) // what the old hook path used to do+ // Right already: a subfolder launch whose transcript lives under that subfolder.+ bind(open('b', '%2', join(project, 'cli')), 'sess-b', [join(project, 'cli')], join(project, 'cli'))+ // Renamed since: no line names the folder the transcript sits in.+ const renamed = bind(open('c', '%3', join(project, 'cli')), 'sess-c', [join(directory, 'old-name')])+ // Archived and drifted, with a name and activity time that must survive.+ const archivedRow = bind(open('d', '%4', project), 'sess-d', [join(project, 'cli'), project])+ registry.setCwd(archivedRow.agentId, join(project, 'cli'))+ store.save({ ...registry.byAgent(archivedRow.agentId)!, defaultName: 'harness Desktop' })+ registry.removeAgent(archivedRow.agentId)+ const archivedBefore = store.get(archivedRow.agentId)!+ // A transcript-less fork of the drifted row, live and archived.+ const forkLive = open('e', '%5', join(project, 'cli'), { forkedFrom: { agentId: drifted.agentId, name: 'a' } })+ const forkSaved = open('f', '%6', join(project, 'cli'), { forkedFrom: { agentId: archivedRow.agentId, name: 'd' } })+ store.save(forkSaved); registry.removeAgent(forkSaved.agentId)+ // A fork of a row that was never drifted keeps its own folder.+ const forkFine = open('g', '%7', join(project, 'cli'), { forkedFrom: { agentId: 'someone-else', name: 'x' } })++ const first = await repairClaudeCwd({ registry, stoppedAgents: store, log })+ expect(first).toEqual({ registry: 2, archived: 2 })+ expect(registry.byAgent(drifted.agentId)?.cwd).toBe(project)+ expect(registry.byAgent(forkLive.agentId)?.cwd).toBe(project)+ expect(registry.byAgent(forkFine.agentId)?.cwd).toBe(join(project, 'cli'))+ expect(registry.byAgent(renamed.agentId)?.cwd).toBe(join(project, 'cli'))+ expect(store.get(archivedRow.agentId)).toEqual({ ...archivedBefore, cwd: project })+ expect(store.get(forkSaved.agentId)?.cwd).toBe(project)+ expect(logs.filter((l) => l.includes("left as is")), logs.join("\n")).toHaveLength(1)+ expect(logs.filter((l) => l.includes('→'))).toHaveLength(4)++ logs.length = 0+ expect(await repairClaudeCwd({ registry, stoppedAgents: store, log })).toEqual({ registry: 0, archived: 0 })+ expect(logs.filter((l) => l.includes('→'))).toHaveLength(0)+ // Persisted, not just in memory.+ vi.resetModules()+ const { registry: reloaded } = await import('./registry.js')+ reloaded.load()+ expect(reloaded.byAgent(drifted.agentId)?.cwd).toBe(project)+ })++ it('does not touch rows without a transcript, of other engines, or whose transcript is gone', async () => {+ const { registry, store, repairClaudeCwd, project, open, bind, log } = await fixture()+ open('a', '%1', join(project, 'cli'))+ const codex = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%2' }], cwd: join(project, 'cli'), defaultName: 'codex' })!+ const gone = bind(open('c', '%3', project), 'sess-c', [project])+ registry.setCwd(gone.agentId, join(project, 'cli'))+ rmSync(gone.transcriptPath!)+ expect(await repairClaudeCwd({ registry, stoppedAgents: store, log })).toEqual({ registry: 0, archived: 0 })+ expect(registry.byAgent(codex.agentId)?.cwd).toBe(join(project, 'cli'))+ expect(registry.byAgent(gone.agentId)?.cwd).toBe(join(project, 'cli'))+ })+})diff --git a/cli/src/lib/cwdRepair.ts b/cli/src/lib/cwdRepair.tsnew file mode 100644index 000000000..a8c6a33b2--- /dev/null+++ b/cli/src/lib/cwdRepair.ts@@ -0,0 +1,95 @@+/**+ * Put Claude rows back in the folder their transcript belongs to.+ *+ * Until `register` stopped taking the hook's cwd on every prompt (registry.ts), a Claude row's `cwd`+ * followed the session's shell into whatever subfolder, sibling repo or temp dir the agent last+ * `cd`'d — and a resume, restore or restart then `cd`'d there too. The rows written in that time are+ * still on disk, in the live registry and in the stopped-agents archive, and a daemon that comes up on+ * the corrected code would still relaunch them in the wrong place. So it puts them right first, before+ * `restoreAgents` recreates a single pane.+ *+ * The proof is the transcript's own location (claudeProject.ts): a row whose cwd does not round-trip to+ * the project directory its transcript lives in is moved to the folder the transcript names. A row whose+ * transcript names no such folder (renamed since; a bridge file with no cwd line) is left alone and said+ * so, once per boot. Cheap and idempotent — only mismatching rows read a transcript, and a repaired row+ * matches next time — so it runs on every start rather than behind a version marker the daemon does not+ * keep.+ */+import type { RegisteredSession } from './registry.js'+import { claudeProjectMatches, claudeTranscriptCwd, isClaudeProjectTranscript } from './claudeProject.js'++export interface CwdRepairDeps {+ registry: {+ list(): RegisteredSession[]+ byAgent(agentId: string): RegisteredSession | undefined+ setCwd(agentId: string, cwd: string): boolean+ transaction<T>(apply: () => T | Promise<T>): Promise<T>+ }+ stoppedAgents: {+ list(): RegisteredSession[]+ patch(agentId: string, patch: { cwd: string }): boolean+ }+ log: (message: string) => void+}++export interface CwdRepairSummary { registry: number; archived: number }++/** The folder a row should be in, or null when the row is fine or nothing can prove otherwise. */+export function repairedCwd(row: RegisteredSession, log: (message: string) => void): string | null {+ if (row.engine !== 'claude' || !row.cwd || !row.transcriptPath || !isClaudeProjectTranscript(row.transcriptPath)) return null+ if (claudeProjectMatches(row.cwd, row.transcriptPath)) return null+ const folder = claudeTranscriptCwd(row.transcriptPath)+ if (!folder) {+ log(`[repair] ${row.agentId.slice(0, 8)} cwd ${row.cwd} is not its transcript's project folder, and the transcript names no matching folder — left as is`)+ return null+ }+ return folder === row.cwd ? null : folder+}++export async function repairClaudeCwd(deps: CwdRepairDeps): Promise<CwdRepairSummary> {+ const summary: CwdRepairSummary = { registry: 0, archived: 0 }+ // Folders proved so far, by agent: what a transcript-less fork (its history lives in the source's+ // file, not one of its own) inherits from the row it was forked from.+ const proved = new Map<string, string>()+ const forks: RegisteredSession[] = []+ const inherit = (row: RegisteredSession): string | null => {+ const source = row.forkedFrom?.agentId+ if (!source || row.transcriptPath || row.engine !== 'claude' || !row.cwd) return null+ const folder = proved.get(source)+ return folder && folder !== row.cwd ? folder : null+ }++ await deps.registry.transaction(() => {+ for (const row of deps.registry.list()) {+ const folder = repairedCwd(row, deps.log)+ if (!folder) { if (row.forkedFrom && !row.transcriptPath) forks.push(row); continue }+ const was = row.cwd // `setCwd` mutates this very object+ if (deps.registry.setCwd(row.agentId, folder)) {+ summary.registry+++ proved.set(row.agentId, folder)+ deps.log(`[repair] ${row.agentId.slice(0, 8)} cwd ${was} → ${folder} (transcript project folder)`)+ }+ }+ })+ for (const row of deps.stoppedAgents.list()) {+ const folder = repairedCwd(row, deps.log)+ if (!folder) { if (row.forkedFrom && !row.transcriptPath) forks.push(row); continue }+ if (deps.stoppedAgents.patch(row.agentId, { cwd: folder })) {+ summary.archived+++ proved.set(row.agentId, folder)+ deps.log(`[repair] ${row.agentId.slice(0, 8)} (saved) cwd ${row.cwd} → ${folder} (transcript project folder)`)+ }+ }+ // Forks last, once every source that could be proved has been: a fork only moves with its source.+ for (const row of forks) {+ const folder = inherit(row)+ if (!folder) continue+ const live = deps.registry.byAgent(row.agentId)+ const was = row.cwd+ const done = live ? deps.registry.setCwd(row.agentId, folder) : deps.stoppedAgents.patch(row.agentId, { cwd: folder })+ if (!done) continue+ if (live) summary.registry++; else summary.archived+++ deps.log(`[repair] ${row.agentId.slice(0, 8)}${live ? '' : ' (saved)'} cwd ${was} → ${folder} (forked from ${row.forkedFrom!.agentId.slice(0, 8)})`)+ }+ return summary+}diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 78c1e8802..571522a29 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -743,14 +743,56 @@ describe('agent identity: the process owns the agent, the session is bound to itexpect(registry.resolve('agent-1')?.boundAt).toBe(Date.now())})- it('a re-register of the same session is not a rotation', async () => {+ it('a re-register of the same session is not a rotation, and keeps the folder the row already has', async () => {const { registry } = await loadRegistryModule()registry.load()registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })- const again = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })+ // Claude's UserPromptSubmit carries the session's tracked SHELL directory, which follows every+ // Bash `cd`; the row's folder — what a resume or restore `cd`s into — must not follow it.+ const again = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })expect(again?.isNew).toBe(false)expect(again?.rebound).toBeNull()expect(registry.list()).toHaveLength(1)+ expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo')+ // A rotation is a new session and takes the folder it reports.+ const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })+ expect(rot?.isNew).toBe(true)+ expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')+ })++ it('a first bind whose cwd is not the transcript\'s project folder takes the folder from the transcript', async () => {+ // A fork inherits its source's drifted cwd; `claude --resume` typed from a subfolder announces+ // that subfolder. Claude never moves the transcript out of the project dir it was started in,+ // so the file's own directory says which folder is the session's.+ const { registry } = await loadRegistryModule()+ registry.load()+ const project = join(dataDir, 'repo')+ const projectDir = join(dataDir, project.replace(/[^A-Za-z0-9]/g, '-'))+ mkdirSync(projectDir, { recursive: true })+ const path = join(projectDir, 's1.jsonl')+ writeFileSync(path, [+ JSON.stringify({ type: 'mode' }),+ JSON.stringify({ type: 'user', cwd: join(project, 'cli') }),+ JSON.stringify({ type: 'user', cwd: project }),+ ].join('\n') + '\n')+ const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: path, tmuxPane: '%1', cwd: join(project, 'cli') })+ expect(bound?.isNew).toBe(true)+ expect(registry.byAgent('agent-1')?.cwd).toBe(project)+ // The folder itself, spelled as given, is accepted as is.+ const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: (() => { const p2 = join(projectDir, 's2.jsonl'); writeFileSync(p2, JSON.stringify({ cwd: project }) + '\n'); return p2 })(), tmuxPane: '%1', cwd: project })+ expect(rot?.isNew).toBe(true)+ expect(registry.byAgent('agent-1')?.cwd).toBe(project)+ })++ it('re-observing a pane follows the shell until a session is bound, then leaves the folder alone', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ registry.openProcessAgent({ agentId: 'agent-1', engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })+ registry.openProcessAgent({ engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo/cli', processIdentity: processIdentity(101) })+ expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')+ registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })+ registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo/cli', processIdentity: processIdentity(102) })+ expect(registry.byAgent('agent-2')?.cwd).toBe('/tmp/demo')})it('one engine session cannot belong to two agents', async () => {diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 7c835e5cc..058ebcb2a 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -16,6 +16,7 @@import { DSH_ID_RE } from '../dsh/manifest.js'import { AGENT_NAME_RE } from './engineLaunch.js'import { namingTitle } from './sessionTitle.js'+import { claudeProjectMatches, claudeTranscriptCwd, isClaudeProjectTranscript } from './claudeProject.js'import { automaticAgentName, engineLabel, isAutomaticName } from './agentNames.js'import {closeSync,@@ -1018,7 +1019,10 @@ class Registry {existing.runtimes = mergeTerminalRuntimes(existing.runtimes, runtimes)existing.tmuxPane = tmuxProjection(existing.runtimes)existing.primaryRuntimeKey = selectedRuntimeKey(existing.runtimes, input.primaryRuntimeKey || existing.primaryRuntimeKey)- existing.cwd = input.cwd ?? existing.cwd+ // The pane's current path follows a terminal tile around until an engine session is bound to+ // it; from then on the bind owns the folder (see `register`), and a pane re-observed in the+ // subfolder its engine `cd`'d into must not move the row there.+ if (!existing.sessionId || !existing.cwd) existing.cwd = input.cwd ?? existing.cwdexisting.processIdentity = processIdentityexisting.active = trueif (existing.launch && !existing.resumeOnly) existing.launch = { state: 'ready' }@@ -1318,10 +1322,18 @@ class Registry {// "the agent did not accept this message" and produced no recap. Its layout is deterministic, so derive// the path rather than wait to be told. A file that does not exist yet is fine — the watcher starts at// offset 0 and chokidar fires when it appears.+ // WHOSE cwd this bind takes. A re-register of the session the row already holds (every+ // UserPromptSubmit; the SessionStart a resume gets for the row it was opened into) keeps the row's:+ // Claude reports its tracked SHELL directory, which follows every Bash `cd`, and a row that took+ // it each time drifted into subfolders, sibling repos and temp dirs — then the next resume,+ // restore or restart `cd`'d there and ran the engine in the wrong project. A first bind or a+ // rotation takes the hook's — that is what gives a terminal-turned-claude row its folder at all.+ const sameSession = !!existing && existing.sessionId === sessionId+ const baseCwd = sameSession ? existing.cwd ?? input.cwd ?? null : input.cwd ?? existing?.cwd ?? nullconst derived = !transcriptPath && engine === 'commandcode'- ? commandcodeTranscriptPath(input.cwd ?? existing?.cwd, sessionId)- : !transcriptPath && engine === 'grok' && (input.cwd ?? existing?.cwd)- ? join(env.GROK_HOME, 'sessions', encodeURIComponent((input.cwd ?? existing?.cwd)!), sessionId, 'updates.jsonl')+ ? commandcodeTranscriptPath(baseCwd ?? undefined, sessionId)+ : !transcriptPath && engine === 'grok' && baseCwd+ ? join(env.GROK_HOME, 'sessions', encodeURIComponent(baseCwd), sessionId, 'updates.jsonl')// agy's layout is deterministic from the conversation id alone, and its `PreInvocation` hook can// land before the first line is flushed — derive rather than wait a turn for the path.: !transcriptPath && engine === 'agy'@@ -1332,6 +1344,15 @@ class Registry {? copilotTranscriptPath(env.COPILOT_HOME, sessionId): nullconst effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null+ // Even a first bind can carry a drifted cwd (a fork inherits its source's; `claude --resume` typed+ // from a subfolder). Claude's transcript never moves from the project dir it was started in, so a+ // cwd that does not round-trip to that directory name is not this session's folder — the row's own+ // is kept when it does, else the transcript names the folder itself (claudeProject.ts).+ const cwd = !sameSession && engine === 'claude' && effectiveTranscriptPath && input.cwd+ && isClaudeProjectTranscript(effectiveTranscriptPath) && !claudeProjectMatches(input.cwd, effectiveTranscriptPath)+ ? (existing?.cwd && claudeProjectMatches(existing.cwd, effectiveTranscriptPath) ? existing.cwd+ : claudeTranscriptCwd(effectiveTranscriptPath) ?? input.cwd)+ : baseCwdconst entry: RegisteredSession = {schemaVersion: 2,active: existing?.active ?? true,@@ -1358,11 +1379,11 @@ class Registry {defaultName: existing?.defaultName,transcriptPath: effectiveTranscriptPath,projectDir: engine === 'grok' || engine === 'agy' || engine === 'copilot'- ? basename(input.cwd ?? existing?.cwd ?? '') || sessionId+ ? basename(cwd ?? '') || sessionId: effectiveTranscriptPath? basename(dirname(effectiveTranscriptPath))- : basename(input.cwd ?? existing?.cwd ?? '') || sessionId,- cwd: input.cwd ?? existing?.cwd ?? null,+ : basename(cwd ?? '') || sessionId,+ cwd,runtimes: mergeTerminalRuntimes(existing?.runtimes ?? [], inputRuntimes),primaryRuntimeKey: '',tmuxPane: '',@@ -1645,6 +1666,17 @@ class Registry {/** Fill in the Codex profile a row did not know (discovery read it off the live process). Never* replaces one it already has — the profile is chosen once, see `codexHome`. */+ /** Put a row back in the folder its transcript belongs to (cwdRepair.ts). Any engine, any value:+ * the caller has already proved the new folder from the transcript. */+ setCwd(agentId: string, cwd: string): boolean {+ const session = this.agents.get(agentId)+ if (!session || session.cwd === cwd) return false+ session.cwd = cwd+ session.updatedAt = Date.now()+ this.save()+ return true+ }+setCodexHome(agentId: string, codexHome: string): boolean {const session = this.agents.get(agentId)if (!session || session.engine !== 'codex' || session.codexHome) return falsediff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex c4e2a28c4..654f59202 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -478,7 +478,7 @@ describe('restoreAgents — terminals', () => {})-it('retains a missing strict-resume pane for explicit Open after daemon restart', async () => {+it('retains a missing strict-resume pane whose resume was never confirmed for explicit Open', async () => {const entry = row({ resumeOnly: true, launch: { state: 'starting' } })const h = harness([entry])h.deps.retainStopped = vi.fn((saved, _paneAlive) => { h.rows.delete(saved.agentId) })@@ -489,6 +489,23 @@ it('retains a missing strict-resume pane for explicit Open after daemon restart'expect(h.respawns).toBe(0)})+it('restores a confirmed strict-resume pane by exact resume, and never falls back to fresh', async () => {+ const entry = row({ resumeOnly: true, launch: { state: 'ready' } })+ const h = harness([entry])+ h.deps.retainStopped = vi.fn()+ h.probes.set('%0', [null, null])+ h.states.set('%0', [{ dead: true }])+ const summary = await restoreAgents(h.deps)+ expect(h.deps.retainStopped).not.toHaveBeenCalled()+ expect(summary.restored).toEqual(['agent-a'])+ expect(h.paneCreates).toBe(1)+ expect(h.launches).toEqual([{ agentId: 'agent-a', resumeSessionId: 'session-a' }])+ await settled(h, 1)+ expect(h.respawns).toBe(0)+ expect(h.rows.get('agent-a')?.launch).toMatchObject({ state: 'failed', error: 'RESUME_FAILED' })+ expect(h.calls).not.toContain('unbind:session-a')+})+it('archives an engine that exited while the daemon was down without overwriting its shell', async () => {const entry = row()const h = harness([entry], { alivePanes: ['%3'] })diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex c65c881d2..30ba4d449 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -163,7 +163,15 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum}continue}- if (entry.resumeOnly && deps.retainStopped) {+ // A strict-resume row that was never CONFIRMED (its launch still `starting` when the daemon+ // died) goes back to the archive for an explicit Open: nothing proved the engine ever loaded+ // that conversation, and this pass has no way to ask. One that was confirmed — hook received,+ // engine bound, `launch: ready` — was a live agent like any other on the desk, and its tile+ // comes back the same way the others do: the exact resume below, never the fresh fallback+ // (`relaunchFresh` refuses it for a resume-only row). Measured: a harness opened from the+ // catalog, then `harness stop` + `tmux kill-server` + app relaunch — every other tile came+ // back, this one sat on "no verified terminal pane" with nothing to press.+ if (entry.resumeOnly && entry.launch?.state !== 'ready' && deps.retainStopped) {deps.retainStopped(entry, false)summary.skipped.push({ agentId: entry.agentId, reason: 'saved conversation awaits explicit Open' })continuediff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.tsindex 52d08f4c9..d360f6da3 100644--- a/cli/src/lib/stoppedAgents.spec.ts+++ b/cli/src/lib/stoppedAgents.spec.ts@@ -40,6 +40,18 @@ describe('stopped harness persistence', () => {expect(statSync(join(directory, 'stopped-agents', `${saved.agentId}.json`)).mode & 0o777).toBe(0o600)})+ it('patches one field of an archive without touching its name or activity time', async () => {+ const { saved, store } = await fixture()+ store.save({ ...saved, defaultName: 'harness Desktop' })+ const before = store.get(saved.agentId)!+ expect(store.patch(saved.agentId, { cwd: '/tmp/work-repaired' })).toBe(true)+ const after = store.get(saved.agentId)!+ expect(after).toEqual({ ...before, cwd: '/tmp/work-repaired' })+ expect(after.updatedAt).toBe(before.updatedAt)+ expect(after.defaultName).toBe('harness Desktop')+ expect(store.patch('never-saved', { cwd: '/tmp' })).toBe(false)+ })+it('hides a running identity or conversation, without discarding its archive', async () => {const { saved, store } = await fixture()store.save(saved)diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.tsindex 085dafcb4..cf20c228b 100644--- a/cli/src/lib/stoppedAgents.ts+++ b/cli/src/lib/stoppedAgents.ts@@ -73,6 +73,18 @@ export class StoppedAgentStore {atomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })}+ /** Correct one field of an archive in place — the folder a Claude row drifted out of (cwdRepair.ts).+ * Not `save`: that recomputes the name and stamps `updatedAt`, and a repair must not reorder the+ * catalog or rename anything. Nothing else on the row changes. */+ patch(agentId: string, patch: Partial<Pick<RegisteredSession, 'cwd'>>): boolean {+ const saved = this.get(agentId)+ if (!saved) return false+ secureStateDirectory(dirname(this.directory))+ secureStateDirectory(this.directory)+ atomicWriteJson(join(this.directory, `${agentId}.json`), { version: 1, session: { ...saved, ...patch } })+ return true+ }+/** Reserve before tmux allocation. A crash between allocation and registry persistence* must not permit a second process under a new request/receipt ID. */beginResume(agentId: string): string | null {diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.mdindex 676e1af23..141c00589 100644--- a/desktop/design/agent-lifecycle-map.md+++ b/desktop/design/agent-lifecycle-map.md@@ -145,7 +145,7 @@ Natural engine exit sends `agent_synced` with `status: stopped` and no terminal- `creationId` uses the existing durable receipt protocol and `agent_create_status`. A retry of the same intent returns its recorded result or uncertainty, never a new process.- A private, fsynced per-agent `.resume` reservation is written **before** history preparation and tmux allocation. It protects the gap between starting tmux and persisting a new registry row, including requests with a different receipt ID after daemon restart.- Confirmed native binding, verified completion or a confirmed stop clears the reservation. Unknown allocation/readiness keeps it; startup failure keeps history and preserves the shell/output when available.-- On daemon restart, a strict-resume row whose pane disappeared is archived for explicit Open. It never enters restore's fresh fallback. A surviving engine is re-observed, and a surviving shell is separated from the saved conversation.+- On daemon restart, a strict-resume row whose pane disappeared is restored by exact resume when its previous resume was confirmed (`launch: ready`); one still unconfirmed (`starting`) is archived for explicit Open. Neither ever enters restore's fresh fallback. A surviving engine is re-observed, and a surviving shell is separated from the saved conversation.## Scope and review limits