diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts index 3ed4b8e40b..943a185813 100644 --- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts +++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts @@ -11,6 +11,10 @@ import { resolve } from 'node:path'; import { describe, expect, it, vi } from 'vitest'; import { ScriptTarget, transpileModule } from 'typescript'; import type { AgentEvent } from '@cindy/maker-core'; +import { + rehydrateCloseSuppression, + withRehydrateCloseSuppressed, +} from '../maker-host/rehydrateCloseSuppression.js'; const sourcePath = resolve(__dirname, '..', 'maker-ipc', 'register.ts'); const source = readFileSync(sourcePath, 'utf8').replace(/\r\n?/g, '\n'); @@ -1424,4 +1428,62 @@ describe('session context window budget reconciler', () => { expect(desktopSend).toContain('applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId)'); expect(desktopSend).toContain('replayPendingSessionContextWindowBudgetUnderLock(sessionId)'); }); + + it('runs drift-recycle closes inside the rehydrate suppression window so the in-flight send survives (cancelled-before-dispatch regression)', async () => { + // 2026-11-08 实报:openspec init 后每个存量会话首条消息必失败一次 —— 漂移回收的 + // close 在抑制窗口外执行,onSessionClosed abort 了正在驱动这次回收的发送边界, + // session.send 拿到已 abort 的 signal 直接 cancelled-before-dispatch,手动重试 + // 才过。回归锚点:发送事务的 closeSessionIfCurrent 依赖必须包在 + // withRehydrateCloseSuppressed 里,且 close adapters 的 preserve 读数仍来自 + // 同一个抑制表(机制层契约见 agent-input-coordinator #1930 用例)。 + const start = source.indexOf(' closeSessionIfCurrent: async (sessionId) => {'); + const end = source.indexOf(' getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId),', start); + if (start < 0 || end < 0) throw new Error('send-transaction closeSessionIfCurrent source changed'); + // 整条语句切片转译(loadBudgetReconciler 同型):直接转译表达式会带语句分号,截断 return 包装。 + const js = transpileModule( + `const closeSessionIfCurrent = { ${source.slice(start, end)} };`, + { compilerOptions: { target: ScriptTarget.ES2022 } }, + ).outputText; + const closeCalls: Array<[{ id: string }, string]> = []; + let suppressedDuringClose: boolean | null = null; + const maker = { + getSession: (sessionId: string) => ({ id: sessionId }), + closeSessionIfCurrent: async (session: { id: string }, reason: string) => { + suppressedDuringClose = rehydrateCloseSuppression.isSuppressed(session.id); + closeCalls.push([session, reason]); + }, + }; + const closeSessionIfCurrent = new Function( + 'maker', + 'withRehydrateCloseSuppressed', + `${js}; return closeSessionIfCurrent.closeSessionIfCurrent;`, + )(maker, withRehydrateCloseSuppressed) as (sessionId: string) => Promise; + + await closeSessionIfCurrent('drift-task'); + expect(closeCalls).toEqual([[{ id: 'drift-task' }, 'runtime-refresh']]); + // close await 期间抑制窗口开着:close adapters 的 shouldPreserveInputBoundary + // 读到 true → 在途发送边界不被 abort,事务继续 lazy bootstrap 投递。 + expect(suppressedDuringClose).toBe(true); + expect(rehydrateCloseSuppression.isSuppressed('drift-task')).toBe(false); + + // send_to_session 通道的同型直发点(独立于发送事务 deps)也必须包在抑制窗口内。 + const laneStart = source.indexOf('async function sendToSessionInternal'); + const driftStart = source.indexOf( + "if (live?.agentKind === 'pi' && live.hasRecyclableProjectResourceDrift()) {", + laneStart, + ); + const driftEnd = source.indexOf('live = undefined;', driftStart); + expect(driftStart).toBeGreaterThan(laneStart); + const driftBlock = source.slice(driftStart, driftEnd); + expect(driftBlock).toContain('withRehydrateCloseSuppressed(targetSessionId'); + + // 消费端:close adapters 的边界保留读数必须仍指向抑制表(两条直发点共用)。 + const adaptersStart = source.indexOf( + 'const sessionBindings = createSessionBindingLifecycle({', + ); + const adaptersEnd = source.indexOf('beforeCloseTeardown:', adaptersStart); + expect(source.slice(adaptersStart, adaptersEnd)).toContain( + 'shouldPreserveInputBoundary: () => rehydrateCloseSuppression.isSuppressed(session.id)', + ); + }); }); diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts index e412e67a4f..85e48b38b3 100644 --- a/apps/desktop/src/main/bootstrap-electron.ts +++ b/apps/desktop/src/main/bootstrap-electron.ts @@ -1627,6 +1627,13 @@ async function attemptStartSchedulerOnce(): Promise { try { startGoalController({ maker, + // 项目资源漂移(会话中途新增 skill/extension):空闲时经 Maker 以 runtime-refresh + // 回收,goal 直派随后的 ensureSession 活化即重扫重建(与桌面发送事务同口径)。 + recyclePiRuntimeIfResourcesDrifted: async (sessionId) => { + const live = maker.getSession(sessionId); + if (!live) return false; + return maker.recyclePiRuntimeIfResourcesDrifted(live); + }, getDb: () => getDbClient().drizzle, broadcastStatus: broadcastGoalStatus, ...automationGitBaselineHooks, @@ -2155,6 +2162,13 @@ async function teardownAuthAccountBoundary(reason: string): Promise { const automationGitBaselineHooks = createAutomationUserTurnGitBaselineHooks(); startGoalController({ maker, + // 项目资源漂移(会话中途新增 skill/extension):空闲时经 Maker 以 runtime-refresh + // 回收,goal 直派随后的 ensureSession 活化即重扫重建(与桌面发送事务同口径)。 + recyclePiRuntimeIfResourcesDrifted: async (sessionId) => { + const live = maker.getSession(sessionId); + if (!live) return false; + return maker.recyclePiRuntimeIfResourcesDrifted(live); + }, getDb: () => getDbClient().drizzle, broadcastStatus: broadcastGoalStatus, ...automationGitBaselineHooks, diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts index 46a134fb37..a4bb7607ab 100644 --- a/apps/desktop/src/main/goal-host/controller.ts +++ b/apps/desktop/src/main/goal-host/controller.ts @@ -2506,6 +2506,12 @@ export class GoalController { releaseAgentSwitchLock = (await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {}); if (!isCurrentLifecycle()) return; + // 项目资源漂移:先经注入的回收 seam 回收旧运行时(runtime-refresh),随后的 + // ensureSession 活化即重扫重建;与桌面发送事务同口径。测试装配不注入即跳过 + // (不能顶层 import maker-host:其模块图带 Electron 访问,会污染单测收集)。 + if (await this.deps.recyclePiRuntimeIfResourcesDrifted?.(sessionId)) { + this.deps.logger.info?.('[goal] project resources drifted, recycled runtime before dispatch', { sessionId }); + } const session = await this.deps.ensureSession(sessionId); if (!isCurrentLifecycle()) return; if (!session) throw new GoalSessionRestoreError(); diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts index 2e97b742da..121d6c490f 100644 --- a/apps/desktop/src/main/goal-host/index.ts +++ b/apps/desktop/src/main/goal-host/index.ts @@ -41,6 +41,9 @@ import type { GoalStatusUpdate, SessionLike } from './types'; export interface StartGoalControllerDeps { maker: Maker; getDb: () => GoalDrizzleDb; + /** 项目资源漂移回收 seam(pi 本地根任务):空闲时经 Maker 以 runtime-refresh 原因 + * 关闭旧运行时,goal 直派随后的 ensureSession 活化即重扫重建。默认用 deps.maker。 */ + recyclePiRuntimeIfResourcesDrifted?: (sessionId: string) => Promise; /** 状态变化广播到 renderer(→ GOAL_STATUS_CHANGED)。 */ broadcastStatus: (update: GoalStatusUpdate) => void; beforeDispatchUserTurn?: (sessionId: string, signal?: AbortSignal) => void | Promise; @@ -73,6 +76,7 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll warn: (message, meta) => logger.warn(message, meta), }), acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend, + recyclePiRuntimeIfResourcesDrifted: deps.recyclePiRuntimeIfResourcesDrifted, isSessionInTurn, ensureInputReady: ensureGoalInputReady, isInputBlocked: isGoalInputBlocked, diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts index 56a1879fa5..8a910eb651 100644 --- a/apps/desktop/src/main/goal-host/types.ts +++ b/apps/desktop/src/main/goal-host/types.ts @@ -185,6 +185,10 @@ export interface GoalControllerDeps { * 调用方在重新读取 live session 且 Session.send 返回后执行 release。 */ acquirePendingAgentSwitch?: (sessionId: string) => Promise<() => void>; + /** 项目资源漂移回收 seam(pi 本地根任务):空闲时经 Maker 以 runtime-refresh 原因 + * 关闭旧运行时,调用方随后的 ensureSession 活化即重扫重建。生产装配经 Maker; + * 测试可不注入(跳过回收,与桌面发送事务同口径)。 */ + recyclePiRuntimeIfResourcesDrifted?: (sessionId: string) => Promise; /** ← maker-ipc/register.isSessionInTurn(main 侧 turn 活跃跟踪)。 */ isSessionInTurn(sessionId: string): boolean; /** Restore the existing input queue, then yield to its FIFO/locks/recovery. */ diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts index 5ce09a0f9a..565b213288 100644 --- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts +++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts @@ -343,10 +343,16 @@ function makePermissionModeFake() { } /** fake maker: createSession 返回"send 即接受、随后立刻 done"的会话。 */ -function makeFakeSession(id: string) { +function makeFakeSession( + id: string, + status: 'active' | 'aborting' | 'closed' | 'error' = 'active', +) { const permission = makePermissionModeFake(); return { id, + // close 失败会让真实 Session 停在 error;测试用初始状态复刻这一后果。 + getStatus: () => status, + ...({ instanceId: `instance-${id}` } as { instanceId?: string }), workDir: 'D:/repo', get permissionModeState() { @@ -395,6 +401,8 @@ function makeFakeSession(id: string) { const fakeMaker = { createSession: vi.fn(async (opts: { id?: string }) => makeFakeSession(opts.id ?? 'sess-x')), + // 默认无漂移:漂移相关用例按需覆写(maker 方法缺省 false → 不回收) + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSessionMeta: vi.fn(async () => ({ workDir: 'D:/repo', model: 'meta-model', @@ -817,6 +825,53 @@ describe('hook task model selection on next send', () => { expect(release).toHaveBeenCalledOnce(); }); + it('surfaces the real rebuild failure after a drift recycle instead of sending on the closed instance', async () => { + // 回收已关旧实例后重建失败:错误必须原样上抛,不得吞掉后拿已关闭实例投递 + // (那只会报误导性的「会话已关闭」,真正的启动原因被吞 —— Greptile P2)。 + const oldSession = makeFakeSession('sess-old'); + fakeMaker.recyclePiRuntimeIfResourcesDrifted.mockResolvedValueOnce(true); + fakeMaker.createSession + .mockImplementationOnce(async () => oldSession) + .mockRejectedValueOnce(new Error('pi startup failed: bad extension')); + const result = await createMakerHookSessionRunner({ log }).run(baseReq({ isNew: false })); + expect(result.status).toBe('error'); + expect(result.errorMessage).toContain('pi startup failed: bad extension'); + expect(fakeMaker.createSession).toHaveBeenCalledTimes(2); + expect(oldSession.send).not.toHaveBeenCalled(); + }); + + it('keeps delivering on the live instance when the recycle itself fails', async () => { + // 回收本身失败但实例仍 active → 原样投递(hook 轮次不因回收故障中断)。 + const session = makeFakeSession('sess-new'); + session.send.mockResolvedValue({ accepted: true }); + fakeMaker.createSession.mockResolvedValueOnce(session); + fakeMaker.recyclePiRuntimeIfResourcesDrifted.mockRejectedValueOnce(new Error('recycle boom')); + const run = createMakerHookSessionRunner({ log }).run(baseReq({ isNew: false })); + await vi.waitFor(() => expect(session.send).toHaveBeenCalledOnce()); + h.eventCbs.get('sess-new')!({ type: 'done', data: null }); + const result = await run; + expect(result.status).toBe('ok'); + expect(fakeMaker.createSession).toHaveBeenCalledTimes(1); + expect(session.send).toHaveBeenCalledOnce(); + }); + + it('rebuilds when the recycle fails and the session is no longer active', async () => { + // Codex P2:close 抛出时 Session 已停在 error,旧实例不可用 —— 必须重建, + // 否则 send 被 ensureActive 拒、runner 永远绑在坏实例上。 + const broken = makeFakeSession('sess-new', 'error'); + const rebuilt = makeFakeSession('sess-new'); + rebuilt.send.mockResolvedValue({ accepted: true }); + fakeMaker.createSession.mockResolvedValueOnce(broken).mockResolvedValueOnce(rebuilt); + fakeMaker.recyclePiRuntimeIfResourcesDrifted.mockRejectedValueOnce(new Error('close boom')); + const run = createMakerHookSessionRunner({ log }).run(baseReq({ isNew: false })); + await vi.waitFor(() => expect(rebuilt.send).toHaveBeenCalledOnce()); + h.eventCbs.get('sess-new')!({ type: 'done', data: null }); + const result = await run; + expect(result.status).toBe('ok'); + expect(fakeMaker.createSession).toHaveBeenCalledTimes(2); + expect(broken.send).not.toHaveBeenCalled(); + }); + it('does not send with the old model when applying the choice fails', async () => { h.acquirePendingAgentSwitch.mockRejectedValueOnce(new Error('selection failed')); await expect(createMakerHookSessionRunner({ log }).run(baseReq({ isNew: false }))) @@ -1741,6 +1796,8 @@ describe('进度快照(turn.progress 链路)', () => { return permission.permissionModeState; }, id, + // 与 makeFakeSession 同形状:生产代码按 getStatus 判定实例是否仍可用。 + getStatus: () => 'active' as const, workDir: 'D:/repo', onEvent( cb: (ev: { @@ -2738,6 +2795,7 @@ describe('上游过载自动重试期间的渠道进度(零产出窗口)', () => return { ...makePermissionModeFake(), id, + getStatus: () => 'active' as const, workDir: 'D:/repo', onEvent(cb: (ev: { type: string; data: unknown }) => void) { h.eventCbs.set(id, cb); @@ -3058,6 +3116,7 @@ describe('交互卡链路(interaction listener 覆盖)', () => { return { ...makePermissionModeFake(), id, + getStatus: () => 'active' as const, workDir: 'D:/repo', onEvent( cb: (ev: { diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts index 0a105886f2..049016266e 100644 --- a/apps/desktop/src/main/hook-control/dispatcher.ts +++ b/apps/desktop/src/main/hook-control/dispatcher.ts @@ -194,6 +194,12 @@ export interface HookContinuationWatchRequest { export interface HookRunRequest { /** Host-resolved companion channel lane; never accepted from the wire. */ companionBotId?: string; + /** + * 取消探针(dispatcher 侧 task.cancel 账本):runner 在回收/重建等长窗口后、 + * 发送前查询 —— 喊停若落在窗口内, 中止信号对旧实例无目标、对新实例未登记, + * 只有这个账本能告诉 runner「用户已喊停」。未注入 = 无取消通道。 + */ + isCancelRequested?: () => boolean; /** Untruncated user body for persistence; source.userText is only a bounded display preview. */ userText?: string; /** Local display snapshot; not part of the server wire protocol. */ @@ -2016,6 +2022,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher { outcome = await runner.run({ ...task.run, ...xVideoRelayOption(task, runningEntry), + // 取消探针:runner 在回收/重建窗口后发送前查询,喊停不落进新进程执行。 + isCancelRequested: () => cancelRequested.has(requestKey), onTurnTerminal: () => { runningEntry.observing = false; }, onProgress, ...(task.run.source?.im === 'telegram' ? { diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts index 615dcf8b6b..5972958d19 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -972,6 +972,68 @@ export function createMakerHookSessionRunner(deps: { return fail(err instanceof Error ? err.message : String(err)); } + // 项目资源漂移(会话中途新增 skill/extension):createSession 可能复用活实例, + // 空闲时经 Maker 回收后重取 —— 再走一次同样的获取路径即得重建实例。 + // 两种失败分开:回收本身失败 → 旧实例大概率仍可用,原样投递(hook 轮次 + // 不因回收故障中断);回收成功(旧实例已关)后的重建失败必须上抛 —— 继续 + // 用已关闭实例只会把真实启动原因(如新增扩展导致 pi 启动失败)换成误导 + // 性的「会话已关闭」(2026-11-09 Greptile P2)。 + let driftedRecycled = false; + try { + driftedRecycled = await maker.recyclePiRuntimeIfResourcesDrifted(session); + } catch { + // 回收抛出时 Session 已停在 error(close 失败不回退),旧实例不可用 —— + // 继续投递只会被 ensureActive 拒,必须走重建(Codex P2,2026-11-10)。 + driftedRecycled = session.getStatus() !== 'active'; + } + if (driftedRecycled) { + try { + session = req.isNew + ? await openChannelSession(req.sessionId, newSessionRoute, (admitted) => { + sessionProviderId = admitted.providerId; + return maker.createSession({ + ...createOpts, + model: admitted.model, + ...(admitted.providerId !== null ? { providerId: admitted.providerId } : {}), + ...(admitted.effort !== undefined ? { effort: admitted.effort } : {}), + }); + }, assertAccount) + : await maker.createSession(createOpts); + } catch (err) { + // session 未建成: 预建 worktree 同步回收(同上方新建失败路径), 防孤儿泄漏 + if (req.isNew && worktreeStore.get(req.sessionId)) { + void WorktreeManager.removeWorktreeForSession(req.sessionId).catch(() => undefined); + } + return fail(err instanceof Error ? err.message : String(err)); + } + } + + // 运行时来源注入(路由层经 session-provider-store 决定上游与钥匙)必须先于 + // 取消探针:新建任务的行已落库但 providerId 未写(DesktopSessionStorage.create + // 不写、freezeSessionProviderAtStart 只写内存),取消早返回若跳过这里,应用重启 + // 后复用会读到空来源,改走默认供应商或因模型不可用而失败。 + // 新建显式 set(与 scheduler 4.4.2 的显式 providerId 分支同款); 复用走 + // hydrate —— 仅内存无条目时写入, 不覆盖运行中会话刚在聊天里切的更新值。 + if (req.isNew) { + if (sessionProviderId && accountStillCurrent()) { + setSessionProvider(session.id, sessionProviderId); + } + } else { + hydrateSessionProvider(session.id, rowProviderId); + } + + // 取消探针:回收/重建是异步窗口,期间 task.cancel 的 abort 对旧实例无目标、 + // 对新实例未登记 —— 喊停后不得把消息投给新进程执行。此处尚未发送,提前以 + // error 收口;execute 收口会按取消账本把状态统一改写为 cancelled。 + if (req.isCancelRequested?.()) { + return { + status: 'error', + finalText: '', + errorMessage: '任务已被用户喊停,本条消息没有执行。', + durationMs: Date.now() - startedAt, + }; + } + /** * 拿到的可能是**进程里早就活着的那个实例**: maker.createSession 对已在 * activeSessions 里的 id 直接返回它, 忽略上面传的 workingDir。侧边栏 @@ -1005,17 +1067,6 @@ export function createMakerHookSessionRunner(deps: { ); } - // 运行时来源注入(路由层经 session-provider-store 决定上游与钥匙): - // 新建显式 set(与 scheduler 4.4.2 的显式 providerId 分支同款); 复用走 - // hydrate —— 仅内存无条目时写入, 不覆盖运行中会话刚在聊天里切的更新值。 - if (req.isNew) { - if (sessionProviderId && accountStillCurrent()) { - setSessionProvider(session.id, sessionProviderId); - } - } else { - hydrateSessionProvider(session.id, rowProviderId); - } - // renderer 可见性: 不 wire 则消息不落库、UI 空白(scheduler Phase 6 老坑) wireSessionToIpc(session); diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts index 9ef2374e12..df19b9500a 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts @@ -255,6 +255,7 @@ beforeEach(() => { mocks.getMaker.mockReturnValue({ getSession: vi.fn((id: string) => harnesses.get(id)?.session), on: vi.fn(() => () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), createSession: vi.fn(async (args: { id?: string }) => { createSessionArgs.push(args as Record); const id = args.id ?? 'anon'; @@ -578,6 +579,7 @@ describe('turnRunner: connection handed to a companion bot', () => { }; mocks.getMaker.mockReturnValue({ createSession: base.createSession, + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn((id: string) => live ?? harnesses.get(id)?.session), on: vi.fn((listener: (event: MakerEvent) => void) => { listeners.push(listener); @@ -623,6 +625,7 @@ describe('turnRunner: connection handed to a companion bot', () => { createSession: (args: { id?: string }) => Promise; }; mocks.getMaker.mockReturnValue({ + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), createSession: vi.fn(async (args: { id?: string }) => { if (args.id === 'mimi-main' && live === null) { live = rebuilt.session; diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts index 7bb058dc43..7f9c556b51 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts @@ -365,6 +365,7 @@ function createMakerHarness(session: Session) { return { getSession: vi.fn(() => session), createSession: vi.fn(async () => session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); return () => { @@ -1440,6 +1441,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () let live: Session | undefined = oldSession.session; const maker = { createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -1940,6 +1942,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () let live: Session | undefined = oldSession.session; const maker = { createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -1997,6 +2000,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () let live: Session | undefined = oldSession.session; const maker = { createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -2097,6 +2101,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () let live: Session | undefined = oldSession.session; mocks.getMaker.mockReturnValue({ createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -2166,6 +2171,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () const releaseLock = vi.fn(); mocks.getMaker.mockReturnValue({ createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -2247,6 +2253,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', () let live: Session | undefined = oldSession.session; const maker = { createSession: vi.fn(async () => oldSession.session), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), getSession: vi.fn(() => live), on: vi.fn((listener: (event: MakerEvent) => void) => { makerEventListeners.push(listener); @@ -4865,6 +4872,7 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => { let wired = false; return { getSession: vi.fn(() => (wired ? session : undefined)), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), createSession: vi.fn(async () => { order.push('wire'); wired = true; diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index c38e83ccf3..e9150d0a05 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1718,6 +1718,49 @@ export function createTurnRunner( return { kind: 'rejected', reason: 'aborted' }; } + // 项目资源漂移(如会话中途 openspec init):空闲时经 Maker 以 runtime-refresh + // 回收运行时,再按 DB 行自愈重建 —— 与桌面发送事务同口径,IM 直发不用旧资源。 + // 无 agent-switch 锁的装配不支持关闭后重建,保持原样投递。 + let driftRecycled = false; + try { + driftRecycled = !!(deps.acquirePendingAgentSwitch + && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)); + } catch (err) { + // close 抛出时 Session 已停在 error(performClose 不回退),旧实例不可用: + // 只能走重建;仍 active 才原样投递(Codex P2, 2026-11-10)。 + driftRecycled = !!deps.acquirePendingAgentSwitch && state.makerSession.getStatus() !== 'active'; + log.warn('im send: resource-drift recycle failed', + err instanceof Error ? err.message : String(err)); + } + if (driftRecycled) { + await refreshSessionAfterPendingAgentSwitch(state, state.makerSession.id, userId); + log.info('im send: project resources drifted, recycled runtime before dispatch'); + } + // 回收+重建是异步窗口:/stop 可能恰好落在其中;喊停后不得再开始执行,与上方 + // aborted 分支同口径收尾(此时尚未发送,无需补终态章)。经函数读取:上方检查 + // 已把控制流收窄到 'done'|'error',但运行时值在回收窗口内仍可变为 'aborted'。 + const turnTerminalNow = (): 'done' | 'aborted' | 'error' => item.turn.terminalKind; + if (turnTerminalNow() === 'aborted') { + const index = state.queue.indexOf(item.turn); + if (index >= 0) state.queue.splice(index, 1); + if (output.kind === 'chunked-text' && item.turn.chunkedReplyBegun) { + try { + await output.commitFinal({ + userId, + text: ui.agent.stopDone(0), + terminal: 'aborted', + threadTs: item.turn.scopeKey, + }); + } catch (err) { + log.warn(`cancelled reply finalization failed: ${err instanceof Error ? err.message : String(err)}`); + } + } + await completeTurnCallbackAfterAck(item.turn); + settleTurnTerminal(item.turn); + if (!finishDeferredDetachIfIdle(state)) armDispatchRetry(state, userId); + return { kind: 'rejected', reason: 'aborted' }; + } + const sendResult = await state.makerSession.send(outgoingMessage as typeof item.userMessage, { planMode: false, // IM owns successful replies, including turns in an attached desktop task. diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts index 3e83df8008..2a1222a0cc 100644 --- a/apps/desktop/src/main/local-agent/runtime.ts +++ b/apps/desktop/src/main/local-agent/runtime.ts @@ -207,7 +207,7 @@ export function createEventProjection( } export async function openLocalAgentRuntime( - maker: Pick, + maker: Pick, directory: string, input: LocalAgentOpen, bridge: { url: string; token: string; emit(event: unknown): void }, @@ -570,6 +570,38 @@ export async function openLocalAgentRuntime( handle = await start(previous.sdkSessionId, current); appliedInstructions = applying; } + // 项目资源漂移(pi 本地根任务):发送前原地重建,重扫项目资源重算 argv —— + // 与上方 instructions 换代同一空闲窗口(尚未投递);空闲口径同 + // hasRecyclableProjectResourceDrift,非 pi agent 恒 false 跳过。 + if (handle.hasRecyclableProjectResourceDrift()) { + const previous = handle; + // 可见变体的 Session 由 Maker 托管:必须走 Maker 的 runtime-refresh 关闭 + // (实例方法自带 rehydrate 抑制窗口)。直接 Session.close 不登记原因,会 + // 被按 unexpected 丢掉排队回合,未抑制的 onClose 会在重建前清掉暂存附件 + // (Codex P1,2026-11-10)。 + // 回收抛错时**不得**在抑制窗口外裸 close 重试:那样一旦成功,onClose 的 + // 临时附件清理会在 start() 恢复同一份转录前删掉它引用的暂存文件 + // (Codex P2,2026-11-10)。抛错后的处置:实例已非 active(close 失败停在 + // error)则直接重建 —— Maker.createSession 自带 error 实例的关闭重试; + // 仍 active 则本轮跳过重建,保住旧运行时与暂存附件,下一条消息再试。 + // 不可见变体不由 Maker 托管(不在 activeSessions),没有抑制窗口语义, + // 直关即可。 + let rebuild = false; + if (visibleHost) { + try { + rebuild = await maker.recyclePiRuntimeIfResourcesDrifted(previous); + } catch { + rebuild = previous.getStatus() !== 'active'; + } + } else { + await previous.close(); + rebuild = true; + } + if (rebuild) { + assertCurrent(current); + handle = await start(previous.sdkSessionId, current); + } + } if (params.effort !== undefined) { await handle.setEffort(params.effort as Parameters[0]); effort = string(params.effort); diff --git a/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts b/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts index 15aa3ec690..d2006b6739 100644 --- a/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts +++ b/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts @@ -107,7 +107,9 @@ export function createCodexPickerHarness(input: { const beforeSend = vm.runInContext(closure('pendingAgentSwitchApplyHolder'), context) as (id: string) => Promise<{ release(): void }>; const transactionDeps: MakerSendTransactionDeps = { statDirectory: async () => ({ isDirectory: () => true }), - getSession: id => maker.getSession(id), closeSession: id => maker.closeSession(id), getSessionMeta: id => maker.getSessionMeta(id), + getSession: id => maker.getSession(id), closeSession: id => maker.closeSession(id), + closeSessionIfCurrent: async id => { const s = maker.getSession(id); if (s) await maker.closeSessionIfCurrent(s, 'runtime-refresh'); }, + getSessionMeta: id => maker.getSessionMeta(id), preflightBotRuntimeResources: asyncNoop, ensureRemoteReadyForSessionStart: asyncNoop, checkWorkDirExists: async () => true, readSessionWorkingDirFromDb: async () => workingDir, readWorkingDirectoryRecoveryCreateOpts: async id => { diff --git a/apps/desktop/src/main/maker-host/__tests__/codexTerraProxy.integration.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexTerraProxy.integration.test.ts index e9db33dc5c..48ab73b3da 100644 --- a/apps/desktop/src/main/maker-host/__tests__/codexTerraProxy.integration.test.ts +++ b/apps/desktop/src/main/maker-host/__tests__/codexTerraProxy.integration.test.ts @@ -56,7 +56,7 @@ describe.skipIf(!binary)('native Terra Ultra and Fast through the Cindy proxy', let server: ReturnType | undefined; let catalogForCleanup: typeof import('../active-catalog.js') | undefined; let routingForCleanup: typeof import('../provider-route.js') | undefined; - let proxyForCleanup: typeof import('../codex-proxy-host.js') | undefined; + let proxyForCleanup: typeof import('../codex-proxy-host.desktop.js') | undefined; let sessionsForCleanup: typeof import('../session-provider-store.js') | undefined; let agent: CodexAgent | undefined; let handle: AgentSessionHandle | undefined; @@ -95,7 +95,7 @@ describe.skipIf(!binary)('native Terra Ultra and Fast through the Cindy proxy', catalogForCleanup = catalog; const routing = await import('../provider-route.js'); routingForCleanup = routing; - const proxy = await import('../codex-proxy-host.js'); + const proxy = await import('../codex-proxy-host.desktop.js'); proxyForCleanup = proxy; const sessions = await import('../session-provider-store.js'); sessionsForCleanup = sessions; diff --git a/apps/desktop/src/main/maker-host/__tests__/withRehydrateCloseSuppressed.test.ts b/apps/desktop/src/main/maker-host/__tests__/withRehydrateCloseSuppressed.test.ts index 8594b8f355..d750c6349c 100644 --- a/apps/desktop/src/main/maker-host/__tests__/withRehydrateCloseSuppressed.test.ts +++ b/apps/desktop/src/main/maker-host/__tests__/withRehydrateCloseSuppressed.test.ts @@ -134,4 +134,23 @@ describe('withRehydrateCloseSuppressed', () => { { sessionId: 'session-1' }, ); }); + + it('forceSkip skips side-effects even after the suppression window has been released', async () => { + // 回归(Greptile P1):Maker.close 不等 onClose;漂移回收包裹的窗口在 close + // 返回后即释放,而 onClose 先等 worktree lease 的文件操作才查抑制表 —— + // 重查会错过窗口照删暂存附件。入口取样(forceSkip)必须独立于当前表生效。 + const log = makeLog(); + const suppression = createRehydrateCloseSuppression(log); + const sideEffect = vi.fn(async () => undefined); + + await suppression.withSuppressed('session-1', async () => undefined); + // 此刻窗口已释放(生产里对应 close 返回后调用方 finally 释放),但 onClose + // 入口在窗口内取样的抑制态必须仍然生效。 + await suppression.runOnCloseSideEffects('session-1', sideEffect, { forceSkip: true }); + + expect(sideEffect).not.toHaveBeenCalled(); + // 不传 forceSkip 时照常执行(其余调用方不受影响)。 + await suppression.runOnCloseSideEffects('session-1', sideEffect); + expect(sideEffect).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts index d9eb96684b..c1f17ce1bc 100644 --- a/apps/desktop/src/main/maker-host/built-in-skills.ts +++ b/apps/desktop/src/main/maker-host/built-in-skills.ts @@ -25,7 +25,7 @@ const VERSIONS_DIRECTORY = '.versions'; const ACTIVE_BUNDLE_LINK = '.active'; const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000; /** Increment whenever shipped built-in Skill bytes change between releases. */ -export const BUILT_IN_SKILLS_BUNDLE_VERSION = 93; +export const BUILT_IN_SKILLS_BUNDLE_VERSION = 95; const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13; export interface BuiltInSkillDescriptor { diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts index f1e33d477d..689ae51328 100644 --- a/apps/desktop/src/main/maker-host/index.ts +++ b/apps/desktop/src/main/maker-host/index.ts @@ -55,6 +55,7 @@ import path from 'node:path'; import { Maker, + type Session, isBotMcpServerAllowed, ClaudeCodeAgent, CodexAgent, @@ -2885,6 +2886,11 @@ export function getMaker(): Maker { await writeCodexHistoryHasProductPrompt(sessionId, historyHasProductPrompt); }, onClose: async (sessionId, options) => { + // 抑制态必须在首个 await 前取样:Maker.close 不等 onClose,调用方(漂移 + // 回收包裹/任务移动/桌面发送 seam)的抑制窗口会在 close 返回后即释放, + // 而本钩子先等 worktree lease 的文件操作才查抑制表 —— 重查会错过窗口, + // 让重建期间的 close 照删暂存附件(Greptile P1,2026-11-10)。 + const rehydrateSuppressedAtClose = rehydrateCloseSuppression.isSuppressed(sessionId); clearUsagePricing(sessionId); const lease = worktreeRuntimeLeases.get(options); if (lease) { @@ -2904,10 +2910,19 @@ export function getMaker(): Maker { // 这)。回收只由会话显式删除/归档驱动,见 localDb/ipc/sessions.ts → // worktree/sessionRemovalRecycle.ts。 await WorktreePool.releaseWorktree(sessionId).catch(() => undefined); - }); + }, { forceSkip: rehydrateSuppressedAtClose }); }, }, }); + // 漂移回收的 close 必须在抑制窗口内:直发链路(IM turnRunner/hook/scheduler/goal) + // 回收后立刻按 DB 行重建同一任务,窗口内 onClose 跳过临时附件清理与 worktree + // 释放 —— 否则重建后的 turn 会丢转录里引用的暂存附件(Codex P2,2026-11-10)。 + // 桌面发送事务的同一 close 在 register.ts 的 deps seam 处已各自包裹,此处收口 + // 其余全部直发调用方(getMaker 侧不经过 seam)。 + const baseRecyclePiRuntimeIfResourcesDrifted + = _maker.recyclePiRuntimeIfResourcesDrifted.bind(_maker); + _maker.recyclePiRuntimeIfResourcesDrifted = async (session: Session) => + withRehydrateCloseSuppressed(session.id, () => baseRecyclePiRuntimeIfResourcesDrifted(session)); // 本机作为「Agent 运行的电脑」:同账号另一台电脑的任务可让 Agent 在这里运行。 installRemoteAgentHost({ getMaker: () => getMaker(), diff --git a/apps/desktop/src/main/maker-host/rehydrateCloseSuppression.ts b/apps/desktop/src/main/maker-host/rehydrateCloseSuppression.ts index d78076a2eb..22fa695a12 100644 --- a/apps/desktop/src/main/maker-host/rehydrateCloseSuppression.ts +++ b/apps/desktop/src/main/maker-host/rehydrateCloseSuppression.ts @@ -41,7 +41,14 @@ export function createRehydrateCloseSuppression( async function runOnCloseSideEffects( sessionId: string, fn: () => Promise, + opts?: { forceSkip?: boolean }, ): Promise { + if (opts?.forceSkip === true) { + // 关闭方在首个 await 前取样的抑制态:Maker.close 不等 onClose,调用方的 + // 窗口可能在本钩子跑到这里之前就已释放 —— 时序上必须信入口取样,不能重查。 + log.debug('skip onClose side-effects: suppression captured at close entry', { sessionId }); + return; + } if (shutdownSuppressed) { log.debug('skip onClose side-effects during shutdown', { sessionId }); return; diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts index 7604818221..f28791db2c 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts @@ -13105,7 +13105,7 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修 }; const transaction=createMakerSendTransaction({ statDirectory:async()=>({isDirectory:()=>true}), - getSession:()=>session,closeSession:async()=>{},preflightBotRuntimeResources:async()=>{}, + getSession:()=>session,closeSession:async()=>{},closeSessionIfCurrent:async()=>{},preflightBotRuntimeResources:async()=>{}, getSessionMeta:async()=>({}),ensureRemoteReadyForSessionStart:async()=>{},checkWorkDirExists:async()=>true, isOrcaMcpHydrated:()=>true,buildCreateOptsWithStderr:x=>x,synthesizeOrcaVendorOptionsFromDb:async()=>false, readSessionExtraDirsFromDb:async()=>[],readSessionWorkingDirFromDb:async()=>'/answer', @@ -15327,7 +15327,7 @@ describe('usage-limit wait (ordinary tasks)', () => { })).mockRejectedValueOnce(quota); const transaction = createMakerSendTransaction({ getSession: () => rehydrate ? session : undefined, - closeSession: async () => {}, preflightBotRuntimeResources: async () => {}, + closeSession: async () => {}, closeSessionIfCurrent: async () => {}, preflightBotRuntimeResources: async () => {}, getSessionMeta: async () => ({}), ensureRemoteReadyForSessionStart: async () => {}, checkWorkDirExists: async () => true, isOrcaMcpHydrated: () => !rehydrate, buildCreateOptsWithStderr: x => x, synthesizeOrcaVendorOptionsFromDb: async () => rehydrate, diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts index d15090e0fb..380da0e2b4 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts @@ -94,6 +94,31 @@ describe('local application task takeover', () => { expect(session.send).not.toHaveBeenCalled(); }); }); + +describe('project resource drift recycling', () => { + function driftDeps() { + const { deps, session } = createDeps(); + const live = createSession({ hasRecyclableProjectResourceDrift: () => true }); + deps.getSession = () => live; + return { deps, live, session }; + } + + it('recycles a drifted live runtime when createOpts allows lazy rebuild', async () => { + const { deps, live } = driftDeps(); + await createMakerSendTransaction(deps).sendToAgentAccepted( + 'session-1', 'hello', { id: 'session-1', agentKind: 'pi', workingDir: 'C:\\repo' }); + expect(deps.closeSessionIfCurrent).toHaveBeenCalledWith('session-1'); + expect(live.send).not.toHaveBeenCalled(); + }); + + it('keeps the live-send path when no createOpts can rebuild the runtime', async () => { + const { deps, live } = driftDeps(); + // 直发/老链路无 createOpts:回收后 lazy-create 无法重建,按原运行时投递 + await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'hello'); + expect(deps.closeSessionIfCurrent).not.toHaveBeenCalled(); + expect(live.send).toHaveBeenCalledOnce(); + }); +}); describe('MCP App next-turn context', () => { it('keeps ordinary user intent when validating App context without a replacement intent', async () => { const assertCurrent = vi.fn(async () => {}); @@ -299,6 +324,7 @@ function createDeps(overrides: Partial = {}) { readScheduledPermissions: vi.fn(async () => ({ permissionMode: 'ask', planModeEnabled: false })), getSession: vi.fn((sessionId: string) => (sessionId === session.id ? session : undefined)), closeSession: vi.fn(async () => {}), + closeSessionIfCurrent: vi.fn(async () => {}), preflightBotRuntimeResources: vi.fn(async () => {}), getSessionMeta: vi.fn(async () => ({ title: '现有会话' })), ensureRemoteReadyForSessionStart: vi.fn(async () => {}), diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts index 27f254ae4d..b202e0a0e9 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts @@ -460,6 +460,29 @@ describe('Orca lead/worker dispatcher', () => { expect(liveSession.send).not.toHaveBeenCalled(); }); + it('recycles a drifted runtime before live dispatch and rebuilds via the queued path', async () => { + // Orca 直发绕过发送事务:漂移时先回收(重建窗口内),本条消息转 + // sendToSessionInternal 的 lazy/queued 路径重扫重建投递,不拿旧 argv 跑。 + const recycleProjectResourceRuntime = vi.fn(async () => true); + const h = createHarness({ recycleProjectResourceRuntime }); + + const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({ + targetSessionId: 'target-session', + rawContent: 'Run with the refreshed skill set', + source: 'lead', + senderLabel: 'Lead', + meta: { source: 'orca', context: 'drift-recycle-test' }, + }); + + expect(recycleProjectResourceRuntime).toHaveBeenCalledWith('target-session'); + expect(h.liveSession.send).not.toHaveBeenCalled(); + expect(result).toMatchObject({ ok: true, mode: 'dispatched' }); + expect(h.deps.sendToSessionInternal).toHaveBeenCalledWith(expect.objectContaining({ + targetSessionId: 'target-session', + clientId: 'client-1', + })); + }); + it('still sends through the live handle after prepare leaves it open', async () => { const prepareUnhealthySession = vi.fn(async () => false); const h = createHarness({ prepareUnhealthySession }); diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts index e72b435966..647eb6cd0b 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts @@ -492,7 +492,7 @@ describe('companion internal delivery after automation', () => { limit: async () => [{ role, botId: 'companion' }] }; const enqueue = vi.fn(async () => undefined); const h = botTaskDispatchHarness({ child: { permissionMode: 'auto', planModeEnabled: false } }, { - child: { id: 'child', agentKind: 'pi', isTurnRunning: () => false, getStatus: () => 'active' }, + child: { id: 'child', agentKind: 'pi', isTurnRunning: () => false, getStatus: () => 'active', hasRecyclableProjectResourceDrift: () => false }, }, { getDbClient: () => ({ drizzle: { select: () => dbChain } }), isShadowedCompanionSession, isCompanionShadowed: () => shadowed, @@ -514,7 +514,7 @@ describe('companion internal delivery after automation', () => { const dbChain = { from: () => dbChain, where: () => dbChain, limit: async () => [{ role: 'canonical', botId: 'companion' }] }; const h = botTaskDispatchHarness({ child: { permissionMode: 'auto', planModeEnabled: false } }, - path === 'live' ? { child: { id: 'child', agentKind: 'pi', isTurnRunning: () => false, getStatus: () => 'active' } } : {}, { + path === 'live' ? { child: { id: 'child', agentKind: 'pi', isTurnRunning: () => false, getStatus: () => 'active', hasRecyclableProjectResourceDrift: () => false } } : {}, { getDbClient: () => ({ drizzle: { select: () => dbChain } }), isShadowedCompanionSession, isCompanionShadowed: () => shadowed, createDbMessage: async () => { shadowed = true; }, @@ -534,6 +534,7 @@ describe('companion internal delivery after automation', () => { const live: Record = {}; let dispatchedModel: string | undefined; const makeLive = () => ({ id: 'child', ...current, isTurnRunning: () => false, getStatus: () => 'active', + hasRecyclableProjectResourceDrift: () => false, send: async () => { dispatchedModel = current.model; return { accepted: true }; } }); if (path === 'live') live.child = makeLive(); const scope = createScheduledModelScope({ diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts index 78a6522c9a..de96061898 100644 --- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts +++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts @@ -259,6 +259,8 @@ export interface MakerSendTransactionSession { /** Codex host-owned evidence: a provider turn crossed acceptance on this runtime. */ codexThreadMayHaveRollout?: boolean; isTurnRunning(): boolean; + /** 项目资源漂移且满足回收空闲口径(仅 pi 本地根任务实现;其余会话缺省,永不回收)。 */ + hasRecyclableProjectResourceDrift?(): boolean; send(message: UserMessage | string, opts?: SessionSendOptions): Promise; } @@ -270,6 +272,9 @@ export interface MakerSendTransactionLog { export interface MakerSendTransactionDeps { getSession(sessionId: string): MakerSendTransactionSession | undefined | null; closeSession(sessionId: string): Promise; + /** 资源漂移回收必须走 Maker 的 runtime-refresh 原因(直接 Session.close 会被 + * IM runner 当 unexpected 丢弃排队回合);内部用 closeSessionIfCurrent 幂等。 */ + closeSessionIfCurrent(sessionId: string): Promise; preflightBotRuntimeResources(opts: CreateOpts): Promise; getSessionMeta(sessionId: string): Promise<{ title?: string } | null>; /** The same clear/rewind-filtered transcript used for native context handoffs. */ @@ -1114,6 +1119,17 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make deps.log.info('send: error session requires recovery before dispatch', { sessionId }); sess = undefined; } + // 会话中途新增的项目资源(如 openspec init):空闲时经 Maker 以 + // 'runtime-refresh' 回收运行时(session:closed 带刷新原因,IM runner 保留 + // 排队回合),下面的 lazy bootstrap 会重扫重算 argv 后再投递 + // (见 Session.hasRecyclableProjectResourceDrift 的空闲口径说明)。 + // 无 createOpts 的直发/老链路调用无法走 lazy-create 重建,跳过回收按 + // 原运行时投递(维持回收前行为,不把触发消息拒成 NOT_FOUND)。 + if (createOpts && sess?.hasRecyclableProjectResourceDrift?.()) { + await deps.closeSessionIfCurrent(sessionId); + deps.log.info('send: project resources drifted, recycling runtime before dispatch', { sessionId }); + sess = undefined; + } if (sess?.isTurnRunning()) { throwIpcError('SESSION_RUNNING', `Session ${sessionId} is already running a turn`); } diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts index 28d1af8263..9d8dbfb9cf 100644 --- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts +++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts @@ -191,6 +191,11 @@ export interface OrcaInterAgentDispatcherDeps { withSendToSessionLock?: (sessionId: string, task: () => Promise) => Promise; /** 直发前与 sendToSessionInternal 共用同一套满窗 / compact 失败换窗预检。 */ prepareUnhealthySession?: (sessionId: string) => Promise; + /** + * 项目资源漂移时的 runtime 回收(空闲口径, pi only)。true=已按 runtime-refresh + * 关闭旧 runtime,调用方应转 queued/lazy 路径重建投递,不拿旧 argv 跑这一轮。 + */ + recycleProjectResourceRuntime?: (sessionId: string) => Promise; /** * 直发前补齐 Orca 装载:目标在 runtime 已启动后才成为 Lead/Worker(例如从协同面板 * 开启协同)时,live handle 还没有 Orca 说明与工具。与用户发送共用同一套重建; @@ -625,6 +630,11 @@ export function createOrcaInterAgentDispatcher( } const live = deps.getLiveSession(params.targetSessionId); if (!live) return null; + // 项目资源漂移:回收旧 runtime 后转 queued/lazy 路径(sendToSessionInternal + // 的 lazy-resume 会重扫重算 argv 重建),不在旧 argv 上跑这一轮。 + if (await deps.recycleProjectResourceRuntime?.(params.targetSessionId) === true) { + return null; + } const origin = await resolveOrigin(); const result = await sendPersistedUserMessageToSession(deps, { session: live, diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts index 458b57d65f..0f12d3e728 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -13252,6 +13252,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) // whose Maker.createSession call performs the existing bounded close retry. live = undefined; } + // 会话中途新增的项目资源(如 openspec init):空闲时经 Maker 以 + // 'runtime-refresh' 回收运行时(直接 Session.close 会丢 Maker 原因,IM 侧按 + // unexpected 清排队回合),lazy resume 重扫重建 + if (live?.agentKind === 'pi' && live.hasRecyclableProjectResourceDrift()) { + // 同 makerSendTransaction 的漂移回收:关闭包在抑制窗口内(保留重建窗口, + // 不 abort 本通道在途的派发边界,不释放 worktree/临时附件),下面的 + // lazy resume 随即重扫重建再投递。 + const driftedLive = live; + await withRehydrateCloseSuppressed(targetSessionId, () => + maker.closeSessionIfCurrent(driftedLive, 'runtime-refresh')); + live = undefined; + } if (live) { if (live.isTurnRunning?.()) { lockStage = 'enqueue-queued-message'; @@ -15868,6 +15880,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId).catch(() => null), getSessionRowSnapshot, getLiveSession: (sessionId) => maker.getSession(sessionId), + recycleProjectResourceRuntime: async (sessionId) => { + const current = maker.getSession(sessionId); + if (current?.agentKind !== 'pi' || current.hasRecyclableProjectResourceDrift() !== true) return false; + // 与发送事务 deps.closeSessionIfCurrent 同一「重建窗口」:抑制窗口内关闭, + // 否则 close 广播 abort 在途派发边界(2026-11-08 自鲨实报);后续 queued/lazy + // 路径用重建后的 runtime 投递。 + await withRehydrateCloseSuppressed(sessionId, () => + maker.closeSessionIfCurrent(current, 'runtime-refresh')); + return true; + }, validateImageAttachments: async (paths) => { // 图片来源两类: 会话受管地址(cindy-media:// / xdt-image://)与任意本机绝对路径。 const images: Array<{ path: string; name: string; ext: string; size: number; mimeType: string }> = []; @@ -18849,6 +18871,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) }, getSession: (sessionId) => maker.getSession(sessionId), closeSession: (sessionId) => maker.closeSession(sessionId), + closeSessionIfCurrent: async (sessionId) => { + const current = maker.getSession(sessionId); + if (!current) return; + // 漂移回收是「重建窗口」,不是生命周期终止:本次发送事务随即 lazy bootstrap + // 重建并投递。必须在抑制窗口内关闭 —— 否则 onSessionClosed 会 abort 正在 + // 驱动这次回收的发送边界,首条消息被标成 cancelled-before-dispatch,用户 + // 手动重试才过(2026-11-08 实报)。副作用语义同 closeIdleSessionForMove + // (任务移动):跳过 worktree 释放与临时附件清理,交给重建后的 runtime。 + await withRehydrateCloseSuppressed(sessionId, () => + maker.closeSessionIfCurrent(current, 'runtime-refresh')); + }, getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId), ensureRemoteReadyForSessionStart: async (params) => { await ensureRemoteReadyForSessionStart(params); diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts index 8901264d45..4ea1fd4e36 100644 --- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts +++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts @@ -315,12 +315,15 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand const teardown = async (mode: 'close' | 'detach', opts?: AgentSessionTeardownOptions) => { deps.cancelPendingConfirmations?.(); const reason = opts?.reason ?? 'navigation'; + // 远端会话无项目资源启动快照,永不漂移,不存在资源回收关闭;资源刷新关闭由 + // Maker 侧以 'runtime-refresh' 原因走 closeSessionIfCurrent,不进远端 wire。 + const wireReason: RemoteAgentTeardownReason = reason; if (reason === 'account-boundary') { // The Agent uses the other computer's credentials. A failed notification // is not evidence of a surviving local Pi process (#6921). Release local // resources independently, even while the remote request is still pending. const [remote, local] = await Promise.allSettled([ - Promise.resolve().then(() => link.close(mode, reason)), + Promise.resolve().then(() => link.close(mode, wireReason)), dispose(), ]); if (remote.status === 'rejected') { @@ -332,7 +335,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand return; } try { - await link.close(mode, reason); + await link.close(mode, wireReason); } catch (error) { // A remote notification failure cannot keep an already disposed local // Session running. The next explicit send will reopen its native history. diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerAgentMeta.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerAgentMeta.test.ts index 742963bcf0..ec45744694 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerAgentMeta.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerAgentMeta.test.ts @@ -146,6 +146,7 @@ function createRunnerHarness( getSessionMeta: vi.fn(async () => opts.sessionMeta ?? null), isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts index 60a8f273af..4de1c00e50 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts @@ -197,6 +197,7 @@ function createRunnerHarness(session: Session, overrides: Partial null), isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerDefer.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerDefer.test.ts index babf337c4d..c77a9c41a4 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerDefer.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerDefer.test.ts @@ -137,6 +137,7 @@ function createRunnerHarness(session: Session, options: RunnerHarnessOptions = { // heartbeat alive 分支:getSessionMeta 返回有效 meta(非 null → 不归档) getSessionMeta: vi.fn(async () => ({ sdkSessionId: 'sdk-1', workDir: 'F:\\X', model: 'gpt-5.4' })), isSessionAlive: vi.fn(() => options.sessionAlive ?? true), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, getDb: () => ({}) as never, notifier, logger, findUsageLimitWait: options.findUsageLimitWait }); diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts index bee11d19bb..00497010ea 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts @@ -290,6 +290,7 @@ function createRunnerHarness( // 默认 false = fresh spawn(opts.model/effort 已生效);true 模拟进程内 // 复用 active session 的路径(createSession 忽略 opts, setModel/setEffort 是唯一通道)。 isSessionAlive: vi.fn(() => opts.sessionAlive ?? false), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const notifier: Notifier = { notify: vi.fn(async () => undefined) }; const runner = new MakerScheduleRunner({ diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts index 97e484a9fa..4b2b041d57 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts @@ -100,6 +100,7 @@ function createRunner(getSessionMeta: Maker['getSessionMeta']) { getSessionMeta, isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts index e174c03ea4..5e8af6ea02 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts @@ -467,6 +467,7 @@ function createRunnerHarness( }), // issue #456:排队派发路径也按所选模型 efforts reconcile effort;测试经 availableModels 注入能力。 getCapabilities: vi.fn((_agent: string) => ({ availableModels: opts.availableModels ?? [] })), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts index b0db0f30bc..779fbb7be4 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts @@ -173,6 +173,7 @@ function createRunnerHarness( getSessionMeta: vi.fn(async () => null), isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, @@ -790,4 +791,52 @@ describe('MakerScheduleRunner send outcome policy', () => { expect(isHeadlessGhostSetupTurn('scheduler-session')).toBe(false); expect(mocks.createMessage).not.toHaveBeenCalled(); }); + + it('rebuilds a recycled runtime in place and dispatches on the rebuilt instance (direct-send degradation)', async () => { + // 回归(MagicLizi P1):直发降级的「漂移回收 → 就地重建 → wireSessionToIpc 重接」 + // 分支此前零覆盖;换实例不重接会让本轮回复与工具记录不进聊天页(两次踩中的隐性契约)。 + const h = createSessionHarness(async () => ({ accepted: true })); + const rebuilt = createSessionHarness(async () => ({ accepted: true })); + const { runner, maker, logger, notifier } = createRunnerHarness(h.session); + (maker.recyclePiRuntimeIfResourcesDrifted as ReturnType).mockResolvedValue(true); + let created = 0; + (maker.createSession as ReturnType).mockImplementation(async () => { + created += 1; + return created === 1 ? h.session : rebuilt.session; + }); + const ctx = createFireContext(); + const firePromise = runner.fire(baseSchedule(), ctx); + await vi.waitFor(() => expect(rebuilt.send).toHaveBeenCalled()); + // accepted 后 fire 等 turn 终态:重建实例上发出 done 收口本轮。 + rebuilt.emit({ type: 'done', data: {} } as AgentEvent); + await firePromise; + + expect(maker.recyclePiRuntimeIfResourcesDrifted).toHaveBeenCalledWith(h.session); + expect(logger.info).toHaveBeenCalledWith( + '[runner] project resources drifted, recycled runtime before dispatch', + { sessionId: 'scheduler-session' }, + ); + // 投递必须落在重建实例上;旧实例已关闭,打到它只会得到误导性的失败。 + expect(mocks.wireSessionToIpc).toHaveBeenCalledWith(rebuilt.session); + expect(rebuilt.send).toHaveBeenCalledTimes(1); + expect(h.send).not.toHaveBeenCalled(); + expect(latestNotifiedRun(notifier).status).toBe('success'); + }); + + it('surfaces rebuild failure loudly after a successful recycle instead of sending to a closed instance', async () => { + // 回归(fe45afa803 语义):回收成功(旧实例已关)后的重建失败必须上抛原始原因, + // 继续用已关闭实例只会把真实原因换成误导性的「会话已关闭」。 + const h = createSessionHarness(async () => ({ accepted: true })); + const { runner, maker, notifier } = createRunnerHarness(h.session); + (maker.recyclePiRuntimeIfResourcesDrifted as ReturnType).mockResolvedValue(true); + (maker.createSession as ReturnType) + .mockImplementationOnce(async () => h.session) + .mockRejectedValueOnce(new Error('pi startup failed: model catalog unavailable')); + const ctx = createFireContext(); + + // 重建失败在 run 组装前裸上抛(不产出 failed run):大声失败正是修复语义。 + await expect(runner.fire(baseSchedule(), ctx)).rejects.toThrow(/pi startup failed/); + expect(h.send).not.toHaveBeenCalled(); + expect(notifier.notify).not.toHaveBeenCalled(); + }); }); diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSessionClose.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSessionClose.test.ts index acc1d36529..bb523c5952 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSessionClose.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSessionClose.test.ts @@ -165,6 +165,7 @@ function createRunnerHarness(session: Session) { getSessionMeta: vi.fn(async () => null), isSessionAlive: vi.fn(() => false), closeSession, + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts index d8537b147e..d04fe6d5f6 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts @@ -152,6 +152,7 @@ function createRunnerHarness( getSessionMeta: vi.fn(async () => null), isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerWorkingDirFallback.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerWorkingDirFallback.test.ts index b2a19a12b1..d3d561d013 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerWorkingDirFallback.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerWorkingDirFallback.test.ts @@ -142,6 +142,7 @@ function createRunnerHarness( getSessionMeta: vi.fn(async () => null), isSessionAlive: vi.fn(() => false), closeSession: vi.fn(async () => undefined), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false), } as unknown as Maker; const runner = new MakerScheduleRunner({ maker, diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts index da1ad8f02b..1b903769a8 100644 --- a/apps/desktop/src/main/scheduler-host/runner.ts +++ b/apps/desktop/src/main/scheduler-host/runner.ts @@ -1930,6 +1930,17 @@ export class MakerScheduleRunner implements ScheduleRunner { ); } + // 直发降级路径(无 schedulerQueue):项目资源漂移时先经 Maker 以 runtime-refresh + // 回收;回收后必须就地重建 —— 下方的 stale 自愈只在 Pi 模型路由分支内,否则 + // 直发会打到已关闭的实例上。 + if (await this.deps.maker.recyclePiRuntimeIfResourcesDrifted(session)) { + this.deps.logger.info?.('[runner] project resources drifted, recycled runtime before dispatch', { sessionId: session.id }); + session = await this.deps.maker.createSession({ ...createSessionOpts }); + // wireSessionToIpc 按 Session 实例幂等,换实例需重接广播/落库链路, + // 否则本轮回复与工具记录不进聊天页(上游已改为 runtime 注入的依赖)。 + this.runtime.wireSessionToIpc(session); + } + // Resolve Pi's last provider change before listener, abort and handoff // state bind to the Session instance. The transaction may retire it. if (!agentDeviceId && effectiveAgentKind === 'pi' && this.deps.checkModelRoute) { diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md index 81d90eb479..1177ed5a4c 100644 --- a/docs/dev-rules/pi-harness.md +++ b/docs/dev-rules/pi-harness.md @@ -372,7 +372,13 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见 不得读取/复制项目 `.pi/settings.json`,不得传 `--approve`, 不得依赖 `PI_OFFLINE=1` 代替该 settings 硬门。root 不传 `--no-skills`,以保留现有 user/global skill 行为;项目 skill 的 `loaded` 由当前会话 `get_commands` 对原路径 provenance - 证明。 + 证明。运行时空闲且盘上资源集合相对启动快照漂移时,host 可在发送前回收进程 + (经 Maker `closeSessionIfCurrent(session, 'runtime-refresh')`,让 session:closed + 带上 IM runner 认识的刷新原因;直接 Session.close 会被按 unexpected 丢弃排队回合。 + 空闲口径与 closeIfIdle 一致:turn 运行中、结束未收口的 turn、换代续接、手动压缩 / + rewind 等宿主排他操作进行中绝不回收),由既有 lazy bootstrap + 以相同的显式装配语义重扫重建 —— 资源集合是 spawn argv 的输入,只能进程重建时重算; + 远端/Bot/受邀者会话无启动快照,不参与漂移检测。 9. **Pi bash bounded timeout**:Cindy 覆盖的模型可调 `bash` 在 execute 入口强制默认 `300s`、上限 `1800s`。缺省或非正数用默认;大于上限或非有限数字 fail-fast(参数错误, 不是 `Command timed out`);合法秒数原样交给 Pi 原生执行器。不另起 timer / AbortController。 diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts index e3f68c51ab..b34accb82a 100644 --- a/packages/maker-core/src/agents/base-agent.ts +++ b/packages/maker-core/src/agents/base-agent.ts @@ -2708,6 +2708,11 @@ export interface AgentSessionHandle { * 默认实现为 false (capability 缺失时 host 不该问)。 */ isTurnRunning?(): boolean; + /** + * 盘上项目资源相对运行时启动快照是否已漂移(仅原地加载项目资源的 pi 本地根任务实现, + * 其余 agent 恒缺省)。host 可据此回收运行时,让下次 spawn 重扫并重算资源 argv。 + */ + hasProjectResourceDrift?(): boolean; /** A provider-owned preparatory turn still precedes the accepted user input. * Host timeouts must not resume it with a generic CONTINUE. Read synchronously * before abort clears the provider's existing preparation state. diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-project-resource-drift.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-project-resource-drift.test.ts new file mode 100644 index 0000000000..90cb716d5e --- /dev/null +++ b/packages/maker-core/src/agents/pi/__tests__/pi-project-resource-drift.test.ts @@ -0,0 +1,305 @@ +/** + * 项目资源漂移检测 —— 纯 fs 单测(不 spawn pi)。 + * + * 契约:启动快照只存「argv 实际使用的路径集合」;piProjectResourcesDrifted 用 + * 同一个 collector 重新采集一遍后逐项比较。**没有任何基线镜像**(无 mtime、无条目 + * 指纹、无逐 key 解析身份),因此不存在「镜像与 collector 分歧」导致的漏检: + * 同一 tick 内的增删、清单后落地、软链改指同 mtime 孪生树都直接反映为集合变化。 + * + * 下面每个用例都不再需要手工推 mtime —— 过去那层依赖正是盲区的来源。 + */ + +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + collectPiProjectResourceCliPaths, + type PiProjectResourceCliPaths, + piProjectResourcesDrifted, + snapshotPiProjectResourceLaunch, +} from '../project-resource-cli.js'; + +let project = ''; + +beforeEach(() => { + project = mkdtempSync(path.join(tmpdir(), 'pi-resource-drift-')); +}); + +afterEach(() => { + rmSync(project, { recursive: true, force: true }); +}); + +function writeSkill(relativeDir: string, name: string): void { + mkdirSync(path.join(project, relativeDir, name), { recursive: true }); + writeFileSync(path.join(project, relativeDir, name, 'SKILL.md'), `---\nname: ${name}\ndescription: test\n---\n`); +} + +/** 生产调用点同序:快照 = 当前采集结果(采集即 argv)。 */ +function snapshot(toCliPaths?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), toCliPaths); +} + +function real(target: string): string { + return realpathSync(target); +} + +/** Windows 无软链特权:目录软链用 junction,其余平台用 dir。 */ +function linkDir(target: string, at: string): void { + symlinkSync(target, at, process.platform === 'win32' ? 'junction' : 'dir'); +} + +describe('piProjectResourcesDrifted', () => { + it('reports no drift for an unchanged project', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + expect(piProjectResourcesDrifted(snapshot())).toBe(false); + }); + + it('detects a skill added after launch', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('returns to no drift when the added skill is removed again (no baseline to refresh)', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + rmSync(path.join(project, '.pi', 'skills', 'beta'), { recursive: true, force: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('ignores skill content edits when the path set is unchanged', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + writeFileSync(path.join(project, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: rewritten\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('ignores unrelated files dropped in the working directory root', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + writeFileSync(path.join(project, 'notes.txt'), 'unrelated'); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('detects a prompt template added after launch', () => { + const baseline = snapshot(); + mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); + writeFileSync(path.join(project, '.pi', 'prompts', 'opsx-propose.md'), '---\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a project extension file added after launch', () => { + const baseline = snapshot(); + mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); + writeFileSync(path.join(project, '.pi', 'extensions', 'hook.ts'), 'export {};\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects index.ts added inside an existing extension dir', () => { + mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: true }); + const baseline = snapshot(); + writeFileSync(path.join(project, '.pi', 'extensions', 'myext', 'index.ts'), 'export {};\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a skill created in a missing .pi/skills (dir from nothing)', () => { + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a skill created in a missing .agents/skills ancestor (dir from nothing)', () => { + writeFileSync(path.join(project, '.git'), ''); + const nested = path.join(project, 'sub'); + mkdirSync(nested, { recursive: true }); + const baseline = snapshotPiProjectResourceLaunch( + nested, collectPiProjectResourceCliPaths(nested)); + writeSkill(path.join('.agents', 'skills'), 'gamma'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a skill added inside an existing namespace dir (nested level)', () => { + writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills', '@scope'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a skill removed from an existing namespace dir (nested level)', () => { + writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); + writeSkill(path.join('.pi', 'skills', '@scope'), 'beta'); + const baseline = snapshot(); + rmSync(path.join(project, '.pi', 'skills', '@scope', 'beta'), { recursive: true, force: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects SKILL.md added into an existing non-skill nested dir', () => { + mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'empty'), { recursive: true }); + const baseline = snapshot(); + writeFileSync(path.join(project, '.pi', 'skills', '@scope', 'empty', 'SKILL.md'), '---\nname: empty\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects SKILL.md removed from an existing top-level skill dir', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + rmSync(path.join(project, '.pi', 'skills', 'alpha', 'SKILL.md'), { force: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a manifest installed into an in-repo direct-linked skill after launch', () => { + // 直链 skill 指向仓内真实的空目录,之后才落地 SKILL.md:集合由空变非空, + // 必须检出(过去靠清单指纹才能在同一 tick 内发现,现在集合比较天然覆盖)。 + writeFileSync(path.join(project, '.git'), ''); + mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); + mkdirSync(path.join(project, 'target-dir'), { recursive: true }); + linkDir(path.join(project, 'target-dir'), path.join(project, '.pi', 'skills', 'foo')); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeFileSync(path.join(project, 'target-dir', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('does not recycle for a symlinked namespace retarget to a twin tree (collector never walks it)', () => { + // collector 明文不走进软链 namespace(可越界/成环)→ 改指前后集合都为空 → + // 运行时消费的资源没有变,不触发回收。 + const targetA = path.join(project, 'ns-a'); + const targetB = path.join(project, 'ns-b'); + mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); + writeSkill('ns-a', 'alpha'); + linkDir(targetA, path.join(project, '.pi', 'skills', '@scope')); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeSkill('ns-b', 'alpha'); + rmSync(path.join(project, '.pi', 'skills', '@scope')); + linkDir(targetB, path.join(project, '.pi', 'skills', '@scope')); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('does not recycle when entries change inside a symlinked namespace target', () => { + const target = path.join(project, 'ns-target'); + mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); + writeSkill('ns-target', 'alpha'); + linkDir(target, path.join(project, '.pi', 'skills', '@scope')); + const baseline = snapshot(); + writeSkill('ns-target', 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('detects a symlinked .pi retarget even when the twin tree is structurally identical', () => { + // 采集按 realpath 出路径:改指后 argv 里的路径全部换成另一棵树的真实路径, + // 集合必然不同 —— 与 mtime 是否相等无关。 + writeSkill(path.join('workspaces', 'real-a', '.pi', 'skills'), 'alpha-a'); + writeSkill(path.join('workspaces', 'real-b', '.pi', 'skills'), 'alpha-b'); + mkdirSync(path.join(project, '.git'), { recursive: true }); + linkDir(path.join(project, 'workspaces', 'real-a'), path.join(project, 'wd')); + const baseline = snapshotPiProjectResourceLaunch( + path.join(project, 'wd'), collectPiProjectResourceCliPaths(path.join(project, 'wd'))); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + rmSync(path.join(project, 'wd')); + linkDir(path.join(project, 'workspaces', 'real-b'), path.join(project, 'wd')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('does not collect or watch pruned generated dirs (node_modules/dist)', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + mkdirSync(path.join(project, '.pi', 'skills', 'node_modules', 'big'), { recursive: true }); + for (let i = 0; i < 40; i += 1) writeFileSync(path.join(project, '.pi', 'skills', 'node_modules', 'big', `f${i}.js`), ''); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 剪枝目录内部的变化不会进 argv,即使里面出现 SKILL.md 也不收集 + writeFileSync(path.join(project, '.pi', 'skills', 'node_modules', 'big', 'SKILL.md'), '---\nname: nope\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('detects a dangling prompt symlink whose target lands later', () => { + mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); + const target = path.join(project, 'later.md'); + symlinkSync(target, path.join(project, '.pi', 'prompts', 'opsx.md')); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeFileSync(target, '---\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('disabled skills do not affect argv, so their removal is not drift', () => { + // argv 只含未被停用的项目技能;删掉一个从未加载的停用技能不应触发冷启动。 + // 停用清单在 spawn 时冻结,启动与比较共用同一口径(toCliPaths)。 + writeSkill(path.join('.pi', 'skills'), 'alpha'); + writeSkill(path.join('.pi', 'skills'), 'disabled'); + const disabled = [real(path.join(project, '.pi', 'skills', 'disabled'))]; + const toCliPaths = (paths: PiProjectResourceCliPaths): PiProjectResourceCliPaths => ({ + ...paths, + skills: Object.freeze(paths.skills.filter((entry) => !disabled.includes(entry))), + }); + const collected = collectPiProjectResourceCliPaths(project); + const baseline = snapshotPiProjectResourceLaunch(project, toCliPaths(collected), toCliPaths); + expect(baseline.paths.skills).toEqual([real(path.join(project, '.pi', 'skills', 'alpha'))]); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + rmSync(path.join(project, '.pi', 'skills', 'disabled'), { recursive: true, force: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 未被停用的技能变化仍然必须检出 + writeSkill(path.join('.pi', 'skills'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('guest restriction: outside-scope set change is not drift, inside-scope is', () => { + // 受邀者 argv 只含 guestRoot 裁剪后的集合,比较必须用同一口径;否则镜像外 + // 任何变化恒判漂移 → 回收死循环。 + writeFileSync(path.join(project, '.git'), ''); + writeSkill(path.join('mirror', 'sub', '.pi', 'skills'), 'alpha'); + writeSkill(path.join('.agents', 'skills'), 'global'); // 枚举链越过 mirror:收集到但被裁剪 + const wd = path.join(project, 'mirror', 'sub'); + const scope = path.join(real(project), 'mirror') + path.sep; + const restrict = (paths: PiProjectResourceCliPaths): PiProjectResourceCliPaths => ({ + skills: Object.freeze(paths.skills.filter((entry) => entry.startsWith(scope))), + promptTemplates: Object.freeze(paths.promptTemplates.filter((entry) => entry.startsWith(scope))), + extensions: Object.freeze([] as readonly string[]), + }); + const collected = collectPiProjectResourceCliPaths(wd); + expect(collected.skills.some((entry) => !entry.startsWith(scope))).toBe(true); + const baseline = snapshotPiProjectResourceLaunch(wd, restrict(collected), restrict); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeSkill(path.join('.agents', 'skills'), 'global-2'); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeSkill(path.join('mirror', 'sub', '.pi', 'skills'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a nearer git boundary that cuts a previously collected skill', () => { + mkdirSync(path.join(project, 'outer', '.agents', 'skills'), { recursive: true }); + writeFileSync(path.join(project, 'outer', '.git'), ''); + writeSkill(path.join('outer', '.agents', 'skills'), 'outer-skill'); + const nested = path.join(project, 'outer', 'sub'); + mkdirSync(nested, { recursive: true }); + const baseline = snapshotPiProjectResourceLaunch(nested, collectPiProjectResourceCliPaths(nested)); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + mkdirSync(path.join(nested, '.git'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('does not recycle for a git boundary change that excludes no resources', () => { + mkdirSync(path.join(project, 'outer'), { recursive: true }); + writeFileSync(path.join(project, 'outer', '.git'), ''); + const nested = path.join(project, 'outer', 'sub'); + writeSkill(path.join('outer', 'sub', '.pi', 'skills'), 'alpha'); + const baseline = snapshotPiProjectResourceLaunch(nested, collectPiProjectResourceCliPaths(nested)); + mkdirSync(path.join(nested, '.git'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('reports collected paths as realpaths so duplicates across roots collapse', () => { + writeFileSync(path.join(project, '.git'), ''); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + writeSkill(path.join('.agents', 'skills'), 'beta'); + const collected = collectPiProjectResourceCliPaths(project); + expect(collected.skills).toEqual([ + real(path.join(project, '.agents', 'skills', 'beta')), + real(path.join(project, '.pi', 'skills', 'alpha')), + ]); + }); +}); 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.ts index 2a13e73fb4..b6e0facf4e 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 @@ -427,6 +427,40 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => { } finally { await handle.close(); } }); + it('exposes project resource drift on the handle for local root tasks', async () => { + const agent = new PiAgent(buildDeps()); + mkdirSync(path.join(cwd, '.pi', 'skills', 'alpha'), { recursive: true }); + writeFileSync(path.join(cwd, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\n---\n'); + const handle = await agent.startSession({ ...opts(), sessionId: 'resource-drift' }); + try { + expect(repeatedArgValues(knobs.spawnedArgs.at(-1)!, '--skill')) + .toContain(path.join(cwd, '.pi', 'skills', 'alpha')); + expect(handle.hasProjectResourceDrift?.()).toBe(false); + mkdirSync(path.join(cwd, '.pi', 'skills', 'beta'), { recursive: true }); + writeFileSync(path.join(cwd, '.pi', 'skills', 'beta', 'SKILL.md'), '---\nname: beta\n---\n'); + expect(handle.hasProjectResourceDrift?.()).toBe(true); + rmSync(path.join(cwd, '.pi', 'skills', 'beta'), { recursive: true, force: true }); + expect(handle.hasProjectResourceDrift?.()).toBe(false); + } finally { + await handle.close(); + } + }); + + it('never reports project resource drift for bot profiles', async () => { + const agent = new PiAgent(buildDeps()); + const handle = await agent.startSession({ ...opts(), sessionId: 'bot-no-drift', botRuntimeProfile: { + botId: 'bot', profileVersion: 1, + skillPolicy: { mode: 'allowlist', configured: [], catalog: [] }, + mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] }, + toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] }, + } }); + try { + expect(handle.hasProjectResourceDrift?.()).toBe(false); + } finally { + await handle.close(); + } + }); + it('disposes ctx (and does not close a nonexistent proc) when the process constructor throws synchronously', async () => { knobs.ctorThrows = true; const agent = new PiAgent(buildDeps()); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 4a29ce7653..e14cd9fb0d 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -246,8 +246,11 @@ import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, emptyPiProjectResourceCliPaths, + type PiProjectResourceCliPaths, filterPiProjectCliSkills, piProjectResourceCliArgs, + piProjectResourcesDrifted, + snapshotPiProjectResourceLaunch, } from './project-resource-cli.js'; import { createPiTranslateContext, @@ -4065,20 +4068,30 @@ export class PiAgent extends BaseAgent { // Local root tasks load project skills/prompts/extensions in place via // explicit CLI flags. Keep --no-approve so `.pi/settings.json` is unread. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 - const collectedProjectResources = loadProjectResourcesInPlace - ? guestRoot - ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) - : collectPiProjectResourceCliPaths(opts.workingDir) - : emptyPiProjectResourceCliPaths(); + // 采集只发生这一次:其结果既是 argv 资源段,也是漂移检测的基准。漂移判定 + // 复用同一个 collector 重新采集后逐项比较(见 piProjectResourcesDrifted), + // 不另存任何基线 —— 存基线就等于手写一份「collector 消费什么」的镜像, + // 镜像与实现必然分歧(2026-11-10 六轮漏检全部出在这里)。 + // spawn 时冻结的停用清单:argv 与漂移比较都必须用这一份,否则「删掉一个 + // 从未加载的停用 skill」会被当成漂移,白等一次冷启动(Greptile P2)。 + const disabledSkillPathsAtLaunch = currentDisabledSkillLaunchPaths(disabledSkillLaunch); + // 采集 → argv 资源集合的唯一口径(受邀者裁剪 + 停用过滤)。启动与漂移比较 + // 共用它,所以「比较口径」不可能与「实际 argv」分叉。 + const projectResourceToCliPaths = (collected: PiProjectResourceCliPaths): PiProjectResourceCliPaths => { + const scoped = guestRoot ? restrictPiGuestProjectResources(collected, guestRoot) : collected; + return { + ...scoped, + skills: filterPiProjectCliSkills(scoped.skills, disabledSkillPathsAtLaunch), + }; + }; const projectResourceCli = loadProjectResourcesInPlace - ? { - ...collectedProjectResources, - skills: filterPiProjectCliSkills( - collectedProjectResources.skills, - currentDisabledSkillLaunchPaths(disabledSkillLaunch), - ), - } - : collectedProjectResources; + ? projectResourceToCliPaths(collectPiProjectResourceCliPaths(opts.workingDir)) + : emptyPiProjectResourceCliPaths(); + // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 + // 只存 argv 实际用的集合与该口径 —— 没有第二份基线。 + const projectResourceLaunchSnapshot = loadProjectResourcesInPlace + ? snapshotPiProjectResourceLaunch(opts.workingDir, projectResourceCli, projectResourceToCliPaths) + : null; // Own the entire managed-skill setup in the existing startup rollback: // discovery and path checks can fail before any projection is created. @@ -7789,6 +7802,10 @@ export class PiAgent extends BaseAgent { return runtimeCapabilityManifest; }, disabledSkillPaths: disabledSkillSnapshot, + hasProjectResourceDrift() { + return projectResourceLaunchSnapshot !== null + && piProjectResourcesDrifted(projectResourceLaunchSnapshot); + }, onRuntimeCapabilitiesChange(listener) { if (closed) { notifyRuntimeCapabilityListener(listener, undefined); diff --git a/packages/maker-core/src/agents/pi/project-resource-cli.ts b/packages/maker-core/src/agents/pi/project-resource-cli.ts index 7bb8ebe842..8ce6e9327e 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -89,14 +89,25 @@ function isSymlinkDirectory(target: string): boolean { } } +/** readdir 把 Windows junction 报成目录时 Dirent.isSymbolicLink 为 false,需 lstat + * 兜底:软链 namespace 不枚举(可越界/成环)这条规则在 Windows 上也必须成立。 */ +function isSymlinkEntry(entry: fs.Dirent, absPath: string): boolean { + return entry.isSymbolicLink() || (entry.isDirectory() && isSymlinkDirectory(absPath)); +} + function hasSkillFile(dir: string): boolean { return ['SKILL.md', 'skill.md'].some((name) => isFile(path.join(dir, name))); } +/** + * 走一遍 skills 根的两层树(collector 的枚举深度,不往更深处看)。 + * 先判清单(2 次 stat)再决定是否枚举 namespace:skill 目录不必付 readdir 代价。 + */ function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set): void { const resolvedDir = realpathOrNull(skillsDir); if (!resolvedDir || !isDir(resolvedDir) || !isWithinRoot(repoRoot, resolvedDir)) return; + // 清单经 realpath 后须仍在仓内,否则这个目录不算本项目的 skill。 const addSkill = (realFolder: string): void => { const skillMd = ['SKILL.md', 'skill.md'] .map((name) => path.join(realFolder, name)) @@ -118,9 +129,8 @@ function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set//. for (const nested of listDir(realFolder)) { @@ -132,6 +142,11 @@ function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set PiProjectResourceCliPaths) | null; +} + +export function snapshotPiProjectResourceLaunch( + workingDir: string, + paths: PiProjectResourceCliPaths, + toCliPaths?: (collected: PiProjectResourceCliPaths) => PiProjectResourceCliPaths, +): PiProjectResourceLaunchSnapshot { + return Object.freeze({ workingDir, paths, toCliPaths: toCliPaths ?? null }); +} + +function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { + return left.length === right.length && left.every((entry, index) => entry === right[index]); +} + +/** + * 盘上项目资源是否已偏离运行时实际使用的 argv。 + * + * 判定 = 用 collector 采集一遍,与快照里的集合逐项相等比较。**没有任何其他信号**: + * - argv 的输入是路径集合,不是内容 → 集合相等即无需回收(改文件内容/在已收集的 + * skill 目录里加文件都不影响 argv); + * - 采集按 realpath 出路径 → 软链改指到别处(哪怕 mtime 逐位相同)必然改变集合; + * - 清单后落地、模板目标移动、扩展目录补 index.ts → 都直接改变集合; + * - 与时间戳无关 → 同一 tick 内的增删不会漏(不需要 mtime 或条目指纹)。 + * + * 代价:每次空闲发送前一次采集(约「每目录 1 readdir + 每资源 3~5 stat」,与过去 + * 那套 mtime/身份快检的 syscall 数量同量级)。这是买「结构上不可能分歧」付的钱; + * 若将来资源规模大到有感知,应当减采集范围,不要恢复基线镜像。 + */ +export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + const compare = snapshot.toCliPaths ? snapshot.toCliPaths(fresh) : fresh; + return !( + samePiResourceList(compare.skills, snapshot.paths.skills) + && samePiResourceList(compare.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(compare.extensions, snapshot.paths.extensions) + ); +} + /** Locale-independent path order so duplicate Skill names pick the same winner everywhere. */ export function comparePiResourcePaths(left: string, right: string): number { if (left < right) return -1; diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts index 147c035224..2a3e2cbe54 100644 --- a/packages/maker-core/src/maker.test.ts +++ b/packages/maker-core/src/maker.test.ts @@ -1392,6 +1392,31 @@ describe('Maker session close events', () => { queue.end(); }); + it('recycles drifted pi runtimes with the runtime-refresh reason for direct senders', async () => { + const queue = createAsyncQueue(); + const handle = createHandle({ id: 'drifted', agentKind: 'pi' }); + handle.hasProjectResourceDrift = () => true; + handle.events = () => queue; + const start = vi.fn().mockResolvedValue(handle); + const maker = new Maker({ agents: { pi: createAgent(start, 'pi') }, storage: createStorage(), logger: createLogger() }); + const session = await maker.createSession({ id: 'drifted', agentKind: 'pi' as const, workingDir: '/repo', model: 'm' }); + expect(await maker.recyclePiRuntimeIfResourcesDrifted(session)).toBe(true); + expect(maker.getSessionCloseReason(session)).toBe('runtime-refresh'); + expect(maker.getSession(session.id)).toBeUndefined(); + queue.end(); + }); + + it('recycle is a no-op when project resources have not drifted', async () => { + const handle = createHandle({ id: 'fresh', agentKind: 'pi' }); + handle.hasProjectResourceDrift = () => false; + const start = vi.fn().mockResolvedValue(handle); + const maker = new Maker({ agents: { pi: createAgent(start, 'pi') }, storage: createStorage(), logger: createLogger() }); + const session = await maker.createSession({ id: 'fresh', agentKind: 'pi' as const, workingDir: '/repo', model: 'm' }); + expect(await maker.recyclePiRuntimeIfResourcesDrifted(session)).toBe(false); + expect(maker.getSession(session.id)).toBe(session); + await session.close(); + }); + it.each([ { initial: 'runtime-refresh', begun: false, next: 'agent-switch', expected: 'agent-switch' }, { initial: 'runtime-refresh', begun: false, next: 'requested', expected: 'requested' }, diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts index 319cce9dc9..f73e4478e2 100644 --- a/packages/maker-core/src/maker.ts +++ b/packages/maker-core/src/maker.ts @@ -1457,6 +1457,19 @@ export class Maker { // status listener 会自动清理 activeSessions 并 emit } + /** + * 项目资源漂移的 pi 本地根任务:空闲时经 Maker 以 runtime-refresh 原因回收运行时。 + * 供直发链路(IM turnRunner / scheduler 直发降级 / goal)在 send 前调用,与桌面发送 + * 事务(makerSendTransaction 的 lazy bootstrap)同口径;调用方随后按各自的自愈路径 + * 重建会话再投递。非本 maker 会话/未漂移/非空闲一律 no-op 返回 false。 + */ + async recyclePiRuntimeIfResourcesDrifted(session: Session): Promise { + if (this.activeSessions.get(session.id) !== session) return false; + if (!session.hasRecyclableProjectResourceDrift()) return false; + await this.closeSessionIfCurrent(session, 'runtime-refresh'); + return true; + } + /** 关闭并移除一个 session */ async closeSession( id: string, diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts index dfbf4f7549..9665a27817 100644 --- a/packages/maker-core/src/session.close.test.ts +++ b/packages/maker-core/src/session.close.test.ts @@ -211,6 +211,28 @@ describe('Session close lifecycle', () => { expect(handle.close).toHaveBeenCalledOnce(); }); + it('resource recycling shares the closeIfIdle idle predicate and never breaks manual compaction', async () => { + const { session, handle } = liveTurn(); + let hostOperationInFlight = true; + handle.hasPendingHostOperation = () => hostOperationInFlight; + handle.hasProjectResourceDrift = () => true; + + // 手动压缩等宿主排他操作进行中:即使资源已漂移也判定不可回收(否则会关掉 + // 正在等待结果的压缩请求),与 closeIfIdle 同一口径。 + expect(session.hasRecyclableProjectResourceDrift()).toBe(false); + + hostOperationInFlight = false; + expect(session.hasRecyclableProjectResourceDrift()).toBe(true); + }); + + it('skips resource recycling while a turn is running even if resources drifted', async () => { + const { session, handle } = liveTurn(); + handle.hasProjectResourceDrift = () => true; + await session.send('work'); + expect(session.hasRecyclableProjectResourceDrift()).toBe(false); + await session.close(); + }); + it('rejects a non-Host send while a retiring silent-stop claim is live', async () => { const { session, handle, queue, seen, idle } = liveTurn(); await session.send('work'); diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts index 3f9467f7ad..b8b5f09b34 100644 --- a/packages/maker-core/src/session.ts +++ b/packages/maker-core/src/session.ts @@ -2351,6 +2351,26 @@ export class Session { ); } + /** + * 项目资源漂移且满足回收空闲口径时返回 true(仅 pi 本地根任务实现,其余 agent + * 恒 false)。只判定不执行 close:close 必须由持有 Maker 的调用方走 + * closeSessionIfCurrent(session, 'runtime-refresh'),让 session:closed 带上 Maker + * 认识的刷新原因 —— 直接 Session.close 绕过 Maker 的 closeReasons 登记,IM + * runner 会按 unexpected 清掉排队中的回合、丢失已接受的派发。空闲口径与 + * closeIfIdle 一致:turn 运行中、结束未收口的 turn、换代续接、手动压缩 / + * rewind 等宿主排他操作进行中绝不回收。回收后由既有 lazy bootstrap 在下次 + * 发送时重扫项目资源、重算 argv。 + */ + hasRecyclableProjectResourceDrift(): boolean { + if (this.status !== 'active' || this.closePromise) return false; + if (this.isTurnRunning() || this.hasUnsettledTurn() + || this.retirementContinuationGeneration === this.turnGeneration + || this.hasPendingHostOperation()) { + return false; + } + return this.handle.hasProjectResourceDrift?.() === true; + } + getCurrentTurnId(): string | null { return this.handle.getCurrentTurnId?.() ?? null; }