Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve worktrees when recovery or runtime evidence is uncertain
DavidShen4cdc41fe6c9a
diff --git a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.tsindex d4ea9a0257..e8dd80e076 100644--- a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts@@ -208,7 +208,7 @@ describe('user rename notification ordering', () => {// patchSessionMetaInDb(device-link 远程改名)['if (patch.title !== undefined) noteUserTitleWritten(sessionId);',- 'withStatusWriteLock(sessionId, patch.status, async () => {',+ 'withStatusWriteLock(db, sessionId, patch.status, async () => {',],// renameSessionTitlesInDb(MCP 批量改名)[diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.tsindex bd62e084a3..1d916de904 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -234,6 +234,20 @@ describe('shared worktree recycling', () => {expect(await recycle()).toBe(false);expect(archive).not.toHaveBeenCalled();});+ it('preserves indexed submodules before creating incomplete recovery evidence', async () => {+ const originalGit = git.getMockImplementation()!;+ git.mockImplementation(async (args: string[]) => args.includes('--stage')+ ? { stdout: `160000 ${'a'.repeat(40)} 0\tchild\0` } : originalGit(args));+ expect(await recycle()).toBe(false);+ expect(archive).not.toHaveBeenCalled();+ expect(state.registry.has(meta.sessionId)).toBe(true);+ });+ it('preserves submodule metadata even after its gitlink was removed from the index', async () => {+ await fs.mkdir(path.join(meta.baseRepo, '.git', 'worktrees', 'one', 'modules', 'child'), { recursive: true });+ expect(await recycle()).toBe(false);+ expect(archive).not.toHaveBeenCalled();+ expect(state.registry.has(meta.sessionId)).toBe(true);+ });it('rejects a Git link pointing at another repository', async () => {const originalGit = git.getMockImplementation()!;git.mockImplementation(async (args: string[], cwd: string) => args.includes('--git-common-dir') && cwd === meta.pathdiff --git a/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.ts b/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.tsnew file mode 100644index 0000000000..8721339f74--- /dev/null+++ b/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.ts@@ -0,0 +1,193 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import type { LocalWorktreeReference } from '../localDb/worker/worktreeReferences';+import type { WorktreeMeta } from '../worktree/types';++const state = vi.hoisted(() => ({+ root: '',+ rows: [] as LocalWorktreeReference[],+ metas: [] as WorktreeMeta[],+}));+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));+vi.mock('../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../localDb/client/current', () => ({+ getDbClient: () => ({ readLocalWorktreeReferences: async () => state.rows }),+}));+vi.mock('../worktree/runtimeLeases', () => ({ readWorktreeRuntimePaths: async () => new Set() }));+vi.mock('../worktree/worktreeStore', () => ({ getAll: () => state.metas }));++import { hasLiveSessionReference, loadLiveSessionPathKeys } from '../worktree/liveSessionRefs';+import { readPiSubagentWorktreeReferences } from '../worktree/piSubagentReferences';++describe('detached Pi Subagent worktree references', () => {+ let worktree: string;+ const runRoot = (sessionId = 'parent') => path.join(+ state.root, 'pi-agent-home', 'runtime', 'pi-subagent-runs', sessionId,+ );+ const writeRun = async (sessionId = 'parent', config: unknown = { version: 1, cwd: worktree, tasks: [{}] }) => {+ const directory = path.join(runRoot(sessionId), 'durable-generation');+ await fs.mkdir(directory, { recursive: true });+ await fs.writeFile(path.join(directory, 'config.json'), JSON.stringify(config));+ return directory;+ };+ const livePaths = () => loadLiveSessionPathKeys({ excludeSessionId: 'parent', isSessionRuntimeAlive: () => false });+ const protects = async (target = worktree) => hasLiveSessionReference({ path: target }, await livePaths());++ beforeEach(async () => {+ state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-pi-refs-'));+ worktree = path.join(state.root, 'repo', '.cindy-worktrees', 'original');+ await fs.mkdir(worktree, { recursive: true });+ state.rows = [{+ id: 'parent', status: 'archived', source: 'desktop', currentDatabase: true,+ workingDir: worktree, worktreePath: worktree,+ }];+ state.metas = [];+ });+ afterEach(async () => {+ vi.restoreAllMocks();+ await fs.rm(state.root, { recursive: true, force: true });+ });++ it('allows the excluded terminal parent without durable runs to be recycled', async () => {+ expect(await protects()).toBe(false);+ await fs.mkdir(runRoot(), { recursive: true });+ expect(await protects()).toBe(false);+ });++ it('keeps an excluded archived parent after its root runtime lease has gone', async () => {+ await writeRun();+ expect(await protects()).toBe(true);+ });++ it.each(['completed', 'failed', 'cancelled'])('does not use %s or dead pid as proof that every child stopped', async (status) => {+ const run = await writeRun();+ await fs.writeFile(path.join(run, 'status.json'), JSON.stringify({ state: status, pid: 99999999, heartbeatAt: 0 }));+ expect(await protects()).toBe(true);+ });++ it('protects the old and child-specific cwd after the parent switches to an ordinary directory', async () => {+ const childDir = path.join(state.root, 'other-repo', '.xdt-worktrees', 'child');+ const currentDir = path.join(state.root, 'ordinary-project');+ state.rows[0] = { ...state.rows[0], workingDir: currentDir, worktreePath: null };+ await writeRun('parent', { version: 1, cwd: worktree, tasks: [{ cwd: childDir }] });+ expect(await protects()).toBe(true);+ expect(await protects(childDir)).toBe(true);+ expect(await protects(currentDir)).toBe(true);+ });++ it('preserves current and registered parent paths as well as the durable cwd', async () => {+ const registered = path.join(state.root, 'repo', '.cindy-worktrees', 'registered');+ state.metas = [{+ sessionId: 'parent', path: registered, name: 'registered', baseRepo: path.dirname(path.dirname(registered)),+ branch: 'cindy/registered', sourceBranch: 'main', createdAt: '2026-09-08T00:00:00.000Z',+ }];+ await writeRun('parent', { version: 1, cwd: path.join(state.root, 'old-project'), tasks: [{}] });+ expect(await protects()).toBe(true);+ expect(await protects(registered)).toBe(true);+ });++ it('keeps durable cwd even when no parent database or registry row remains', async () => {+ state.rows = [];+ await writeRun('orphaned-parent');+ expect(await protects()).toBe(true);+ });++ it('keeps terminal parent references from another local database', async () => {+ state.rows[0] = { ...state.rows[0], currentDatabase: false, status: 'deleted' };+ await writeRun('parent', { version: 1, cwd: path.join(state.root, 'other-cwd'), tasks: [{}] });+ expect(await protects()).toBe(true);+ });++ it.each([+ { version: 2, cwd: '/unknown-format', tasks: [] },+ { version: 1, cwd: 'relative-cwd', tasks: [] },+ { version: 1, tasks: [] },+ { version: 1, cwd: '/root', tasks: [{ cwd: 42 }] },+ ])('preserves all worktrees when a durable config cannot establish every cwd', async (config) => {+ await writeRun('parent', config);+ expect(await livePaths()).toBeNull();+ expect(await protects()).toBe(true);+ });++ it('does not filter out unfinished or malformed run directories', async () => {+ await fs.mkdir(path.join(runRoot(), 'not-a-uuid'), { recursive: true });+ expect(await livePaths()).toBeNull();+ });++ it('preserves when the durable directory cannot be read', async () => {+ await writeRun();+ const readdir = fs.readdir;+ vi.spyOn(fs, 'readdir').mockImplementation(((directory: Parameters<typeof fs.readdir>[0], ...args: unknown[]) => {+ if (String(directory) === runRoot()) {+ return Promise.reject(Object.assign(new Error('permission denied'), { code: 'EACCES' }));+ }+ return Reflect.apply(readdir, fs, [directory, ...args]);+ }) as typeof fs.readdir);+ expect(await livePaths()).toBeNull();+ });++ it('preserves when config disappears or becomes corrupt during the read', async () => {+ const run = await writeRun();+ await fs.writeFile(path.join(run, 'config.json'), '{');+ expect(await readPiSubagentWorktreeReferences()).toBeNull();+ await fs.unlink(path.join(run, 'config.json'));+ expect(await readPiSubagentWorktreeReferences()).toBeNull();+ });++ it.each(['root', 'session', 'run'])('preserves when a %s directory redirects through a junction', async (level) => {+ const redirected = level === 'root' ? path.dirname(runRoot())+ : level === 'session' ? runRoot() : path.join(runRoot(), 'durable-generation');+ const target = path.join(state.root, 'redirect-target');+ await fs.mkdir(target);+ await fs.mkdir(path.dirname(redirected), { recursive: true });+ await fs.symlink(target, redirected, process.platform === 'win32' ? 'junction' : 'dir');+ expect(await livePaths()).toBeNull();+ });++ it('preserves when the config path is a link', async () => {+ const run = await writeRun();+ const configFile = path.join(run, 'config.json');+ const lstat = fs.lstat;+ vi.spyOn(fs, 'lstat').mockImplementation((async (file: Parameters<typeof fs.lstat>[0]) => {+ const stat = await lstat(file);+ if (String(file) === configFile) stat.isSymbolicLink = () => true;+ return stat;+ }) as typeof fs.lstat);+ expect(await livePaths()).toBeNull();+ });++ it.each(['root', 'session', 'run'])('preserves when %s entries change while being read', async (level) => {+ const run = await writeRun();+ const changedDirectory = level === 'root' ? path.dirname(runRoot()) : level === 'session' ? runRoot() : run;+ const readdir = fs.readdir;+ let reads = 0;+ vi.spyOn(fs, 'readdir').mockImplementation(((directory: Parameters<typeof fs.readdir>[0], ...args: unknown[]) => {+ if (String(directory) === changedDirectory && ++reads === 2) {+ return Promise.resolve(['changed-after-first-read']);+ }+ return Reflect.apply(readdir, fs, [directory, ...args]);+ }) as typeof fs.readdir);+ expect(await livePaths()).toBeNull();+ });++ it('does not confuse a root disappearing during enumeration with an absent root', async () => {+ await writeRun();+ const root = path.dirname(runRoot());+ const readdir = fs.readdir;+ vi.spyOn(fs, 'readdir').mockImplementation(((directory: Parameters<typeof fs.readdir>[0], ...args: unknown[]) => {+ if (String(directory) === root) return Promise.reject(Object.assign(new Error('gone'), { code: 'ENOENT' }));+ return Reflect.apply(readdir, fs, [directory, ...args]);+ }) as typeof fs.readdir);+ expect(await livePaths()).toBeNull();+ });++ it('does not treat a redirected agent home without a run root as absence', async () => {+ const target = path.join(state.root, 'redirect-target');+ await fs.mkdir(target);+ await fs.symlink(target, path.join(state.root, 'pi-agent-home'), process.platform === 'win32' ? 'junction' : 'dir');+ expect(await livePaths()).toBeNull();+ });+});diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.tsindex 6949186f95..0340b15655 100644--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts@@ -22,7 +22,9 @@ vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorvi.mock('../worktree/runtimeLeases', () => ({ readWorktreeRuntimePaths: async () => new Set() }));vi.mock('../worktree/gitExec', async (original) => {const actual = await original<typeof import('../worktree/gitExec')>();- return { ...actual, gitExec: vi.fn(actual.gitExec) };+ return { ...actual, gitExec: vi.fn<typeof actual.gitExec>((args, cwd, options) => actual.gitExec(args, cwd, {+ ...options, extraEnv: { ...options?.extraEnv, GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'), GIT_CONFIG_NOSYSTEM: '1' },+ })) };});import { recycleManagedWorktree } from '../worktree/managedRecycle';@@ -86,6 +88,7 @@ describe('worktree recovery with real Git and encrypted archives', () => {expect(archivedTree).not.toContain('untracked.txt');expect(await restoreRecordedWorktree(meta.sessionId, worktree)).toBe(true);expect(await git(worktree, 'rev-parse', 'HEAD')).toBe(head);+ await expect(git(worktree, 'symbolic-ref', '--quiet', 'HEAD')).rejects.toThrow();expect(await git(worktree, 'show', ':tracked.txt')).toBe('staged');expect(await fs.readFile(path.join(worktree, 'tracked.txt'), 'utf8')).toBe('unstaged\n');expect(await fs.readFile(path.join(worktree, '.env'), 'utf8')).toBe('INVALID_TEST_SECRET=keep-me\n');@@ -95,6 +98,42 @@ describe('worktree recovery with real Git and encrypted archives', () => {expect((await readRecycleRecord(worktree))?.phase).toBe('restored');}, 60_000);+ it('restores an attached branch and advances it with subsequent commits', async () => {+ const meta = await createFixture('attached');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ expect((await readRecycleRecord(meta.path))?.snapshot?.headRef).toBe('refs/heads/cindy/attached');+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);+ expect(await git(meta.path, 'symbolic-ref', 'HEAD')).toBe('refs/heads/cindy/attached');+ await git(meta.path, 'add', 'draft.txt');+ await git(meta.path, 'commit', '-m', 'continue restored work');+ expect(await git(repo, 'rev-parse', 'cindy/attached')).toBe(await git(meta.path, 'rev-parse', 'HEAD'));+ }, 30_000);++ it('keeps an advanced branch and its missing worktree untouched', async () => {+ const meta = await createFixture('advanced');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ const { stdout } = await exec('git', ['commit-tree', 'HEAD^{tree}', '-p', 'HEAD', '-m', 'external advance'], {+ cwd: repo, windowsHide: true, env: { ...process.env, GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'), GIT_CONFIG_NOSYSTEM: '1' },+ });+ const advanced = stdout.trim();+ await git(repo, 'update-ref', 'refs/heads/cindy/advanced', advanced);+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(false);+ expect(await git(repo, 'rev-parse', 'cindy/advanced')).toBe(advanced);+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });+ }, 30_000);++ it('does not take a saved branch from another worktree', async () => {+ const meta = await createFixture('occupied');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ const elsewhere = path.join(state.root, 'branch-occupant');+ await git(repo, 'worktree', 'add', elsewhere, 'cindy/occupied');+ await fs.writeFile(path.join(elsewhere, 'user-edit.txt'), 'keep occupant\n');+ await expect(restoreRecordedWorktree(meta.sessionId, meta.path)).rejects.toThrow();+ expect(await git(elsewhere, 'symbolic-ref', 'HEAD')).toBe('refs/heads/cindy/occupied');+ expect(await fs.readFile(path.join(elsewhere, 'user-edit.txt'), 'utf8')).toBe('keep occupant\n');+ expect(state.registry.has(meta.sessionId)).toBe(false);+ }, 30_000);+it('taking a snapshot never modifies the original index or working files', async () => {const worktree = path.join(repo, '.cindy-worktrees', 'snapshot');await git(repo, 'worktree', 'add', '-b', 'cindy/snapshot', worktree, 'main');@@ -171,4 +210,28 @@ describe('worktree recovery with real Git and encrypted archives', () => {expect(await restoreRecordedWorktree(previous.sessionId, previous.path)).toBe(true);expect(await fs.readFile(path.join(previous.path, 'draft.txt'), 'utf8')).toBe('history contents\n');}, 30_000);++ it('preserves submodule-only commits whose Git objects lie outside the archived directory', async () => {+ const origin = path.join(state.root, 'child-origin');+ await fs.mkdir(origin);+ await git(origin, 'init', '-b', 'main');+ await git(origin, 'config', 'user.name', 'Recovery Test');+ await git(origin, 'config', 'user.email', 'recovery-test@localhost');+ await fs.writeFile(path.join(origin, 'child.txt'), 'base\n');+ await git(origin, 'add', '.'); await git(origin, 'commit', '-m', 'child fixture');+ const meta = await createFixture('submodule');+ await git(meta.path, '-c', 'protocol.file.allow=always', 'submodule', 'add', origin, 'child');+ await git(meta.path, 'commit', '-am', 'add child');+ const child = path.join(meta.path, 'child');+ await git(child, 'config', 'user.name', 'Recovery Test');+ await git(child, 'config', 'user.email', 'recovery-test@localhost');+ await fs.writeFile(path.join(child, 'child.txt'), 'child-only work\n');+ await git(child, 'commit', '-am', 'child-only commit');+ const childHead = await git(child, 'rev-parse', 'HEAD');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(false);+ expect(state.registry.has(meta.sessionId)).toBe(true);+ expect(await git(child, 'rev-parse', 'HEAD')).toBe(childHead);+ expect(await fs.readFile(path.join(child, 'child.txt'), 'utf8')).toBe('child-only work\n');+ expect((await readRecycleRecord(meta.path))?.archive).toBeUndefined();+ }, 30_000);});diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex 229b6bccaf..131bae701f 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -26,14 +26,38 @@ describe('worktree runtime evidence and physical locks', () => {});it('publishes a root lease before using a descendant and wakes retries only on actual release', async () => {- await acquireWorktreeRuntimeLease('one', path.join(worktree, 'src'));+ const lease = (await acquireWorktreeRuntimeLease('one', path.join(worktree, 'src')))!;expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));- await releaseWorktreeRuntimeLease('one');- await releaseWorktreeRuntimeLease('one');+ await releaseWorktreeRuntimeLease(lease);+ await releaseWorktreeRuntimeLease(lease);expect(await readWorktreeRuntimePaths()).toEqual(new Set());expect(notify).toHaveBeenCalledOnce();});+ it('keeps the replacement runtime protected when an older close finishes late', async () => {+ const oldLease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ const replacementLease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ expect(oldLease.file).not.toBe(replacementLease.file);+ await releaseWorktreeRuntimeLease(oldLease);+ await releaseWorktreeRuntimeLease(oldLease);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ await releaseWorktreeRuntimeLease(replacementLease);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('cleans only the failed acquisition when publishing a replacement lease fails', async () => {+ const oldLease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ const write = fs.writeFile.bind(fs);+ vi.spyOn(fs, 'writeFile').mockImplementationOnce(async (...args) => {+ await write(...args);+ throw Object.assign(new Error('lease write interrupted'), { code: 'EIO' });+ });+ await expect(acquireWorktreeRuntimeLease('one', worktree)).rejects.toThrow('lease write interrupted');+ expect(await fs.readdir(path.dirname(oldLease.file))).toEqual([path.basename(oldLease.file)]);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ await releaseWorktreeRuntimeLease(oldLease);+ });+it('preserves when another live instance cannot publish runtime evidence', async () => {vi.spyOn(process, 'kill').mockReturnValue(true);await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242 }));@@ -55,6 +79,25 @@ describe('worktree runtime evidence and physical locks', () => {expect(await readWorktreeRuntimePaths()).toBeNull();});+ it('keeps a crashed owner lease protective because its child may still run', async () => {+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ vi.spyOn(process, 'kill').mockImplementation(() => {+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });+ });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ await releaseWorktreeRuntimeLease(lease);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('does not treat a crashed owner partial lease as evidence of an idle directory', async () => {+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ await fs.writeFile(lease.file, '{');+ vi.spyOn(process, 'kill').mockImplementation(() => {+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });+ });+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });+it('serializes independent callers and allows a nested call in the same operation', async () => {let release!: () => void;let entered!: () => void;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex 4746e0ac6c..50766917c5 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -5,6 +5,8 @@* 一条条件 UPDATE 同时校验 archived 状态和项目身份,不能用 get + update 两步校验。*/import Database from 'better-sqlite3';+import os from 'node:os';+import path from 'node:path';import { drizzle } from 'drizzle-orm/better-sqlite3';import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';@@ -19,6 +21,7 @@ const h = vi.hoisted(() => ({sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,handlers: new Map<string, (...args: unknown[]) => unknown>(),tapWindowBroadcast: vi.fn(),+ resourceLock: vi.fn(async (_resources: readonly string[], task: () => Promise<unknown>) => task()),routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>task(),) as SessionRouteLockMock,@@ -52,6 +55,11 @@ vi.mock('../../../device-link/broadcast-tap.js', () => ({vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));+vi.mock('../../../worktree/resourceLock', () => ({+ physicalWorktreeKey: async (value: string) => value,+ withWorktreeResourceLocks: h.resourceLock,+}));+vi.mock('../../../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportunity: vi.fn() }));import { registerSessionIpc } from '../sessions';import { setSessionRouteLockImplementation } from '../../sessionRouteLock';@@ -161,6 +169,7 @@ function readStatus(): string {beforeEach(() => {vi.clearAllMocks();h.routeLock.mockImplementation(async (_sessionId, task) => task());+ h.resourceLock.mockImplementation(async (_resources, task) => task());h.handlers.clear();createDb();setSessionRouteLockImplementation(h.routeLock);@@ -172,6 +181,61 @@ afterEach(() => {});describe('local-db:sessions:restore-if-archived', () => {+ function managedIdentity(): ExpectedIdentity {+ const root = path.join(os.tmpdir(), 'cindy-restore-lock-fixture', '.cindy-worktrees', 'work');+ const workingDir = path.join(root, 'src');+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ?, worktree_path = ? WHERE id = ?')+ .run(workingDir, root, 'target');+ return { ...ORIGINAL_IDENTITY, workingDir };+ }++ it('waits for a recycler holding the physical worktree lock before making the task active', async () => {+ const identity = managedIdentity();+ let acquired!: () => void;+ const waiting = new Promise<void>((resolve) => { acquired = resolve; });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ h.resourceLock.mockImplementationOnce(async (_resources, task) => {+ acquired();+ await gate;+ return task();+ });++ const restoring = restore('target', identity);+ await waiting;+ expect(readStatus()).toBe('archived');+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ expect(h.resourceLock).toHaveBeenCalledWith(+ expect.arrayContaining([path.dirname(identity.workingDir!)]), expect.any(Function),+ );+ release();+ await expect(restoring).resolves.toMatchObject({ status: 'active' });+ });++ it('publishes active status before a later recycler can enter the resource lock', async () => {+ const identity = managedIdentity();+ let entered!: () => void;+ const waiting = new Promise<void>((resolve) => { entered = resolve; });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ let tail = Promise.resolve<unknown>(undefined);+ h.resourceLock.mockImplementation((_resources, task) => {+ const next = tail.then(task);+ tail = next;+ return next;+ });+ // Hold the first lock holder long enough to enqueue both the restore and a later recycler.+ const blocker = h.resourceLock([], async () => { entered(); await gate; });+ await waiting;+ const restoring = restore('target', identity);+ await vi.waitFor(() => expect(h.resourceLock).toHaveBeenCalledTimes(2));+ const canRecycle = h.resourceLock([], async () => readStatus() === 'archived');+ release();+ await blocker;+ await expect(restoring).resolves.toMatchObject({ status: 'active' });+ await expect(canRecycle).resolves.toBe(false);+ });+it('restores when archived status and the full project identity still match', async () => {const updated = (await restore()) as { id: string; status: string };diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 41879ec56d..6fa45d2051 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1539,7 +1539,7 @@ export function registerSessionIpc(}const db = getDbClient().drizzle;- const updated = await withSessionRouteLock(sid, async () => {+ const updated = await withStatusWriteLock(db, sid, 'active', async () => {if (!isOwnerScopeCurrent(ownerScope)) return null;await assertGenericSessionLifecycleAllowed(db, sid);// 显式 .run() 才能从生产 DbClient.drizzle proxy 拿到 changes;隐式 awaitdiff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 830f56fa2c..d59c5241d4 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -9,7 +9,7 @@*/import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval.js';-import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from '../worktree/runtimeLeases';+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, type WorktreeRuntimeLease } from '../worktree/runtimeLeases';import { readCodexContextWindowInfo } from './codex-context-window.js';import { app, BrowserWindow } from 'electron';import { createHash } from 'node:crypto';@@ -333,6 +333,8 @@ type RemoteCcQuery = Awaited<let _maker: Maker | null = null;/** Prepared Bot runtime records waiting for the matching Maker startup result. */const pendingBotRuntimeSnapshots = new Map<string, BotProfileRuntimeSnapshot>();+// Maker copies start options for every runtime, including rebuilds of one task.+const worktreeRuntimeLeases = new WeakMap<object, WorktreeRuntimeLease>();let botRuntimeResourcePreflight:| ((opts: MakerSessionCreateOpts) => Promise<BotProfileRuntimeSnapshot | null>)| null = null;@@ -2416,7 +2418,8 @@ export function getMaker(): Maker {createOpts.id ??= sessionId;await prepareBotWorkspaceRuntime(createOpts);if (!createOpts.remoteHostId && createOpts.workingDir) {- await acquireWorktreeRuntimeLease(sessionId, createOpts.workingDir);+ const lease = await acquireWorktreeRuntimeLease(sessionId, createOpts.workingDir);+ if (lease) worktreeRuntimeLeases.set(opts, lease);}let skillLinksChanged = false;if (!createOpts.remoteHostId && createOpts.workingDir) {@@ -2513,10 +2516,13 @@ export function getMaker(): Maker {}}},- onStartFailed: async ({ sessionId, stage, error }) => {- await releaseWorktreeRuntimeLease(sessionId).catch((error) => {- desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });- });+ onStartFailed: async ({ sessionId, options, stage, error, runtimeMayBeAlive }) => {+ const lease = worktreeRuntimeLeases.get(options);+ if (lease && !runtimeMayBeAlive) {+ await releaseWorktreeRuntimeLease(lease).catch((error) => {+ desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });+ });+ }const snapshot = pendingBotRuntimeSnapshots.get(sessionId);if (!snapshot) return;try {@@ -2532,14 +2538,25 @@ export function getMaker(): Maker {pendingBotRuntimeSnapshots.delete(sessionId);}},+ onStartCleanupSucceeded: async (sessionId, options) => {+ const lease = worktreeRuntimeLeases.get(options);+ if (lease) {+ await releaseWorktreeRuntimeLease(lease).catch((error) => {+ desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });+ });+ }+ },getCodexHistoryHasProductPrompt: (sessionId) => readCodexHistoryHasProductPrompt(sessionId),onCodexProductPromptDelivery: async ({ sessionId, historyHasProductPrompt }) => {await writeCodexHistoryHasProductPrompt(sessionId, historyHasProductPrompt);},- onClose: async (sessionId) => {- await releaseWorktreeRuntimeLease(sessionId).catch((error) => {- desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });- });+ onClose: async (sessionId, options) => {+ const lease = worktreeRuntimeLeases.get(options);+ if (lease) {+ await releaseWorktreeRuntimeLease(lease).catch((error) => {+ desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });+ });+ }// rehydrate close suppression 只跳过 worktree / temp file 这类重副作用;// registry 必须先清,后续 resume 会在首个 /responses 前重新登记,避免旧 thread prompt 驻留。unregisterCodexProxyPrompt(sessionId);diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 2cec6dab22..fd00311b23 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -1039,8 +1039,8 @@ async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktr// 后台跑全 checkout。fullCheckoutPromise 故意 fire-and-forget,// 失败仅日志, 不阻塞 IPC 返回。let bgPromise: Promise<void> | undefined;- const checkoutLease = `checkout:${req.sessionId}`;- await acquireWorktreeRuntimeLease(checkoutLease, worktreePath);+ const checkoutLease = await acquireWorktreeRuntimeLease(`checkout:${req.sessionId}`, worktreePath);+ if (!checkoutLease) throw new Error('managed checkout runtime lease is missing');try {const stageRes = await timed('stage checkout', () => stageCheckout(worktreePath));bgPromise = stageRes.fullCheckoutPromise.finally(() => releaseWorktreeRuntimeLease(checkoutLease));diff --git a/apps/desktop/src/main/worktree/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.tsindex 2dfe8cd080..285840aecc 100644--- a/apps/desktop/src/main/worktree/contentSnapshot.ts+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts@@ -3,7 +3,7 @@ import os from 'node:os';import path from 'node:path';import { createHash } from 'node:crypto';-import { gitExec } from './gitExec';+import { gitExec, GitExecError } from './gitExec';import type { WorktreeRecycleRecord } from './recycleJournal';async function indexHash(worktreePath: string): Promise<string> {@@ -11,12 +11,26 @@ async function indexHash(worktreePath: string): Promise<string> {return createHash('sha256').update(await fs.readFile(stdout.trim())).digest('hex');}+/** Distinguish a deliberately detached HEAD from an unreadable symbolic ref. */+export async function readWorktreeHeadRef(worktreePath: string): Promise<string | null> {+ try {+ const { stdout } = await gitExec(['symbolic-ref', '--quiet', 'HEAD'], worktreePath);+ const ref = stdout.trim();+ if (!ref.startsWith('refs/heads/')) throw new Error('unsupported worktree HEAD ref');+ return ref;+ } catch (error) {+ if (error instanceof GitExecError && error.exitCode === 1) return null;+ throw error;+ }+}+export async function worktreeContentBaselineMatches(worktreePath: string,snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,): Promise<boolean> {const { stdout } = await gitExec(['rev-parse', 'HEAD'], worktreePath);- return stdout.trim() === snapshot.head && await indexHash(worktreePath) === snapshot.indexHash;+ return stdout.trim() === snapshot.head && await indexHash(worktreePath) === snapshot.indexHash+ && (snapshot.headRef === undefined || await readWorktreeHeadRef(worktreePath) === snapshot.headRef);}/** Snapshot the actual HEAD, index and file tree without stashing or changing the live checkout. */@@ -30,6 +44,7 @@ export async function captureWorktreeContent(try {const { stdout: headOutput } = await gitExec(['rev-parse', '--verify', 'HEAD^{commit}'], worktreePath);const head = headOutput.trim();+ const headRef = await readWorktreeHeadRef(worktreePath);const { stdout: indexPath } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);await fs.copyFile(indexPath.trim(), index);const originalIndexHash = createHash('sha256').update(await fs.readFile(index)).digest('hex');@@ -54,7 +69,7 @@ export async function captureWorktreeContent();const commit = commitOutput.trim();await gitExec(['update-ref', ref, commit], worktreePath);- const snapshot = { head, tree, indexTree, commit, ref, indexHash: originalIndexHash };+ const snapshot = { head, headRef, tree, indexTree, commit, ref, indexHash: originalIndexHash };if (!(await worktreeContentBaselineMatches(worktreePath, snapshot))) throw new Error('worktree HEAD or index changed during snapshot');return snapshot;} finally {diff --git a/apps/desktop/src/main/worktree/liveSessionRefs.ts b/apps/desktop/src/main/worktree/liveSessionRefs.tsindex 8407ccc8d9..4e3cf7546f 100644--- a/apps/desktop/src/main/worktree/liveSessionRefs.ts+++ b/apps/desktop/src/main/worktree/liveSessionRefs.ts@@ -17,6 +17,7 @@ import fs from 'node:fs';import { getDbClient } from '../localDb/client/current';import { physicalWorktreeKey } from './resourceLock';import { readWorktreeRuntimePaths } from './runtimeLeases';+import { readPiSubagentWorktreeReferences } from './piSubagentReferences';import * as store from './worktreeStore';import { createLogger } from '../logger';@@ -66,18 +67,30 @@ export async function loadLiveSessionPathKeys(const rows = await db.readLocalWorktreeReferences();const runtimePaths = await readWorktreeRuntimePaths();if (!runtimePaths) return null;+ const subagentReferences = await readPiSubagentWorktreeReferences();+ if (!subagentReferences) return null;const keys = new Set(runtimePaths);+ // Config cwd can refer to an earlier workdir or a child-specific directory,+ // even after the parent row changes or disappears from the task database.+ for (const paths of subagentReferences.values()) {+ for (const value of paths) {+ keys.add(pathKey(value)!);+ keys.add(await physicalWorktreeKey(value));+ }+ }const knownSessionIds = new Set(rows.map((row) => row.id));for (const meta of store.getAll()) {- if (meta.sessionId !== opts.excludeSessionId && !knownSessionIds.has(meta.sessionId)) {+ if (subagentReferences.has(meta.sessionId)+ || (meta.sessionId !== opts.excludeSessionId && !knownSessionIds.has(meta.sessionId))) {keys.add(await physicalWorktreeKey(meta.path));}}for (const row of rows) {+ const hasSubagentRuns = subagentReferences.has(row.id);// The same id in another database is not the row the caller just closed.- if (row.currentDatabase && opts.excludeSessionId && row.id === opts.excludeSessionId) continue;+ if (!hasSubagentRuns && row.currentDatabase && opts.excludeSessionId && row.id === opts.excludeSessionId) continue;const isTerminal = row.status === 'archived' || row.status === 'deleted';- if (row.source !== 'bot' && isTerminal && (!row.currentDatabase || opts.isSessionRuntimeAlive?.(row.id) !== true)) {+ if (!hasSubagentRuns && row.source !== 'bot' && isTerminal && (!row.currentDatabase || opts.isSessionRuntimeAlive?.(row.id) !== true)) {continue;}const workingDirKey = pathKey(row.workingDir);diff --git a/apps/desktop/src/main/worktree/piSubagentReferences.ts b/apps/desktop/src/main/worktree/piSubagentReferences.tsnew file mode 100644index 0000000000..24b9e25369--- /dev/null+++ b/apps/desktop/src/main/worktree/piSubagentReferences.ts@@ -0,0 +1,100 @@+import fs from 'node:fs/promises';+import type { Stats } from 'node:fs';+import path from 'node:path';+import { app } from 'electron';+import { piSubagentRunRoot } from '@cindy/maker-core/pi-subagent-runs';++import { createLogger } from '../logger';++const log = createLogger('worktreePiRefs');++interface DirectorySnapshot {+ stat: Stats;+ entries: string[];+}++function sameFile(before: Stats, after: Stats): boolean {+ return !after.isSymbolicLink() && before.dev === after.dev && before.ino === after.ino+ && before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs;+}++async function readDirectory(directory: string): Promise<DirectorySnapshot> {+ const stat = await fs.lstat(directory);+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('redirected PI run directory');+ return { stat, entries: (await fs.readdir(directory)).sort() };+}++async function directoryUnchanged(directory: string, before: DirectorySnapshot): Promise<boolean> {+ const after = await readDirectory(directory);+ return sameFile(before.stat, after.stat) && before.entries.length === after.entries.length+ && before.entries.every((entry, index) => entry === after.entries[index]);+}++/**+ * Detached runners can outlive both the parent task and the owning Main process.+ * Keep every durable generation, including terminal or stale ones: its status is+ * not proof that all children stopped, and resume reuses the recorded cwd.+ * This is an on-demand, read-only view; it never controls Pi processes.+ */+export async function readPiSubagentWorktreeReferences(): Promise<ReadonlyMap<string, readonly string[]> | null> {+ try {+ const agentHome = path.join(app.getPath('userData'), 'pi-agent-home');+ const root = path.dirname(piSubagentRunRoot(agentHome, 'worktree-reference-probe'));+ const ancestorStats = new Map<string, Stats>();+ for (const directory of [agentHome, path.dirname(root), root]) {+ let stat: Stats;+ try {+ stat = await fs.lstat(directory);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ for (const [ancestor, before] of ancestorStats) {+ if (!sameFile(before, await fs.lstat(ancestor))) return null;+ }+ return new Map();+ }+ if (stat.isSymbolicLink() || !stat.isDirectory()) return null;+ ancestorStats.set(directory, stat);+ }+ // Once the root exists, any subsequent ENOENT is a changed view, not absence.+ const rootSnapshot = await readDirectory(root);+ const references = new Map<string, readonly string[]>();+ for (const sessionId of rootSnapshot.entries) {+ const sessionRoot = piSubagentRunRoot(agentHome, sessionId);+ const sessionSnapshot = await readDirectory(sessionRoot);+ const paths = new Set<string>();+ for (const entry of sessionSnapshot.entries) {+ const runDirectory = path.join(sessionRoot, entry);+ const runSnapshot = await readDirectory(runDirectory);+ const configFile = path.join(runDirectory, 'config.json');+ const configStat = await fs.lstat(configFile);+ if (configStat.isSymbolicLink() || !configStat.isFile() || configStat.size > 2 * 1024 * 1024) return null;+ const config: unknown = JSON.parse(await fs.readFile(configFile, 'utf8'));+ if (!sameFile(configStat, await fs.lstat(configFile))) return null;+ if (!config || typeof config !== 'object' || Array.isArray(config)) return null;+ const value = config as Record<string, unknown>;+ if (value.version !== 1 || typeof value.cwd !== 'string' || !path.isAbsolute(value.cwd)+ || !Array.isArray(value.tasks)) return null;+ paths.add(value.cwd);+ for (const task of value.tasks) {+ if (!task || typeof task !== 'object' || Array.isArray(task)) return null;+ const cwd = (task as Record<string, unknown>).cwd;+ if (cwd === undefined) continue;+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return null;+ paths.add(cwd);+ }+ if (!(await directoryUnchanged(runDirectory, runSnapshot))) return null;+ }+ if (!(await directoryUnchanged(sessionRoot, sessionSnapshot))) return null;+ if (sessionSnapshot.entries.length) references.set(sessionId, [...paths]);+ }+ if (!(await directoryUnchanged(root, rootSnapshot))) return null;+ for (const [ancestor, before] of ancestorStats) {+ if (!sameFile(before, await fs.lstat(ancestor))) return null;+ }+ return references;+ } catch {+ // Configs can contain user content. Do not log parse errors or their excerpts.+ log.warn('PI Subagent worktree references are unreadable; preserving');+ return null;+ }+}diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.tsindex ba04c9ebc3..4670c7b04b 100644--- a/apps/desktop/src/main/worktree/recycleJournal.ts+++ b/apps/desktop/src/main/worktree/recycleJournal.ts@@ -24,7 +24,7 @@ export interface WorktreeRecycleRecord {nextAttemptAt: number;reason?: string;directoryIdentity?: string;- snapshot?: { head: string; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };+ snapshot?: { head: string; headRef?: string | null; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };restoredGeneration?: string;archive?: WorktreeRecoveryArchive;}diff --git a/apps/desktop/src/main/worktree/resourceSafety.ts b/apps/desktop/src/main/worktree/resourceSafety.tsindex 7f4c7bac4b..9d0b0edaeb 100644--- a/apps/desktop/src/main/worktree/resourceSafety.ts+++ b/apps/desktop/src/main/worktree/resourceSafety.ts@@ -49,4 +49,11 @@ export async function assertWorktreeGitIdentity(meta: WorktreeMeta): Promise<voiconst metadataRoot = path.join(await physicalWorktreeKey(common.trim()), 'worktrees');if (path.dirname(await physicalWorktreeKey(gitDir.trim())) !== metadataRoot) throw new Error('Git worktree metadata mismatch');for (const name of ['locked', 'index.lock', 'HEAD.lock']) await assertAbsent(path.join(gitDir.trim(), name));+ // A parent snapshot preserves gitlink OIDs, not the submodule's objects/index.+ // worktree remove --force deletes modules/ too, including child-only commits.+ await assertAbsent(path.join(gitDir.trim(), 'modules'));+ const { stdout: entries } = await gitExec(['ls-files', '--stage', '-z'], meta.path);+ if (entries.split('\0').some((entry) => entry.startsWith('160000 '))) {+ throw new Error('submodule recovery is not supported; preserving worktree');+ }}diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.tsindex 4c94cceeb6..fa96619602 100644--- a/apps/desktop/src/main/worktree/restoreRecovery.ts+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts@@ -12,6 +12,7 @@ import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRimport { assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';import * as store from './worktreeStore';import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';+import { readWorktreeHeadRef } from './contentSnapshot';async function indexIsRestorable(worktreePath: string, indexTree: string): Promise<boolean> {const { stdout } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);@@ -35,6 +36,8 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sif (!record?.snapshot || !record.archive || record.phase === 'restored' || record.phase === 'pending') return null;if ([record.snapshot.head, record.snapshot.tree, record.snapshot.indexTree, record.snapshot.commit].some((value) => typeof value !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value))) return false;+ const headRef = record.snapshot.headRef;+ if (headRef != null && (typeof headRef !== 'string' || !headRef.startsWith('refs/heads/'))) return false;if (await physicalWorktreeKey(record.meta.path) !== await physicalWorktreeKey(worktreePath)) return false;const registered = store.get(sessionId);if (registered && worktreeGeneration(registered) === record.restoredGeneration) {@@ -70,6 +73,11 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s}if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;await verifyRecoveryArchive(record.archive);+ if (headRef) {+ // Never reset a branch that advanced or was replaced while this task was archived.+ const { stdout: branchHead } = await gitExec(['rev-parse', '--verify', `${headRef}^{commit}`], record.meta.baseRepo);+ if (branchHead.trim() !== record.snapshot.head) return false;+ }if (!legacyGuardHeld()) return false;if (identity === null) {await fs.mkdir(worktreePath, { recursive: false });@@ -89,7 +97,9 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sconst checkout = path.join(temp, 'checkout');try {await gitExec(['worktree', 'prune'], record.meta.baseRepo);- await gitExec(['worktree', 'add', '--detach', '--no-checkout', checkout, record.snapshot.head], record.meta.baseRepo);+ // Git checks branch occupancy itself; no --force/-B may bypass another checkout.+ const target = headRef ? headRef.slice('refs/heads/'.length) : record.snapshot.head;+ await gitExec(['worktree', 'add', '--no-checkout', ...(headRef ? [] : ['--detach']), checkout, target], record.meta.baseRepo);await fs.copyFile(path.join(checkout, '.git'), gitLink, constants.COPYFILE_EXCL);await gitExec(['worktree', 'repair', worktreePath], record.meta.baseRepo);} finally {@@ -101,15 +111,21 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sif (!legacyGuardHeld()) return false;const { stdout: head } = await gitExec(['rev-parse', 'HEAD'], worktreePath);if (head.trim() !== record.snapshot.head) return false;+ if (headRef !== undefined && await readWorktreeHeadRef(worktreePath) !== headRef) return false;if (!(await indexIsRestorable(worktreePath, record.snapshot.indexTree))) return false;await extractRecoveryArchive(record.archive, worktreePath, true);if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;await assertManagedResourcePath(record.meta, [worktreePath]);await assertWorktreeGitIdentity(record.meta);if (!legacyGuardHeld()) return false;+ const { stdout: currentHead } = await gitExec(['rev-parse', 'HEAD'], worktreePath);+ if (currentHead.trim() !== record.snapshot.head) return false;+ if (headRef !== undefined && await readWorktreeHeadRef(worktreePath) !== headRef) return false;if (!(await indexIsRestorable(worktreePath, record.snapshot.indexTree))) return false;await gitExec(['read-tree', record.snapshot.indexTree], worktreePath);- await store.set(sessionId, { ...record.meta, sessionId, generation: record.restoredGeneration, quarantinePath: undefined });+ await store.set(sessionId, { ...record.meta, sessionId,+ ...(headRef ? { branch: headRef.slice('refs/heads/'.length) } : {}),+ generation: record.restoredGeneration, quarantinePath: undefined });record.phase = 'restored';await writeRecycleRecord(record);return true;diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.tsindex 39e780d2aa..916cbb4859 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -1,4 +1,4 @@-import { createHash } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import fs from 'node:fs/promises';import path from 'node:path';import { app } from 'electron';@@ -23,35 +23,45 @@ export function managedWorktreeRoot(value: string): string | null {}function leaseFile(sessionId: string): string {- const key = createHash('sha256').update(sessionId).digest('hex');+ const key = createHash('sha256').update(`${sessionId}:${randomUUID()}`).digest('hex');return path.join(runtimeRoot(), `${process.pid}-${key}.json`);}-export async function acquireWorktreeRuntimeLease(sessionId: string, cwd: string): Promise<void> {+/** A startup owns its own file, even when the business task id is reused. */+export interface WorktreeRuntimeLease {+ readonly file: string;+ readonly physicalPath: string;+}++export async function acquireWorktreeRuntimeLease(sessionId: string, cwd: string): Promise<WorktreeRuntimeLease | null> {const root = managedWorktreeRoot(cwd);- if (!root) return;- await withWorktreeResourceLock(root, async () => {+ if (!root) return null;+ return withWorktreeResourceLock(root, async () => {await fs.mkdir(runtimeRoot(), { recursive: true });+ const lease = { file: leaseFile(sessionId), physicalPath: await physicalWorktreeKey(root) };// A partial write is intentionally unreadable, hence protective to deletion.- await fs.writeFile(leaseFile(sessionId), JSON.stringify({- version: 1, pid: process.pid, path: await physicalWorktreeKey(root),- }), { mode: 0o600 });+ try {+ await fs.writeFile(lease.file, JSON.stringify({+ version: 1, pid: process.pid, path: lease.physicalPath,+ }), { flag: 'wx', mode: 0o600 });+ } catch (error) {+ // No runtime can start after acquisition fails. Only remove this attempt's+ // file; an older/newer runtime of the same task keeps its separate lease.+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {+ await fs.unlink(lease.file).catch(() => undefined);+ }+ throw error;+ }+ return lease;});}-export async function releaseWorktreeRuntimeLease(sessionId: string): Promise<void> {- let physicalPath: string | undefined;- try {- const lease = JSON.parse(await fs.readFile(leaseFile(sessionId), 'utf8'));- if (typeof lease.path === 'string') physicalPath = lease.path;- } catch {- // Releasing our own malformed/partial lease is still safe; it cannot wake another resource.- }- try { await fs.unlink(leaseFile(sessionId)); } catch (error) {+export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease): Promise<void> {+ try { await fs.unlink(lease.file); } catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;throw error;}- if (physicalPath) notifyWorktreeRecycleOpportunity(physicalPath);+ notifyWorktreeRecycleOpportunity(lease.physicalPath);}function pidMayBeAlive(pid: number): boolean {@@ -107,7 +117,10 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {const paths = new Set<string>();for (const name of leases) {const match = /^(\d+)-[a-f0-9]{64}\.json$/.exec(name);- if (!match || !pidMayBeAlive(Number(match[1]))) continue;+ if (!match) continue;+ // Main may have crashed while a detached child still uses the directory.+ // Only explicit lease release proves that startup stopped; a dead owner PID+ // is not sufficient evidence and its leftover lease remains protective.try {const lease = JSON.parse(await fs.readFile(path.join(runtimeRoot(), name), 'utf8'));if (lease.version !== 1 || typeof lease.path !== 'string') return null;diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 90e87ce84c..b2b162e7e4 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1468,6 +1468,17 @@ export class AgentNotAuthenticatedError extends Error {}}+/** An adapter failed before returning a handle, but its process has not confirmed exit. */+export class AgentStartupCleanupPendingError extends Error {+ readonly whenStopped: Promise<void>;++ constructor(message: string, options: { cause: unknown; whenStopped: Promise<void> }) {+ super(message, { cause: options.cause });+ this.name = 'AgentStartupCleanupPendingError';+ this.whenStopped = options.whenStopped;+ }+}+export interface BotRuntimeSkillEntry {name: string;runtimeCommandName?: string;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex 2cee4490af..544c60c95e 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -121,7 +121,7 @@ import { Session } from '../../../session.js';import * as piSubagentRuns from '../pi-subagent-runs.js';import type { PiSubagentRunStatus } from '../pi-subagent-runs.js';import { piProjectKey } from '../project-trust.js';-import type { AgentDeps } from '../../base-agent.js';+import { AgentStartupCleanupPendingError, type AgentDeps } from '../../base-agent.js';import type { Logger } from '../../../interfaces/logger.js';import type { PiProjectTrustInputSnapshot } from '../../../types/pi-project-trust.js';@@ -357,16 +357,22 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {knobs.closeRejects = true;const agent = new PiAgent(buildDeps());- await expect(agent.startSession(opts())).rejects.toThrow(/cleanup remains unconfirmed/);+ const failure = await agent.startSession(opts()).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(AgentStartupCleanupPendingError);+ if (!(failure instanceof AgentStartupCleanupPendingError)) throw new Error('missing cleanup evidence');+ const stopped = vi.fn();+ void failure.whenStopped.then(stopped);expect(knobs.spawnedEnvs).toHaveLength(1);// Same business id cannot spawn while the old proc still fails cleanup.await expect(agent.startSession(opts())).rejects.toThrow(/close unconfirmed/);expect(knobs.spawnedEnvs).toHaveLength(1);+ expect(stopped).not.toHaveBeenCalled();knobs.closeRejects = false;knobs.getStateRejects = false;const handle = await agent.startSession(opts());expect(knobs.spawnedEnvs).toHaveLength(2);+ expect(stopped).toHaveBeenCalledOnce();await handle.close();});@@ -375,17 +381,23 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {knobs.closeRejects = true;const agent = new PiAgent(buildDeps());- await expect(agent.startSession(opts())).rejects.toThrow(/cleanup remains unconfirmed/);+ const failure = await agent.startSession(opts()).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(AgentStartupCleanupPendingError);+ if (!(failure instanceof AgentStartupCleanupPendingError)) throw new Error('missing cleanup evidence');+ const stopped = vi.fn();+ void failure.whenStopped.then(stopped);await expect(agent.startSession({ ...opts(), sessionId: 's2' })).rejects.toThrow(/cleanup remains unconfirmed/,);expect(knobs.closeCount).toBe(2);+ expect(stopped).not.toHaveBeenCalled();knobs.closeRejects = false;await agent.dispose();await agent.dispose();expect(knobs.closeCount).toBe(4);+ expect(stopped).toHaveBeenCalledOnce();});it('reclaims a startup cleanup entry registered after dispose begins', async () => {diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex dceb8267e6..fd6bc130e1 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -56,6 +56,7 @@ function validateSdkSessionId(value: string): string {import {AgentNotAuthenticatedError,+ AgentStartupCleanupPendingError,BaseAgent,MAIN_OWNED_SEND_CONTEXT,PiManagedPackageMutationCancelledError,@@ -1184,6 +1185,7 @@ interface FailedPiStartupCleanup {proc: PiRpcProcess;promise: Promise<void> | null;cleanupLocal?: () => void;+ confirmStopped: () => void;}/**@@ -1406,6 +1408,7 @@ export class PiAgent extends BaseAgent {}if (this.failedStartupCleanups.get(sessionId) === entry) {this.failedStartupCleanups.delete(sessionId);+ entry.confirmStopped();entry.cleanupLocal?.();}}@@ -5136,14 +5139,20 @@ export class PiAgent extends BaseAgent {// quarantine;后续同 session startSession 会先重试 cleanup,绝不直接 spawn。// 远端失败时不清 runtime 文件;本地也只有确认进程结束后才清,避免存活// 进程丢 bridge/permission 状态。- let closeError: unknown = null;+ let cleanupPending: AgentStartupCleanupPendingError | null = null;try {await proc.close();} catch (error) {- closeError = error;+ let confirmStopped!: () => void;+ const whenStopped = new Promise<void>((resolve) => { confirmStopped = resolve; });+ cleanupPending = new AgentStartupCleanupPendingError(+ `pi startup failed and process cleanup remains unconfirmed: ${error instanceof Error ? error.message : String(error)}`,+ { cause: err, whenStopped },+ );this.failedStartupCleanups.set(startupCleanupKey, {proc,promise: null,+ confirmStopped,...(!remote? { cleanupLocal: () => {cleanupConfigHome();@@ -5152,16 +5161,11 @@ export class PiAgent extends BaseAgent {: {}),});}- if (!remote && !closeError) {+ if (!remote && !cleanupPending) {cleanupConfigHome();cleanupRuntimeFiles();}- if (closeError) {- throw new Error(- `pi startup failed and process cleanup remains unconfirmed: ${closeError instanceof Error ? closeError.message : String(closeError)}`,- { cause: err },- );- }+ if (cleanupPending) throw cleanupPending;throw err;}diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 39b5b64994..5e043da916 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -10,10 +10,11 @@ import {import { tmpdir } from 'node:os';import path from 'node:path';-import { Maker, type CreateSessionOptions } from './maker.js';+import { Maker, type CreateSessionOptions, type SessionStartFailureContext } from './maker.js';import { Session } from './session.js';import { createAsyncQueue } from './agents/shared/async-queue.js';import {+ AgentStartupCleanupPendingError,TurnPermissionPolicyUnsupportedError,type AgentSessionHandle,type BaseAgent,@@ -1372,6 +1373,225 @@ describe('Maker start-option lifecycle hooks', () => {expect(maker.listActiveSessions()).toEqual([]);});+ it('binds a delayed close and a failed rebuild to their own startup options', async () => {+ const closeEntered = createDeferred();+ const allowClose = createDeferred();+ const prepared: CreateSessionOptions[] = [];+ const disposed: CreateSessionOptions[] = [];+ const startSession = vi.fn(async () => createHandle({ id: 'thread-lifecycle' }));+ const onStartFailed = vi.fn();+ const maker = new Maker({+ agents: { codex: createAgent(startSession) },+ storage: createStorage(),+ logger: createLogger(),+ lifecycleHooks: {+ prepareStartOptions: async (_id, options) => {+ prepared.push(options);+ if (prepared.length === 2) {+ await Promise.resolve();+ throw new Error('replacement preparation failed');+ }+ },+ onStartFailed,+ onClose: async (_id, options) => {+ closeEntered.resolve();+ await allowClose.promise;+ disposed.push(options);+ },+ },+ });+ const options: CreateSessionOptions = {+ id: 'same-task', agentKind: 'codex', workingDir: '/repo', model: 'gpt-5.4',+ };+ const first = await maker.createSession(options);+ await first.close();+ await closeEntered.promise;+ await expect(maker.createSession(options)).rejects.toThrow('replacement preparation failed');+ const replacement = await maker.createSession(options);+ allowClose.resolve();+ await vi.waitFor(() => expect(disposed).toHaveLength(1));+ expect(new Set(prepared).size).toBe(3);+ expect(prepared).not.toContain(options);+ expect(disposed[0]).toBe(prepared[0]);+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({+ options: prepared[1], stage: 'prepare', runtimeMayBeAlive: false,+ }));+ expect(maker.getSession('same-task')).toBe(replacement);+ await replacement.close();+ await vi.waitFor(() => expect(disposed).toHaveLength(2));+ expect(disposed[1]).toBe(prepared[2]);+ });++ it.each([false, true])('reports whether a failed startup still has a live handle: %s', async (cleanupFails) => {+ const handle = createHandle({ id: 'failed-storage' });+ handle.close = vi.fn(async () => {+ if (cleanupFails) throw new Error('termination unconfirmed');+ });+ const storage = createStorage();+ storage.create = vi.fn().mockRejectedValue(new Error('storage unavailable'));+ const onStartFailed = vi.fn();+ const maker = new Maker({+ agents: { codex: createAgent(async () => handle) },+ storage, logger: createLogger(), lifecycleHooks: { onStartFailed },+ });+ await expect(maker.createSession({+ id: 'storage-failure', agentKind: 'codex', workingDir: '/repo', model: 'gpt-5.4',+ })).rejects.toThrow('storage unavailable');+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({+ stage: 'storage', runtimeMayBeAlive: cleanupFails,+ }));+ });++ it('runs startup cleanup when a prepared runtime cannot claim its thread', async () => {+ const threadId = '11111111-1111-4111-8111-111111111111';+ const startSession = vi.fn(async () => createHandle({ id: threadId }));+ const onStartFailed = vi.fn();+ const maker = new Maker({+ agents: { codex: createAgent(startSession) }, storage: createStorage(), logger: createLogger(),+ lifecycleHooks: { onStartFailed },+ });+ const options: CreateSessionOptions = {+ id: 'thread-owner', agentKind: 'codex', workingDir: '/repo', model: 'gpt-5.4',+ resumeSessionId: threadId,+ };+ const owner = await maker.createSession(options);+ await expect(maker.createSession({ ...options, id: 'thread-conflict' })).rejects.toThrow('already active');+ expect(startSession).toHaveBeenCalledOnce();+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({+ sessionId: 'thread-conflict', stage: 'agent-start', runtimeMayBeAlive: false,+ }));+ await owner.close();+ });++ it('releases deferred failed-start resources without touching the successful replacement', async () => {+ const cleanupEntered = createDeferred();+ const allowCleanup = createDeferred();+ const leased = new Set<CreateSessionOptions>();+ const prepared: CreateSessionOptions[] = [];+ const failedHandle = createHandle({ id: 'failed-pi', agentKind: 'pi' });+ failedHandle.close = vi.fn().mockRejectedValueOnce(new Error('still alive')).mockResolvedValue(undefined);+ const storage = createStorage();+ const create = storage.create.bind(storage);+ storage.create = vi.fn().mockRejectedValueOnce(new Error('storage failed')).mockImplementation(create);+ const maker = new Maker({+ agents: { pi: createAgent(vi.fn()+ .mockResolvedValueOnce(failedHandle)+ .mockResolvedValueOnce(createHandle({ id: 'replacement-pi', agentKind: 'pi' })), 'pi') },+ storage, logger: createLogger(),+ lifecycleHooks: {+ prepareStartOptions: (_id, options) => { prepared.push(options); leased.add(options); },+ onStartFailed: ({ options, runtimeMayBeAlive }) => { if (!runtimeMayBeAlive) leased.delete(options); },+ onStartCleanupSucceeded: async (_id, options) => {+ cleanupEntered.resolve();+ await allowCleanup.promise;+ leased.delete(options);+ },+ onClose: (_id, options) => { leased.delete(options); },+ },+ });+ const options: CreateSessionOptions = {+ id: 'same-failed-task', agentKind: 'pi', workingDir: '/repo', model: 'pi-model',+ };+ await expect(maker.createSession(options)).rejects.toThrow('storage failed');+ expect(leased.size).toBe(1);+ const replacement = await maker.createSession(options);+ await cleanupEntered.promise;+ expect(leased.size).toBe(2);+ allowCleanup.resolve();+ await vi.waitFor(() => expect(leased).toEqual(new Set([prepared[1]])));+ expect(maker.getSession(options.id!)).toBe(replacement);+ await replacement.close();+ await vi.waitFor(() => expect(leased.size).toBe(0));+ });++ it('keeps an adapter-owned unpublished runtime protected until its own close completes', async () => {+ const stopped = createDeferred();+ const cleanupEntered = createDeferred();+ const allowCleanup = createDeferred();+ const pending = new AgentStartupCleanupPendingError('opaque adapter failure', {+ cause: new Error('startup RPC failed'), whenStopped: stopped.promise,+ });+ const leased = new Set<CreateSessionOptions>();+ const prepared: CreateSessionOptions[] = [];+ const onStartFailed = vi.fn(({ options, runtimeMayBeAlive }: SessionStartFailureContext) => {+ if (!runtimeMayBeAlive) leased.delete(options);+ });+ const maker = new Maker({+ agents: { pi: createAgent(vi.fn().mockRejectedValueOnce(pending)+ .mockResolvedValueOnce(createHandle({ id: 'recovered-pi', agentKind: 'pi' })), 'pi') },+ storage: createStorage(), logger: createLogger(),+ lifecycleHooks: {+ prepareStartOptions: (_id, options) => { prepared.push(options); leased.add(options); },+ onStartFailed,+ onStartCleanupSucceeded: async (_id, options) => {+ cleanupEntered.resolve();+ await allowCleanup.promise;+ leased.delete(options);+ },+ onClose: (_id, options) => { leased.delete(options); },+ },+ });+ const options: CreateSessionOptions = {+ id: 'adapter-cleanup', agentKind: 'pi', workingDir: '/repo', model: 'pi-model',+ };+ await expect(maker.createSession(options)).rejects.toBe(pending);+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({+ stage: 'agent-start', runtimeMayBeAlive: true,+ }));+ expect(leased).toEqual(new Set([prepared[0]]));+ stopped.resolve();+ await cleanupEntered.promise;+ const replacement = await maker.createSession(options);+ expect(leased.size).toBe(2);+ allowCleanup.resolve();+ await vi.waitFor(() => expect(leased).toEqual(new Set([prepared[1]])));+ await replacement.close();+ await vi.waitFor(() => expect(leased.size).toBe(0));+ });++ it('does not release adapter startup resources when exit confirmation fails', async () => {+ let rejectStopped!: (error: unknown) => void;+ const whenStopped = new Promise<void>((_resolve, reject) => { rejectStopped = reject; });+ const pending = new AgentStartupCleanupPendingError('adapter failed', {+ cause: new Error('startup RPC failed'), whenStopped,+ });+ const logger = createLogger();+ const onStartFailed = vi.fn();+ const onStartCleanupSucceeded = vi.fn();+ const maker = new Maker({+ agents: { pi: createAgent(vi.fn().mockRejectedValue(pending), 'pi') },+ storage: createStorage(), logger,+ lifecycleHooks: { onStartFailed, onStartCleanupSucceeded },+ });+ await expect(maker.createSession({+ id: 'unconfirmed-exit', agentKind: 'pi', workingDir: '/repo', model: 'pi-model',+ })).rejects.toBe(pending);+ rejectStopped(new Error('exit could not be verified'));+ await vi.waitFor(() => expect(logger.warn).toHaveBeenCalledWith(+ 'adapter startup cleanup remains unconfirmed', expect.objectContaining({ sessionId: 'unconfirmed-exit' }),+ ));+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({ runtimeMayBeAlive: true }));+ expect(onStartCleanupSucceeded).not.toHaveBeenCalled();+ });++ it('preserves runtime protection for an ordinary adapter failure without exit evidence', async () => {+ const onStartFailed = vi.fn();+ const onStartCleanupSucceeded = vi.fn();+ const startSession = vi.fn().mockRejectedValue(new Error('ordinary startup failure'));+ const maker = new Maker({+ agents: { codex: createAgent(startSession) }, storage: createStorage(), logger: createLogger(),+ lifecycleHooks: { onStartFailed, onStartCleanupSucceeded },+ });+ await expect(maker.createSession({+ id: 'unknown-startup-exit', agentKind: 'codex', workingDir: '/repo', model: 'gpt-5.4',+ })).rejects.toThrow('ordinary startup failure');+ expect(startSession).toHaveBeenCalledOnce();+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({+ sessionId: 'unknown-startup-exit', stage: 'agent-start', runtimeMayBeAlive: true,+ }));+ expect(onStartCleanupSucceeded).not.toHaveBeenCalled();+ });+it('does not run the success hook when agent startup fails', async () => {const onStartSucceeded = vi.fn();const onStartFailed = vi.fn();diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex ef19bf0d1c..44512b9941 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -38,6 +38,7 @@ import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilitieimport { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';import { Session, generateSessionId } from './session.js';+import { AgentStartupCleanupPendingError } from './agents/base-agent.js';import type {AgentSessionHandle,AgentSessionTeardownOptions,@@ -73,6 +74,8 @@ export interface SessionStartFailureContext {options: CreateSessionOptions;stage: 'prepare' | 'agent-start' | 'storage';error: unknown;+ /** Startup entered the adapter without confirmed exit; host runtime guards must remain protective. */+ runtimeMayBeAlive?: boolean;}export interface SessionLifecycleHooks {@@ -90,8 +93,10 @@ export interface SessionLifecycleHooks {* hook 自身失败只记日志,绝不覆盖原始启动错误。*/onStartFailed?: (context: SessionStartFailureContext) => void | Promise<void>;- /** session 关闭时 (Maker.closeSession 主动 / 内部异常 / handle 自然结束)。 */- onClose?: (sessionId: string) => void | Promise<void>;+ /** Failed startup's handle was finally closed after deferred cleanup; no task ownership change. */+ onStartCleanupSucceeded?: (sessionId: string, options: CreateSessionOptions) => void | Promise<void>;+ /** session 关闭时调用;options 始终属于该次启动,不从当前同 id 的 runtime 取值。 */+ onClose?: (sessionId: string, options: CreateSessionOptions) => void | Promise<void>;/*** Codex-only: resume 前读取该业务 session 对应 thread history 是否已可靠包含* 产品 prompt。读取失败由 Maker 视为 unknown,让 Codex fail toward restore。@@ -605,6 +610,7 @@ export class Maker {const notifyStartFailed = async (stage: SessionStartFailureContext['stage'],error: unknown,+ runtimeMayBeAlive = false,): Promise<void> => {if (!this.lifecycleHooks.onStartFailed) return;try {@@ -613,6 +619,7 @@ export class Maker {options: startOpts,stage,error,+ runtimeMayBeAlive,});} catch (hookError) {this.logger.warn('lifecycleHooks.onStartFailed threw; preserving original startup error', {@@ -622,6 +629,13 @@ export class Maker {});}};+ const notifyStartCleanupSucceeded = (): void => {+ void Promise.resolve()+ .then(() => this.lifecycleHooks.onStartCleanupSucceeded?.(id, startOpts))+ .catch((error) => this.logger.warn('lifecycleHooks.onStartCleanupSucceeded threw', {+ sessionId: id, error: String(error),+ }));+ };if (this.lifecycleHooks.prepareStartOptions) {try {await this.lifecycleHooks.prepareStartOptions(id, startOpts);@@ -669,17 +683,19 @@ export class Maker {// business id 在 close/rebuild 后会复用;另铸一个只活在本次内存实例里的// 代号,让迟到的旧 MCP 请求不能借用新 Session 的权限状态。const sessionInstanceId = generateSessionId();- let codexThreadClaim =- opts.agentKind === 'codex' && isClaimableCodexThreadId(startOpts.resumeSessionId)- ? this.claimCodexThread({- sessionId: id,- sessionInstanceId,- remoteHostId: startOpts.remoteHostId,- threadId: startOpts.resumeSessionId,- })- : null;+ let codexThreadClaim: CodexThreadClaimLease | null = null;let handle: AgentSessionHandle;+ let agentStartAttempted = false;try {+ if (opts.agentKind === 'codex' && isClaimableCodexThreadId(startOpts.resumeSessionId)) {+ codexThreadClaim = this.claimCodexThread({+ sessionId: id,+ sessionInstanceId,+ remoteHostId: startOpts.remoteHostId,+ threadId: startOpts.resumeSessionId,+ });+ }+ agentStartAttempted = true;handle = await agent.startSession({...startOpts,sessionId: id,@@ -698,7 +714,18 @@ export class Maker {});} catch (error) {codexThreadClaim?.release();- await notifyStartFailed('agent-start', error);+ // A generic adapter error does not prove its process stopped. Preserve+ // host guards; only pre-adapter failure or explicit exit evidence releases them.+ await notifyStartFailed('agent-start', error, agentStartAttempted);+ if (error instanceof AgentStartupCleanupPendingError) {+ // The adapter still owns this unpublished process. Its eventual close+ // must release only this startup's resources, even after a rebuild.+ void error.whenStopped.then(notifyStartCleanupSucceeded).catch((cleanupError) => {+ this.logger.warn('adapter startup cleanup remains unconfirmed', {+ sessionId: id, error: String(cleanupError),+ });+ });+ }throw error;}if (opts.agentKind === 'codex' && isClaimableCodexThreadId(handle.id)) {@@ -714,16 +741,21 @@ export class Maker {});}} catch (error) {+ let cleanupFailed = false;try {await handle.close({ reason: 'navigation' });} catch (closeError) {+ cleanupFailed = true;+ this.failedHandleCleanups.set(id, {+ handle, promise: null, onCleaned: notifyStartCleanupSucceeded,+ });this.logger.warn('failed to close Codex handle after thread claim conflict', {sessionId: id,error: String(closeError),});}codexThreadClaim?.release();- await notifyStartFailed('agent-start', error);+ await notifyStartFailed('agent-start', error, cleanupFailed);throw error;}}@@ -740,19 +772,24 @@ export class Maker {localPiPackageGeneration !== null&& localPiPackageGeneration !== this.localPiPackageRuntimeGeneration) {+ let cleanupFailed = false;try {await handle.close({ reason: 'navigation' });} catch (closeError) {+ cleanupFailed = true;this.failedHandleCleanups.set(id, {handle,promise: null,+ onCleaned: notifyStartCleanupSucceeded,});this.logger.warn('failed to close stale local Pi handle after package mutation', {sessionId: id,error: String(closeError),});}- throw new Error('Local Pi runtime startup was invalidated by a package change; retry the task.');+ const error = new Error('Local Pi runtime startup was invalidated by a package change; retry the task.');+ await notifyStartFailed('agent-start', error, cleanupFailed);+ throw error;}// 落地元数据 —— storage 已有同 id 的 row 时跳过 insert, 走 update 把 sdkSessionId 写回@@ -801,9 +838,10 @@ export class Maker {this.failedHandleCleanups.set(id, {handle,promise: null,- ...(codexThreadClaim- ? { onCleaned: () => codexThreadClaim?.release() }- : {}),+ onCleaned: () => {+ codexThreadClaim?.release();+ notifyStartCleanupSucceeded();+ },});this.logger.warn('failed to close agent handle after session storage failure', {sessionId: id,@@ -813,7 +851,7 @@ export class Maker {if (!cleanupFailed && codexThreadClaim) {codexThreadClaim.release();}- await notifyStartFailed('storage', error);+ await notifyStartFailed('storage', error, cleanupFailed);throw error;}@@ -843,12 +881,15 @@ export class Maker {error: String(error),});}+ let cleanupFailed = false;try {await handle.close({ reason: 'navigation' });} catch (closeError) {+ cleanupFailed = true;this.failedHandleCleanups.set(id, {handle,promise: null,+ onCleaned: notifyStartCleanupSucceeded,});this.logger.warn('failed to close stale local Pi handle after package mutation', {sessionId: id,@@ -858,7 +899,9 @@ export class Maker {// This handle was never published. Ordinary onClose may release a task's// worktree and other durable ownership, so it belongs only to published// session closure—not startup rollback.- throw new Error('Local Pi runtime startup was invalidated by a package change; retry the task.');+ const error = new Error('Local Pi runtime startup was invalidated by a package change; retry the task.');+ await notifyStartFailed('storage', error, cleanupFailed);+ throw error;};if (localPiPackageGeneration !== null@@ -972,7 +1015,7 @@ export class Maker {// 自己的 invariant 先一致。if (this.lifecycleHooks.onClose) {void Promise.resolve()- .then(() => this.lifecycleHooks.onClose!(meta.id))+ .then(() => this.lifecycleHooks.onClose!(meta.id, startOpts)).catch((err) => {this.logger.warn('lifecycleHooks.onClose threw', { sessionId: meta.id, error: String(err) });});