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.

Keep Muse and Pi repair independent of optional readers (#1106)

Dee2477d7e1d8f7
diff --git a/cli/e2e/eagerRepair.e2e.ts b/cli/e2e/eagerRepair.e2e.ts
new file mode 100644
index 000000000..0dd9b1e9b
--- /dev/null
+++ b/cli/e2e/eagerRepair.e2e.ts
@@ -0,0 +1,97 @@
+/** Native Muse discovery and Pi Close/resume with optional interpretation absent or stalled. */
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'
+import { readLeanBundle } from '../src/harnessd/leanBundle.js'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { withLean } from './harness/release.js'
+
+let scratch = '', bundle = ''
+let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+beforeAll(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'eager-repair-'))
+ bundle = join(scratch, 'build', 'cli.js')
+ execFileSync(process.execPath, ['build-bundle.mjs'], { cwd: CLI_ROOT,
+ env: { ...process.env, BUNDLE_OUT_DIR: dirname(bundle) }, stdio: 'pipe' })
+}, 120_000)
+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })
+
+it.each(['missing', 'stalled'] as const)('discovers Muse and closes/resumes Pi with %s optional readers', async mode => {
+ const lean = readLeanBundle(readFileSync(bundle))!
+ const files = Object.fromEntries([...lean.files].map(([name, value]) => [name, value.toString('utf8')]))
+ for (const marker of ['MuseNormalizer', 'PiNormalizer']) {
+ const chunks = Object.keys(files).filter(name => name.startsWith('core-inProcess-') && files[name]!.includes(marker))
+ expect(chunks, marker).toHaveLength(1)
+ if (mode === 'missing') delete files[chunks[0]!]
+ else files[chunks[0]!] = `console.error('[fixture] ${marker} stalled'); await new Promise(() => {});\n`
+ }
+ const script = join(scratch, mode, 'cli.js'); mkdirSync(dirname(script), { recursive: true })
+ writeFileSync(script, withLean(readFileSync(bundle, 'utf8'), files), { mode: 0o755 })
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: script, env: { HARNESS_CONNECTIONS_PORT: '0' } })
+ onTestFailed(() => console.log(d.log()))
+ d.env.MUSE_HOME = join(d.root, 'muse'); d.env.PI_HOME = join(d.root, 'pi')
+ const museId = 'aaaaaaaa-1111-4222-8333-444444444444'
+ const piIds = { unwritten: 'bbbbbbbb-1111-4222-8333-444444444444', written: 'cccccccc-1111-4222-8333-444444444444' }
+ for (const engine of ['muse', 'pi'] as const) {
+ const path = join(d.root, 'bin', engine); d.env[`${engine.toUpperCase()}_PATH`] = path
+ writeFileSync(path, `#!${process.execPath}
+const fs = require('node:fs'), path = require('node:path');
+if (process.argv.includes('--version') || process.argv.includes('--help')) { console.log('1.0.0'); process.exit(0) }
+const id = process.argv.includes('--session') ? process.argv[process.argv.indexOf('--session') + 1] : (${JSON.stringify(piIds)})[path.basename(process.cwd())];
+process.title = (${JSON.stringify(engine)} === 'pi' ? 'pi --session-id ' + id : 'muse').padEnd(160);
+fs.appendFileSync(${JSON.stringify(join(d.root, `${engine}-launches.jsonl`))}, JSON.stringify({ id, args: process.argv.slice(2) }) + '\\n');
+${engine === 'muse' ? `const folder = path.join(process.env.MUSE_HOME, 'sessions', '2026', '10', '09', '${museId}');
+fs.mkdirSync(folder, { recursive: true }); fs.writeFileSync(path.join(folder, 'session.jsonl'), [
+{payload:{record:{workspace_root:process.cwd()}}}, {payload:{kind:'run',event:{kind:'started',prompt:''}}}
+].map(JSON.stringify).join('\\n') + '\\n');` : ''}
+console.log('fixture-${engine}-ready'); setInterval(() => {}, 1000);
+`, { mode: 0o755 })
+ }
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ const rows = async () => (await c.request('agents_list', { includeStopped: true })).agents as Array<Record<string, any>>
+ const create = async (engine: string, name: string) => {
+ const cwd = join(d.projectsDir, name); mkdirSync(cwd)
+ const result = await c.request('agent_create', { engine, cwd }, 60_000)
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ return result.agent as Record<string, any>
+ }
+ const muse = await create('muse', 'muse')
+ await until('Muse scheduled run binds without its interpreter', async () => (await rows()).find(row => row.id === muse.id)?.sessionId === museId || null, 30_000, 100)
+ for (const name of ['unwritten', 'written'] as const) {
+ const pi = await create('pi', name)
+ const id = piIds[name]
+ const bound = await until('Pi preallocated identity binds', async () => {
+ const row = (await rows()).find(row => row.id === pi.id)
+ return row?.sessionId === id && row.status === 'active' ? row : null
+ }, 30_000, 100)
+ const close = () => c.request('agent_close', { agentId: pi.id, sessionId: id, createdAt: bound.createdAt, mode: 'now' }, 45_000)
+ if (name === 'written') {
+ const cwd = join(d.projectsDir, name)
+ const folder = `--${cwd.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`
+ const path = join(d.env.PI_HOME, 'agent', 'sessions', folder, `2026-10-09_${id}.jsonl`)
+ mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, '')
+ const held = await close()
+ expect(held.error).toBeTruthy()
+ expect(held.detail).toContain('could not be read')
+ expect((await rows()).find(row => row.id === pi.id)).toMatchObject({ status: 'active', sessionId: id })
+ writeFileSync(path, JSON.stringify({ type: 'session', id, cwd }) + '\n')
+ }
+ expect(await close()).toMatchObject({ closed: true })
+ expect((await rows()).find(row => row.id === pi.id)).toMatchObject({ status: 'stopped', sessionId: id })
+ // Before a first reply Pi has no native conversation to resume; Close still preserves its screen.
+ if (name === 'unwritten') continue
+ const resumed = await c.request('agent_resume', { agentId: pi.id }, 60_000)
+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()
+ await until('Pi resumes its exact preallocated conversation', async () =>
+ (await rows()).find(row => row.id === pi.id)?.status === 'active' || null, 30_000, 100)
+ await until('the private Pi process received the saved resume ID', () => readFileSync(join(d.root, 'pi-launches.jsonl'), 'utf8')
+ .split('\n').filter(Boolean).map(line => JSON.parse(line)).some(row => row.id === id && row.args.includes('--session')) || null, 15_000, 100)
+ }
+ expect((await fetch(`http://127.0.0.1:${d.port}/api/health`)).ok).toBe(true)
+ expect(d.coresStarted()).toBe(1)
+}, 240_000)
diff --git a/cli/scripts/handoff-2026-10-08/mutate-repair-identity.py b/cli/scripts/handoff-2026-10-08/mutate-repair-identity.py
new file mode 100644
index 000000000..ed9db0de1
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-repair-identity.py
@@ -0,0 +1,65 @@
+"""Break native identity declarations/control wiring. Only assertion failures count."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+golden = 'src/engines/repairIdentity.golden.spec.ts'
+eager = 'src/lib/sessionRepair.eager.spec.ts'
+bounded = 'src/engines/kit/sessionIdentity.spec.ts'
+bind = 'src/core/agents/bind.spec.ts'
+stop = 'src/lib/stopAgentService.spec.ts'
+saved = 'src/lib/stoppedAgents.spec.ts'
+mutations = [
+ ('Muse workspace field', 'src/engines/muse/contract.ts', "'workspace_root'", "'missing_workspace'", golden),
+ ('Muse task mistaken for run', 'src/engines/muse/contract.ts', "value: 'run'", "value: 'task'", golden),
+ ('Muse run start lost', 'src/engines/muse/contract.ts', "value: 'started'", "value: 'stopped'", golden),
+ ('Pi header type', 'src/engines/pi/contract.ts', "type: 'session'", "type: 'message'", golden),
+ ('Pi folder prefix', 'src/engines/pi/contract.ts', "prefix: '--'", "prefix: 'wrong-'", golden),
+ ('Pi file path mistaken for id', 'src/engines/pi/contract.ts', r'(?!.*\.jsonl$)', '', golden),
+ ('Pi header cwd', 'src/engines/pi/contract.ts', "cwd: ['cwd']", "cwd: ['other']", golden),
+ ('Pi partial entry accepted', 'src/engines/kit/sessionIdentity.ts', "head.split('\\n').slice(0, -1)", "head.split('\\n')", golden),
+ ('Pi wrong first entry ignored', 'src/engines/kit/sessionIdentity.ts', "if (valueAt(record, ['type']) !== rule.type) return null", "if (valueAt(record, ['type']) !== rule.type) continue", golden),
+ ('Pi duplicate chosen', 'src/lib/sessionRepair.ts', 'if (matches.length > 1)', 'if (false)', golden),
+ ('Pi core header disconnected', 'src/lib/sessionRepair.ts', 'const head = await readPiHead(join(directory, file))', 'const head = null', golden),
+ ('Muse core identity disconnected', 'src/lib/sessionRepair.ts', 'const identity = await museSessionIdentity(path, root => sameDir(root, cwd))', 'const identity = null', golden),
+ ('Muse waits on optional code', 'src/lib/sessionRepair.ts', 'const identity = await museSessionIdentity', "await (await import('../engines/inProcess.js')).loadEngine('muse')\n const identity = await museSessionIdentity", eager),
+ ('Read bound mistaken for absence', 'src/engines/kit/sessionIdentity.ts', "throw new Error('The conversation identity exceeds the bounded read; discovery is held.')", 'return null', bounded),
+ ('One hold aborts discovery', 'src/core/agents/bind.ts', 'binding held · ${error instanceof Error ? error.message : error}`)\n return null', 'binding held · ${error instanceof Error ? error.message : error}`)\n throw error', bind),
+ ('Stop capture erased by live snapshot', 'src/lib/stoppedAgents.ts', 'session = { ...session, transcriptPath: previous.transcriptPath }', 'session = { ...session, transcriptPath: null }', stop),
+ ('Saved path crosses a conversation', 'src/lib/stoppedAgents.ts', 'session.sessionId === previous.sessionId && session.engine === previous.engine', 'session.engine === previous.engine', saved),
+ ('Saved path crosses a process', 'src/lib/stoppedAgents.ts', '&& (session.hermesHome ?? null) === (previous.hermesHome ?? null)\n && sameProcessIdentity(session.processIdentity, previous.processIdentity)', '&& (session.hermesHome ?? null) === (previous.hermesHome ?? null)\n && !!session.processIdentity && !!previous.processIdentity', saved),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for name in ['TMUX', 'TMUX_PANE', 'RECORD_REPAIR_IDENTITY_GOLDEN']:
+ env.pop(name, None)
+
+
+def run(specs):
+ # Ownership mutants need these focused regressions, not the unrelated 2,050-file catalog cost test.
+ pattern = ['--testNamePattern=pathless observation|captured path'] if specs == [saved] else []
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, *pattern, '--maxWorkers=2'],
+ cwd=cli, env=env, capture_output=True, text=True, timeout=180)
+
+
+for specs in [[golden, eager, bounded, bind, stop], [saved]]:
+ baseline = run(specs)
+ if baseline.returncode:
+ print(baseline.stdout + baseline.stderr)
+ raise SystemExit('baseline failed; no mutants ran')
+print('unchanged baseline passed', flush=True)
+for label, relative, before, after, spec in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == 1, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([spec])
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ print(output)
+ raise SystemExit(f'{label}: not caught by an assertion')
+ print(f'{label}: caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index d513dfa1e..6f3a83c93 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -445,7 +445,8 @@ describe('the daemon\'s shape', () => {
it('transcript location, native process evidence and profile discovery have no lazy implementation dependency', () => {
for (const entry of ['core/agents/bind.ts', 'core/engines/cursorDiscovery.ts', 'engines/identities.ts',
- 'engines/kit/sessionLocation.ts', 'engines/kit/transcriptDiscovery.ts', 'lib/terminalAgentDiscovery.ts', 'lib/sqliteRead.ts']) {
+ 'engines/kit/sessionLocation.ts', 'engines/kit/transcriptDiscovery.ts', 'lib/terminalAgentDiscovery.ts', 'lib/sqliteRead.ts',
+ 'lib/sessionRepair.ts', 'engines/repairIdentities.ts', 'engines/kit/sessionIdentity.ts']) {
const imports = importsFor(entry, readFileSync(join(SRC, entry), 'utf8'))
expect(imports.filter(one => one.dynamic || /inProcess\.js$/.test(one.from)), entry).toEqual([])
}
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index e0e56c275..55510cb27 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -9,6 +9,7 @@ import { isRecentlyDeleted } from '../../lib/deletedSessions.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'
import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
+import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { createBinding, statBirthMs, type BindDeps, type RegisteredMeta } from './bind.js'
vi.mock('../../engines/identities.js', () => ({ transcriptOf: vi.fn(), processSessionOf: vi.fn() }))
@@ -318,6 +319,41 @@ describe('binding a running process to its session', () => {
expect(run.deps.attachSession).toHaveBeenCalledOnce()
})
+ it.each([new Error('identity read limit'), 'identity read limit'])('holds only the unreadable native identity and finishes the discovery/readiness pass: %s', async error => {
+ const run = setup()
+ const rows = [agent({ engine: 'muse', agentId: 'held', sessionId: '', runtimes: [], active: true,
+ processIdentity: { pid: 42, executable: 'muse', startMarker: '2026-10-09T00:00:00Z' } }),
+ agent({ engine: 'codex', agentId: 'next', sessionId: '', runtimes: [], active: true,
+ processIdentity: { pid: 43, executable: 'codex', startMarker: '2026-10-09T00:00:00Z' } })]
+ for (const row of rows) run.byAgent.set(row.agentId, row)
+ vi.mocked(run.deps.registry.byProcess).mockImplementation(engine => rows.find(row => row.engine === engine))
+ vi.mocked(findLiveSession).mockImplementation(async engine => {
+ if (engine === 'muse') throw error
+ return { sessionId: 'found', transcriptPath: '/t/found.jsonl' }
+ })
+ vi.mocked(run.deps.registry.register).mockImplementation(request => {
+ Object.assign(rows[1]!, { sessionId: request.sessionId, transcriptPath: request.transcriptPath })
+ return { entry: rows[1]!, ...meta({ isNew: true }) } as never
+ })
+ const onProbeStatus = vi.fn(), onRemoved = vi.fn(), onDormant = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => rows, backends: [], backendOrder: ['tmux'], onProbeStatus, onRemoved, onDormant,
+ onDiscovered: run.binding.bindObservedAgent, onObserved: run.binding.bindObservedAgent,
+ probe: async () => ({ processTableAvailable: true, targets: [], ambiguousPlacements: new Set(),
+ agents: rows.map(row => observed({ engine: row.engine, processIdentity: row.processIdentity! })) }),
+ })
+ try {
+ await expect(reconciler.start(60_000)).resolves.toBeUndefined()
+ expect(rows[0]!.sessionId).toBe('')
+ expect(rows[1]!.sessionId).toBe('found')
+ expect(run.deps.registry.register).toHaveBeenCalledOnce()
+ expect(run.deps.stoppedAgents.save).toHaveBeenCalledExactlyOnceWith(rows[1])
+ expect(onRemoved).not.toHaveBeenCalled(); expect(onDormant).not.toHaveBeenCalled()
+ expect(onProbeStatus).toHaveBeenCalledWith({ ready: true, error: null })
+ expect(console.log).toHaveBeenCalledWith('[discovery] held binding held · identity read limit')
+ } finally { reconciler.stop() }
+ })
+
it.each([new Error('reader unavailable'), 'reader unavailable'])('contains an optional attachment failure after binding', async error => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {})
const run = setup({ attachSession: vi.fn(async () => { throw error }) })
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index 82cb7155c..e3623886a 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -319,6 +319,11 @@ export function createBinding({
bornOnly: true,
pid: observed.processIdentity.pid,
codexHome: agent.codexHome ?? undefined,
+ }).catch(error => {
+ // A native store can be unreadable or exceed a safe identity bound. That holds this
+ // process alone; rejecting onObserved would abort the serial discovery/readiness pass.
+ console.log(`[discovery] ${sid(agent.agentId)} binding held · ${error instanceof Error ? error.message : error}`)
+ return null
})
if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return
sessionId = found.sessionId
diff --git a/cli/src/engines/__fixtures__/repair-identity.golden.json b/cli/src/engines/__fixtures__/repair-identity.golden.json
new file mode 100644
index 000000000..a4148ac08
--- /dev/null
+++ b/cli/src/engines/__fixtures__/repair-identity.golden.json
@@ -0,0 +1,84 @@
+{
+ "muse:spoken": {
+ "sessionId": "spoken",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/09/spoken/session.jsonl"
+ },
+ "muse:scheduled": {
+ "sessionId": "scheduled",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/09/scheduled/session.jsonl"
+ },
+ "muse:task": null,
+ "muse:reminder": null,
+ "muse:delayed": {
+ "sessionId": "delayed",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/09/delayed/session.jsonl"
+ },
+ "muse:malformed": null,
+ "muse:incomplete": null,
+ "muse:noWorkspace": null,
+ "muse:wrongWorkspace": null,
+ "muse:wrongEnvelope": null,
+ "muse:arrayEvent": null,
+ "muse:subagent": null,
+ "muse:ambiguous": null,
+ "muse:older-than-process": null,
+ "pi:header:valid": {
+ "sessionId": "custom.id-12",
+ "cwd": "/work/pi"
+ },
+ "pi:header:unicode": {
+ "sessionId": "custom.id-12",
+ "cwd": "/work/本"
+ },
+ "pi:header:malformedLead": {
+ "sessionId": "custom.id-12",
+ "cwd": "/work/pi"
+ },
+ "pi:header:wrongFirst": null,
+ "pi:header:arrayFirst": null,
+ "pi:header:stringFirst": null,
+ "pi:header:empty": "<unsettled>",
+ "pi:header:partial": "<unsettled>",
+ "pi:header:wrongId": null,
+ "pi:header:shortId": null,
+ "pi:header:longId": null,
+ "pi:header:fileId": null,
+ "pi:header:relativeCwd": null,
+ "pi:header:noCwd": null,
+ "pi:header:large": {
+ "sessionId": "custom.id-12",
+ "cwd": "/work/pi"
+ },
+ "pi:header:tooLarge": null,
+ "pi:folder:/work/pi": "--work-pi--",
+ "pi:folder:/work/pi/a-b": "--work-pi-a-b--",
+ "pi:folder:/work/pi-a/b": "--work-pi-a-b--",
+ "pi:folder:C:\\work\\pi": "--C--work-pi--",
+ "pi:folder:/work/本": "--work-本--",
+ "pi:resume:exact": "<root>/home/.pi/agent/sessions/--work-pi-resume--/2026-10-09_custom.id-12.jsonl",
+ "pi:resume:unwritten": null,
+ "pi:resume:missing-folder": null,
+ "pi:resume:missing-cwd": {
+ "error": "The Pi conversation location is unavailable."
+ },
+ "pi:resume:invalid:../escape": {
+ "error": "The Pi conversation location is unavailable."
+ },
+ "pi:resume:invalid:a": {
+ "error": "The Pi conversation location is unavailable."
+ },
+ "pi:resume:invalid:a.jsonl": {
+ "error": "The Pi conversation location is unavailable."
+ },
+ "pi:resume:empty": {
+ "error": "The Pi conversation file could not be read."
+ },
+ "pi:resume:bad-header": {
+ "error": "The Pi conversation file could not be read."
+ },
+ "pi:resume:duplicate": {
+ "error": "More than one file matches this Pi conversation."
+ },
+ "pi:resume:folder-collision": null,
+ "pi:resume:header-id-wins": null
+}
diff --git a/cli/src/engines/kit/sessionIdentity.spec.ts b/cli/src/engines/kit/sessionIdentity.spec.ts
new file mode 100644
index 000000000..29ed3ca78
--- /dev/null
+++ b/cli/src/engines/kit/sessionIdentity.spec.ts
@@ -0,0 +1,55 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { readRunIdentity, readSessionHeader, type RunIdentity, UNSETTLED } from './sessionIdentity.js'
+import { readPiHead } from '../repairIdentities.js'
+
+const roots: string[] = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+const pathFor = (text: string) => {
+ const root = mkdtempSync(join(tmpdir(), 'identity-head-')); roots.push(root)
+ const path = join(root, 'session.jsonl'); writeFileSync(path, text); return path
+}
+const rule: RunIdentity = { bytes: [64, 128], cwd: ['header', 'cwd'], run: [{ field: ['run', 'kind'], value: 'started' }] }
+const header = JSON.stringify({ header: { cwd: '/work' } }) + '\n'
+const run = JSON.stringify({ run: { kind: 'started' } })
+
+it('does not read a conversation body once its identity is in the first bounded head', async () => {
+ const path = pathFor(header + run + '\n' + 'x'.repeat(1024 * 1024))
+ await expect(readRunIdentity(rule, path, async () => true)).resolves.toEqual({ cwd: '/work' })
+})
+it('expands a head for later identity and accepts a complete final line without a newline', async () => {
+ const path = pathFor(header + ' '.repeat(40) + '\n' + run)
+ await expect(readRunIdentity(rule, path, async () => true)).resolves.toEqual({ cwd: '/work' })
+})
+it('holds when a run marker lies beyond the bound, instead of ruling out a competing conversation', async () => {
+ const path = pathFor(header + ' '.repeat(200) + '\n' + run)
+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('discovery is held')
+})
+it('holds when even the first line exceeds the bound', async () => {
+ const path = pathFor(JSON.stringify({ padding: 'x'.repeat(200), header: { cwd: '/work' } }) + '\n' + run)
+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('discovery is held')
+})
+it('a file from another workspace cannot hold this workspace on a late marker', async () => {
+ const matches = vi.fn(async () => false)
+ const path = pathFor(header + 'x'.repeat(200))
+ await expect(readRunIdentity(rule, path, matches)).resolves.toBeNull()
+ expect(matches).toHaveBeenCalledExactlyOnceWith('/work')
+})
+it.each(['', 'bad\n', 'null\n', '[]\n', '{"header":[]}\n', header + '{"run":{"kind":"task"}}'])('refuses a complete file without identity: %j', async text => {
+ await expect(readRunIdentity(rule, pathFor(text), async () => true)).resolves.toBeNull()
+})
+it('keeps native I/O failure distinct from an absent run', async () => {
+ const path = pathFor(''); rmSync(path)
+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toMatchObject({ code: 'ENOENT' })
+ await expect(readPiHead(path)).resolves.toBe(UNSETTLED)
+ mkdirSync(path)
+ await expect(readPiHead(path)).resolves.toBe(UNSETTLED)
+})
+it('reads a header from declared fields and preserves an optional reader\'s I/O refusal', async () => {
+ const headerRule = { bytes: [100], type: 'begin', id: { field: ['record', 'id'], pattern: /^id$/ }, cwd: ['record', 'cwd'] }
+ await expect(readSessionHeader(headerRule, async () => '{"type":"begin","record":{"id":"id","cwd":"/work"}}\n'))
+ .resolves.toEqual({ sessionId: 'id', cwd: '/work' })
+ await expect(readSessionHeader(headerRule, async () => { throw new Error('read failed') })).rejects.toThrow('read failed')
+})
diff --git a/cli/src/engines/kit/sessionIdentity.ts b/cli/src/engines/kit/sessionIdentity.ts
new file mode 100644
index 000000000..d8746d2cc
--- /dev/null
+++ b/cli/src/engines/kit/sessionIdentity.ts
@@ -0,0 +1,76 @@
+/** Small native identity records needed by session control, independent of optional readers. */
+import { resolve } from 'node:path'
+import { headBytes } from './continuation.js'
+
+export const UNSETTLED: unique symbol = Symbol('unsettled')
+type Field = readonly string[]
+export interface SessionHeader {
+ bytes: readonly number[]
+ type: string
+ id: { field: Field; pattern: RegExp }
+ cwd: Field
+}
+export interface SessionFolder {
+ prefix: string; suffix: string; trim: RegExp; mangle: RegExp; replacement: string
+}
+export interface RunIdentity {
+ bytes: readonly number[]
+ cwd: Field
+ run: readonly { field: Field; value: string }[]
+}
+export interface NativeSessionHead { sessionId: string; cwd: string }
+
+function valueAt(value: unknown, field: Field): unknown {
+ for (const key of field) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
+ value = (value as Record<string, unknown>)[key]
+ }
+ return value
+}
+function parsed(line: string): unknown {
+ try { return JSON.parse(line) } catch { return null }
+}
+
+export function sessionFolder(rule: SessionFolder, cwd: string): string {
+ return rule.prefix + cwd.replace(rule.trim, '').replace(rule.mangle, rule.replacement) + rule.suffix
+}
+
+/** A complete first JSON entry; blank/malformed lines are skipped, another valid entry refuses it.
+ * The optional reader supplies its own I/O wrapper to retain its scan's read-failure evidence. */
+export async function readSessionHeader(rule: SessionHeader, read: (bytes: number) => Promise<string>): Promise<NativeSessionHead | null | typeof UNSETTLED> {
+ for (const bytes of rule.bytes) {
+ const head = await read(bytes)
+ for (const line of head.split('\n').slice(0, -1)) {
+ if (!line.trim()) continue
+ const record = parsed(line)
+ if (record === null) continue
+ if (valueAt(record, ['type']) !== rule.type) return null
+ const id = valueAt(record, rule.id.field)
+ const cwd = valueAt(record, rule.cwd)
+ return typeof id === 'string' && rule.id.pattern.test(id)
+ && typeof cwd === 'string' && cwd.startsWith('/') ? { sessionId: id, cwd: resolve(cwd) } : null
+ }
+ if (Buffer.byteLength(head) < bytes) return UNSETTLED
+ }
+ return null
+}
+
+/** A workspace in line one and a declared run marker. A bound never establishes absence:
+ * if relevant evidence lies beyond it, the caller holds the lookup instead of guessing a sibling. */
+export async function readRunIdentity(rule: RunIdentity, path: string, matches: (cwd: string) => Promise<boolean>): Promise<{ cwd: string } | null> {
+ for (const bytes of rule.bytes) {
+ const head = await headBytes(path, bytes + 1)
+ const complete = head.length <= bytes
+ const lines = head.subarray(0, bytes).toString('utf8').split('\n')
+ if (!complete) lines.pop()
+ if (!lines.length) continue
+ const cwd = valueAt(parsed(lines[0]!), rule.cwd)
+ if (typeof cwd !== 'string' || !cwd || !await matches(cwd)) return null
+ for (const line of lines) {
+ const record = parsed(line)
+ if (rule.run.every(part => valueAt(record, part.field) === part.value)) return { cwd }
+ }
+ if (complete) return null
+ }
+ throw new Error('The conversation identity exceeds the bounded read; discovery is held.')
+}
diff --git a/cli/src/engines/muse/contract.ts b/cli/src/engines/muse/contract.ts
new file mode 100644
index 000000000..04845ffd8
--- /dev/null
+++ b/cli/src/engines/muse/contract.ts
@@ -0,0 +1,8 @@
+/** Muse's native identity facts. A task start is bookkeeping; a run with an empty prompt is real. */
+import type { RunIdentity } from '../kit/sessionIdentity.js'
+
+export const MUSE_IDENTITY: RunIdentity = {
+ bytes: [64 * 1024, 4 * 1024 * 1024],
+ cwd: ['payload', 'record', 'workspace_root'],
+ run: [{ field: ['payload', 'kind'], value: 'run' }, { field: ['payload', 'event', 'kind'], value: 'started' }],
+}
diff --git a/cli/src/engines/pi/contract.ts b/cli/src/engines/pi/contract.ts
new file mode 100644
index 000000000..3e9866c89
--- /dev/null
+++ b/cli/src/engines/pi/contract.ts
@@ -0,0 +1,12 @@
+/** Pi's folder is lossy. Only its complete first entry establishes the session id and cwd. */
+import type { SessionFolder, SessionHeader } from '../kit/sessionIdentity.js'
+
+// Pi accepts custom ids. A .jsonl suffix makes --session interpret the value as a file instead.
+export const PI_SESSION_ID = /^(?!.*\.jsonl$)[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/
+export const PI_HEADER: SessionHeader = {
+ bytes: [16 * 1024, 1024 * 1024], type: 'session',
+ id: { field: ['id'], pattern: PI_SESSION_ID }, cwd: ['cwd'],
+}
+export const PI_FOLDER: SessionFolder = {
+ prefix: '--', suffix: '--', trim: /^[/\\]/, mangle: /[/\\:]/g, replacement: '-',
+}
diff --git a/cli/src/engines/repairIdentities.ts b/cli/src/engines/repairIdentities.ts
new file mode 100644
index 000000000..c2cacf536
--- /dev/null
+++ b/cli/src/engines/repairIdentities.ts
@@ -0,0 +1,10 @@
+/** Native repair facts available while optional history readers are missing or loading. */
+import { MUSE_IDENTITY } from './muse/contract.js'
+import { PI_FOLDER, PI_HEADER } from './pi/contract.js'
+import { headBytes } from './kit/continuation.js'
+import { readRunIdentity, readSessionHeader, sessionFolder, UNSETTLED } from './kit/sessionIdentity.js'
+
+export const museSessionIdentity = (path: string, matches: (cwd: string) => Promise<boolean>) => readRunIdentity(MUSE_IDENTITY, path, matches)
+export const piSessionFolder = (cwd: string): string => sessionFolder(PI_FOLDER, cwd)
+export const readPiHead = (path: string) => readSessionHeader(PI_HEADER,
+ async bytes => (await headBytes(path, bytes)).toString('utf8')).catch(() => UNSETTLED)
diff --git a/cli/src/engines/repairIdentity.golden.spec.ts b/cli/src/engines/repairIdentity.golden.spec.ts
new file mode 100644
index 000000000..e0bb06c87
--- /dev/null
+++ b/cli/src/engines/repairIdentity.golden.spec.ts
@@ -0,0 +1,139 @@
+/** Muse/Pi session-control answers, recorded from main before moving their optional readers.
+ * Linux, UTC, the clock, file birth/mtime, homes and input are fixed. No engine binary runs.
+ * RECORD_REPAIR_IDENTITY_GOLDEN=1 records the former implementation in its own commit. */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
+
+const clock = vi.hoisted(() => ({ root: '', time: Date.parse('2026-10-09T00:00:00Z') }))
+vi.mock('fs/promises', async original => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ return { ...fs, stat: async (path: string, ...args: unknown[]) => {
+ const result = await Reflect.apply(fs.stat, fs, [path, ...args])
+ return String(path).startsWith(clock.root + '/')
+ ? new Proxy(result, { get: (value, key) => key === 'birthtimeMs' ? clock.time : Reflect.get(value, key) })
+ : result
+ } }
+})
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/repair-identity.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_REPAIR_IDENTITY_GOLDEN === '1'
+const saved: Record<string, string | undefined> = {}
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const captured: Record<string, unknown> = {}
+let expected: Record<string, unknown> = {}
+let repair: typeof import('../lib/sessionRepair.js')
+let pi: typeof import('../lib/sessionSearch/externals/pi.js')
+
+const lines = (...values: unknown[]) => values.map(value => typeof value === 'string' ? value : JSON.stringify(value)).join('\n') + '\n'
+function file(path: string, body: string, time = clock.time): string {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, body)
+ utimesSync(path, time / 1000, time / 1000)
+ return path
+}
+async function check(key: string, run: () => unknown | Promise<unknown>): Promise<void> {
+ let value: unknown
+ try { value = await run() } catch (error) { value = { error: (error as Error).message } }
+ if (typeof value === 'symbol') value = '<unsettled>'
+ captured[key] = JSON.parse(JSON.stringify(value ?? null).split(clock.root).join('<root>'))
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+}
+
+beforeAll(async () => {
+ clock.root = realpathSync(mkdtempSync(join(tmpdir(), 'repair-identity-golden-')))
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.useFakeTimers({ toFake: ['Date'], now: clock.time })
+ const home = join(clock.root, 'home')
+ for (const [key, value] of Object.entries({ HOME: home, TZ: 'UTC', ADAPTER_DATA_DIR: join(clock.root, 'data'),
+ ADAPTER_RUNTIME_DIR: join(clock.root, 'runtime'), MUSE_HOME: join(home, '.muse'), PI_HOME: join(home, '.pi'),
+ CLAUDE_PROJECTS_DIR: join(home, '.claude', 'projects'), CODEX_HOME: join(home, '.codex') })) {
+ saved[key] = process.env[key]; process.env[key] = value
+ }
+ vi.resetModules()
+ repair = await import('../lib/sessionRepair.js')
+ pi = await import('../lib/sessionSearch/externals/pi.js')
+ if (!RECORD) expected = JSON.parse(readFileSync(GOLDEN, 'utf8'))
+})
+afterAll(() => {
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')
+ for (const [key, value] of Object.entries(saved)) if (value === undefined) delete process.env[key]; else process.env[key] = value
+ Object.defineProperty(process, 'platform', platform)
+ vi.useRealTimers()
+ rmSync(clock.root, { recursive: true, force: true })
+})
+
+it('records which Muse files identify a conversation', async () => {
+ const root = join(process.env.MUSE_HOME!, 'sessions', '2026', '10', '09')
+ const header = (cwd: unknown) => ({ payload: { record: { workspace_root: cwd } } })
+ const event = (scope: string, kind: string, prompt = '') => ({ payload: { kind: scope, event: { kind, prompt } } })
+ const cases = {
+ spoken: (cwd: string) => lines(header(cwd), event('run', 'started', 'hello')),
+ scheduled: (cwd: string) => lines(header(cwd), event('run', 'started')),
+ task: (cwd: string) => lines(header(cwd), event('task', 'started')),
+ reminder: (cwd: string) => lines(header(cwd), event('memory', 'memory_reminder_child_session_linked')),
+ delayed: (cwd: string) => lines(header(cwd), ...Array.from({ length: 300 }, () => event('task', 'started')), event('run', 'started')),
+ malformed: (cwd: string) => lines('{', header(cwd), event('run', 'started')),
+ incomplete: (cwd: string) => lines(header(cwd), '{'),
+ noWorkspace: () => lines(header(null), event('run', 'started')),
+ wrongWorkspace: () => lines(header('/elsewhere'), event('run', 'started')),
+ wrongEnvelope: (cwd: string) => lines({ workspace_root: cwd }, event('run', 'started')),
+ arrayEvent: (cwd: string) => lines(header(cwd), { payload: { kind: 'run', event: [] } }),
+ }
+ for (const [name, body] of Object.entries(cases)) {
+ const cwd = `/work/muse/${name}`
+ file(join(root, name, 'session.jsonl'), body(cwd))
+ await check(`muse:${name}`, () => repair.findLiveSession('muse', cwd, clock.time, { bornOnly: true }))
+ }
+ file(join(root, 'parent', 'subagent', 'session.jsonl'), lines(header('/work/muse/child'), event('run', 'started')))
+ await check('muse:subagent', () => repair.findLiveSession('muse', '/work/muse/child', clock.time))
+ file(join(root, 'duplicate-a', 'session.jsonl'), lines(header('/work/muse/duplicate'), event('run', 'started')))
+ file(join(root, 'duplicate-b', 'session.jsonl'), lines(header('/work/muse/duplicate'), event('run', 'started')))
+ await check('muse:ambiguous', () => repair.findLiveSession('muse', '/work/muse/duplicate', clock.time))
+ await check('muse:older-than-process', () => repair.findLiveSession('muse', '/work/muse/spoken', clock.time + 60_000))
+})
+
+it('records Pi header authority and incomplete-file answers', async () => {
+ const header = (id: unknown = 'custom.id-12', cwd: unknown = '/work/pi') => ({ type: 'session', id, cwd })
+ const cases: Record<string, string> = {
+ valid: lines(header()), unicode: lines(header('custom.id-12', '/work/本/../本')),
+ malformedLead: lines('', '{', 'null', header()), wrongFirst: lines({ type: 'message' }, header()),
+ arrayFirst: lines([], header()), stringFirst: lines('"text"', header()), empty: '', partial: JSON.stringify(header()),
+ wrongId: lines(header('../escape')), shortId: lines(header('a')), longId: lines(header('a'.repeat(129))),
+ fileId: lines(header('a.jsonl')), relativeCwd: lines(header('valid', 'relative')), noCwd: lines(header('valid', null)),
+ large: lines({ ...header(), padding: 'x'.repeat(20 * 1024) }),
+ tooLarge: lines({ ...header(), padding: 'x'.repeat(1024 * 1024) }),
+ }
+ for (const [name, body] of Object.entries(cases)) {
+ const path = file(join(clock.root, 'headers', name + '.jsonl'), body)
+ await check(`pi:header:${name}`, () => pi.readPiHead(path))
+ }
+ for (const cwd of ['/work/pi', '/work/pi/a-b', '/work/pi-a/b', 'C:\\work\\pi', '/work/本']) {
+ await check(`pi:folder:${cwd}`, () => pi.piSessionFolder(cwd))
+ }
+})
+
+it('records Pi resume identity, including what must hold Close', async () => {
+ const home = join(process.env.PI_HOME!, 'agent', 'sessions')
+ const put = (cwd: string, name: string, body: string) => file(join(home, pi.piSessionFolder(cwd), name), body)
+ const header = (id: string, cwd: string) => lines({ type: 'session', id, cwd })
+ const cwd = '/work/pi/resume'
+ put(cwd, '2026-10-09_custom.id-12.jsonl', header('custom.id-12', cwd))
+ await check('pi:resume:exact', () => repair.findResumedTranscript('pi', 'custom.id-12', { cwd }))
+ await check('pi:resume:unwritten', () => repair.findResumedTranscript('pi', 'not-written', { cwd }))
+ await check('pi:resume:missing-folder', () => repair.findResumedTranscript('pi', 'not-written', { cwd: '/work/absent' }))
+ await check('pi:resume:missing-cwd', () => repair.findResumedTranscript('pi', 'custom.id-12'))
+ for (const id of ['../escape', 'a', 'a.jsonl']) await check(`pi:resume:invalid:${id}`, () => repair.findResumedTranscript('pi', id, { cwd }))
+ put(cwd, '2026-10-09_empty-file.jsonl', '')
+ await check('pi:resume:empty', () => repair.findResumedTranscript('pi', 'empty-file', { cwd }))
+ put(cwd, '2026-10-09_bad-header.jsonl', lines({ type: 'message' }))
+ await check('pi:resume:bad-header', () => repair.findResumedTranscript('pi', 'bad-header', { cwd }))
+ put(cwd, '2026-10-10_custom.id-12.jsonl', header('custom.id-12', cwd))
+ await check('pi:resume:duplicate', () => repair.findResumedTranscript('pi', 'custom.id-12', { cwd }))
+ put('/work/pi/a-b', '2026-10-09_colliding-id.jsonl', header('colliding-id', '/work/pi/a-b'))
+ await check('pi:resume:folder-collision', () => repair.findResumedTranscript('pi', 'colliding-id', { cwd: '/work/pi-a/b' }))
+ put(cwd, '2026-10-09_wrong-id.jsonl', header('different-id', cwd))
+ await check('pi:resume:header-id-wins', () => repair.findResumedTranscript('pi', 'wrong-id', { cwd }))
+})
diff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.ts
index 715a2c899..0d57ccd23 100644
--- a/cli/src/engines/sessionStore.golden.spec.ts
+++ b/cli/src/engines/sessionStore.golden.spec.ts
@@ -14,8 +14,8 @@
* - what Stop captures before a pause, and which finder the handoff asks for each engine.
*
* Each case runs with `process.platform` pinned to darwin and to linux, and linux's are stored where they
- * differ. File birth times are a property of the filesystem, so only sessions born after their process are
- * recorded; the `wrote` tier is the unit specs'.
+ * differ. Fixture birth/mtime and the clock are fixed: running both platform passes under load must not
+ * age a "new" transcript beyond the process-start slack. The `wrote` tier is the unit specs'.
*
* `RECORD_SESSION_STORE_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter what
* core finds, and say so in that change.
@@ -27,6 +27,17 @@ import { fileURLToPath } from 'node:url'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
+const fixtureClock = vi.hoisted(() => ({ root: '', now: Date.parse('2026-10-09T00:00:00Z') }))
+vi.mock('fs/promises', async original => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ return { ...fs, stat: async (path: string, ...args: unknown[]) => {
+ const result = await Reflect.apply(fs.stat, fs, [path, ...args])
+ return String(path).startsWith(fixtureClock.root + '/')
+ ? new Proxy(result, { get: (value, key) => key === 'birthtimeMs' || key === 'mtimeMs' ? fixtureClock.now : Reflect.get(value, key) })
+ : result
+ } }
+})
+
// The record holds a UTC record read against a process started in local time, so the answer depends on the zone.
// It was recorded in America/New_York; pinned here, it is the same on every host (Linux CI runs in UTC, run 37828754630).
process.env.TZ = 'America/New_York'
@@ -75,6 +86,8 @@ let paths: Record<string, string> = {}
beforeAll(async () => {
root = realpathSync(mkdtempSync(join(tmpdir(), 'session-store-golden-')))
+ fixtureClock.root = root
+ vi.useFakeTimers({ toFake: ['Date'], now: fixtureClock.now })
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')
@@ -127,6 +140,7 @@ beforeAll(async () => {
})
afterAll(() => {
+ vi.useRealTimers()
for (const name of VARS) {
if (saved[name] === undefined) delete process.env[name]
else process.env[name] = saved[name]
diff --git a/cli/src/lib/sessionRepair.lazy.spec.ts b/cli/src/lib/sessionRepair.eager.spec.ts
similarity index 58%
rename from cli/src/lib/sessionRepair.lazy.spec.ts
rename to cli/src/lib/sessionRepair.eager.spec.ts
index 0a6479b51..f1a7c9f33 100644
--- a/cli/src/lib/sessionRepair.lazy.spec.ts
+++ b/cli/src/lib/sessionRepair.eager.spec.ts
@@ -4,21 +4,14 @@ import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
/**
- * Repair reads the other engines' files with their own code, loaded when it is asked (engines/inProcess.ts). An
- * engine whose code could not be loaded has no repair answer, as when nothing is found; Claude Code's and Codex's
- * repair loads nothing. `sessionRepair.spec.ts` and `engines/otherIdentity.golden.spec.ts` pin the answers.
+ * Native repair remains available while optional interpretation is missing or still loading.
+ * The former-code golden pins the answers; these tests deliberately withhold all optional readers.
*/
-const loader = vi.hoisted(() => ({ refused: new Set<string>(), asked: [] as string[] }))
-vi.mock('../engines/inProcess.js', async (real) => {
- const actual = await real<typeof import('../engines/inProcess.js')>()
- return {
- ...actual,
- loadEngine: vi.fn(async (name: Parameters<typeof actual.loadEngine>[0]) => {
- loader.asked.push(name)
- return loader.refused.has(name) ? null : actual.loadEngine(name)
- }),
- }
-})
+const loader = vi.hoisted(() => ({ stalled: false, asked: [] as string[] }))
+vi.mock('../engines/inProcess.js', () => ({ loadEngine: vi.fn(async (name: string) => {
+ loader.asked.push(name)
+ return loader.stalled ? new Promise(() => {}) : null
+}) }))
const STARTED_AT = Date.parse('2026-10-08T09:00:00Z')
const CWD = '/work/project'
@@ -43,6 +36,9 @@ beforeAll(async () => {
JSON.stringify({ payload: { kind: 'run', event: { kind: 'started', prompt: 'hi' } } }),
].join('\n') + '\n')
utimesSync(museFile, new Date(STARTED_AT + 5_000), new Date(STARTED_AT + 5_000))
+ const piDirectory = join(root, 'pi', 'agent', 'sessions', '--work-project--')
+ mkdirSync(piDirectory, { recursive: true })
+ writeFileSync(join(piDirectory, '2026-10-09_abc123.jsonl'), JSON.stringify({ type: 'session', id: 'abc123', cwd: CWD }) + '\n')
vi.resetModules()
repair = await import('./sessionRepair.js')
})
@@ -52,21 +48,20 @@ afterAll(() => {
rmSync(root, { recursive: true, force: true })
})
-describe('session repair, with the other engines\' code loaded when asked', () => {
- it('binds by the engine\'s own reader, loaded for that engine alone', async () => {
+describe('session repair, independent of optional readers', () => {
+ it.each(['missing', 'stalled'])('finds Muse and Pi identity while optional code is %s', async mode => {
+ loader.stalled = mode === 'stalled'
loader.asked.length = 0
- expect(await repair.findLiveSession('muse', CWD, STARTED_AT)).toMatchObject({ sessionId: UUID })
- expect(loader.asked).toEqual(['muse'])
- })
-
- it('has no answer for an engine whose code could not be loaded', async () => {
- loader.refused = new Set(['muse', 'copilot', 'agy', 'pi'])
+ let timer: ReturnType<typeof setTimeout> | undefined
try {
- expect(await repair.findLiveSession('muse', CWD, STARTED_AT)).toBeNull()
- expect(await repair.findLiveSession('copilot', CWD, STARTED_AT, { pid: 4242 })).toBeNull()
- expect(await repair.findLiveSession('agy', CWD, STARTED_AT, { pid: 4242 })).toBeNull()
- await expect(repair.findResumedTranscript('pi', 'abc123', { cwd: CWD })).rejects.toThrow('The Pi conversation location is unavailable.')
- } finally { loader.refused = new Set() }
+ const value = await Promise.race([
+ Promise.all([repair.findLiveSession('muse', CWD, STARTED_AT), repair.findResumedTranscript('pi', 'abc123', { cwd: CWD })]),
+ new Promise(resolve => { timer = setTimeout(() => resolve('blocked on optional code'), 1000) }),
+ ])
+ expect(value).toEqual([{ sessionId: UUID, transcriptPath: join(root, 'muse', 'sessions', '2026', '10', '08', UUID, 'session.jsonl') },
+ join(root, 'pi', 'agent', 'sessions', '--work-project--', '2026-10-09_abc123.jsonl')])
+ expect(loader.asked).toEqual([])
+ } finally { clearTimeout(timer); loader.stalled = false }
})
it('loads nothing for Claude Code, Codex, or an engine whose files or stores it reads itself', async () => {
@@ -76,6 +71,7 @@ describe('session repair, with the other engines\' code loaded when asked', () =
await repair.findResumedTranscript('claude', UUID)
await repair.findLiveSession('grok', CWD, STARTED_AT)
await repair.findLiveSession('pi', CWD, STARTED_AT)
+ await repair.findLiveSession('copilot', CWD, STARTED_AT, { pid: 4242 })
// Hermes's homes are declared: its stores are read without its code.
await repair.findLiveSession('hermes', CWD, STARTED_AT)
expect(loader.asked).toEqual([])
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index e011c4281..80463cb3a 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -25,7 +25,8 @@ import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
import type { AgentEngine } from '../engines/types.js'
import { HERMES_HOMES, hermesDbPath } from '../engines/hermes/contract.js'
import { listStoreHomes } from '../engines/kit/storeHomes.js'
-import { loadEngine, type InProcessModules } from '../engines/inProcess.js'
+import { museSessionIdentity, piSessionFolder, readPiHead } from '../engines/repairIdentities.js'
+import { PI_SESSION_ID } from '../engines/pi/contract.js'
import { transcriptOf, processSessionOf as nativeProcessSession } from '../engines/identities.js'
import { COPILOT_CWD } from '../engines/copilot/contract.js'
import { recordCwd } from '../engines/kit/sessionLocation.js'
@@ -183,23 +184,6 @@ export async function sameDir(a: string, b: string): Promise<boolean> {
*/
interface TranscriptMeta { cwd: string | null; sessionId?: string }
-const str = (v: unknown): string => (typeof v === 'string' ? v : '')
-
-/**
- * True once a muse session has opened a RUN — the lifecycle a conversation is made of.
- *
- * Not "has a prompt": a scheduled run is a real turn whose prompt is empty, because the scheduler
- * triggered it rather than a person. `payload.kind` is what separates the two lifecycles that share the
- * name `started`; a `task` one is scheduler bookkeeping and several fire inside a single run.
- */
-function hasRun(lines: string[], museEvent: InProcessModules['muse']['museEvent']): boolean {
- for (const line of lines) {
- const record = museEvent(line)
- if (record?.scope === 'run' && str(record.event.kind) === 'started') return true
- }
- return false
-}
-
async function fileEngineSession(
root: string | string[],
cwd: string,
@@ -330,34 +314,27 @@ export async function findLiveSession(
const real = await realpath(cwd).catch(() => cwd)
const dirs = real === cwd ? [cwd] : [cwd, real]
const dirList = placeholders(dirs.length)
- // Muse's transcript interpretation still lives with its optional reader
- // (engines/inProcess.ts); Hermes's homes are declared (engines/hermes/contract.ts). An engine whose code could not be loaded has no repair answer: its process stays
- // unbound, as when nothing is found.
+ // Native identity is eager. Optional interpretation cannot keep a process unbound.
switch (engine) {
case 'pi':
return fileEngineSession(join(env.PI_HOME, 'agent', 'sessions'), cwd, startedAtMs, readTranscriptMeta, opts)
case 'commandcode':
return fileEngineSession(join(env.COMMANDCODE_HOME, 'projects'), cwd, startedAtMs, readTranscriptMeta, opts)
case 'muse': {
- const muse = await loadEngine('muse')
- if (!muse) return null
// Muse's hooks never fire, so this scan is the ONLY way a muse pane is ever bound. The tree is
// `sessions/YYYY/MM/DD/<session-uuid>/session.jsonl` (4 levels — exactly MAX_DEPTH) and nothing in
// the path names the project: `workspace_root` in the first record is the only link. Sub-agent
// files live one level deeper under `subagent/`, and must never be adopted as agents of their own.
return fileEngineSession(join(env.MUSE_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
if (path.includes(`${sep}subagent${sep}`)) return null
- const lines = (await readFile(path, 'utf-8').catch(() => '')).split('\n')
- const root = muse.museWorkspaceRoot(lines[0] ?? '')
- if (!root) return null
// Muse opens sessions of its OWN under the same workspace_root — memory reminders
// (`memory_reminder_child_session_linked`) are the ones seen live. They are indistinguishable from
// the user's session by path, workspace or birth time, and being younger they WIN the `born` tier:
// measured, the daemon tailed an 11-line reminder session while the real conversation ran on in
// another file, so web and device received nothing at all. What separates them is that a session
// being conversed in has opened a RUN.
- if (!hasRun(lines, muse.museEvent)) return null
- return { cwd: root, sessionId: basename(dirname(path)) }
+ const identity = await museSessionIdentity(path, root => sameDir(root, cwd))
+ return identity ? { ...identity, sessionId: basename(dirname(path)) } : null
}, opts)
}
case 'amp':
@@ -486,12 +463,8 @@ export async function findResumedTranscript(
if (engine === 'pi') {
// Pi allocates an ID before its first reply creates the file. Look up that
// exact ID again at Close, including after exit, without guessing by mtime.
- if (!opts?.cwd || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/.test(sessionId)
- || sessionId.endsWith('.jsonl')) throw new Error('The Pi conversation location is unavailable.')
- // Pi's own code names its folders and reads its files (engines/inProcess.ts): without it, the location is not known.
- const pi = await loadEngine('pi')
- if (!pi) throw new Error('The Pi conversation location is unavailable.')
- const { piSessionFolder, readPiHead } = pi
+ if (!opts?.cwd || !PI_SESSION_ID.test(sessionId)) throw new Error('The Pi conversation location is unavailable.')
+ // The folder and header are native identity, available even when Pi's history reader cannot load.
const directory = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(opts.cwd))
let files: string[]
try { files = await readdir(directory) } catch (error) {
diff --git a/cli/src/lib/sessionSearch/externals/pi.ts b/cli/src/lib/sessionSearch/externals/pi.ts
index 9c9863604..025d78261 100644
--- a/cli/src/lib/sessionSearch/externals/pi.ts
+++ b/cli/src/lib/sessionSearch/externals/pi.ts
@@ -19,26 +19,19 @@ import { externalReadFailed } from '../evidence.js'
import { stat } from 'node:fs/promises'
import { homedir } from 'node:os'
-import { isAbsolute, join, resolve } from 'node:path'
+import { isAbsolute, join } from 'node:path'
+import { PI_FOLDER, PI_HEADER } from '../../../engines/pi/contract.js'
+import { readSessionHeader, sessionFolder, type NativeSessionHead } from '../../../engines/kit/sessionIdentity.js'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch, resumeSessionId } from '../../tmux.js'
import { forEachLine } from '../../transcriptLines.js'
-import { absoluteFolder, entries, fileStamp, parseLine, readHead, readJson, readTail, record, text } from './support.js'
+import { 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'
-/** How much of a file is read for its header first: headers are a few hundred bytes. */
-const FIRST_BYTES = 16 * 1024
-/** Pi's own bound on a header: a larger first entry is not a session. */
-const HEAD_BYTES = 1024 * 1024
/** Enough of a header to see its version, which a migration rewrites. */
const LEAD_BYTES = 256
const TAIL_BYTES = 64 * 1024
-/**
- * Pi's rule for an id (`--session-id` takes any such), kept to what Harness takes as one: 2 to 128
- * characters. One that ends `.jsonl` is read by `--session` as a file path, so it cannot be resumed.
- */
-const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/
/**
* A process row carries no file identity, so the PATH walk behind a full ownership snapshot could
@@ -49,35 +42,19 @@ const NO_FILE_OWNERS: AgentCommandOwnershipSnapshot = {
agentCandidates: [], cursorAgentCandidates: [], grokCandidates: [],
}
-export interface PiHead { sessionId: string; cwd: string }
+export type PiHead = NativeSessionHead
/**
* A session file's id and folder, from its first entry. Blank and malformed lines before it are
* skipped, as Pi skips them; any other first entry means the file is not a session.
*/
export async function readPiHead(path: string): Promise<PiHead | null | typeof UNSETTLED> {
- for (const bytes of [FIRST_BYTES, HEAD_BYTES]) {
- const head = await readHead(path, bytes)
- // The last piece has no newline: an entry still being written, or one cut by the read.
- for (const line of head.split('\n').slice(0, -1)) {
- if (!line.trim()) continue
- const value = parseLine(line)
- if (value === null) continue
- const row = record(value)
- if (row?.type !== 'session') return null
- const id = text(row.id)
- const cwd = absoluteFolder(row.cwd)
- return SESSION_ID.test(id) && !id.endsWith('.jsonl') && cwd ? { sessionId: id, cwd: resolve(cwd) } : null
- }
- // The whole file, and no entry in it yet: its first one is still being written.
- if (Buffer.byteLength(head) < bytes) return UNSETTLED
- }
- return null
+ return readSessionHeader(PI_HEADER, bytes => readHead(path, bytes))
}
/** The folder Pi keeps a working directory's sessions in, named as Pi names it. */
export function piSessionFolder(cwd: string): string {
- return `--${cwd.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`
+ return sessionFolder(PI_FOLDER, cwd)
}
/** How far a title read got: where it stopped, the header's start then, and the name so far. */
diff --git a/cli/src/lib/sessionSearch/externals/types.ts b/cli/src/lib/sessionSearch/externals/types.ts
index d38204f55..ae68c5181 100644
--- a/cli/src/lib/sessionSearch/externals/types.ts
+++ b/cli/src/lib/sessionSearch/externals/types.ts
@@ -52,7 +52,8 @@ export interface ExternalSession {
}
/** A file's head that cannot be judged yet: the engine is still writing its first lines. */
-export const UNSETTLED: unique symbol = Symbol('unsettled')
+export { UNSETTLED } from '../../../engines/kit/sessionIdentity.js'
+import { UNSETTLED } from '../../../engines/kit/sessionIdentity.js'
export interface ScanContext {
/** `read`, run again only when `fingerprint` (a file's size and time) changed since the last scan. */
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index a1a5ba544..827d26465 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -5,8 +5,11 @@ import { registry, type RegisteredSession } from './registry.js'
import { stoppedAgents } from './stoppedAgents.js'
import { AgentRestartCoordinator } from './restartAgent.js'
import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
+import { createForgetSession } from '../core/agents/forget.js'
+import { env } from '../config/env.js'
vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))
vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
+vi.mock('../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
let row: RegisteredSession
let deps: StopAgentServiceDeps
beforeEach(() => {
@@ -36,6 +39,32 @@ it('saves history before removing the runtime, joins concurrent stops, and clear
it('missing identities are harmless and never allocate or signal anything', async () => {
await createStopAgentService(deps)('missing'); expect(deps.forgetSession).not.toHaveBeenCalled(); expect(terminateDeletedAgent).not.toHaveBeenCalled()
})
+it.each(['forget', 'checkpoint'] as const)('retains a captured Pi resume path through a pathless %s save', async stage => {
+ Object.assign(row, { engine: 'pi', transcriptPath: null,
+ processIdentity: { pid: 77, executable: 'pi', startMarker: 'fixture' } })
+ vi.mocked(captureResumeIdentity).mockImplementation(async session => ({ ...session,
+ transcriptPath: '/fixture/native.jsonl', source: 'stop-repair' }))
+ deps.forgetSession = createForgetSession({
+ registry, stoppedAgents, syncRecapPool: vi.fn(), normalizers: { forget: vi.fn() },
+ forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
+ clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
+ runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
+ stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
+ dataDir: env.ADAPTER_DATA_DIR,
+ })
+ await createStopAgentService(deps)(row.agentId, { checkpoint: async (_session, phase) => {
+ if (stage === 'checkpoint' && phase === 'before') {
+ // A hook can save the same live row while Close awaits its checkpoint, before tombstones exist.
+ expect(row.transcriptPath).toBeNull()
+ stoppedAgents.save({ ...row, title: 'Hook arrived' })
+ expect(stoppedAgents.get(row.agentId)?.transcriptPath).toBe('/fixture/native.jsonl')
+ }
+ } })
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(stoppedAgents.get(row.agentId)).toMatchObject({ sessionId: row.sessionId,
+ transcriptPath: '/fixture/native.jsonl', active: false })
+})
it('cancels immediately, then joins the core pane commit before capturing the runtime to stop', async () => {
let committed!: () => void
deps.settlePane = vi.fn(() => new Promise<void>(done => { committed = done }))
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index 0c0802b53..fb6bc580b 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -415,6 +415,36 @@ it('an unbound observation of the same process keeps its confirmed conversation'
store.save({ ...saved, sessionId: '', transcriptPath: null, title: 'Renamed', boundAt: null, source: null })
expect(store.get(saved.agentId)).toMatchObject({ sessionId: saved.sessionId, transcriptPath: '/history.jsonl', title: 'Renamed', boundAt: 1, source: 'hook' })
})
+it('a pathless observation of the same conversation keeps its captured native path', async () => {
+ const { saved, store } = await fixture()
+ saved.hermesHome = '/fixture/hermes'
+ store.save({ ...saved, transcriptPath: '/history.jsonl', source: 'stop-repair' })
+ store.save({ ...saved, transcriptPath: null, title: 'A newer title', source: 'hook' })
+ expect(store.get(saved.agentId)).toMatchObject({ sessionId: saved.sessionId,
+ transcriptPath: '/history.jsonl', title: 'A newer title', source: 'hook' })
+ store.save({ ...saved, transcriptPath: '/replacement.jsonl' })
+ expect(store.get(saved.agentId)?.transcriptPath).toBe('/replacement.jsonl')
+})
+it.each(['agent', 'conversation', 'engine', 'registration', 'profile', 'hermes home', 'missing process', 'pid', 'start', 'ticks', 'executable'])
+('never transfers a captured path across a changed identity: %s', async mode => {
+ const { saved, store } = await fixture()
+ saved.processIdentity!.startTicks = 100
+ store.save({ ...saved, transcriptPath: '/history.jsonl' })
+ const next: RegisteredSession = { ...saved, transcriptPath: null, processIdentity: { ...saved.processIdentity! } }
+ if (mode === 'agent') next.agentId = 'another-agent'
+ if (mode === 'conversation') next.sessionId = 'another-conversation'
+ if (mode === 'engine') next.engine = 'claude'
+ if (mode === 'registration') next.registeredAt++
+ if (mode === 'profile') next.codexHome = '/another/profile'
+ if (mode === 'hermes home') next.hermesHome = '/another/hermes'
+ if (mode === 'missing process') next.processIdentity = null
+ if (mode === 'pid') next.processIdentity!.pid++
+ if (mode === 'start') { delete next.processIdentity!.startTicks; next.processIdentity!.startMarker = 'new' }
+ if (mode === 'ticks') next.processIdentity!.startTicks = 200
+ if (mode === 'executable') next.processIdentity!.executable = 'other'
+ store.save(next)
+ expect(store.get(next.agentId)?.transcriptPath).toBeNull()
+})
it.each(['engine', 'missing', 'previous missing', 'pid', 'start', 'executable'])('does not transfer a binding to a different process: %s', async mode => {
const { saved, store } = await fixture()
store.save(mode === 'previous missing' ? { ...saved, processIdentity: null } : saved)
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 27458f638..acca5cea9 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -122,6 +122,18 @@ export class StoppedAgentStore {
session = { ...session, sessionId: previous.sessionId, transcriptPath: previous.transcriptPath,
boundAt: previous.boundAt, source: previous.source }
}
+ // With optional readers absent, Stop can capture a path the live row has not learned.
+ // Hooks during its checkpoint and the final forget both save that pathless row. They
+ // must not erase the captured path, or Close succeeds but Resume loses the conversation.
+ if (session.sessionId && !session.transcriptPath && previous?.transcriptPath
+ && session.sessionId === previous.sessionId && session.engine === previous.engine
+ && session.registeredAt === previous.registeredAt
+ && (session.codexHome ?? null) === (previous.codexHome ?? null)
+ && (session.hermesHome ?? null) === (previous.hermesHome ?? null)
+ && sameProcessIdentity(session.processIdentity, previous.processIdentity)
+ && session.processIdentity!.executable === previous.processIdentity!.executable) {
+ session = { ...session, transcriptPath: previous.transcriptPath }
+ }
secureStateDirectory(dirname(this.directory))
secureStateDirectory(this.directory)
const snapshot = {
diff --git a/docs/research/2026-10-09-eager-repair.md b/docs/research/2026-10-09-eager-repair.md
new file mode 100644
index 000000000..3e6c1900a
--- /dev/null
+++ b/docs/research/2026-10-09-eager-repair.md
@@ -0,0 +1,19 @@
+# Eager Muse and Pi repair
+
+Muse discovery and Pi's lookup at Close were the remaining optional-engine imports in `lib/sessionRepair.ts`. Native conversation identity must be available before interpretation loads. The new declarations name the record fields, run marker, header limits and folder encoding; the eager kit reads them. Pi's optional search provider delegates to the same header parser while retaining its own read-failure evidence and unsettled-header memo semantics.
+
+The former-code golden was recorded from main `d81fea66b526bee3ab2e7612d7c407ed55e1bd66` in separate commit `38717f6c0`. Its 47 observations include scheduled Muse runs with no prompt, task/reminder rejection, subagents, ambiguous conversations, custom Pi header IDs, incomplete headers, wrong first entries, lossy folder collisions, duplicate exact IDs and the refusal that keeps an unreadable Pi conversation open. Linux, UTC, clock, file times and disposable homes are pinned. It invokes no host engine binary. The golden fixture remains unchanged after the move.
+
+Muse formerly read an entire transcript on each repair. It now reads 64 KiB, expanding to 4 MiB only when necessary. If a relevant file exceeds the bound without establishing its identity, discovery holds with the reason; it never assumes that the file is absent and selects a competing session. A file known to belong to another workspace cannot hold this lookup. Native I/O failures also preserve uncertainty. The discovery boundary contains these refusals so that another agent and daemon readiness can proceed; Stop/Close still receive the refusal before destructive work. Independent review identified that boundary requirement, and the regression drives the real reconciler through a held Muse process followed by a bindable process.
+
+The older Claude/Codex session-store golden had a separate fixture defect: its second platform pass used a later real clock against the files created for the first pass. Under load, those files aged past the five-second process-start slack. The unchanged main test passed alone. Its fixture clock and stat birth/mtime are now pinned; its recorded JSON is unchanged.
+
+A local cost comparison used the same Node 22.23.2 toolchain on macOS x64, one synthetic transcript of about 64 MiB, its workspace header and run marker first, and 4,096 output records afterward. Ten sequential `findLiveSession` calls were measured after importing the module, in fresh Node processes with disposable homes. Before the move: 913.3 ms elapsed, 993.2 ms CPU, 752.4 MiB process peak RSS. After: 9.8 ms elapsed, 10.7 ms CPU, 90.5 MiB peak RSS. Peak RSS includes the whole process; this is one controlled workload, not a startup benchmark or a new performance gate.
+
+Private-daemon acceptance removes or stalls the Muse/Pi optional chunks. It covers a scheduled Muse run binding, Pi's preallocated ID closing before a first reply, an incomplete Pi file keeping its process active, and a written Pi conversation closing and resuming with its exact ID. There is no vendor login or synthetic input to an owner's daemon. Mutation checks break the declarations, reader independence, read bound and discovery containment; only assertion failures count.
+
+That acceptance exposed a persistence bug masked by reader attachment: Stop captured and saved Pi's native path, then final retirement saved the still-pathless live row over it. Close succeeded but Resume refused the lost path. A hook could make the same destructive save while Stop awaited its checkpoint. Saved native paths now survive pathless observations only for the same agent, engine, registration, conversation, profile homes and exact process identity. A new known path still replaces the old one; changed identities inherit nothing. Regression tests combine the real Stop, forget and stopped-record store at both save boundaries, with process termination mocked. Additional mutations check that preservation cannot be removed or carried across a different conversation or process.
+
+Two existing Pi compatibility limits are separate from this move. Process-argument discovery accepts a narrower ID syntax than Pi's header reader; broadening it changes the argv golden and search-owner claims. Also, a preallocated ID with no native file can Close with its screen saved, but the resume guard still requires a native conversation file. The acceptance uses ordinary generated IDs and resumes a written conversation. These behaviors need explicit compatibility work rather than silently changing the extraction's golden.
+
+The broader native tree scan and remaining whole-file sidecar/process reads still need bounds and an ambiguity audit. Eager OpenCode launch, Stop/turn-closing facts, Cursor task cleanup and submission declarations also remain. This change completes the eager repair imports, not the full session-control audit.