From dc666fee3f18a9b95f11f1efc8341153835a1ca9 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 14:42:08 +0800 Subject: [PATCH 01/45] =?UTF-8?q?fix(pi):=20=E9=A1=B9=E7=9B=AE=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8F=98=E6=9B=B4=E5=90=8E=E7=A9=BA=E9=97=B2=E5=9B=9E?= =?UTF-8?q?=E6=94=B6=E8=BF=90=E8=A1=8C=E6=97=B6,=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E6=9D=A1=E6=B6=88=E6=81=AF=E8=87=AA=E5=8A=A8=E9=87=8D=E6=89=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #4437 的原地加载把项目 skill/prompt/extension 冻结在 spawn argv 里:会话中途 跑 openspec init(或任何新增项目资源)后,只有进程重启才会重算 argv —— 长活 任务(如协同模式)永远吃不到新资源,命令面板一直置灰。 - startSessionPrepared 冻结启动快照(路径集合 + watch root mtime 基线), handle 暴露 hasProjectResourceDrift()(仿 disabledSkillPaths 先例) - 两级漂移判定:先 stat 全部 watch root(全等 → 零扫描直接返回);mtime 变化才全量重扫,按最终路径集合判定 —— 集合不变不回收,路径集合才是 argv 的输入;watch roots 覆盖 collector 枚举的每个资源目录及其父目录, 捕获目录从无到有的创建事件 - Session.recycleIfProjectResourcesDrifted():turn 运行中绝不回收; 以新 teardown reason 'resource-refresh' 走既有 close 语义,host 的 lazy bootstrap 在下次发送时重扫重建 - 接进 desktop 两个发消息入口(与 codex remote MCP drift 的 live=undefined → lazy-resume 重建同构);远端 wire 协议不扩值, 远端会话无启动快照永不漂移,proxyHandle 仅做类型收窄 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../main/maker-ipc/makerSendTransaction.ts | 8 ++ apps/desktop/src/main/maker-ipc/register.ts | 4 + .../remote-agent/controller/proxyHandle.ts | 7 +- docs/dev-rules/pi-harness.md | 5 +- packages/maker-core/src/agents/base-agent.ts | 7 +- .../pi-project-resource-drift.test.ts | 122 ++++++++++++++++++ .../__tests__/pi-startsession-cleanup.test.ts | 34 +++++ packages/maker-core/src/agents/pi/index.ts | 12 ++ .../src/agents/pi/project-resource-cli.ts | 82 ++++++++++++ packages/maker-core/src/session.ts | 19 +++ 10 files changed, 296 insertions(+), 4 deletions(-) create mode 100644 packages/maker-core/src/agents/pi/__tests__/pi-project-resource-drift.test.ts diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts index 602f9a6995..54f8a6938c 100644 --- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts +++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts @@ -383,6 +383,8 @@ export interface MakerSendTransactionSession { /** Codex host-owned evidence: a provider turn crossed acceptance on this runtime. */ codexThreadMayHaveRollout?: boolean; isTurnRunning(): boolean; + /** 项目资源漂移回收(仅 pi 本地根任务实现;其余会话缺省,永漂移)。 */ + recycleIfProjectResourcesDrifted?(): Promise; send(message: UserMessage | string, opts?: SessionSendOptions): Promise; } @@ -1193,6 +1195,12 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make deps.log.info('send: error session requires recovery before dispatch', { sessionId }); sess = undefined; } + // 会话中途新增的项目资源(如 openspec init):空闲时回收运行时, + // 下面的 lazy bootstrap 会重扫重算 argv 后再投递(见 Session.recycleIfProjectResourcesDrifted)。 + if (sess && await sess.recycleIfProjectResourcesDrifted?.()) { + 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/register.ts b/apps/desktop/src/main/maker-ipc/register.ts index 13d672e13e..5e22aedb93 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -13204,6 +13204,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) // whose Maker.createSession call performs the existing bounded close retry. live = undefined; } + // 会话中途新增的项目资源(如 openspec init):空闲时回收运行时,lazy resume 重扫重建 + if (live?.agentKind === 'pi' && await live.recycleIfProjectResourcesDrifted()) { + live = undefined; + } if (live) { if (live.isTurnRunning?.()) { lockStage = 'enqueue-queued-message'; diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts index 891e41d137..44e3fa9677 100644 --- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts +++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts @@ -311,12 +311,15 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand const teardown = async (mode: 'close' | 'detach', opts?: AgentSessionTeardownOptions) => { deps.cancelPendingConfirmations?.(); const reason = opts?.reason ?? 'navigation'; + // 'resource-refresh' 只由本地根任务的资源回收(Session.recycleIfProjectResourcesDrifted)产生; + // 远端会话无启动快照永不漂移,wire 协议不扩这个值,跨机器时按 navigation 关闭。 + const wireReason: RemoteAgentTeardownReason = reason === 'resource-refresh' ? 'navigation' : 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') { @@ -328,7 +331,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/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md index e1d4ad4e02..bb73556fbb 100644 --- a/docs/dev-rules/pi-harness.md +++ b/docs/dev-rules/pi-harness.md @@ -365,7 +365,10 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见 不得读取/复制项目 `.pi/settings.json`,不得传 `--approve`, 不得依赖 `PI_OFFLINE=1` 代替该 settings 硬门。root 不传 `--no-skills`,以保留现有 user/global skill 行为;项目 skill 的 `loaded` 由当前会话 `get_commands` 对原路径 provenance - 证明。 + 证明。运行时空闲且盘上资源集合相对启动快照漂移时,host 可在发送前回收进程 + (teardown reason `resource-refresh`,turn 运行中绝不回收),由既有 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 a940f326ec..75e5b58cff 100644 --- a/packages/maker-core/src/agents/base-agent.ts +++ b/packages/maker-core/src/agents/base-agent.ts @@ -2338,7 +2338,7 @@ export type TurnContinuationState = 'awaiting' | 'active' | 'cancelled'; * Callers that cannot identify their boundary must omit the reason: teardown * then fails closed to `account-boundary`. */ -export type AgentSessionTeardownReason = 'navigation' | 'account-boundary' | 'app-quit'; +export type AgentSessionTeardownReason = 'navigation' | 'account-boundary' | 'app-quit' | 'resource-refresh'; export interface AgentSessionTeardownOptions { readonly reason: AgentSessionTeardownReason; @@ -2697,6 +2697,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..3a090e6976 --- /dev/null +++ b/packages/maker-core/src/agents/pi/__tests__/pi-project-resource-drift.test.ts @@ -0,0 +1,122 @@ +/** + * 项目资源漂移检测 —— 纯 fs 单测(不 spawn pi)。 + * + * 契约:snapshotPiProjectResourceLaunch 冻结"路径集合 + watch root mtime 基线"; + * piProjectResourcesDrifted 两级判定 —— mtime 全等 → 无漂移(stat 快检,零扫描); + * mtime 变化 → 全量重扫按路径集合判定(集合相同不回收,路径集合才是 argv 的输入)。 + * watch roots 必须覆盖 collector 枚举的每个资源目录及其父目录,否则"目录从无到有" + * 的创建事件会被漏掉。 + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + collectPiProjectResourceCliPaths, + collectPiProjectResourceWatchRootMtimes, + 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`); +} + +function snapshot() { + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project)); +} + +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', () => { + 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 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 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 created in a missing .pi/skills (dir from nothing)', () => { + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('watch roots cover .pi and the .agents ancestor chain', () => { + writeFileSync(path.join(project, '.git'), ''); + const nested = path.join(project, 'sub'); + mkdirSync(nested, { recursive: true }); + const roots = collectPiProjectResourceWatchRootMtimes(nested); + expect(roots.has(path.join(nested, '.pi'))).toBe(true); + expect(roots.has(path.join(nested, '.agents'))).toBe(true); + expect(roots.has(path.join(nested, '.agents', 'skills'))).toBe(true); + expect(roots.has(path.join(project, '.agents'))).toBe(true); + expect(roots.has(path.join(project, '.agents', 'skills'))).toBe(true); + }); + + it('missing directories baseline as -1 and compare against real mtimes', () => { + const roots = collectPiProjectResourceWatchRootMtimes(project); + expect(roots.get(path.join(project, '.pi'))).toBe(-1); + }); +}); 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 ade83061bf..3e94b60910 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -248,6 +248,8 @@ import { emptyPiProjectResourceCliPaths, filterPiProjectCliSkills, piProjectResourceCliArgs, + piProjectResourcesDrifted, + snapshotPiProjectResourceLaunch, } from './project-resource-cli.js'; import { createPiTranslateContext, @@ -4075,6 +4077,12 @@ export class PiAgent extends BaseAgent { ), } : collectedProjectResources; + // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 + // 快照存未经禁用过滤的原始收集结果,与 drift 检测的 fresh collect 同口径; + // 受邀者会话的 collected 已按 guestRoot 裁剪,与全量扫描口径不一致,不参与漂移检测。 + const projectResourceLaunchSnapshot = loadProjectResourcesInPlace && !guestRoot + ? snapshotPiProjectResourceLaunch(opts.workingDir, collectedProjectResources) + : null; // Own the entire managed-skill setup in the existing startup rollback: // discovery and path checks can fail before any projection is created. @@ -7720,6 +7728,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..b56010072d 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -187,6 +187,88 @@ export function collectPiProjectResourceCliPaths(workingDir: string): PiProjectR }); } +function statMtimeMs(target: string): number { + try { + return fs.statSync(target).mtimeMs; + } catch { + return -1; + } +} + +/** + * 启动快照:spawn 时冻结的项目资源清单 + watch root 的 mtime 基线。 + * paths 是未经禁用过滤的原始收集结果(与后续 fresh collect 同口径可比)。 + */ +export interface PiProjectResourceLaunchSnapshot { + readonly workingDir: string; + readonly paths: PiProjectResourceCliPaths; + readonly watchRootMtimes: ReadonlyArray; +} + +/** + * 收集漂移快检要盯的目录 mtime 基线。目录集合必须覆盖 collector 实际枚举的 + * 每个资源目录及其父目录(父目录捕获"目录从无到有"的创建事件): + * - `/.pi` 本身 + `.pi/skills` / `.pi/prompts` / `.pi/extensions` + * - cwd→git root 链上每级的 `.agents` + `.agents/skills` + * 不含 workingDir 本身:往项目根丢无关文件不应触发全量重扫。 + */ +export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map { + const roots = new Map(); + const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); + if (!isDir(scanRoot)) return roots; + const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot; + const piDir = path.join(scanRoot, '.pi'); + for (const dir of [piDir, path.join(piDir, 'skills'), path.join(piDir, 'prompts'), path.join(piDir, 'extensions')]) { + roots.set(dir, statMtimeMs(dir)); + } + let current = scanRoot; + while (true) { + const agentsDir = path.join(current, '.agents'); + roots.set(agentsDir, statMtimeMs(agentsDir)); + roots.set(path.join(agentsDir, 'skills'), statMtimeMs(path.join(agentsDir, 'skills'))); + if (current === repoRoot) break; + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + return roots; +} + +/** 冻结一份启动快照(mtime 基线在调用时采集)。 */ +export function snapshotPiProjectResourceLaunch( + workingDir: string, + paths: PiProjectResourceCliPaths, +): PiProjectResourceLaunchSnapshot { + return Object.freeze({ + workingDir, + paths, + watchRootMtimes: Object.freeze([...collectPiProjectResourceWatchRootMtimes(workingDir)]), + }); +} + +function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { + return left.length === right.length && left.every((entry, index) => entry === right[index]); +} + +/** + * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。两级判定: + * 1. stat 快检:所有 watch root 的 mtime 与启动基线一致(含缺失态 -1) → 无漂移; + * 2. mtime 有变化才全量重扫,按最终路径集合判定 —— mtime 变了但集合相同(如 + * 触碰无关目录)不算漂移,集合相同也不要求内容相同(路径集合才是 argv 的输入)。 + */ +export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { + for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { + if (statMtimeMs(dir) === mtimeAtLaunch) continue; + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + return !( + samePiResourceList(fresh.skills, snapshot.paths.skills) + && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(fresh.extensions, snapshot.paths.extensions) + ); + } + return false; +} + /** 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/session.ts b/packages/maker-core/src/session.ts index d383e3bf4d..c842335f5c 100644 --- a/packages/maker-core/src/session.ts +++ b/packages/maker-core/src/session.ts @@ -2291,6 +2291,25 @@ export class Session { ); } + /** + * 盘上项目资源相对运行时启动快照是否已漂移(仅 pi 本地根任务实现,其余 agent 恒 false)。 + */ + hasProjectResourceDrift(): boolean { + return this.handle.hasProjectResourceDrift?.() === true; + } + + /** + * 空闲且项目资源漂移时回收运行时:close 后由 host 的 lazy bootstrap 在下次发送时 + * 重新 startSession(重扫项目资源、重算 argv)。返回是否发生了回收。 + * turn 运行中绝不回收;中途新增的 openspec 类项目 skill 由此在下一条消息前生效。 + */ + async recycleIfProjectResourcesDrifted(): Promise { + if (this.isTurnRunning()) return false; + if (!this.hasProjectResourceDrift()) return false; + await this.close({ reason: 'resource-refresh' }); + return true; + } + getCurrentTurnId(): string | null { return this.handle.getCurrentTurnId?.() ?? null; } From cc661d0b18c757d121e85de57e497561ddae4612 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 14:57:28 +0800 Subject: [PATCH 02/45] =?UTF-8?q?fix(pi):=20=E6=BC=82=E7=A7=BB=E6=A3=80?= =?UTF-8?q?=E8=A7=86=E8=A1=A5=E5=B5=8C=E5=A5=97=E5=B1=82=E7=BA=A7,?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E5=AE=88=E5=8D=AB=E5=AF=B9=E9=BD=90=20closeI?= =?UTF-8?q?fIdle=20=E7=A9=BA=E9=97=B2=E5=8F=A3=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile review 三条(2×P1, 1×P2): - watch roots 补齐 collector 实际枚举的嵌套层:skills namespace 级与 namespace 内 skill 级、extensions 子目录。已有目录内增删 SKILL.md / index.ts / 子 skill 只改子目录自身 mtime,原先漏检 - piProjectResourcesDrifted 重扫确认集合未变后就地刷新 mtime 基线: 无关文件的 mtime 变化不再每条消息触发全量重扫 - recycleIfProjectResourcesDrifted 采用与 closeIfIdle 同一空闲口径: 手动压缩 / rewind 等宿主排他操作进行中绝不回收,不打断等待中的压缩 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 77 +++++++++++++++- .../src/agents/pi/project-resource-cli.ts | 90 +++++++++++++++---- packages/maker-core/src/session.close.test.ts | 25 ++++++ packages/maker-core/src/session.ts | 11 ++- 4 files changed, 180 insertions(+), 23 deletions(-) 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 index 3a090e6976..026ce86fc0 100644 --- 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 @@ -3,12 +3,13 @@ * * 契约:snapshotPiProjectResourceLaunch 冻结"路径集合 + watch root mtime 基线"; * piProjectResourcesDrifted 两级判定 —— mtime 全等 → 无漂移(stat 快检,零扫描); - * mtime 变化 → 全量重扫按路径集合判定(集合相同不回收,路径集合才是 argv 的输入)。 - * watch roots 必须覆盖 collector 枚举的每个资源目录及其父目录,否则"目录从无到有" - * 的创建事件会被漏掉。 + * mtime 变化 → 全量重扫(每次调用至多一次)按路径集合判定(集合相同不回收, + * 路径集合才是 argv 的输入),且就地刷新基线让后续快检恢复零扫描。 + * watch roots 必须覆盖 collector 实际枚举的每一层目录:在已存在子目录内增删 + * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 */ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -34,6 +35,10 @@ function writeSkill(relativeDir: string, name: string): void { writeFileSync(path.join(project, relativeDir, name, 'SKILL.md'), `---\nname: ${name}\ndescription: test\n---\n`); } +function statMtime(target: string): number { + return statSync(target).mtimeMs; +} + function snapshot() { return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project)); } @@ -115,6 +120,70 @@ describe('piProjectResourcesDrifted', () => { expect(roots.has(path.join(project, '.agents', 'skills'))).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 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('refreshes the mtime baseline after a rescan finds the same path set', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + const skillsDir = path.join(project, '.pi', 'skills'); + const mtimeAtLaunch = baseline.watchRootMtimes.get(skillsDir)!; + // 无关子目录:改了 skills 根 mtime,但不改变路径集合 + mkdirSync(path.join(skillsDir, 'unrelated'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 基线已就地刷新:下一次快检恢复零扫描,且真实漂移仍能检出 + expect(baseline.watchRootMtimes.get(skillsDir)).toBe(statMtime(skillsDir)); + expect(baseline.watchRootMtimes.get(skillsDir)).not.toBe(mtimeAtLaunch); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + writeSkill(path.join('.pi', 'skills'), 'beta'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('watch roots cover namespace and nested skill levels plus extension child dirs', () => { + writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); + mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'plain'), { recursive: true }); + mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: true }); + const roots = collectPiProjectResourceWatchRootMtimes(project); + const ns = path.join(project, '.pi', 'skills', '@scope'); + expect(roots.has(ns)).toBe(true); + expect(roots.has(path.join(ns, 'alpha'))).toBe(true); + expect(roots.has(path.join(ns, 'plain'))).toBe(true); + expect(roots.has(path.join(project, '.pi', 'extensions', 'myext'))).toBe(true); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); 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 b56010072d..886851f78f 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -202,13 +202,23 @@ function statMtimeMs(target: string): number { export interface PiProjectResourceLaunchSnapshot { readonly workingDir: string; readonly paths: PiProjectResourceCliPaths; - readonly watchRootMtimes: ReadonlyArray; + /** + * watch root 的 mtime 基线。Map 值可在重扫确认路径集合未变后就地刷新(见 + * piProjectResourcesDrifted),避免 mtime 变化来自无关文件时每条消息重复全量重扫; + * 路径集合与 paths 一样保持启动口径不变。 + */ + readonly watchRootMtimes: Map; } /** * 收集漂移快检要盯的目录 mtime 基线。目录集合必须覆盖 collector 实际枚举的 - * 每个资源目录及其父目录(父目录捕获"目录从无到有"的创建事件): + * 每一层目录:在已存在的子目录内增删条目只改该子目录自身的 mtime,父目录不动, + * 漏盯哪层就在哪层漏检(如已有 namespace 下增删 skill、已有扩展目录内补 index.ts、 + * 已有 skill 目录内删 SKILL.md): * - `/.pi` 本身 + `.pi/skills` / `.pi/prompts` / `.pi/extensions` + * - `.pi/skills` 与 `.agents/skills` 各自的两层 skill 树(skills 根、namespace 级、 + * namespace 内 skill 级;与 collector 的枚举深度一致,不往更深处看) + * - `.pi/extensions` 的每个子目录(index.ts 增删只改子目录 mtime) * - cwd→git root 链上每级的 `.agents` + `.agents/skills` * 不含 workingDir 本身:往项目根丢无关文件不应触发全量重扫。 */ @@ -218,14 +228,15 @@ export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map if (!isDir(scanRoot)) return roots; const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot; const piDir = path.join(scanRoot, '.pi'); - for (const dir of [piDir, path.join(piDir, 'skills'), path.join(piDir, 'prompts'), path.join(piDir, 'extensions')]) { - roots.set(dir, statMtimeMs(dir)); - } + roots.set(piDir, statMtimeMs(piDir)); + watchPiSkillTreeMtimes(roots, path.join(piDir, 'skills')); + roots.set(path.join(piDir, 'prompts'), statMtimeMs(path.join(piDir, 'prompts'))); + watchPiExtensionChildMtimes(roots, path.join(piDir, 'extensions')); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); roots.set(agentsDir, statMtimeMs(agentsDir)); - roots.set(path.join(agentsDir, 'skills'), statMtimeMs(path.join(agentsDir, 'skills'))); + watchPiSkillTreeMtimes(roots, path.join(agentsDir, 'skills')); if (current === repoRoot) break; const parent = path.dirname(current); if (parent === current) break; @@ -234,7 +245,46 @@ export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map return roots; } -/** 冻结一份启动快照(mtime 基线在调用时采集)。 */ +/** + * stat 一个 skills 根及其下 collector 实际枚举的两层子目录。statSync 跟随符号 + * 链接:软链 skill 的增删由父目录 mtime 捕获,软链目标内的 SKILL.md 增删由目标 + * 目录 mtime 捕获,与 realpath 收集口径一致。跳过 collector 不枚举的子树 + * (隐藏/bak、软链 namespace、剪枝名),避免无关变化触发无谓重扫。 + */ +function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): void { + roots.set(skillsDir, statMtimeMs(skillsDir)); + if (!isDir(skillsDir)) return; + for (const entry of listDir(skillsDir)) { + if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; + if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; + const childPath = path.join(skillsDir, entry.name); + roots.set(childPath, statMtimeMs(childPath)); + if (entry.isSymbolicLink()) continue; + const realChild = realpathOrNull(childPath); + if (!realChild || !isDir(realChild)) continue; + if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 + if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace + for (const nested of listDir(realChild)) { + if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; + if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; + roots.set(path.join(realChild, nested.name), statMtimeMs(path.join(realChild, nested.name))); + } + } +} + +/** stat 一个 extensions 根及其子目录:已有扩展目录内 index.ts 增删只改子目录 mtime。 */ +function watchPiExtensionChildMtimes(roots: Map, extDir: string): void { + roots.set(extDir, statMtimeMs(extDir)); + if (!isDir(extDir)) return; + for (const entry of listDir(extDir)) { + if (entry.name.startsWith('.')) continue; + if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; + const childPath = path.join(extDir, entry.name); + roots.set(childPath, statMtimeMs(childPath)); + } +} + +/** 冻结一份启动快照(mtime 基线在调用时采集,后续可由 drift 检测就地刷新)。 */ export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, @@ -242,7 +292,7 @@ export function snapshotPiProjectResourceLaunch( return Object.freeze({ workingDir, paths, - watchRootMtimes: Object.freeze([...collectPiProjectResourceWatchRootMtimes(workingDir)]), + watchRootMtimes: collectPiProjectResourceWatchRootMtimes(workingDir), }); } @@ -252,19 +302,25 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): /** * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。两级判定: - * 1. stat 快检:所有 watch root 的 mtime 与启动基线一致(含缺失态 -1) → 无漂移; - * 2. mtime 有变化才全量重扫,按最终路径集合判定 —— mtime 变了但集合相同(如 - * 触碰无关目录)不算漂移,集合相同也不要求内容相同(路径集合才是 argv 的输入)。 + * 1. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1) → 无漂移; + * 2. mtime 有变化才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 + * (如触碰无关目录)不算漂移,且就地刷新该 root 的基线,让下一次快检恢复零扫描; + * 集合相同不要求内容相同(路径集合才是 argv 的输入)。判定漂移时不动基线: + * 调用方将回收运行时并重建新快照。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { + let freshPaths: PiProjectResourceCliPaths | null = null; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { - if (statMtimeMs(dir) === mtimeAtLaunch) continue; - const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); - return !( - samePiResourceList(fresh.skills, snapshot.paths.skills) - && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) - && samePiResourceList(fresh.extensions, snapshot.paths.extensions) + const mtimeNow = statMtimeMs(dir); + if (mtimeNow === mtimeAtLaunch) continue; + freshPaths ??= collectPiProjectResourceCliPaths(snapshot.workingDir); + const driftedNow = !( + samePiResourceList(freshPaths.skills, snapshot.paths.skills) + && samePiResourceList(freshPaths.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(freshPaths.extensions, snapshot.paths.extensions) ); + if (driftedNow) return true; + snapshot.watchRootMtimes.set(dir, mtimeNow); } return false; } diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts index fb09ef114e..4e83a8c3d2 100644 --- a/packages/maker-core/src/session.close.test.ts +++ b/packages/maker-core/src/session.close.test.ts @@ -211,6 +211,31 @@ 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 同一口径。 + await expect(session.recycleIfProjectResourcesDrifted()).resolves.toBe(false); + expect(handle.close).not.toHaveBeenCalled(); + + hostOperationInFlight = false; + await expect(session.recycleIfProjectResourcesDrifted()).resolves.toBe(true); + expect(handle.close).toHaveBeenCalledOnce(); + }); + + 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(await session.recycleIfProjectResourcesDrifted()).toBe(false); + expect(handle.close).not.toHaveBeenCalled(); + 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 c842335f5c..ea24cecab4 100644 --- a/packages/maker-core/src/session.ts +++ b/packages/maker-core/src/session.ts @@ -2301,10 +2301,17 @@ export class Session { /** * 空闲且项目资源漂移时回收运行时:close 后由 host 的 lazy bootstrap 在下次发送时 * 重新 startSession(重扫项目资源、重算 argv)。返回是否发生了回收。 - * turn 运行中绝不回收;中途新增的 openspec 类项目 skill 由此在下一条消息前生效。 + * 与 closeIfIdle 同一空闲口径:turn 运行中、结束未收口的 turn、换代续接、以及 + * 手动压缩 / rewind 等宿主排他操作进行中绝不回收 —— 否则会关掉正在等待结果的 + * 压缩请求;中途新增的 openspec 类项目 skill 由此在下一条消息前生效。 */ async recycleIfProjectResourcesDrifted(): Promise { - if (this.isTurnRunning()) return false; + if (this.status !== 'active' || this.closePromise) return false; + if (this.isTurnRunning() || this.hasUnsettledTurn() + || this.retirementContinuationGeneration === this.turnGeneration + || this.hasPendingHostOperation()) { + return false; + } if (!this.hasProjectResourceDrift()) return false; await this.close({ reason: 'resource-refresh' }); return true; From e6bd8447328beceba50fb2851eb0cb4a3d8568e3 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 15:17:41 +0800 Subject: [PATCH 03/45] =?UTF-8?q?fix(pi):=20=E5=9B=9E=E6=94=B6=E6=94=B9?= =?UTF-8?q?=E8=B5=B0=20Maker=20runtime-refresh,=E5=90=AF=E5=8A=A8=E5=BF=AB?= =?UTF-8?q?=E7=85=A7=E5=85=88=E9=87=87=E6=A0=B7=E5=9F=BA=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 3 条 + Codex 4 条 review 的收口: - 资源回收从 Session.close 改为调用方经 Maker closeSessionIfCurrent(session, 'runtime-refresh'):Session 只保留 hasRecyclableProjectResourceDrift() 判定(与 closeIfIdle 同一空闲口径)。 直接 Session.close 绕过 Maker closeReasons 登记,IM runner 会按 unexpected 丢弃排队回合、丢失已接受的派发 - 启动快照的 watch mtime 基线改由调用方在路径收集之前采样传入: 基线在前,采样窗口内新增的资源最多多一次重扫后收敛;反序会静默漏检 - 移除不再产生的 teardown reason 'resource-refresh'(回收关闭现在 走 Maker 侧原因,不进远端 wire) Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../__tests__/codexPickerHarness.ts | 4 +++- .../__tests__/agent-input-coordinator.test.ts | 4 ++-- .../__tests__/makerSendTransaction.test.ts | 1 + .../main/maker-ipc/makerSendTransaction.ts | 16 ++++++++++----- apps/desktop/src/main/maker-ipc/register.ts | 11 ++++++++-- .../remote-agent/controller/proxyHandle.ts | 6 +++--- docs/dev-rules/pi-harness.md | 5 ++++- packages/maker-core/src/agents/base-agent.ts | 2 +- .../pi-project-resource-drift.test.ts | 20 +++++++++++++++++-- packages/maker-core/src/agents/pi/index.ts | 10 ++++++++-- .../src/agents/pi/project-resource-cli.ts | 13 ++++++------ packages/maker-core/src/session.close.test.ts | 11 ++++------ packages/maker-core/src/session.ts | 18 ++++++++--------- 13 files changed, 80 insertions(+), 41 deletions(-) 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-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts index 7899ce692d..922618cda3 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 @@ -12923,7 +12923,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', @@ -15145,7 +15145,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 a72c848dca..606cc3c190 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts @@ -299,6 +299,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/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts index 54f8a6938c..dedbb879ec 100644 --- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts +++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts @@ -383,8 +383,8 @@ export interface MakerSendTransactionSession { /** Codex host-owned evidence: a provider turn crossed acceptance on this runtime. */ codexThreadMayHaveRollout?: boolean; isTurnRunning(): boolean; - /** 项目资源漂移回收(仅 pi 本地根任务实现;其余会话缺省,永漂移)。 */ - recycleIfProjectResourcesDrifted?(): Promise; + /** 项目资源漂移且满足回收空闲口径(仅 pi 本地根任务实现;其余会话缺省,永不回收)。 */ + hasRecyclableProjectResourceDrift?(): boolean; send(message: UserMessage | string, opts?: SessionSendOptions): Promise; } @@ -396,6 +396,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. */ @@ -1195,9 +1198,12 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make deps.log.info('send: error session requires recovery before dispatch', { sessionId }); sess = undefined; } - // 会话中途新增的项目资源(如 openspec init):空闲时回收运行时, - // 下面的 lazy bootstrap 会重扫重算 argv 后再投递(见 Session.recycleIfProjectResourcesDrifted)。 - if (sess && await sess.recycleIfProjectResourcesDrifted?.()) { + // 会话中途新增的项目资源(如 openspec init):空闲时经 Maker 以 + // 'runtime-refresh' 回收运行时(session:closed 带刷新原因,IM runner 保留 + // 排队回合),下面的 lazy bootstrap 会重扫重算 argv 后再投递 + // (见 Session.hasRecyclableProjectResourceDrift 的空闲口径说明)。 + if (sess?.hasRecyclableProjectResourceDrift?.()) { + await deps.closeSessionIfCurrent(sessionId); deps.log.info('send: project resources drifted, recycling runtime before dispatch', { sessionId }); sess = undefined; } diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts index 5e22aedb93..23871bb0a5 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -13204,8 +13204,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) // whose Maker.createSession call performs the existing bounded close retry. live = undefined; } - // 会话中途新增的项目资源(如 openspec init):空闲时回收运行时,lazy resume 重扫重建 - if (live?.agentKind === 'pi' && await live.recycleIfProjectResourcesDrifted()) { + // 会话中途新增的项目资源(如 openspec init):空闲时经 Maker 以 + // 'runtime-refresh' 回收运行时(直接 Session.close 会丢 Maker 原因,IM 侧按 + // unexpected 清排队回合),lazy resume 重扫重建 + if (live?.agentKind === 'pi' && live.hasRecyclableProjectResourceDrift()) { + await maker.closeSessionIfCurrent(live, 'runtime-refresh'); live = undefined; } if (live) { @@ -18845,6 +18848,10 @@ 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) await 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 44e3fa9677..0d6bb49ef4 100644 --- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts +++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts @@ -311,9 +311,9 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand const teardown = async (mode: 'close' | 'detach', opts?: AgentSessionTeardownOptions) => { deps.cancelPendingConfirmations?.(); const reason = opts?.reason ?? 'navigation'; - // 'resource-refresh' 只由本地根任务的资源回收(Session.recycleIfProjectResourcesDrifted)产生; - // 远端会话无启动快照永不漂移,wire 协议不扩这个值,跨机器时按 navigation 关闭。 - const wireReason: RemoteAgentTeardownReason = reason === 'resource-refresh' ? 'navigation' : reason; + // 远端会话无项目资源启动快照,永不漂移,不存在资源回收关闭;资源刷新关闭由 + // 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 diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md index bb73556fbb..db0aa0de64 100644 --- a/docs/dev-rules/pi-harness.md +++ b/docs/dev-rules/pi-harness.md @@ -366,7 +366,10 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见 不得依赖 `PI_OFFLINE=1` 代替该 settings 硬门。root 不传 `--no-skills`,以保留现有 user/global skill 行为;项目 skill 的 `loaded` 由当前会话 `get_commands` 对原路径 provenance 证明。运行时空闲且盘上资源集合相对启动快照漂移时,host 可在发送前回收进程 - (teardown reason `resource-refresh`,turn 运行中绝不回收),由既有 lazy bootstrap + (经 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 入口强制默认 diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts index 75e5b58cff..ac09c8da68 100644 --- a/packages/maker-core/src/agents/base-agent.ts +++ b/packages/maker-core/src/agents/base-agent.ts @@ -2338,7 +2338,7 @@ export type TurnContinuationState = 'awaiting' | 'active' | 'cancelled'; * Callers that cannot identify their boundary must omit the reason: teardown * then fails closed to `account-boundary`. */ -export type AgentSessionTeardownReason = 'navigation' | 'account-boundary' | 'app-quit' | 'resource-refresh'; +export type AgentSessionTeardownReason = 'navigation' | 'account-boundary' | 'app-quit'; export interface AgentSessionTeardownOptions { readonly reason: AgentSessionTeardownReason; 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 index 026ce86fc0..10c3593dae 100644 --- 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 @@ -40,7 +40,9 @@ function statMtime(target: string): number { } function snapshot() { - return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project)); + // 与生产调用点同序:基线先采样,路径后收集(见 snapshotPiProjectResourceLaunch)。 + const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), watchRootMtimes); } describe('piProjectResourcesDrifted', () => { @@ -97,7 +99,8 @@ describe('piProjectResourcesDrifted', () => { writeFileSync(path.join(project, '.git'), ''); const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); - const baseline = snapshotPiProjectResourceLaunch(nested, collectPiProjectResourceCliPaths(nested)); + const baseline = snapshotPiProjectResourceLaunch( + nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested)); writeSkill(path.join('.agents', 'skills'), 'gamma'); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -184,6 +187,19 @@ describe('piProjectResourcesDrifted', () => { expect(roots.has(path.join(project, '.pi', 'extensions', 'myext'))).toBe(true); }); + it('launch snapshot samples watch roots before path collection (race-safe order)', () => { + // 生产调用点先采基线后收集路径。基线采样与路径收集之间新增的资源已在集合 + // 里且基线较旧:首次快检多一次重扫确认集合一致后刷新基线 —— 既不误报漂移, + // 也不会静默漏检(反序才会漏)。 + const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshotPiProjectResourceLaunch( + project, collectPiProjectResourceCliPaths(project), watchRootMtimes); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + expect(baseline.watchRootMtimes.get(path.join(project, '.pi', 'skills'))) + .toBe(statMtime(path.join(project, '.pi', 'skills'))); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 3e94b60910..77b6153aef 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -246,6 +246,7 @@ import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, emptyPiProjectResourceCliPaths, + collectPiProjectResourceWatchRootMtimes, filterPiProjectCliSkills, piProjectResourceCliArgs, piProjectResourcesDrifted, @@ -4063,6 +4064,11 @@ 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. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 + // watch 基线必须先于路径收集采样(见 snapshotPiProjectResourceLaunch): + // 基线在前,采样窗口内新增的资源只会让首次快检多一次重扫后收敛;反序会静默漏检。 + const projectResourceWatchRootMtimes = loadProjectResourcesInPlace && !guestRoot + ? collectPiProjectResourceWatchRootMtimes(opts.workingDir) + : null; const collectedProjectResources = loadProjectResourcesInPlace ? guestRoot ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) @@ -4080,8 +4086,8 @@ export class PiAgent extends BaseAgent { // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 // 快照存未经禁用过滤的原始收集结果,与 drift 检测的 fresh collect 同口径; // 受邀者会话的 collected 已按 guestRoot 裁剪,与全量扫描口径不一致,不参与漂移检测。 - const projectResourceLaunchSnapshot = loadProjectResourcesInPlace && !guestRoot - ? snapshotPiProjectResourceLaunch(opts.workingDir, collectedProjectResources) + const projectResourceLaunchSnapshot = projectResourceWatchRootMtimes + ? snapshotPiProjectResourceLaunch(opts.workingDir, collectedProjectResources, projectResourceWatchRootMtimes) : null; // Own the entire managed-skill setup in the existing startup rollback: 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 886851f78f..0b1fb1c53b 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -284,16 +284,17 @@ function watchPiExtensionChildMtimes(roots: Map, extDir: string) } } -/** 冻结一份启动快照(mtime 基线在调用时采集,后续可由 drift 检测就地刷新)。 */ +/** + * 冻结一份启动快照。watchRootMtimes 必须由调用方在收集 paths **之前**采样传入 + * (见 pi/index.ts 调用点):基线在前,采样窗口内新增的资源只会让首次快检多一次 + * 重扫后收敛;反过来(先收集后采样)会漏掉窗口内新增的资源,静默漏检。 + */ export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, + watchRootMtimes: Map, ): PiProjectResourceLaunchSnapshot { - return Object.freeze({ - workingDir, - paths, - watchRootMtimes: collectPiProjectResourceWatchRootMtimes(workingDir), - }); + return Object.freeze({ workingDir, paths, watchRootMtimes }); } function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts index 4e83a8c3d2..e9a49aaee3 100644 --- a/packages/maker-core/src/session.close.test.ts +++ b/packages/maker-core/src/session.close.test.ts @@ -217,22 +217,19 @@ describe('Session close lifecycle', () => { handle.hasPendingHostOperation = () => hostOperationInFlight; handle.hasProjectResourceDrift = () => true; - // 手动压缩等宿主排他操作进行中:即使资源已漂移也绝不回收(否则会关掉 + // 手动压缩等宿主排他操作进行中:即使资源已漂移也判定不可回收(否则会关掉 // 正在等待结果的压缩请求),与 closeIfIdle 同一口径。 - await expect(session.recycleIfProjectResourcesDrifted()).resolves.toBe(false); - expect(handle.close).not.toHaveBeenCalled(); + expect(session.hasRecyclableProjectResourceDrift()).toBe(false); hostOperationInFlight = false; - await expect(session.recycleIfProjectResourcesDrifted()).resolves.toBe(true); - expect(handle.close).toHaveBeenCalledOnce(); + 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(await session.recycleIfProjectResourcesDrifted()).toBe(false); - expect(handle.close).not.toHaveBeenCalled(); + expect(session.hasRecyclableProjectResourceDrift()).toBe(false); await session.close(); }); diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts index ea24cecab4..9d45e81256 100644 --- a/packages/maker-core/src/session.ts +++ b/packages/maker-core/src/session.ts @@ -2299,22 +2299,22 @@ export class Session { } /** - * 空闲且项目资源漂移时回收运行时:close 后由 host 的 lazy bootstrap 在下次发送时 - * 重新 startSession(重扫项目资源、重算 argv)。返回是否发生了回收。 - * 与 closeIfIdle 同一空闲口径:turn 运行中、结束未收口的 turn、换代续接、以及 - * 手动压缩 / rewind 等宿主排他操作进行中绝不回收 —— 否则会关掉正在等待结果的 - * 压缩请求;中途新增的 openspec 类项目 skill 由此在下一条消息前生效。 + * 项目资源漂移且满足回收空闲口径时返回 true。只判定不执行 close:close 必须由 + * 持有 Maker 的调用方走 closeSessionIfCurrent(session, 'runtime-refresh'),让 + * session:closed 带上 Maker 认识的刷新原因 —— 直接 Session.close 绕过 Maker 的 + * closeReasons 登记,IM runner 会按 unexpected 清掉排队中的回合、丢失已接受的 + * 派发。空闲口径与 closeIfIdle 一致:turn 运行中、结束未收口的 turn、换代续接、 + * 手动压缩 / rewind 等宿主排他操作进行中绝不回收。回收后由既有 lazy bootstrap + * 在下次发送时重扫项目资源、重算 argv。 */ - async recycleIfProjectResourcesDrifted(): Promise { + hasRecyclableProjectResourceDrift(): boolean { if (this.status !== 'active' || this.closePromise) return false; if (this.isTurnRunning() || this.hasUnsettledTurn() || this.retirementContinuationGeneration === this.turnGeneration || this.hasPendingHostOperation()) { return false; } - if (!this.hasProjectResourceDrift()) return false; - await this.close({ reason: 'resource-refresh' }); - return true; + return this.hasProjectResourceDrift(); } getCurrentTurnId(): string | null { From 5d665df485582889cf18bf247d93e1e16afa87b1 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 15:22:40 +0800 Subject: [PATCH 04/45] =?UTF-8?q?fix(pi):=20=E9=87=8D=E6=89=AB=E5=90=8E?= =?UTF-8?q?=E9=87=8D=E5=BB=BA=E6=95=B4=E5=BC=A0=E7=9B=AF=E8=A7=86=E8=A1=A8?= =?UTF-8?q?,=E5=BF=AB=E6=A3=80=E6=A0=B8=E5=AF=B9=20git=20=E8=BE=B9?= =?UTF-8?q?=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 复审两条 P2: - 基线刷新原先只更新已有 key:重扫窗口内新建的空 namespace / 空扩展目录 不进 watch map,后续其内部增删(如补 index.ts)只改未盯视子目录的 mtime,快检永远命中。改为集合未变就整表重建(clear + 按当前盘上状态 重灌),新建目录自此被盯住 - 更近的 .git 出现/消失会改变 collector 的枚举链(.agents 向上走到 repoRoot),但任何被盯目录的 mtime 都不动。快检新增 git 边界核对: 启动快照记录 repoRoot,每次判定用同一解析函数恒等比较 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 26 ++++++++++++ .../src/agents/pi/project-resource-cli.ts | 41 +++++++++++++++---- 2 files changed, 59 insertions(+), 8 deletions(-) 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 index 10c3593dae..5247a97118 100644 --- 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 @@ -200,6 +200,32 @@ describe('piProjectResourcesDrifted', () => { .toBe(statMtime(path.join(project, '.pi', 'skills'))); }); + it('rebuilds the watch map after an unchanged rescan so new child dirs are watched', () => { + mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); + const baseline = snapshot(); + // 重扫窗口内新建的空扩展目录:集合未变,但必须从此纳入盯视 + mkdirSync(path.join(project, '.pi', 'extensions', 'newext'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + expect(baseline.watchRootMtimes.has(path.join(project, '.pi', 'extensions', 'newext'))).toBe(true); + // 若不重建基线,这里的 index.ts 只改未盯视的新子目录 mtime,永远检不出 + writeFileSync(path.join(project, '.pi', 'extensions', 'newext', 'index.ts'), 'export {};\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a nearer git boundary appearing after launch (repo root identity)', () => { + 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), collectPiProjectResourceWatchRootMtimes(nested)); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 + mkdirSync(path.join(nested, '.git'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); 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 0b1fb1c53b..18399b4fda 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -68,6 +68,12 @@ function findNearestGitRoot(workingDir: string): string | null { } } +/** collector 与漂移快检共用的 git 边界解析(同输入必同输出,才能恒等比较)。 */ +function resolvePiResourceRepoRoot(workingDir: string): string { + const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); + return findNearestGitRoot(scanRoot) ?? scanRoot; +} + function isWithinRoot(root: string, candidate: string): boolean { const relative = path.relative(root, candidate); return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)); @@ -137,7 +143,7 @@ export function collectPiProjectResourceCliPaths(workingDir: string): PiProjectR return emptyPiProjectResourceCliPaths(); } const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); - const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot; + const repoRoot = resolvePiResourceRepoRoot(workingDir); const skills = new Set(); const promptTemplates = new Set(); const extensions = new Set(); @@ -203,11 +209,14 @@ export interface PiProjectResourceLaunchSnapshot { readonly workingDir: string; readonly paths: PiProjectResourceCliPaths; /** - * watch root 的 mtime 基线。Map 值可在重扫确认路径集合未变后就地刷新(见 + * watch root 的 mtime 基线。Map 值可在重扫确认路径集合未变后就地重建(见 * piProjectResourcesDrifted),避免 mtime 变化来自无关文件时每条消息重复全量重扫; * 路径集合与 paths 一样保持启动口径不变。 */ readonly watchRootMtimes: Map; + /** 启动时认定的 git root:更近的 .git 出现/消失会改变 collector 的枚举链 + * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。 */ + readonly repoRoot: string; } /** @@ -294,7 +303,12 @@ export function snapshotPiProjectResourceLaunch( paths: PiProjectResourceCliPaths, watchRootMtimes: Map, ): PiProjectResourceLaunchSnapshot { - return Object.freeze({ workingDir, paths, watchRootMtimes }); + return Object.freeze({ + workingDir, + paths, + watchRootMtimes, + repoRoot: resolvePiResourceRepoRoot(workingDir), + }); } function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { @@ -302,18 +316,24 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): } /** - * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。两级判定: - * 1. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1) → 无漂移; - * 2. mtime 有变化才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 - * (如触碰无关目录)不算漂移,且就地刷新该 root 的基线,让下一次快检恢复零扫描; + * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。三级判定: + * 1. git 边界核对:更近的 .git 出现/消失会改变 collector 的枚举链(.agents 向上 + * 走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独比较; + * 2. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1) → 无漂移; + * 3. mtime 有变化才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 + * (如触碰无关目录)不算漂移,且就地重建整张基线(新建的空 namespace / 空扩展 + * 目录也要纳入盯视,否则后续其内部增删无人盯),让下一次快检恢复零扫描; * 集合相同不要求内容相同(路径集合才是 argv 的输入)。判定漂移时不动基线: * 调用方将回收运行时并重建新快照。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { + if (resolvePiResourceRepoRoot(snapshot.workingDir) !== snapshot.repoRoot) return true; + let changed = false; let freshPaths: PiProjectResourceCliPaths | null = null; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { const mtimeNow = statMtimeMs(dir); if (mtimeNow === mtimeAtLaunch) continue; + changed = true; freshPaths ??= collectPiProjectResourceCliPaths(snapshot.workingDir); const driftedNow = !( samePiResourceList(freshPaths.skills, snapshot.paths.skills) @@ -321,7 +341,12 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps && samePiResourceList(freshPaths.extensions, snapshot.paths.extensions) ); if (driftedNow) return true; - snapshot.watchRootMtimes.set(dir, mtimeNow); + } + if (changed) { + // mtime 变了但集合相同:重建整张基线,下一次快检恢复零扫描。 + const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); + snapshot.watchRootMtimes.clear(); + for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); } return false; } From bd3b0fffcbb9dd295f142fdd90cc80adf42e41b7 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 15:28:55 +0800 Subject: [PATCH 05/45] =?UTF-8?q?fix(pi):=20git=20=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E5=8F=98=E5=8C=96=E9=99=8D=E7=BA=A7=E4=B8=BA=E9=87=8D=E6=89=AB?= =?UTF-8?q?=E4=BF=A1=E5=8F=B7,=E9=9B=86=E5=90=88=E6=9C=AA=E5=8F=98?= =?UTF-8?q?=E4=B8=8D=E5=9B=9E=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 四轮 P2:嵌套工作目录 git init 时,即使被截断的上层链没有任何 项目资源,边界恒等比较也直接判漂移,两个发送入口会关掉 Pi 冷启动 —— 实际 argv 并未变化,用户下一条消息多等一次启动。 改为:边界变化只作重扫信号,与 mtime 变化共用同一条「全量重扫 → 按最终 路径集合判定」通路;集合相同就不回收,就地重建基线并更新边界持有者 (repoRoot 改存可变 state,冻结快照内就地演进),后续快检恢复零扫描。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 18 +++++- .../src/agents/pi/project-resource-cli.ts | 58 ++++++++++++------- 2 files changed, 53 insertions(+), 23 deletions(-) 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 index 5247a97118..640c86c137 100644 --- 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 @@ -9,7 +9,7 @@ * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 */ -import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -226,6 +226,22 @@ describe('piProjectResourcesDrifted', () => { 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'); + mkdirSync(path.join(nested, '.pi', 'skills', 'alpha'), { recursive: true }); + writeFileSync(path.join(nested, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: t\n---\n'); + const baseline = snapshotPiProjectResourceLaunch( + nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested)); + // 嵌套目录 git init:被截断的上层链没有任何项目资源,集合不变,不应触发回收 + mkdirSync(path.join(nested, '.git'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 边界持有者已就地更新:后续快检恢复零扫描,不再重复重扫判定 + expect(baseline.state.repoRoot).toBe(realpathSync(nested)); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); 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 18399b4fda..7c719a6e87 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -214,9 +214,11 @@ export interface PiProjectResourceLaunchSnapshot { * 路径集合与 paths 一样保持启动口径不变。 */ readonly watchRootMtimes: Map; - /** 启动时认定的 git root:更近的 .git 出现/消失会改变 collector 的枚举链 - * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。 */ - readonly repoRoot: string; + /** 启动时认定的 git root 可变持有器:更近的 .git 出现/消失会改变 collector 的枚举链 + * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。边界 + * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 + * 嵌套目录 git init 在无实际资源变化时多余回收。 */ + readonly state: { repoRoot: string }; } /** @@ -307,7 +309,7 @@ export function snapshotPiProjectResourceLaunch( workingDir, paths, watchRootMtimes, - repoRoot: resolvePiResourceRepoRoot(workingDir), + state: { repoRoot: resolvePiResourceRepoRoot(workingDir) }, }); } @@ -318,35 +320,47 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): /** * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。三级判定: * 1. git 边界核对:更近的 .git 出现/消失会改变 collector 的枚举链(.agents 向上 - * 走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独比较; - * 2. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1) → 无漂移; - * 3. mtime 有变化才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 - * (如触碰无关目录)不算漂移,且就地重建整张基线(新建的空 namespace / 空扩展 - * 目录也要纳入盯视,否则后续其内部增删无人盯),让下一次快检恢复零扫描; + * 走到 repoRoot),而任何被盯目录的 mtime 都不动 —— 但边界变化只作重扫信号, + * 不直接判漂移:被截断的上层可能没有任何项目资源,集合相同就不该回收; + * 2. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1)且边界未变 → 无漂移; + * 3. 有重扫信号才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 + * (如触碰无关目录)不算漂移,且就地重建基线并更新边界持有者(新建的空 namespace / + * 空扩展目录也要纳入盯视,否则后续其内部增删无人盯),让下一次快检恢复零扫描; * 集合相同不要求内容相同(路径集合才是 argv 的输入)。判定漂移时不动基线: * 调用方将回收运行时并重建新快照。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { - if (resolvePiResourceRepoRoot(snapshot.workingDir) !== snapshot.repoRoot) return true; - let changed = false; - let freshPaths: PiProjectResourceCliPaths | null = null; + const boundaryChanged = resolvePiResourceRepoRoot(snapshot.workingDir) !== snapshot.state.repoRoot; + let rescanDone = false; + let needsRebuild = false; + const comparePaths = (): boolean => { + rescanDone = true; + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + return !( + samePiResourceList(fresh.skills, snapshot.paths.skills) + && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(fresh.extensions, snapshot.paths.extensions) + ); + }; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { const mtimeNow = statMtimeMs(dir); if (mtimeNow === mtimeAtLaunch) continue; - changed = true; - freshPaths ??= collectPiProjectResourceCliPaths(snapshot.workingDir); - const driftedNow = !( - samePiResourceList(freshPaths.skills, snapshot.paths.skills) - && samePiResourceList(freshPaths.promptTemplates, snapshot.paths.promptTemplates) - && samePiResourceList(freshPaths.extensions, snapshot.paths.extensions) - ); - if (driftedNow) return true; + needsRebuild = true; + if (comparePaths()) return true; } - if (changed) { - // mtime 变了但集合相同:重建整张基线,下一次快检恢复零扫描。 + if (boundaryChanged) { + // 边界变化只作重扫信号:被截断/扩展的上层链可能没有任何项目资源, + // 集合相同就不该回收(嵌套目录 git init 不应触发多余冷启动)。 + needsRebuild = true; + if (!rescanDone && comparePaths()) return true; + } + if (needsRebuild) { + // 有重扫信号但集合未变:重建整张基线(新建的空目录纳入盯视)并更新边界持有者, + // 下一次快检恢复零扫描。 const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); + snapshot.state.repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); } return false; } From dfc67131b7537cdd0a7513e6dc5aac2684096c7a Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 15:36:48 +0800 Subject: [PATCH 06/45] =?UTF-8?q?refactor(pi):=20=E6=BC=82=E7=A7=BB?= =?UTF-8?q?=E5=BF=AB=E6=A3=80=E6=94=B6=E6=95=9B=E4=B8=BA=E5=8D=95=E6=AC=A1?= =?UTF-8?q?=E6=94=B6=E9=9B=86=E7=BB=93=E6=9E=84,=E4=BF=AE=E5=A4=9A?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=8F=98=E5=8C=96=E9=87=8D=E5=A4=8D=E6=94=B6?= =?UTF-8?q?=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 五轮 P2:多个监测目录 mtime 同时变化时,逐 key 分支会为每个 变化目录重复调用 collectPiProjectResourceCliPaths(bd3b0fffcb 重构丢失 了 memo)—— 同一 failure family 第三次复发,按收敛 checkpoint 做结构化 收口而非再加补丁: - 结构改为「一次 stat 扫描判有无信号 → 至多一次全量收集 → 一次集合 比较」,收集次数与变化目录数解耦,不变量由结构本身保证 - 判定语义不变:集合不同→漂移;集合相同(含仅边界变化)→重建基线并 更新边界持有者,下次快检恢复零收集 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../src/agents/pi/project-resource-cli.ts | 72 +++++++++---------- 1 file changed, 34 insertions(+), 38 deletions(-) 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 7c719a6e87..126fa27d0a 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -318,50 +318,46 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): } /** - * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。三级判定: - * 1. git 边界核对:更近的 .git 出现/消失会改变 collector 的枚举链(.agents 向上 - * 走到 repoRoot),而任何被盯目录的 mtime 都不动 —— 但边界变化只作重扫信号, - * 不直接判漂移:被截断的上层可能没有任何项目资源,集合相同就不该回收; - * 2. stat 快检:所有 watch root 的 mtime 与基线一致(含缺失态 -1)且边界未变 → 无漂移; - * 3. 有重扫信号才全量重扫(每次调用至多一次),按最终路径集合判定 —— 集合相同 - * (如触碰无关目录)不算漂移,且就地重建基线并更新边界持有者(新建的空 namespace / - * 空扩展目录也要纳入盯视,否则后续其内部增删无人盯),让下一次快检恢复零扫描; - * 集合相同不要求内容相同(路径集合才是 argv 的输入)。判定漂移时不动基线: - * 调用方将回收运行时并重建新快照。 + * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。结构性契约: + * **每次调用至多一次全量路径收集**。两级信号 → 一次收集 → 一次比较: + * 1. stat 扫描(零收集):所有 watch root 的 mtime 与基线全等(含缺失态 -1)且 + * git 边界未变 → 无漂移;任一不等或有信号 → 进入下一步。信号源: + * - watch root mtime 变化(资源增删只改所在目录自身 mtime,基线必须覆盖 + * collector 实际枚举的每一层目录); + * - git 边界变化(更近的 .git 出现/消失会改变 collector 的枚举链,但不动 + * 任何被盯目录的 mtime)。 + * 2. 全量重扫,按最终路径集合判定(argv 的输入是集合,不是内容): + * - 集合不同 → 漂移,返回 true(不动基线,调用方将回收运行时并重建快照); + * - 集合相同(触碰无关目录 / git init 未截断任何资源)→ 不算漂移,就地重建 + * 整张基线(新建的空 namespace / 空扩展目录纳入盯视)并更新边界持有者, + * 下一次快检恢复零收集。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { const boundaryChanged = resolvePiResourceRepoRoot(snapshot.workingDir) !== snapshot.state.repoRoot; - let rescanDone = false; - let needsRebuild = false; - const comparePaths = (): boolean => { - rescanDone = true; - const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); - return !( - samePiResourceList(fresh.skills, snapshot.paths.skills) - && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) - && samePiResourceList(fresh.extensions, snapshot.paths.extensions) - ); - }; + let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { - const mtimeNow = statMtimeMs(dir); - if (mtimeNow === mtimeAtLaunch) continue; - needsRebuild = true; - if (comparePaths()) return true; + if (statMtimeMs(dir) !== mtimeAtLaunch) { + mtimeChanged = true; + break; + } } - if (boundaryChanged) { - // 边界变化只作重扫信号:被截断/扩展的上层链可能没有任何项目资源, - // 集合相同就不该回收(嵌套目录 git init 不应触发多余冷启动)。 - needsRebuild = true; - if (!rescanDone && comparePaths()) return true; - } - if (needsRebuild) { - // 有重扫信号但集合未变:重建整张基线(新建的空目录纳入盯视)并更新边界持有者, - // 下一次快检恢复零扫描。 - const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); - snapshot.watchRootMtimes.clear(); - for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); - snapshot.state.repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); + if (!boundaryChanged && !mtimeChanged) return false; + + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + if (!( + samePiResourceList(fresh.skills, snapshot.paths.skills) + && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(fresh.extensions, snapshot.paths.extensions) + )) { + return true; } + + // 有信号但集合未变:重建整张基线(新建的空目录纳入盯视)并更新边界持有者, + // 下一次快检恢复零收集。 + const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); + snapshot.watchRootMtimes.clear(); + for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); + snapshot.state.repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); return false; } From 091c2528dad80ac08b2835243942e25040aa76bf Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 15:52:53 +0800 Subject: [PATCH 07/45] =?UTF-8?q?test(desktop):=20live=20=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E6=A1=A9=E8=A1=A5=20hasRecyclableProjectResourceDrift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit verify-checks 红:sendToSessionLazyResumePermission 用 new Function 求值 register.ts 生产切片,其 live 桩缺 #9248 新增的 hasRecyclableProjectResourceDrift 调用,pi 会话场景 TypeError。 三个 pi 桩补 () => false(这些场景不涉及资源漂移)。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../__tests__/sendToSessionLazyResumePermission.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 4788e1450e..0a8388b4a2 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts @@ -318,7 +318,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, @@ -340,7 +340,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; }, @@ -360,6 +360,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({ From 2b44f8922c5633f3a76ffa2935324f84ecdbb2bf Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 16:16:18 +0800 Subject: [PATCH 08/45] =?UTF-8?q?fix(pi):=20=E9=87=8D=E6=89=AB=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=E5=85=88=E9=87=87=E6=A0=B7=E5=9F=BA=E7=BA=BF,?= =?UTF-8?q?=E7=9B=AF=E4=BD=8F=E8=A7=A3=E6=9E=90=E5=90=8E=E7=9A=84=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E7=9B=AE=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 复审两条 P2(同属 watch 基线与 collector 枚举面不一致的家族): - 重扫重建路径与启动路径同序:先采样 watch 基线与边界,再收集路径。 反序时窗口内新增的资源会把新 mtime 与旧集合固化在一起,后续快检 永远命中,静默漏检 - watch 面纳入 collector 实际接受的解析后文件目标:.pi/prompts 的 .md 模板为仓内软链时,目标文件的移动/删除不改变 .pi 目录 mtime, 盯住 realpath 本体(statSync 跟随软链,目标缺失为 -1);扩展目录内的 index.ts 解析路径同样纳入 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 18 +++++++++- .../src/agents/pi/project-resource-cli.ts | 36 ++++++++++++++++--- 2 files changed, 48 insertions(+), 6 deletions(-) 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 index 640c86c137..e6f50156a5 100644 --- 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 @@ -9,7 +9,7 @@ * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 */ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -22,6 +22,9 @@ import { let project = ''; +// Windows CI 无符号链接特权:软链相关用例仅在 POSIX 跑。 +const itPosixOnly = process.platform === 'win32' ? it.skip : it; + beforeEach(() => { project = mkdtempSync(path.join(tmpdir(), 'pi-resource-drift-')); }); @@ -242,6 +245,19 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(false); }); + itPosixOnly('detects the resolved symlink target of a prompt template moved away', () => { + // Windows CI 无符号链接特权,本用例仅在 POSIX 跑(见 itPosixOnly)。 + mkdirSync(path.join(project, 'targets'), { recursive: true }); + mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); + writeFileSync(path.join(project, 'targets', 'opsx.md'), '---\ndescription: t\n---\n'); + symlinkSync(path.join(project, 'targets', 'opsx.md'), path.join(project, '.pi', 'prompts', 'foo.md')); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 目标移动/删除不改变 .pi/prompts 自身的 mtime,只有盯住解析后的文件本体才能检出 + rmSync(path.join(project, 'targets', 'opsx.md')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); 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 126fa27d0a..315009cd45 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -241,7 +241,7 @@ export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map const piDir = path.join(scanRoot, '.pi'); roots.set(piDir, statMtimeMs(piDir)); watchPiSkillTreeMtimes(roots, path.join(piDir, 'skills')); - roots.set(path.join(piDir, 'prompts'), statMtimeMs(path.join(piDir, 'prompts'))); + watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); watchPiExtensionChildMtimes(roots, path.join(piDir, 'extensions')); let current = scanRoot; while (true) { @@ -292,6 +292,28 @@ function watchPiExtensionChildMtimes(roots: Map, extDir: string) if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(extDir, entry.name); roots.set(childPath, statMtimeMs(childPath)); + const realChild = realpathOrNull(childPath); + if (!realChild || !isDir(realChild)) continue; + // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 + const realIndex = path.join(realChild, 'index.ts'); + roots.set(realIndex, statMtimeMs(realIndex)); + } +} + +/** + * stat 一个 prompts 根及其中 collector 实际接受的每个模板文件的**解析后目标**: + * `.pi/prompts/foo.md` 为仓内符号链接时,链接自身的增删由 prompts 根 mtime 捕获, + * 但目标文件的移动/删除只改目标处。statSync 跟随软链,目标缺失时为 -1,与 + * realpath 收集口径一致。枚举条件与 collector 逐条对应(隐藏/非 .md 跳过)。 + */ +function watchPiPromptTargets(roots: Map, promptsDir: string, repoRoot: string): void { + roots.set(promptsDir, statMtimeMs(promptsDir)); + if (!isDir(promptsDir)) return; + for (const entry of listDir(promptsDir)) { + if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; + const realFile = realpathOrNull(path.join(promptsDir, entry.name)); + if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) continue; + roots.set(realFile, statMtimeMs(realFile)); } } @@ -343,6 +365,11 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps } if (!boundaryChanged && !mtimeChanged) return false; + // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 + // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 + // 一起,静默漏检。 + const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); + const freshBoundary = resolvePiResourceRepoRoot(snapshot.workingDir); const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); if (!( samePiResourceList(fresh.skills, snapshot.paths.skills) @@ -352,12 +379,11 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps return true; } - // 有信号但集合未变:重建整张基线(新建的空目录纳入盯视)并更新边界持有者, - // 下一次快检恢复零收集。 - const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); + // 有信号但集合未变:整表重建(新建的空目录/解析后的 prompt 目标纳入盯视) + // 并更新边界持有者,下一次快检恢复零收集。 snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); - snapshot.state.repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); + snapshot.state.repoRoot = freshBoundary; return false; } From 95f70a35492a2fb378fbfbe0e88aebc2fc61c456 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 16:38:36 +0800 Subject: [PATCH 09/45] =?UTF-8?q?fix(pi):=20=E5=90=AF=E5=8A=A8=E9=87=87?= =?UTF-8?q?=E6=A0=B7=E4=B8=89=E6=A0=B7=E5=90=8C=E6=89=B9,=E7=9B=AF?= =?UTF-8?q?=E4=BD=8F=E6=82=AC=E7=A9=BA=E6=A8=A1=E6=9D=BF=E8=BD=AF=E9=93=BE?= =?UTF-8?q?,=E6=97=A0=20createOpts=20=E4=B8=8D=E5=9B=9E=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 三条 P2,两个失败家族各修一处: - 启动原子性:repoRoot 原在路径收集之后于快照内采样,窗口内出现的更近 .git 会把新边界与旧边界收集的路径固化在一起。改为 watchRootMtimes / repoRoot / paths 三样同批、基线与边界先采样,窗口内错配靠首次快检重扫 收敛(与既有先采样后收集契约一致) - 盯视面:悬空的 .pi/prompts 软链既不解析也无人盯,目标落地时只改未盯视 目录的 mtime。软链自身入盯视表,目标落地即检出(statSync 解析,缺失 -1) - 恢复面:无 createOpts 的直发/老链路调用回收后 lazy-create 无法重建, 触发消息会被 NOT_FOUND 拒掉。回收改以 createOpts 存在为前提,无重建 能力时按原运行时投递 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../__tests__/makerSendTransaction.test.ts | 25 ++++++++++++++++++ .../main/maker-ipc/makerSendTransaction.ts | 4 ++- .../pi-project-resource-drift.test.ts | 21 +++++++++++---- packages/maker-core/src/agents/pi/index.ts | 14 +++++++--- .../src/agents/pi/project-resource-cli.ts | 26 +++++++++++++------ 5 files changed, 72 insertions(+), 18 deletions(-) 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 606cc3c190..8c5eae11cd 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 () => {}); diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts index dedbb879ec..7c80299958 100644 --- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts +++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts @@ -1202,7 +1202,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make // 'runtime-refresh' 回收运行时(session:closed 带刷新原因,IM runner 保留 // 排队回合),下面的 lazy bootstrap 会重扫重算 argv 后再投递 // (见 Session.hasRecyclableProjectResourceDrift 的空闲口径说明)。 - if (sess?.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; 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 index e6f50156a5..9c30d625b2 100644 --- 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 @@ -17,6 +17,7 @@ import { collectPiProjectResourceCliPaths, collectPiProjectResourceWatchRootMtimes, piProjectResourcesDrifted, + resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, } from '../project-resource-cli.js'; @@ -45,7 +46,7 @@ function statMtime(target: string): number { function snapshot() { // 与生产调用点同序:基线先采样,路径后收集(见 snapshotPiProjectResourceLaunch)。 const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); - return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), watchRootMtimes); + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), watchRootMtimes, resolvePiResourceRepoRoot(project)); } describe('piProjectResourcesDrifted', () => { @@ -103,7 +104,7 @@ describe('piProjectResourcesDrifted', () => { const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested)); + nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); writeSkill(path.join('.agents', 'skills'), 'gamma'); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -197,7 +198,7 @@ describe('piProjectResourcesDrifted', () => { const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshotPiProjectResourceLaunch( - project, collectPiProjectResourceCliPaths(project), watchRootMtimes); + project, collectPiProjectResourceCliPaths(project), watchRootMtimes, resolvePiResourceRepoRoot(project)); expect(piProjectResourcesDrifted(baseline)).toBe(false); expect(baseline.watchRootMtimes.get(path.join(project, '.pi', 'skills'))) .toBe(statMtime(path.join(project, '.pi', 'skills'))); @@ -222,7 +223,7 @@ describe('piProjectResourcesDrifted', () => { const nested = path.join(project, 'outer', 'sub'); mkdirSync(nested, { recursive: true }); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested)); + nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); expect(piProjectResourcesDrifted(baseline)).toBe(false); // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 mkdirSync(path.join(nested, '.git'), { recursive: true }); @@ -236,7 +237,7 @@ describe('piProjectResourcesDrifted', () => { mkdirSync(path.join(nested, '.pi', 'skills', 'alpha'), { recursive: true }); writeFileSync(path.join(nested, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: t\n---\n'); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested)); + nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); // 嵌套目录 git init:被截断的上层链没有任何项目资源,集合不变,不应触发回收 mkdirSync(path.join(nested, '.git'), { recursive: true }); expect(piProjectResourcesDrifted(baseline)).toBe(false); @@ -258,6 +259,16 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + itPosixOnly('detects a prompt target materializing behind a dangling symlink', () => { + mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); + mkdirSync(path.join(project, 'elsewhere'), { recursive: true }); + symlinkSync(path.join(project, 'elsewhere', 'target.md'), path.join(project, '.pi', 'prompts', 'foo.md')); + const baseline = snapshot(); + // 悬空软链自身已入盯视:目标落地(改动的是未盯视的 elsewhere 目录)也能检出 + writeFileSync(path.join(project, 'elsewhere', 'target.md'), '---\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 77b6153aef..12cd7e4967 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -250,6 +250,7 @@ import { filterPiProjectCliSkills, piProjectResourceCliArgs, piProjectResourcesDrifted, + resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, } from './project-resource-cli.js'; import { @@ -4064,11 +4065,15 @@ 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. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 - // watch 基线必须先于路径收集采样(见 snapshotPiProjectResourceLaunch): - // 基线在前,采样窗口内新增的资源只会让首次快检多一次重扫后收敛;反序会静默漏检。 + // watch 基线与 git 边界必须先于路径收集采样(见 snapshotPiProjectResourceLaunch): + // 三样同批且基线在前,采样窗口内新增的资源/边界变化只会让首次快检多一次重扫后 + // 收敛;反序会漏掉窗口内新增的资源,或让新旧边界与路径集合错配,静默漏检。 const projectResourceWatchRootMtimes = loadProjectResourcesInPlace && !guestRoot ? collectPiProjectResourceWatchRootMtimes(opts.workingDir) : null; + const projectResourceRepoRootAtLaunch = loadProjectResourcesInPlace && !guestRoot + ? resolvePiResourceRepoRoot(opts.workingDir) + : null; const collectedProjectResources = loadProjectResourcesInPlace ? guestRoot ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) @@ -4086,8 +4091,9 @@ export class PiAgent extends BaseAgent { // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 // 快照存未经禁用过滤的原始收集结果,与 drift 检测的 fresh collect 同口径; // 受邀者会话的 collected 已按 guestRoot 裁剪,与全量扫描口径不一致,不参与漂移检测。 - const projectResourceLaunchSnapshot = projectResourceWatchRootMtimes - ? snapshotPiProjectResourceLaunch(opts.workingDir, collectedProjectResources, projectResourceWatchRootMtimes) + const projectResourceLaunchSnapshot = projectResourceWatchRootMtimes && projectResourceRepoRootAtLaunch + ? snapshotPiProjectResourceLaunch( + opts.workingDir, collectedProjectResources, projectResourceWatchRootMtimes, projectResourceRepoRootAtLaunch) : null; // Own the entire managed-skill setup in the existing startup rollback: 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 315009cd45..2bd3a6e1d6 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -69,7 +69,7 @@ function findNearestGitRoot(workingDir: string): string | null { } /** collector 与漂移快检共用的 git 边界解析(同输入必同输出,才能恒等比较)。 */ -function resolvePiResourceRepoRoot(workingDir: string): string { +export function resolvePiResourceRepoRoot(workingDir: string): string { const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); return findNearestGitRoot(scanRoot) ?? scanRoot; } @@ -217,7 +217,8 @@ export interface PiProjectResourceLaunchSnapshot { /** 启动时认定的 git root 可变持有器:更近的 .git 出现/消失会改变 collector 的枚举链 * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。边界 * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 - * 嵌套目录 git init 在无实际资源变化时多余回收。 */ + * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watchRootMtimes 同批采样 + * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ readonly state: { repoRoot: string }; } @@ -243,6 +244,7 @@ export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map watchPiSkillTreeMtimes(roots, path.join(piDir, 'skills')); watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); watchPiExtensionChildMtimes(roots, path.join(piDir, 'extensions')); + watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); @@ -311,27 +313,35 @@ function watchPiPromptTargets(roots: Map, promptsDir: string, re if (!isDir(promptsDir)) return; for (const entry of listDir(promptsDir)) { if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; - const realFile = realpathOrNull(path.join(promptsDir, entry.name)); - if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) continue; + const entryPath = path.join(promptsDir, entry.name); + const realFile = realpathOrNull(entryPath); + if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) { + // 悬空软链(或目标越界):把链接自身入盯视 —— 目标落地时 statSync 解析到 + // 新 mtime(未盯视目录里的变化也能触发重扫);普通文件不存在此形态。 + if (entry.isSymbolicLink()) roots.set(entryPath, statMtimeMs(entryPath)); + continue; + } roots.set(realFile, statMtimeMs(realFile)); } } /** - * 冻结一份启动快照。watchRootMtimes 必须由调用方在收集 paths **之前**采样传入 - * (见 pi/index.ts 调用点):基线在前,采样窗口内新增的资源只会让首次快检多一次 - * 重扫后收敛;反过来(先收集后采样)会漏掉窗口内新增的资源,静默漏检。 + * 冻结一份启动快照。watchRootMtimes 与 repoRoot 必须由调用方在收集 paths **之前** + * 采样传入(见 pi/index.ts 调用点):三样同批且基线在前,采样窗口内新增的资源只会 + * 让首次快检多一次重扫后收敛;反过来(先收集后采样)会漏掉窗口内新增的资源,或让 + * 新旧边界与路径集合错配,静默漏检。 */ export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, watchRootMtimes: Map, + repoRoot: string, ): PiProjectResourceLaunchSnapshot { return Object.freeze({ workingDir, paths, watchRootMtimes, - state: { repoRoot: resolvePiResourceRepoRoot(workingDir) }, + state: { repoRoot }, }); } From 41669c1ac4d25e0aab56adc92f0607c461b50e4f Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 16:47:44 +0800 Subject: [PATCH 10/45] =?UTF-8?q?fix(pi):=20=E5=8D=95=E6=AC=A1=E6=BC=82?= =?UTF-8?q?=E7=A7=BB=E5=88=A4=E5=AE=9A=E5=85=B1=E4=BA=AB=E5=90=8C=E4=B8=80?= =?UTF-8?q?=20git=20root,=E9=87=8D=E5=BB=BA=E5=90=8E=E5=A4=8D=E6=A0=B8?= =?UTF-8?q?=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex P2:drifted() 内三个独立 git root 探测点(边界比较 / watch 基线重建 / 路径收集)在重扫窗口内 .git 消失时会采出不一致状态 —— 集合来自新根、 watch 面停在旧根,写入快照后后续快检永远命中。 改为:每次调用只解析一次 git root,经 repoRootHint 贯穿传给两个收集器; 整表重建后再复核一次解析,边界又动了就按漂移交回收路径重建一致快照, 不把混合口径写回。顺带移除 watchPiPromptTargets 的重复调用。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../src/agents/pi/project-resource-cli.ts | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) 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 2bd3a6e1d6..afca8a7e81 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -138,12 +138,12 @@ function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set(); const promptTemplates = new Set(); const extensions = new Set(); @@ -234,17 +234,16 @@ export interface PiProjectResourceLaunchSnapshot { * - cwd→git root 链上每级的 `.agents` + `.agents/skills` * 不含 workingDir 本身:往项目根丢无关文件不应触发全量重扫。 */ -export function collectPiProjectResourceWatchRootMtimes(workingDir: string): Map { +export function collectPiProjectResourceWatchRootMtimes(workingDir: string, repoRootHint?: string): Map { const roots = new Map(); const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); if (!isDir(scanRoot)) return roots; - const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot; + const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); const piDir = path.join(scanRoot, '.pi'); roots.set(piDir, statMtimeMs(piDir)); watchPiSkillTreeMtimes(roots, path.join(piDir, 'skills')); watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); watchPiExtensionChildMtimes(roots, path.join(piDir, 'extensions')); - watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); @@ -365,7 +364,10 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): * 下一次快检恢复零收集。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { - const boundaryChanged = resolvePiResourceRepoRoot(snapshot.workingDir) !== snapshot.state.repoRoot; + // 本次调用只解析一次 git root,贯穿传给所有收集器;独立探测会在重扫窗口内 + // 采出不一致的边界+盯视面(.git 消失时 watch 面停在旧根、集合来自新根)。 + const repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); + const boundaryChanged = repoRoot !== snapshot.state.repoRoot; let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { if (statMtimeMs(dir) !== mtimeAtLaunch) { @@ -378,9 +380,8 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 // 一起,静默漏检。 - const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir); - const freshBoundary = resolvePiResourceRepoRoot(snapshot.workingDir); - const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir, repoRoot); + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir, repoRoot); if (!( samePiResourceList(fresh.skills, snapshot.paths.skills) && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) @@ -390,10 +391,13 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps } // 有信号但集合未变:整表重建(新建的空目录/解析后的 prompt 目标纳入盯视) - // 并更新边界持有者,下一次快检恢复零收集。 + // 并更新边界持有者,下一次快检恢复零收集。重建后复核边界:重扫窗口内 + // .git 又动了就按漂移交回收路径重建(下次快检从一致的新快照出发), + // 不把混合口径的基线/边界写回快照。 + if (resolvePiResourceRepoRoot(snapshot.workingDir) !== repoRoot) return true; snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); - snapshot.state.repoRoot = freshBoundary; + snapshot.state.repoRoot = repoRoot; return false; } From 1208a97d4d5fb6b83888b61d671cd9b3883d8a46 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 16:59:24 +0800 Subject: [PATCH 11/45] =?UTF-8?q?fix(pi):=20launch=20=E5=85=B1=E4=BA=AB?= =?UTF-8?q?=E5=8D=95=E6=AC=A1=20git=20root=20=E8=A7=A3=E6=9E=90,=E7=9B=AF?= =?UTF-8?q?=E4=BD=8F=E5=B5=8C=E5=A5=97=20skill=20=E8=BD=AF=E9=93=BE?= =?UTF-8?q?=E6=B8=85=E5=8D=95=E6=9C=AC=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 对 41669c1 复审两条 P2: - launch 调用点把已解析的 repoRoot 经 hint 贯穿 watch 基线、路径收集与 快照边界:窗口内 .git 消失不再采出旧根盯视面配新根路径集合的混合口径 - 嵌套 skill 的 SKILL.md/skill.md 为仓内软链时,目标移动/删除只改目标处 mtime:软链清单的解析本体入 watch 面(与 prompts 同款);悬空链盯链接自身 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 23 +++++++++++++ packages/maker-core/src/agents/pi/index.ts | 14 ++++---- .../src/agents/pi/project-resource-cli.ts | 32 +++++++++++++++++-- 3 files changed, 61 insertions(+), 8 deletions(-) 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 index 9c30d625b2..06fdd7b9b5 100644 --- 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 @@ -269,6 +269,29 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + itPosixOnly('detects the symlink target of a nested skill manifest moved away', () => { + // Windows CI 无符号链接特权,本用例仅在 POSIX 跑(见 itPosixOnly)。 + mkdirSync(path.join(project, 'targets'), { recursive: true }); + mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'alpha'), { recursive: true }); + writeFileSync(path.join(project, 'targets', 'real.md'), '---\nname: alpha\ndescription: t\n---\n'); + symlinkSync(path.join(project, 'targets', 'real.md'), path.join(project, '.pi', 'skills', '@scope', 'alpha', 'SKILL.md')); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 目标移动/删除不改变 skill 目录自身 mtime,只有盯住解析后的清单本体才能检出 + rmSync(path.join(project, 'targets', 'real.md')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('collectors honor a shared repoRootHint (launch shares one resolution)', () => { + writeFileSync(path.join(project, '.git'), ''); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const hint = resolvePiResourceRepoRoot(project); + expect([...collectPiProjectResourceCliPaths(project, hint).skills]) + .toEqual([...collectPiProjectResourceCliPaths(project).skills]); + expect([...collectPiProjectResourceWatchRootMtimes(project, hint).keys()]) + .toEqual([...collectPiProjectResourceWatchRootMtimes(project).keys()]); + }); + it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(path.join(project, '.pi'))).toBe(-1); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 12cd7e4967..4edea67635 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -4067,17 +4067,19 @@ export class PiAgent extends BaseAgent { // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 // watch 基线与 git 边界必须先于路径收集采样(见 snapshotPiProjectResourceLaunch): // 三样同批且基线在前,采样窗口内新增的资源/边界变化只会让首次快检多一次重扫后 - // 收敛;反序会漏掉窗口内新增的资源,或让新旧边界与路径集合错配,静默漏检。 - const projectResourceWatchRootMtimes = loadProjectResourcesInPlace && !guestRoot - ? collectPiProjectResourceWatchRootMtimes(opts.workingDir) - : null; + // 收敛;git root 只解析一次,经 hint 贯穿三样 —— 窗口内 .git 消失不会采出旧根 + // 盯视面配新根路径集合的混合口径。 const projectResourceRepoRootAtLaunch = loadProjectResourcesInPlace && !guestRoot ? resolvePiResourceRepoRoot(opts.workingDir) : null; + const projectResourceWatchRootMtimes = projectResourceRepoRootAtLaunch + ? collectPiProjectResourceWatchRootMtimes(opts.workingDir, projectResourceRepoRootAtLaunch) + : null; const collectedProjectResources = loadProjectResourcesInPlace ? guestRoot - ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) - : collectPiProjectResourceCliPaths(opts.workingDir) + ? restrictPiGuestProjectResources( + collectPiProjectResourceCliPaths(opts.workingDir, projectResourceRepoRootAtLaunch ?? undefined), guestRoot) + : collectPiProjectResourceCliPaths(opts.workingDir, projectResourceRepoRootAtLaunch ?? undefined) : emptyPiProjectResourceCliPaths(); const projectResourceCli = loadProjectResourcesInPlace ? { 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 afca8a7e81..77cc5965c4 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -274,16 +274,44 @@ function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): if (entry.isSymbolicLink()) continue; const realChild = realpathOrNull(childPath); if (!realChild || !isDir(realChild)) continue; - if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 + if (hasSkillFile(realChild)) { + // skill 目录:collector 不再往里枚举;但 SKILL.md 本身可能是指向仓内目标的软链, + // 目标移动/删除只改目标处,盯住解析后的清单本体。 + watchPiSkillManifestTargets(roots, realChild); + continue; + } if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace for (const nested of listDir(realChild)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; - roots.set(path.join(realChild, nested.name), statMtimeMs(path.join(realChild, nested.name))); + const nestedPath = path.join(realChild, nested.name); + roots.set(nestedPath, statMtimeMs(nestedPath)); + const realNested = realpathOrNull(nestedPath); + if (realNested && isDir(realNested) && hasSkillFile(realNested)) { + watchPiSkillManifestTargets(roots, realNested); + } } } } +/** 软链清单本体:SKILL.md/skill.md 为指向仓内目标的软链时,目标移动/删除不改变 + * skill 目录自身 mtime,只有盯住解析后的文件才能检出(与 prompts 同款)。悬空链 + * 盯链接自身,目标落地即检出。 */ +function watchPiSkillManifestTargets(roots: Map, realFolder: string): void { + for (const name of ['SKILL.md', 'skill.md']) { + const manifestPath = path.join(realFolder, name); + let manifestLstat: fs.Stats; + try { + manifestLstat = fs.lstatSync(manifestPath); + } catch { + continue; + } + if (!manifestLstat.isSymbolicLink()) continue; + const realManifest = realpathOrNull(manifestPath); + roots.set(realManifest ?? manifestPath, statMtimeMs(realManifest ?? manifestPath)); + } +} + /** stat 一个 extensions 根及其子目录:已有扩展目录内 index.ts 增删只改子目录 mtime。 */ function watchPiExtensionChildMtimes(roots: Map, extDir: string): void { roots.set(extDir, statMtimeMs(extDir)); From 61f85722dd9bd4ae1625c0921fa7b5e7f21f3901 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 19:27:59 +0800 Subject: [PATCH 12/45] =?UTF-8?q?fix(pi):=20=E7=9B=B4=E5=8F=91=E9=93=BE?= =?UTF-8?q?=E8=B7=AF=E6=8E=A5=E5=85=A5=E8=B5=84=E6=BA=90=E6=BC=82=E7=A7=BB?= =?UTF-8?q?=E5=9B=9E=E6=94=B6,=E7=9B=AF=E4=BD=8F=E6=82=AC=E7=A9=BA?= =?UTF-8?q?=E7=9A=84=E5=B5=8C=E5=A5=97=E6=B8=85=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 对 1208a97d 复审两条 P2: - IM turnRunner / scheduler 直发降级 / goal 直派不经桌面发送事务, 项目资源变更后仍用旧 argv 投递。Maker 新增共享回收入口 recyclePiRuntimeIfResourcesDrifted(空闲判定 + runtime-refresh 原因), 三个直发点 send 前调用,随后各自按既有自愈路径重建会话(IM 走 DB 行 重建重绑,scheduler 走 stale 自愈,goal 走 ensureSession 活化) - 嵌套候选目录的清单为悬空软链时(hasSkillFile=false 不入收集), 清单本体未入盯视,目标落地无法检出。改为候选目录一律盯清单本体 (悬空盯链接自身,与 prompts 同款),上层与嵌套两层一致 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/goal-host/controller.ts | 7 ++++++ apps/desktop/src/main/im/shared/turnRunner.ts | 14 +++++++++++ .../desktop/src/main/scheduler-host/runner.ts | 6 +++++ .../pi-project-resource-drift.test.ts | 11 ++++++++ .../src/agents/pi/project-resource-cli.ts | 16 ++++++------ packages/maker-core/src/maker.test.ts | 25 +++++++++++++++++++ packages/maker-core/src/maker.ts | 13 ++++++++++ 7 files changed, 83 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts index 46a134fb37..afb183667f 100644 --- a/apps/desktop/src/main/goal-host/controller.ts +++ b/apps/desktop/src/main/goal-host/controller.ts @@ -21,6 +21,7 @@ import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-contin import { buildContinuationDirective, buildFirstTurnDirective } from './directive'; import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton'; import { onUiSessionIntervention } from '../maker-ipc/uiContinuationSignal'; +import { getMaker } from '../maker-host'; import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff'; import { MAX_CONSECUTIVE_OVERLOAD_TURNS, @@ -2506,6 +2507,12 @@ export class GoalController { releaseAgentSwitchLock = (await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {}); if (!isCurrentLifecycle()) return; + // 项目资源漂移:先经 Maker 回收旧运行时(runtime-refresh),随后的 ensureSession + // 活化即按最新配置重扫重建;与桌面发送事务同口径。 + const preDispatchLive = getMaker().getSession(sessionId); + if (preDispatchLive && await getMaker().recyclePiRuntimeIfResourcesDrifted(preDispatchLive)) { + 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/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index 6cd2d0a6f4..10fb820833 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1653,6 +1653,20 @@ export function createTurnRunner( return { kind: 'rejected', reason: 'aborted' }; } + // 项目资源漂移(如会话中途 openspec init):空闲时经 Maker 以 runtime-refresh + // 回收运行时,再按 DB 行自愈重建 —— 与桌面发送事务同口径,IM 直发不用旧资源。 + // 无 agent-switch 锁的装配不支持关闭后重建,保持原样投递。 + try { + if (deps.acquirePendingAgentSwitch + && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)) { + await refreshSessionAfterPendingAgentSwitch(state, state.makerSession.id, userId); + log.info('im send: project resources drifted, recycled runtime before dispatch'); + } + } catch (err) { + log.warn('im send: resource-drift recycle failed, sending as-is', + err instanceof Error ? err.message : String(err)); + } + 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/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts index c3f6d35feb..24548d9d53 100644 --- a/apps/desktop/src/main/scheduler-host/runner.ts +++ b/apps/desktop/src/main/scheduler-host/runner.ts @@ -1917,6 +1917,12 @@ export class MakerScheduleRunner implements ScheduleRunner { ); } + // 直发降级路径(无 schedulerQueue):项目资源漂移时先经 Maker 以 runtime-refresh + // 回收,stale 自愈(下方 getSession !== session 分支)按最新 DB 行重建后投递。 + if (await this.deps.maker.recyclePiRuntimeIfResourcesDrifted(session)) { + this.deps.logger.info?.('[runner] project resources drifted, recycled runtime before dispatch', { sessionId: session.id }); + } + // 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/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 index 06fdd7b9b5..ece22487d9 100644 --- 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 @@ -282,6 +282,17 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + itPosixOnly('detects a nested skill manifest target materializing behind a dangling symlink', () => { + // 嵌套候选目录的清单是悬空软链时,hasSkillFile 为 false 不入收集,但链接本体 + // 已入盯视:目标落地(改动的 elsewhere 目录未被盯视)也能检出。 + mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'foo'), { recursive: true }); + mkdirSync(path.join(project, 'elsewhere'), { recursive: true }); + symlinkSync(path.join(project, 'elsewhere', 'skill.md'), path.join(project, '.pi', 'skills', '@scope', 'foo', 'SKILL.md')); + const baseline = snapshot(); + writeFileSync(path.join(project, 'elsewhere', 'skill.md'), '---\nname: foo\ndescription: t\n---\n'); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('collectors honor a shared repoRootHint (launch shares one resolution)', () => { writeFileSync(path.join(project, '.git'), ''); writeSkill(path.join('.pi', 'skills'), 'alpha'); 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 77cc5965c4..d2f0bd2eff 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -274,12 +274,10 @@ function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): if (entry.isSymbolicLink()) continue; const realChild = realpathOrNull(childPath); if (!realChild || !isDir(realChild)) continue; - if (hasSkillFile(realChild)) { - // skill 目录:collector 不再往里枚举;但 SKILL.md 本身可能是指向仓内目标的软链, - // 目标移动/删除只改目标处,盯住解析后的清单本体。 - watchPiSkillManifestTargets(roots, realChild); - continue; - } + // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, + // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 + watchPiSkillManifestTargets(roots, realChild); + if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace for (const nested of listDir(realChild)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; @@ -287,9 +285,9 @@ function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): const nestedPath = path.join(realChild, nested.name); roots.set(nestedPath, statMtimeMs(nestedPath)); const realNested = realpathOrNull(nestedPath); - if (realNested && isDir(realNested) && hasSkillFile(realNested)) { - watchPiSkillManifestTargets(roots, realNested); - } + if (!realNested || !isDir(realNested)) continue; + // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 + watchPiSkillManifestTargets(roots, realNested); } } } 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 f9b6e1f3cd..1b99190c99 100644 --- a/packages/maker-core/src/maker.ts +++ b/packages/maker-core/src/maker.ts @@ -1455,6 +1455,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, From e39f10009111e03055fb2a766b6917f8ae6d939b Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 19:52:07 +0800 Subject: [PATCH 13/45] =?UTF-8?q?fix(im,scheduler):=20=E7=9B=B4=E5=8F=91?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E7=AA=97=E5=8F=A3=E7=9A=84=E4=B8=A4=E5=A4=84?= =?UTF-8?q?=20P1=20=E2=80=94=E2=80=94=20=E5=96=8A=E5=81=9C=E5=90=8E?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=E4=B8=8E=E5=9B=9E=E6=94=B6=E5=90=8E=E6=9C=AA?= =?UTF-8?q?=E9=87=8D=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 十一轮复审: - turnRunner:回收+冷启动是异步窗口,/stop 可能恰好落在其中。回收后 重新核对 terminalKind(经函数读取绕开 CFA 收窄,运行时值在窗口内可 变为 aborted),喊停即按与既有检查同口径拒绝,不再开始执行 - scheduler 直发降级:回收后原先依赖 Pi 模型路由分支内的 stale 自愈 重建,非 Pi/无路由依赖时直发会打到已关闭实例。改为回收后就地用 createSessionOpts 重建 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/im/shared/turnRunner.ts | 13 +++++++++++++ apps/desktop/src/main/scheduler-host/runner.ts | 4 +++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index 10fb820833..a1e13ecb4d 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1666,6 +1666,19 @@ export function createTurnRunner( log.warn('im send: resource-drift recycle failed, sending as-is', err instanceof Error ? err.message : String(err)); } + // 回收+重建是异步窗口:/stop 可能恰好落在其中;喊停后不得再开始执行, + // 与上方 aborted 检查同口径收尾(此时尚未发送,无 chunked 终态章要补)。 + // 经函数读取:上方检查已把控制流收窄到 'done'|'error',但运行时值在回收 + // 窗口内仍可变为 'aborted',需要绕开 CFA 的新鲜读取。 + 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); + 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, diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts index 24548d9d53..9f031262c8 100644 --- a/apps/desktop/src/main/scheduler-host/runner.ts +++ b/apps/desktop/src/main/scheduler-host/runner.ts @@ -1918,9 +1918,11 @@ export class MakerScheduleRunner implements ScheduleRunner { } // 直发降级路径(无 schedulerQueue):项目资源漂移时先经 Maker 以 runtime-refresh - // 回收,stale 自愈(下方 getSession !== session 分支)按最新 DB 行重建后投递。 + // 回收;回收后必须就地重建 —— 下方的 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 }); } // Resolve Pi's last provider change before listener, abort and handoff From 2a35bd8f31fa04fb529584e5e192d400f73669bc Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 20:02:15 +0800 Subject: [PATCH 14/45] =?UTF-8?q?fix(pi,im,scheduler):=20=E7=9B=B4?= =?UTF-8?q?=E9=93=BE=20skill=20=E6=A0=B9=E7=9B=AF=E4=BA=8C=E7=BA=A7?= =?UTF-8?q?=E6=B8=85=E5=8D=95=E6=9C=AC=E4=BD=93,scheduler=20=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=E9=87=8D=E6=8E=A5=E7=BA=BF,=E5=96=8A=E5=81=9C?= =?UTF-8?q?=E8=A1=A5=E5=81=9C=E6=AD=A2=E7=BB=88=E7=A8=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 十二轮 + Codex 十一轮复审: - project-resource-cli:直链 skill 根的二级软链清单(SKILL.md → 仓内文件) 目标移动/删除只改目标处,跟随后的目录与 skills 根 mtime 都不动。清单 本体盯视提前到软链 continue 之前,直链根同样覆盖 - scheduler 直发降级:回收重建后重新 wireSessionToIpc —— 该函数按 Session 实例幂等,换实例必须重接广播/落库链路,否则本轮回复与工具记录不进聊天页 - turnRunner 喊停重核分支:beginChunkedReply 在消息准备期已执行(企微 beginReply 已登记未结束流),与上方停止分支同款补发停止终稿再收尾, 避免回复永不结束、下一轮终稿错位 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/im/shared/turnRunner.ts | 14 ++++++++++++++ apps/desktop/src/main/scheduler-host/runner.ts | 3 +++ .../pi/__tests__/pi-project-resource-drift.test.ts | 14 ++++++++++++++ .../src/agents/pi/project-resource-cli.ts | 4 +++- 4 files changed, 34 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index a1e13ecb4d..770581f7b7 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1674,6 +1674,20 @@ export function createTurnRunner( if (turnTerminalNow() === 'aborted') { const index = state.queue.indexOf(item.turn); if (index >= 0) state.queue.splice(index, 1); + // beginChunkedReply 早在消息准备期已执行(企微 beginReply 已登记未结束流), + // 与上方停止分支同款补发停止终稿,否则回复永不结束、下一轮终稿错位。 + 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); diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts index 9f031262c8..e4dc8d253a 100644 --- a/apps/desktop/src/main/scheduler-host/runner.ts +++ b/apps/desktop/src/main/scheduler-host/runner.ts @@ -1923,6 +1923,9 @@ export class MakerScheduleRunner implements ScheduleRunner { 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 实例幂等,换实例需重接广播/落库链路, + // 否则本轮回复与工具记录不进聊天页。 + wireSessionToIpc(session); } // Resolve Pi's last provider change before listener, abort and handoff 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 index ece22487d9..a01eea17e8 100644 --- 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 @@ -293,6 +293,20 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + itPosixOnly('detects a second-level manifest target move for a direct symlinked skill root', () => { + // 直链 skill 根的 SKILL.md 是二级软链:目标删除只改目标处,跟随后的目录与 + // skills 根 mtime 都不变,必须靠清单本体盯视检出。 + mkdirSync(path.join(project, 'real-skill'), { recursive: true }); + mkdirSync(path.join(project, 'targets'), { recursive: true }); + writeFileSync(path.join(project, 'real-skill', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); + symlinkSync(path.join(project, 'real-skill'), path.join(project, '.pi', 'skills', 'foo'), 'dir'); + rmSync(path.join(project, 'real-skill', 'SKILL.md')); + symlinkSync(path.join(project, 'targets', 'real.md'), path.join(project, 'real-skill', 'SKILL.md')); + const baseline = snapshot(); + rmSync(path.join(project, 'targets', 'real.md')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('collectors honor a shared repoRootHint (launch shares one resolution)', () => { writeFileSync(path.join(project, '.git'), ''); writeSkill(path.join('.pi', 'skills'), 'alpha'); 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 d2f0bd2eff..70b3ac0fe4 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -271,12 +271,14 @@ function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(skillsDir, entry.name); roots.set(childPath, statMtimeMs(childPath)); - if (entry.isSymbolicLink()) continue; const realChild = realpathOrNull(childPath); if (!realChild || !isDir(realChild)) continue; // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 + // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, + // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 watchPiSkillManifestTargets(roots, realChild); + if (entry.isSymbolicLink()) continue; if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace for (const nested of listDir(realChild)) { From de853b1fae5cd88931bfd66ffeeb633986862e20 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 20:54:22 +0800 Subject: [PATCH 15/45] =?UTF-8?q?fix(im,hook,goal):=20=E8=A1=A5=20hook-con?= =?UTF-8?q?trol=20=E7=AC=AC=E5=9B=9B=E4=B8=AA=E7=9B=B4=E5=8F=91=E7=82=B9,?= =?UTF-8?q?=E4=BF=AE=20CI=20=E6=B5=8B=E8=AF=95=E6=A1=A9=E4=B8=8E=20goal=20?= =?UTF-8?q?=E6=94=B6=E9=9B=86=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - HookSessionRunner 也直发(createSession 可复用活实例):回收后重走获取 路径即得重建实例,失败按原样投递 - goal 直派改为 deps 可选 seam(回收后 ensureSession 活化即重扫重建): 不能顶层 import maker-host —— 其模块图带 Electron 访问,goalHandlers 单测的 electron mock 缺 app 导致收集失败;bootstrap 两处装配注入 - scheduler 十个测试桩补 recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => false) (直发回收调用落在无 schedulerQueue 的降级路径) Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/bootstrap-electron.ts | 14 +++++++++++++ apps/desktop/src/main/goal-host/controller.ts | 9 ++++---- apps/desktop/src/main/goal-host/index.ts | 4 ++++ apps/desktop/src/main/goal-host/types.ts | 4 ++++ .../src/main/hook-control/session-runner.ts | 21 +++++++++++++++++++ .../__tests__/runnerAgentMeta.test.ts | 1 + .../__tests__/runnerBackgroundTasks.test.ts | 1 + .../__tests__/runnerDefer.test.ts | 1 + .../__tests__/runnerModelSelection.test.ts | 1 + .../__tests__/runnerPreRunHookCwd.test.ts | 1 + .../__tests__/runnerQueuedDispatch.test.ts | 1 + .../__tests__/runnerSendOutcome.test.ts | 1 + .../__tests__/runnerSessionClose.test.ts | 1 + .../__tests__/runnerSilentNotify.test.ts | 1 + .../runnerWorkingDirFallback.test.ts | 1 + 15 files changed, 57 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts index 0d3e1a9d97..7a105c4eef 100644 --- a/apps/desktop/src/main/bootstrap-electron.ts +++ b/apps/desktop/src/main/bootstrap-electron.ts @@ -1445,6 +1445,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, @@ -1904,6 +1911,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 afb183667f..a4bb7607ab 100644 --- a/apps/desktop/src/main/goal-host/controller.ts +++ b/apps/desktop/src/main/goal-host/controller.ts @@ -21,7 +21,6 @@ import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-contin import { buildContinuationDirective, buildFirstTurnDirective } from './directive'; import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton'; import { onUiSessionIntervention } from '../maker-ipc/uiContinuationSignal'; -import { getMaker } from '../maker-host'; import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff'; import { MAX_CONSECUTIVE_OVERLOAD_TURNS, @@ -2507,10 +2506,10 @@ export class GoalController { releaseAgentSwitchLock = (await this.deps.acquirePendingAgentSwitch?.(sessionId)) ?? (() => {}); if (!isCurrentLifecycle()) return; - // 项目资源漂移:先经 Maker 回收旧运行时(runtime-refresh),随后的 ensureSession - // 活化即按最新配置重扫重建;与桌面发送事务同口径。 - const preDispatchLive = getMaker().getSession(sessionId); - if (preDispatchLive && await getMaker().recyclePiRuntimeIfResourcesDrifted(preDispatchLive)) { + // 项目资源漂移:先经注入的回收 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); diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts index 4b4fb71499..f55dc5f152 100644 --- a/apps/desktop/src/main/goal-host/index.ts +++ b/apps/desktop/src/main/goal-host/index.ts @@ -40,6 +40,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; @@ -70,6 +73,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/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts index 8e3de69145..222d71dd39 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -972,6 +972,27 @@ export function createMakerHookSessionRunner(deps: { return fail(err instanceof Error ? err.message : String(err)); } + // 项目资源漂移(会话中途新增 skill/extension):createSession 可能复用活实例, + // 空闲时经 Maker 回收后重取 —— 再走一次同样的获取路径即得重建实例。 + // 失败按原样投递(hook 轮次不应因回收故障而中断)。 + try { + if (await maker.recyclePiRuntimeIfResourcesDrifted(session)) { + 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 { + // 保持原样投递 + } + /** * 拿到的可能是**进程里早就活着的那个实例**: maker.createSession 对已在 * activeSessions 里的 id 直接返回它, 忽略上面传的 workingDir。侧边栏 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 9672447a15..ebf547a324 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 72d9f419b0..1b8a7c87b8 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 e3409adacc..97c19222c9 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 46423d7ae7..a0a64923b8 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 435f117ca6..bbd1bf1f18 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 b614b44ea3..3a218d71a1 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 6e234f52c5..9fee2196fe 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, 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 49f119e880..74594d305c 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 ac4ddede36..c8363fbd8c 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 4de79c27b6..7eb802714c 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, From ebea1016d476afaff5165d505e4a8c0f77f467d1 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 21:11:08 +0800 Subject: [PATCH 16/45] =?UTF-8?q?fix(hook):=20=E5=8F=96=E6=B6=88=E6=8E=A2?= =?UTF-8?q?=E9=92=88=E8=A6=86=E7=9B=96=E5=9B=9E=E6=94=B6/=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=E7=AA=97=E5=8F=A3,=E5=96=8A=E5=81=9C=E4=B8=8D?= =?UTF-8?q?=E8=90=BD=E8=BF=9B=E6=96=B0=E8=BF=9B=E7=A8=8B=E6=89=A7=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 十四轮 P1:回收/重建是异步窗口,期间 task.cancel 的 abort 对已 关闭的旧实例无目标、对新实例未登记,喊停后消息仍可能投给新进程执行工具。 HookRunRequest 新增可选取消探针 isCancelRequested(dispatcher 从 task.cancel 账本注入),session-runner 在回收/重建后、发送前查询:命中 即以 error 收口提前返回(execute 收口按取消账本把状态统一改写为 cancelled),消息不再投给新进程。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/hook-control/dispatcher.ts | 8 ++++++++ apps/desktop/src/main/hook-control/session-runner.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts index baf7b8a9cc..6a9dfe0717 100644 --- a/apps/desktop/src/main/hook-control/dispatcher.ts +++ b/apps/desktop/src/main/hook-control/dispatcher.ts @@ -184,6 +184,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. */ @@ -1978,6 +1984,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 222d71dd39..e573d5ce2a 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -993,6 +993,18 @@ export function createMakerHookSessionRunner(deps: { // 保持原样投递 } + // 取消探针:回收/重建是异步窗口,期间 task.cancel 的 abort 对旧实例无目标、 + // 对新实例未登记 —— 喊停后不得把消息投给新进程执行。此处尚未发送,提前以 + // error 收口;execute 收口会按取消账本把状态统一改写为 cancelled。 + if (req.isCancelRequested?.()) { + return { + status: 'error', + finalText: '', + errorMessage: '任务已被用户喊停,本条消息没有执行。', + durationMs: Date.now() - startedAt, + }; + } + /** * 拿到的可能是**进程里早就活着的那个实例**: maker.createSession 对已在 * activeSessions 里的 id 直接返回它, 忽略上面传的 workingDir。侧边栏 From 565ff75953cbbb25c466088bc802dabbea0d6e12 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 21:23:25 +0800 Subject: [PATCH 17/45] =?UTF-8?q?fix(hook):=20=E5=8F=96=E6=B6=88=E6=97=A9?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=89=8D=E5=85=88=E6=8C=81=E4=B9=85=E5=8C=96?= =?UTF-8?q?=20provider=20=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile 十五轮 P1:新建 hook 任务在 createSession 期间被取消时,取消 探针的提前返回会跳过 setSessionProviderIdInDb —— 任务行已存在,但 DesktopSessionStorage.create 不写 providerId、freezeSessionProviderAtStart 只写内存;应用重启后复用读到空来源,改走默认供应商或因模型不可用失败。 运行时来源注入(新建显式 set / 复用 hydrate)提前到取消探针之前: 先持久化已创建任务的供应商选择,再阻止消息发送。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../src/main/hook-control/session-runner.ts | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts index e573d5ce2a..d68e05353d 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -993,6 +993,20 @@ export function createMakerHookSessionRunner(deps: { // 保持原样投递 } + // 运行时来源注入(路由层经 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。 @@ -1038,17 +1052,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); From a547a433131d8ef59b59ebca1af50ea82e4c07b4 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 21:38:01 +0800 Subject: [PATCH 18/45] =?UTF-8?q?test(pi):=20=E4=BA=8C=E7=BA=A7=E8=BD=AF?= =?UTF-8?q?=E9=93=BE=E7=94=A8=E4=BE=8B=E5=85=88=E5=BB=BA=20.pi/skills=20?= =?UTF-8?q?=E7=88=B6=E7=9B=AE=E5=BD=95(symlinkSync=20=E4=B8=8D=E5=BB=BA?= =?UTF-8?q?=E7=88=B6=E7=BA=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../src/agents/pi/__tests__/pi-project-resource-drift.test.ts | 1 + 1 file changed, 1 insertion(+) 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 index a01eea17e8..65e9abfbeb 100644 --- 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 @@ -296,6 +296,7 @@ describe('piProjectResourcesDrifted', () => { itPosixOnly('detects a second-level manifest target move for a direct symlinked skill root', () => { // 直链 skill 根的 SKILL.md 是二级软链:目标删除只改目标处,跟随后的目录与 // skills 根 mtime 都不变,必须靠清单本体盯视检出。 + mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); mkdirSync(path.join(project, 'real-skill'), { recursive: true }); mkdirSync(path.join(project, 'targets'), { recursive: true }); writeFileSync(path.join(project, 'real-skill', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); From 5f65cdfe80532aa088af9ff02d9d8abc906bb8fb Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sat, 7 Nov 2026 22:13:02 +0800 Subject: [PATCH 19/45] =?UTF-8?q?test(pi):=20=E6=82=AC=E7=A9=BA=E4=BA=8C?= =?UTF-8?q?=E7=BA=A7=E8=BD=AF=E9=93=BE=E7=94=A8=E4=BE=8B=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E7=9B=AE=E6=A0=87=E8=90=BD=E5=9C=B0=E8=A7=A6=E5=8F=91(?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=AF=AF=20rmSync=20=E4=B8=8D=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=E6=96=87=E4=BB=B6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Linux CI 抓出:用例先建悬空链接后 rmSync 了从未写入的目标文件(ENOENT)。 用例本意即悬空链目标落地触发漂移,改为 writeFileSync —— 与 prompts 悬空链用例同款模式。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../src/agents/pi/__tests__/pi-project-resource-drift.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 65e9abfbeb..af0745a781 100644 --- 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 @@ -304,7 +304,8 @@ describe('piProjectResourcesDrifted', () => { rmSync(path.join(project, 'real-skill', 'SKILL.md')); symlinkSync(path.join(project, 'targets', 'real.md'), path.join(project, 'real-skill', 'SKILL.md')); const baseline = snapshot(); - rmSync(path.join(project, 'targets', 'real.md')); + // 目标落地(悬空链的本体已入盯视,写入后 stat 由 -1 变实值)→ 判漂移 + writeFileSync(path.join(project, 'targets', 'real.md'), '---\nname: foo\ndescription: t\n---\n'); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); From c26c616d027eb6e7d694ed5b84cba1c0a4f03ff9 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sun, 8 Nov 2026 03:31:35 +0800 Subject: [PATCH 20/45] =?UTF-8?q?fix(desktop):=20=E6=BC=82=E7=A7=BB?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E7=9A=84=E5=85=B3=E9=97=AD=E5=8C=85=E8=BF=9B?= =?UTF-8?q?=20rehydrate=20=E6=8A=91=E5=88=B6=E7=AA=97=E5=8F=A3,=E4=BF=9D?= =?UTF-8?q?=E4=BD=8F=E5=9C=A8=E9=80=94=E5=8F=91=E9=80=81=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 发送事务里触发 runtime-refresh 回收时,close 广播经 onSessionClosed abort 了正在驱动这次回收的 input boundary;随后的 lazy bootstrap 里 session.send 拿到已 abort 的 signal,直接 cancelled-before-dispatch (2026-11-08 实报:openspec init 后每个存量会话首条消息必失败一次, 手动重试才过)。 修复:两条直发点(发送事务 deps.closeSessionIfCurrent 与 send_to_session lazy-resume 的回收)都把 close 包进 withRehydrateCloseSuppressed —— 与任务移动的 closeIdleSessionForMove 同一「重建窗口」语义:在途发送边界保留,worktree/临时附件清理交给 重建后的 runtime。回归测试钉住两条直发点与 close adapters 的 preserve 读数(红→绿已验证)。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../makerEventHotPathOrdering.test.ts | 62 +++++++++++++++++++ apps/desktop/src/main/maker-ipc/register.ts | 16 ++++- 2 files changed, 76 insertions(+), 2 deletions(-) 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/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts index 23871bb0a5..10f2f25a35 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -13208,7 +13208,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) // 'runtime-refresh' 回收运行时(直接 Session.close 会丢 Maker 原因,IM 侧按 // unexpected 清排队回合),lazy resume 重扫重建 if (live?.agentKind === 'pi' && live.hasRecyclableProjectResourceDrift()) { - await maker.closeSessionIfCurrent(live, 'runtime-refresh'); + // 同 makerSendTransaction 的漂移回收:关闭包在抑制窗口内(保留重建窗口, + // 不 abort 本通道在途的派发边界,不释放 worktree/临时附件),下面的 + // lazy resume 随即重扫重建再投递。 + const driftedLive = live; + await withRehydrateCloseSuppressed(targetSessionId, () => + maker.closeSessionIfCurrent(driftedLive, 'runtime-refresh')); live = undefined; } if (live) { @@ -18850,7 +18855,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions) closeSession: (sessionId) => maker.closeSession(sessionId), closeSessionIfCurrent: async (sessionId) => { const current = maker.getSession(sessionId); - if (current) await maker.closeSessionIfCurrent(current, 'runtime-refresh'); + 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) => { From 1efd7288e45a6583b9c828ccd50431780cc2f09c Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Sun, 8 Nov 2026 04:10:11 +0800 Subject: [PATCH 21/45] =?UTF-8?q?fix(desktop,pi):=20Orca=20=E7=9B=B4?= =?UTF-8?q?=E5=8F=91=E6=8E=A5=E5=85=A5=E6=BC=82=E7=A7=BB=E5=9B=9E=E6=94=B6?= =?UTF-8?q?;=E6=BC=82=E7=A7=BB=E6=B5=8B=E8=AF=95=E6=98=BE=E5=BC=8F?= =?UTF-8?q?=E6=8E=A8=20mtime=20=E6=B2=BB=20Windows=20=E7=B2=92=E5=BA=A6?= =?UTF-8?q?=E5=81=87=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Orca worker→lead 直发(dispatchLive)绕过发送事务的漂移回收,lead 拿旧 argv 跑这一轮:新增 recycleProjectResourceRuntime seam(pi + 空闲口径), 命中则经 withRehydrateCloseSuppressed 抑制窗口内 runtime-refresh 关闭 旧 runtime(与发送事务同一「重建窗口」语义),返回 null 落到既有 queued/lazy 路径由 sendToSessionInternal 重扫重建投递。 pi-project-resource-drift:Windows 文件时间戳粒度(最粗 ~15.6ms)下同 tick 的 mkdir/write 不改父目录 mtime,快检判不出漂移就不重扫,CI 偶发 假失败(run 42406651024 Windows 1/4 实报 213 行);依赖漂移判定的步骤 显式 utimes 推 mtime,本地连跑 5 遍稳定。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../orcaInterAgentDispatcher.test.ts | 23 +++++++++++++++++++ .../maker-ipc/orcaInterAgentDispatcher.ts | 10 ++++++++ apps/desktop/src/main/maker-ipc/register.ts | 10 ++++++++ .../pi-project-resource-drift.test.ts | 16 ++++++++++++- 4 files changed, 58 insertions(+), 1 deletion(-) 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 9af0f9fee9..d20ac34b8b 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/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts index 05a4cb6f37..fa874e9351 100644 --- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts +++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts @@ -190,6 +190,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; /** * 校验 imagePaths(存在性 + 图片扩展名), 返回逐张附件元数据或错误消息。 * fs 属 host 边界, dispatcher 不直接碰文件系统。 @@ -681,6 +686,11 @@ export function createOrcaInterAgentDispatcher( await deps.prepareUnhealthySession?.(params.targetSessionId); 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 10f2f25a35..309711e679 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -15921,6 +15921,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 }> = []; 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 index af0745a781..52c58e7ecc 100644 --- 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 @@ -9,7 +9,7 @@ * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 */ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -43,6 +43,14 @@ function statMtime(target: string): number { return statSync(target).mtimeMs; } +// Windows 文件时间戳有粒度(最粗 ~15.6ms):同一 tick 内的连续 mkdir/write 不改 +// 父目录 mtime,快检判不出漂移就不触发重扫 —— 断言依赖漂移判定的步骤必须显式 +// 推 mtime,否则 Windows CI 会偶发假失败(2026-11-08 run 42406651024 实报)。 +function bumpMtime(target: string): void { + const t = new Date(statSync(target).mtimeMs + 50); + utimesSync(target, t, t); +} + function snapshot() { // 与生产调用点同序:基线先采样,路径后收集(见 snapshotPiProjectResourceLaunch)。 const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); @@ -59,6 +67,7 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshot(); writeSkill(path.join('.pi', 'skills'), 'beta'); + bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -66,8 +75,10 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshot(); writeSkill(path.join('.pi', 'skills'), 'beta'); + bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(true); rmSync(path.join(project, '.pi', 'skills', 'beta'), { recursive: true, force: true }); + bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(false); }); @@ -209,10 +220,12 @@ describe('piProjectResourcesDrifted', () => { const baseline = snapshot(); // 重扫窗口内新建的空扩展目录:集合未变,但必须从此纳入盯视 mkdirSync(path.join(project, '.pi', 'extensions', 'newext'), { recursive: true }); + bumpMtime(path.join(project, '.pi', 'extensions')); expect(piProjectResourcesDrifted(baseline)).toBe(false); expect(baseline.watchRootMtimes.has(path.join(project, '.pi', 'extensions', 'newext'))).toBe(true); // 若不重建基线,这里的 index.ts 只改未盯视的新子目录 mtime,永远检不出 writeFileSync(path.join(project, '.pi', 'extensions', 'newext', 'index.ts'), 'export {};\n'); + bumpMtime(path.join(project, '.pi', 'extensions', 'newext')); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -227,6 +240,7 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(false); // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 mkdirSync(path.join(nested, '.git'), { recursive: true }); + bumpMtime(nested); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); From fe45afa80339d4561178be73cebd352657e479ae Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Mon, 9 Nov 2026 13:13:54 +0800 Subject: [PATCH 22/45] =?UTF-8?q?fix(hook,im):=20=E6=BC=82=E7=A7=BB?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E6=88=90=E5=8A=9F=E5=90=8E=E7=9A=84=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D=E5=90=9E=E9=94=99?= =?UTF-8?q?,=E5=8E=9F=E6=A0=B7=E4=B8=8A=E6=8A=9B=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hook 直发与 IM turnRunner 的漂移回收把两种失败混在一个 catch 里: 回收本身失败(旧实例仍可用,原样投递合理)与回收成功(旧实例已关) 后的重建失败。后者继续拿已关闭实例投递,用户只会看到误导性的 「会话已关闭」,真正的启动原因(如新增扩展导致 pi 启动失败)被吞掉 (2026-11-09 Greptile P2)。 修法:拆开两个 await —— 回收失败保持原样投递;回收成功后的重建 失败返回原始错误(hook 路径带预建 worktree 同步回收,与上方新建 失败路径同款)。goal 与 scheduler 路径本就大声上抛,不动。 回归测试两用例(hook session-runner):重建失败上抛真实原因(红→绿 已验证)+ 回收失败原样投递不误伤。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../__tests__/session-runner.test.ts | 32 +++++++++++++++++++ .../src/main/hook-control/session-runner.ts | 21 +++++++++--- apps/desktop/src/main/im/shared/turnRunner.ts | 15 ++++++--- 3 files changed, 59 insertions(+), 9 deletions(-) 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 15b910d55c..a5823f20ec 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 @@ -395,6 +395,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 +819,36 @@ 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 () => { + // 回收本身失败 → 旧实例仍可用:原样投递(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('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 }))) diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts index d68e05353d..211690ce1c 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -974,9 +974,18 @@ export function createMakerHookSessionRunner(deps: { // 项目资源漂移(会话中途新增 skill/extension):createSession 可能复用活实例, // 空闲时经 Maker 回收后重取 —— 再走一次同样的获取路径即得重建实例。 - // 失败按原样投递(hook 轮次不应因回收故障而中断)。 + // 两种失败分开:回收本身失败 → 旧实例大概率仍可用,原样投递(hook 轮次 + // 不因回收故障中断);回收成功(旧实例已关)后的重建失败必须上抛 —— 继续 + // 用已关闭实例只会把真实启动原因(如新增扩展导致 pi 启动失败)换成误导 + // 性的「会话已关闭」(2026-11-09 Greptile P2)。 + let driftedRecycled = false; try { - if (await maker.recyclePiRuntimeIfResourcesDrifted(session)) { + driftedRecycled = await maker.recyclePiRuntimeIfResourcesDrifted(session); + } catch { + // 保持原样投递 + } + if (driftedRecycled) { + try { session = req.isNew ? await openChannelSession(req.sessionId, newSessionRoute, (admitted) => { sessionProviderId = admitted.providerId; @@ -988,9 +997,13 @@ export function createMakerHookSessionRunner(deps: { }); }, 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)); } - } catch { - // 保持原样投递 } // 运行时来源注入(路由层经 session-provider-store 决定上游与钥匙)必须先于 diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index 673db8c1e4..ce77e19147 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1657,16 +1657,21 @@ export function createTurnRunner( // 项目资源漂移(如会话中途 openspec init):空闲时经 Maker 以 runtime-refresh // 回收运行时,再按 DB 行自愈重建 —— 与桌面发送事务同口径,IM 直发不用旧资源。 // 无 agent-switch 锁的装配不支持关闭后重建,保持原样投递。 + // 两种失败分开:回收本身失败 → 旧实例仍可用,原样投递;回收成功(旧实例 + // 已关)后的重建失败必须上抛 —— 继续用已关闭实例只会把真实原因换成误 + // 导性的「会话已关闭」(2026-11-09 Greptile P2)。 + let driftRecycled = false; try { - if (deps.acquirePendingAgentSwitch - && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)) { - await refreshSessionAfterPendingAgentSwitch(state, state.makerSession.id, userId); - log.info('im send: project resources drifted, recycled runtime before dispatch'); - } + driftRecycled = !!(deps.acquirePendingAgentSwitch + && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)); } catch (err) { log.warn('im send: resource-drift recycle failed, sending as-is', 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 检查同口径收尾(此时尚未发送,无 chunked 终态章要补)。 // 经函数读取:上方检查已把控制流收窄到 'done'|'error',但运行时值在回收 From 0d915d8ea23b475fd477faafbbd73bac998de390 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 08:01:11 +0800 Subject: [PATCH 23/45] =?UTF-8?q?test(pi):=20=E6=BC=82=E7=A7=BB=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=96=AD=E8=A8=80=E6=8C=89=20realpath=20=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E5=8C=96=E8=B7=AF=E5=BE=84=E6=9F=A5=E9=94=AE,?= =?UTF-8?q?=E4=BF=AE=20macOS=206=20=E4=BE=8B=E5=BF=85=E6=8C=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实现以 realpath(scanRoot) 作 watch-root/CLI 路径的 Map 键,而断言用 mkdtemp 的原始路径查键。macOS 的 os.tmpdir()(/var/folders/…)是软链, realpath 后变 /private/var/…,原始键恒缺失 → 6 例必挂(MagicLizi P1, macOS 实测 6 failed | 22 passed)。Windows tmpdir 无软链所以此前未暴露。 修法:断言统一经 canon()(realpathSync 失败回退原值)查键,与实现键 语义对称;Windows 行为零变化(canron 为恒等)。 Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) 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 index 52c58e7ecc..f4297dadf6 100644 --- 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 @@ -43,6 +43,15 @@ function statMtime(target: string): number { return statSync(target).mtimeMs; } +/** 实现内部以 realpath(scanRoot) 作 Map 键(macOS 的 os.tmpdir() 是 /var/folders 软链):断言必须用规范化后的路径查键,否则键恒缺失(MagicLizi P1)。 */ +function canon(target: string): string { + try { + return realpathSync(target); + } catch { + return target; + } +} + // Windows 文件时间戳有粒度(最粗 ~15.6ms):同一 tick 内的连续 mkdir/write 不改 // 父目录 mtime,快检判不出漂移就不触发重扫 —— 断言依赖漂移判定的步骤必须显式 // 推 mtime,否则 Windows CI 会偶发假失败(2026-11-08 run 42406651024 实报)。 @@ -131,11 +140,11 @@ describe('piProjectResourcesDrifted', () => { const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); const roots = collectPiProjectResourceWatchRootMtimes(nested); - expect(roots.has(path.join(nested, '.pi'))).toBe(true); - expect(roots.has(path.join(nested, '.agents'))).toBe(true); - expect(roots.has(path.join(nested, '.agents', 'skills'))).toBe(true); - expect(roots.has(path.join(project, '.agents'))).toBe(true); - expect(roots.has(path.join(project, '.agents', 'skills'))).toBe(true); + expect(roots.has(canon(path.join(nested, '.pi')))).toBe(true); + expect(roots.has(canon(path.join(nested, '.agents')))).toBe(true); + expect(roots.has(canon(path.join(nested, '.agents', 'skills')))).toBe(true); + expect(roots.has(canon(path.join(project, '.agents')))).toBe(true); + expect(roots.has(canon(path.join(project, '.agents', 'skills')))).toBe(true); }); it('detects a skill added inside an existing namespace dir (nested level)', () => { @@ -178,13 +187,13 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshot(); const skillsDir = path.join(project, '.pi', 'skills'); - const mtimeAtLaunch = baseline.watchRootMtimes.get(skillsDir)!; + const mtimeAtLaunch = baseline.watchRootMtimes.get(canon(skillsDir))!; // 无关子目录:改了 skills 根 mtime,但不改变路径集合 mkdirSync(path.join(skillsDir, 'unrelated'), { recursive: true }); expect(piProjectResourcesDrifted(baseline)).toBe(false); // 基线已就地刷新:下一次快检恢复零扫描,且真实漂移仍能检出 - expect(baseline.watchRootMtimes.get(skillsDir)).toBe(statMtime(skillsDir)); - expect(baseline.watchRootMtimes.get(skillsDir)).not.toBe(mtimeAtLaunch); + expect(baseline.watchRootMtimes.get(canon(skillsDir))).toBe(statMtime(skillsDir)); + expect(baseline.watchRootMtimes.get(canon(skillsDir))).not.toBe(mtimeAtLaunch); expect(piProjectResourcesDrifted(baseline)).toBe(false); writeSkill(path.join('.pi', 'skills'), 'beta'); expect(piProjectResourcesDrifted(baseline)).toBe(true); @@ -196,10 +205,10 @@ describe('piProjectResourcesDrifted', () => { mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: true }); const roots = collectPiProjectResourceWatchRootMtimes(project); const ns = path.join(project, '.pi', 'skills', '@scope'); - expect(roots.has(ns)).toBe(true); - expect(roots.has(path.join(ns, 'alpha'))).toBe(true); - expect(roots.has(path.join(ns, 'plain'))).toBe(true); - expect(roots.has(path.join(project, '.pi', 'extensions', 'myext'))).toBe(true); + expect(roots.has(canon(ns))).toBe(true); + expect(roots.has(canon(path.join(ns, 'alpha')))).toBe(true); + expect(roots.has(canon(path.join(ns, 'plain')))).toBe(true); + expect(roots.has(canon(path.join(project, '.pi', 'extensions', 'myext')))).toBe(true); }); it('launch snapshot samples watch roots before path collection (race-safe order)', () => { @@ -211,7 +220,7 @@ describe('piProjectResourcesDrifted', () => { const baseline = snapshotPiProjectResourceLaunch( project, collectPiProjectResourceCliPaths(project), watchRootMtimes, resolvePiResourceRepoRoot(project)); expect(piProjectResourcesDrifted(baseline)).toBe(false); - expect(baseline.watchRootMtimes.get(path.join(project, '.pi', 'skills'))) + expect(baseline.watchRootMtimes.get(canon(path.join(project, '.pi', 'skills')))) .toBe(statMtime(path.join(project, '.pi', 'skills'))); }); @@ -222,7 +231,7 @@ describe('piProjectResourcesDrifted', () => { mkdirSync(path.join(project, '.pi', 'extensions', 'newext'), { recursive: true }); bumpMtime(path.join(project, '.pi', 'extensions')); expect(piProjectResourcesDrifted(baseline)).toBe(false); - expect(baseline.watchRootMtimes.has(path.join(project, '.pi', 'extensions', 'newext'))).toBe(true); + expect(baseline.watchRootMtimes.has(canon(path.join(project, '.pi', 'extensions', 'newext')))).toBe(true); // 若不重建基线,这里的 index.ts 只改未盯视的新子目录 mtime,永远检不出 writeFileSync(path.join(project, '.pi', 'extensions', 'newext', 'index.ts'), 'export {};\n'); bumpMtime(path.join(project, '.pi', 'extensions', 'newext')); @@ -335,6 +344,6 @@ describe('piProjectResourcesDrifted', () => { it('missing directories baseline as -1 and compare against real mtimes', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); - expect(roots.get(path.join(project, '.pi'))).toBe(-1); + expect(roots.get(canon(path.join(project, '.pi')))).toBe(-1); }); }); From 5db8b88ebdde03014869db6d2ce50979d41206be Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 09:06:08 +0800 Subject: [PATCH 24/45] =?UTF-8?q?test(pi):=20canon=20=E5=90=91=E4=B8=8A?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E6=9C=80=E6=B7=B1=E5=AD=98=E5=9C=A8=E7=A5=96?= =?UTF-8?q?=E5=85=88,=E4=BF=AE=20macOS=20=E6=AE=8B=E7=95=99=202=20?= =?UTF-8?q?=E4=BE=8B=E5=BF=85=E6=8C=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0d915d8 的 canon 对已存在路径有效,但断言查尚未创建的 watch root (sub/.pi、sub/.agents 链)时 realpathSync ENOENT 回退原始路径,与实现 「realpath(scanRoot) 前缀 + 词法尾段」的键格式错位,macOS 仍挂 2 例 (MagicLizi 实测 2 failed | 26 passed)。canon 改为与实现同语义:向上 走到最深存在祖先做 realpath,再把缺失尾段按原序拼回;对已存在路径 行为不变(Windows 23/23)。junction 模拟软链语义验证:软链路径+未创建 尾段 → 真实路径+原序尾段。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) 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 index f4297dadf6..dcf85b0fba 100644 --- 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 @@ -43,12 +43,20 @@ function statMtime(target: string): number { return statSync(target).mtimeMs; } -/** 实现内部以 realpath(scanRoot) 作 Map 键(macOS 的 os.tmpdir() 是 /var/folders 软链):断言必须用规范化后的路径查键,否则键恒缺失(MagicLizi P1)。 */ +/** 实现内部以 realpath(scanRoot) 作键前缀、未创建尾段词法拼接(macOS 的 os.tmpdir() 是 /var/folders 软链):断言必须同语义查键,否则键恒缺失(MagicLizi P1 两轮)。canon 向上走到最深存在祖先做 realpath,再把不存在的尾段按原序拼回 —— 对已存在路径等价于 realpathSync。 */ function canon(target: string): string { - try { - return realpathSync(target); - } catch { - return target; + const abs = path.isAbsolute(target) ? target : path.resolve(target); + const missingTail: string[] = []; + let cur = abs; + for (;;) { + try { + return path.join(realpathSync(cur), ...missingTail); + } catch { + const parent = path.dirname(cur); + if (parent === cur) return abs; + missingTail.unshift(path.basename(cur)); + cur = parent; + } } } From e74f6bec066673700aea752661b685d958028b41 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 12:29:09 +0800 Subject: [PATCH 25/45] =?UTF-8?q?test(im,scheduler):=20=E8=A1=A5=E6=BC=82?= =?UTF-8?q?=E7=A7=BB=E5=9B=9E=E6=94=B6=E4=B8=A4=E5=88=86=E6=94=AF=E5=9B=9E?= =?UTF-8?q?=E5=BD=92,=E6=B2=BB=20MagicLizi=20=E4=B8=A4=20P1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit IM 直发的「回收 → 按 DB 行重建 → 换实例投递 → wireSessionToIpcExternal 重接」与直发降级的「回收 → 就地重建 → 重接」此前零覆盖(三个 P1 修复的 共同落点)。新增 3 用例: - IM:recycle true → 重建实例收投递、旧实例不再 send、外部重接按新实例; rebuilt 仅在回收窗口后对 getSession 可见(提前暴露会让 agent-switch 复核 抢先绑定时序失真)。 - scheduler:recycle true → 就地重建 + 重接 + 投递落新实例; 重建失败在 run 组装前裸上抛(fe45afa803 语义,不产出 failed run)。 Signed-off-by: Zhang Yunjin --- .../turnRunnerCompanionRouting.test.ts | 49 +++++++++++++++++++ .../__tests__/runnerSendOutcome.test.ts | 48 ++++++++++++++++++ 2 files changed, 97 insertions(+) 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 57b676f2df..905720413b 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts @@ -598,3 +598,52 @@ describe('turnRunner: connection handed to a companion bot', () => { expect(harnesses.get('desktop-sess-1')!.send).toHaveBeenCalledTimes(1); }); }); + +describe('turnRunner: project-resource drift recycle before IM dispatch', () => { + it('rebuilds the runtime from the DB row and dispatches on the rebuilt instance', async () => { + // 回归(MagicLizi P1):IM 直发的「漂移回收 → 按 DB 行重建 → 换实例投递」分支 + // 此前零测试覆盖,是三个 P1 修复(e39f100091/2a35bd8f31/fe45afa803)的共同落点。 + const original = makeSessionHarness('mimi-main'); + const rebuilt = makeSessionHarness('mimi-main-rebuilt'); + let recycleCalledWith: string | undefined; + let createCalls = 0; + // rebuilt 只在回收窗口之后对 getSession 可见:漂移检查前的 agent-switch 复核 + // 也读 getSession,提前暴露会让它抢先把 rebuilt 绑进 state(时序失真)。 + let rebuiltLive = false; + mocks.getMaker.mockImplementation(() => ({ + getSession: vi.fn((id: string) => (rebuiltLive && id === 'mimi-main' ? rebuilt.session : original.session)), + on: vi.fn(() => () => undefined), + createSession: vi.fn(async () => { + createCalls += 1; + return createCalls === 1 ? original.session : rebuilt.session; + }), + recyclePiRuntimeIfResourcesDrifted: vi.fn(async (id: string) => { + recycleCalledWith = id; + rebuiltLive = true; + return true; + }), + })); + // 重建按 DB 行走:refreshSessionAfterPendingAgentSwitch 读 sessions 表。 + mocks.dbSelect.mockImplementation(() => ({ + from: () => ({ + where: () => ({ + limit: async () => [{ ...botRows.get('mimi-main'), status: 'active' }], + }), + }), + })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + + // 实现传的是 session 实例(不是 id):必须是回收前的旧实例。 + expect((recycleCalledWith as { id: string } | undefined)?.id).toBe('mimi-main'); + // 旧实例已关闭:投递必须落在重建实例上,而不是把真实原因换成「会话已关闭」。 + expect(original.send).not.toHaveBeenCalled(); + expect(rebuilt.send).toHaveBeenCalledTimes(1); + // 换实例必须重接广播/落库链路(wireSessionToIpcExternal 按 Session 实例幂等)。 + expect(mocks.wireSessionToIpcExternal).toHaveBeenCalledWith(rebuilt.session); + }); +}); 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 9fee2196fe..6280bf5c5e 100644 --- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts +++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts @@ -791,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(); + }); }); From 4bea9b9af0109293c031d9c7ac58e1a9aa6f8173 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 12:44:19 +0800 Subject: [PATCH 26/45] =?UTF-8?q?chore(skills):=20built-in=20=E6=8A=80?= =?UTF-8?q?=E8=83=BD=E5=8C=85=E7=89=88=E6=9C=AC=E5=8D=87=E8=87=B3=2091,?= =?UTF-8?q?=E5=90=88=20upstream=20=E5=90=8E=E7=BB=84=E5=90=88=E5=AD=97?= =?UTF-8?q?=E8=8A=82=E5=B7=B2=E5=8F=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Check built-in Skill bundle versions 门禁:合入 upstream/main 后组合内容 变化而版本仍为 90,同版本不同字节 fail-closed。本地以 merge-base 实测 通过(version 91, checkedCommits 1348)。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/maker-host/built-in-skills.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9dd1d5d932..f1786d4bc7 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 = 90; +export const BUILT_IN_SKILLS_BUNDLE_VERSION = 91; const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13; export interface BuiltInSkillDescriptor { From cc2e843244f963a533647fe08bc51617b0c317f0 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 13:03:10 +0800 Subject: [PATCH 27/45] =?UTF-8?q?chore(skills):=20built-in=20=E6=8A=80?= =?UTF-8?q?=E8=83=BD=E5=8C=85=E7=89=88=E6=9C=AC=E5=8D=87=E8=87=B3=2092,?= =?UTF-8?q?=E9=AB=98=E4=BA=8E=E4=B8=8A=E6=B8=B8=E5=90=8C=E7=89=88=E7=BB=84?= =?UTF-8?q?=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit upstream main 亦将版本升至 91 且字节不同;按门禁语义取高于全部组合来源 的 92,并对 CI 实际 checkout 的 refs/pull/9248/merge 树本地复验通过。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/maker-host/built-in-skills.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f1786d4bc7..9dde96ea8e 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 = 91; +export const BUILT_IN_SKILLS_BUNDLE_VERSION = 92; const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13; export interface BuiltInSkillDescriptor { From f34dedee623f17e652178141a7c303349af69c2b Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 13:04:29 +0800 Subject: [PATCH 28/45] =?UTF-8?q?chore(skills):=20=E5=90=88=E5=85=A5?= =?UTF-8?q?=E6=9C=80=E6=96=B0=20upstream/main,=E5=86=85=E7=BD=AE=E6=8A=80?= =?UTF-8?q?=E8=83=BD=E5=8C=85=E7=89=88=E6=9C=AC=E5=8D=87=E8=87=B3=2093?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根治 verify-checks 竞态:main 在 push 与 CI merge-checkout 之间移动会 改变组合字节。先把当前 upstream/main(23c64312d7)合进分支,此后 CI 的 merge 树与分支树一致,版本 93 高于历史全部来源(90/91/92)。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/maker-host/built-in-skills.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9dde96ea8e..d9eb96684b 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 = 92; +export const BUILT_IN_SKILLS_BUNDLE_VERSION = 93; const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13; export interface BuiltInSkillDescriptor { From 09e8139b91c0c1b4d846edd0bae0b265111baa19 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 13:30:05 +0800 Subject: [PATCH 29/45] =?UTF-8?q?fix(desktop):=20=E6=BC=82=E7=A7=BB?= =?UTF-8?q?=E5=9B=9E=E6=94=B6=E7=BB=9F=E4=B8=80=E8=B5=B0=E6=8A=91=E5=88=B6?= =?UTF-8?q?=E7=AA=97=E5=8F=A3,=E7=9B=B4=E5=8F=91=E5=9B=9E=E6=94=B6?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=B8=85=E6=9A=82=E5=AD=98=E9=99=84=E4=BB=B6?= =?UTF-8?q?/=E9=87=8A=E6=94=BE=20worktree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit recyclePiRuntimeIfResourcesDrifted 的直发调用方(IM turnRunner 经 getMaker、 hook/scheduler/goal 经 deps)此前不经 register.ts 的抑制 seam,close 时 onClose 会清暂存附件并释放 worktree —— 重建后的 turn 会丢转录里引用的 暂存附件(Codex P2)。在 maker-host 创建 Maker 处统一包裹 withRehydrateCloseSuppressed,一个收口覆盖全部直发调用方;桌面发送事务 的 close 走 register.ts deps seam(自带包裹),互不重叠。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/maker-host/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts index 2d3babff1c..243d46c1c9 100644 --- a/apps/desktop/src/main/maker-host/index.ts +++ b/apps/desktop/src/main/maker-host/index.ts @@ -52,6 +52,7 @@ import path from 'node:path'; import { Maker, + type Session, isBotMcpServerAllowed, ClaudeCodeAgent, CodexAgent, @@ -3242,6 +3243,15 @@ export function getMaker(): Maker { }, }, }); + // 漂移回收的 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(), From fd166565571cc67f1b761a022f7cf612527847d5 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 14:01:39 +0800 Subject: [PATCH 30/45] =?UTF-8?q?fix(pi):=20=E6=BC=82=E7=A7=BB=E9=94=AE?= =?UTF-8?q?=E7=BA=B3=E5=85=A5=E8=A7=A3=E6=9E=90=E5=90=8E=E7=9A=84=20workin?= =?UTF-8?q?gDir,=E8=BD=AF=E9=93=BE=E6=94=B9=E6=8C=87=E5=90=8C=E4=BB=93?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=94=BE=E8=A1=8C=E6=97=A7=20argv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit workingDir 经软链启动时 collector 与 watch 面都按 realpath(scanRoot) 取 物理路径;软链改指同仓另一目录时 repoRoot 与旧物理根 mtime 均不变, 快检放行旧 argv(Codex P2)。快照 state 增存 resolvedWorkingDir 并在 快检比对,变化即进入重扫;重扫窗口内再次改指按漂移交回收路径重建。 回归测试用 junction(Windows CI 无特权可用)覆盖改指场景。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 23 +++++++++++++++++++ .../src/agents/pi/project-resource-cli.ts | 17 +++++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) 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 index dcf85b0fba..f45c830a13 100644 --- 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 @@ -354,4 +354,27 @@ describe('piProjectResourcesDrifted', () => { const roots = collectPiProjectResourceWatchRootMtimes(project); expect(roots.get(canon(path.join(project, '.pi')))).toBe(-1); }); + it('detects a symlinked workingDir retargeted within the same repo (resolved scan root in drift key)', () => { + // 回归(Codex P2):workingDir 经软链启动、软链改指同仓另一目录时,repoRoot + // 与解析后旧物理根的 mtime 均不变,快检会放行旧 argv。漂移键必须含解析后 + // 的 scanRoot:改指即漂移。junction 在 Windows CI 无特权可用。 + const realA = path.join(project, 'workspaces', 'real-a'); + const realB = path.join(project, 'workspaces', 'real-b'); + 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 }); + const link = path.join(project, 'wd-link'); + const linkType = process.platform === 'win32' ? 'junction' : 'dir'; + symlinkSync(realA, link, linkType); + const baseline = snapshotPiProjectResourceLaunch( + link, + collectPiProjectResourceCliPaths(link), + collectPiProjectResourceWatchRootMtimes(link), + resolvePiResourceRepoRoot(link), + ); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + rmSync(link); + symlinkSync(realB, link, linkType); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); }); 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 70b3ac0fe4..3715e85e45 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -219,7 +219,7 @@ export interface PiProjectResourceLaunchSnapshot { * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watchRootMtimes 同批采样 * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ - readonly state: { repoRoot: string }; + readonly state: { repoRoot: string; resolvedWorkingDir: string | null }; } /** @@ -368,7 +368,10 @@ export function snapshotPiProjectResourceLaunch( workingDir, paths, watchRootMtimes, - state: { repoRoot }, + // 收集器与 watch 面都按解析后的 scanRoot 取物理路径:快照必须同时记住 + // 解析结果,否则 workingDir 经软链启动、软链改指同仓另一目录时,边界与 + // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。 + state: { repoRoot, resolvedWorkingDir: realpathOrNull(workingDir) }, }); } @@ -396,6 +399,10 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 采出不一致的边界+盯视面(.git 消失时 watch 面停在旧根、集合来自新根)。 const repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); const boundaryChanged = repoRoot !== snapshot.state.repoRoot; + // 软链 workingDir 改指同仓另一目录:边界不变、解析后旧物理根的 mtime 不变, + // 解析根变化是唯一信号(Codex P2)。解析失败(悬空)与有值不等同。失败信号。 + const resolvedWorkingDir = realpathOrNull(snapshot.workingDir); + const resolvedWorkingDirChanged = resolvedWorkingDir !== snapshot.state.resolvedWorkingDir; let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { if (statMtimeMs(dir) !== mtimeAtLaunch) { @@ -403,7 +410,7 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps break; } } - if (!boundaryChanged && !mtimeChanged) return false; + if (!boundaryChanged && !resolvedWorkingDirChanged && !mtimeChanged) return false; // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 @@ -423,9 +430,13 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // .git 又动了就按漂移交回收路径重建(下次快检从一致的新快照出发), // 不把混合口径的基线/边界写回快照。 if (resolvePiResourceRepoRoot(snapshot.workingDir) !== repoRoot) return true; + // 重扫窗口内解析根又变了(软链再次改指):按漂移交回收路径重建,不把混合口径 + // 的解析根写回快照。 + if (realpathOrNull(snapshot.workingDir) !== resolvedWorkingDir) return true; snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); snapshot.state.repoRoot = repoRoot; + snapshot.state.resolvedWorkingDir = resolvedWorkingDir; return false; } From c7f13a4ad98f2cdb0ed0ebe658d151104266f632 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 14:40:53 +0800 Subject: [PATCH 31/45] =?UTF-8?q?fix(desktop):=20onClose=20=E5=85=A5?= =?UTF-8?q?=E5=8F=A3=E5=8F=96=E6=A0=B7=E6=8A=91=E5=88=B6=E6=80=81,?= =?UTF-8?q?=E6=BC=82=E7=A7=BB=E5=9B=9E=E6=94=B6=E5=90=8E=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=AF=AF=E5=88=A0=E6=9A=82=E5=AD=98=E9=99=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maker.close 不等 onClose:漂移回收包裹(rehydrate window)在 close 返回后 即释放,而 onClose 先等 worktree lease 的文件操作才查抑制表 —— 重查错过 窗口,照删重建后 turn 需要的暂存附件(Greptile P1)。修:runOnCloseSideEffects 增 forceSkip 口径,onClose 入口(首个 await 前)取样抑制态并透传;取样 后跳过,不再受窗口释放时序影响。桌面发送/任务移动/compact 刷新等全部 抑制用户同享此修正。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../withRehydrateCloseSuppressed.test.ts | 19 +++++++++++++++++++ apps/desktop/src/main/maker-host/index.ts | 7 ++++++- .../maker-host/rehydrateCloseSuppression.ts | 7 +++++++ 3 files changed, 32 insertions(+), 1 deletion(-) 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/index.ts b/apps/desktop/src/main/maker-host/index.ts index 243d46c1c9..02add1b730 100644 --- a/apps/desktop/src/main/maker-host/index.ts +++ b/apps/desktop/src/main/maker-host/index.ts @@ -3220,6 +3220,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) { @@ -3239,7 +3244,7 @@ export function getMaker(): Maker { // 这)。回收只由会话显式删除/归档驱动,见 localDb/ipc/sessions.ts → // worktree/sessionRemovalRecycle.ts。 await WorktreePool.releaseWorktree(sessionId).catch(() => undefined); - }); + }, { forceSkip: rehydrateSuppressedAtClose }); }, }, }); 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; From 028c60371b24fafd7dd8b32272b85a54573142ad Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 15:06:26 +0800 Subject: [PATCH 32/45] =?UTF-8?q?fix(pi):=20=E6=BC=82=E7=A7=BB=E5=BF=AB?= =?UTF-8?q?=E7=85=A7=E7=BA=B3=E5=85=A5=20.pi=20=E8=B5=84=E6=BA=90=E6=A0=B9?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E8=BA=AB=E4=BB=BD,=E8=BD=AF=E9=93=BE?= =?UTF-8?q?=E6=94=B9=E6=8C=87=E5=90=8C=20mtime=20=E6=A0=91=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E6=94=BE=E8=A1=8C=E6=97=A7=20argv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit .pi 本体是仓内软链时,改指结构相同、mtime 碰巧一致的另一资源树:watch 面 取解析后目标的 mtime,碰撞时快检放行旧 argv(Codex P2 追加)。快照 state 增存 resolvedPiRoot(realpath(.pi)),快检比对;重扫窗口内再次改指按漂移 交回收路径重建。回归测试用 junction + 整秒对齐(Windows utimes 有精度 截断,不对齐则 mtime 信号污染判别)覆盖改指场景,红→绿已验证。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 33 +++++++++++++++++++ .../src/agents/pi/project-resource-cli.ts | 19 +++++++++-- 2 files changed, 49 insertions(+), 3 deletions(-) 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 index f45c830a13..8f224d79da 100644 --- 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 @@ -377,4 +377,37 @@ describe('piProjectResourcesDrifted', () => { symlinkSync(realB, link, linkType); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + + it('retargeting the `.pi` junction to a same-mtime twin tree is drift (resolved pi-root identity)', () => { + // 回归(Codex P2):`.pi` 本体是仓内软链时,改指结构相同、mtime 碰巧一致的 + // 另一资源树 —— watch 面取的是解析后目标的 mtime,碰撞时快检放行旧 argv; + // 唯一信号是资源根的解析身份(realpath)。 + const targetA = path.join(project, 'pi-a'); + const targetB = path.join(project, 'pi-b'); + const piLink = path.join(project, '.pi'); + writeSkill(path.join('pi-a', 'skills'), 'alpha'); + // Windows utimes 有精度截断:先把 A 的各层目录对齐到整秒,让快照值与 B 的 + // 对齐值可以逐位相等(mtime 碰撞前提才成立)。 + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { + utimesSync(path.join(targetA, ...dir), aligned, aligned); + } + symlinkSync(targetA, piLink, 'junction'); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + + // B:同名结构、不同内容;目录 mtime 调成与 A 逐层一致(watch 面失明的碰撞前提)。 + // 同名结构:让 mtime 碰撞成为唯一干扰源,解析身份才是本用例的信号。 + writeSkill(path.join('pi-b', 'skills'), 'alpha'); + // 根目录也要对齐:watch 面包含 `.pi` 解析后的目标目录自身。B 的对齐值复用 + // A 的整秒时间,让 watch 面逐位相等(mtime 碰撞前提)。 + for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { + utimesSync(path.join(targetB, ...dir), aligned, aligned); + } + rmSync(piLink); + symlinkSync(targetB, piLink, 'junction'); + + // 改指后 lexical watch 面与 mtime 全等,唯一信号是 `.pi` 解析身份变化。 + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); }); 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 3715e85e45..1f556fe00c 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -219,7 +219,7 @@ export interface PiProjectResourceLaunchSnapshot { * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watchRootMtimes 同批采样 * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ - readonly state: { repoRoot: string; resolvedWorkingDir: string | null }; + readonly state: { repoRoot: string; resolvedWorkingDir: string | null; resolvedPiRoot: string | null }; } /** @@ -371,7 +371,13 @@ export function snapshotPiProjectResourceLaunch( // 收集器与 watch 面都按解析后的 scanRoot 取物理路径:快照必须同时记住 // 解析结果,否则 workingDir 经软链启动、软链改指同仓另一目录时,边界与 // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。 - state: { repoRoot, resolvedWorkingDir: realpathOrNull(workingDir) }, + state: { + repoRoot, + resolvedWorkingDir: realpathOrNull(workingDir), + // `.pi` 本体是仓内软链时改指同 mtime 的另一资源树:watch 面取解析后目标的 + // mtime,碰撞时唯一信号是资源根的解析身份(Codex P2)。 + resolvedPiRoot: realpathOrNull(path.join(workingDir, '.pi')), + }, }); } @@ -403,6 +409,10 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 解析根变化是唯一信号(Codex P2)。解析失败(悬空)与有值不等同。失败信号。 const resolvedWorkingDir = realpathOrNull(snapshot.workingDir); const resolvedWorkingDirChanged = resolvedWorkingDir !== snapshot.state.resolvedWorkingDir; + // `.pi` 资源根本体改指同 mtime 的另一资源树:watch 面取的是解析后目标的 + // mtime,碰撞时唯一信号是资源根的解析身份(Codex P2)。 + const resolvedPiRoot = realpathOrNull(path.join(snapshot.workingDir, '.pi')); + const resolvedPiRootChanged = resolvedPiRoot !== snapshot.state.resolvedPiRoot; let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { if (statMtimeMs(dir) !== mtimeAtLaunch) { @@ -410,7 +420,7 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps break; } } - if (!boundaryChanged && !resolvedWorkingDirChanged && !mtimeChanged) return false; + if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedPiRootChanged && !mtimeChanged) return false; // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 @@ -433,10 +443,13 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 重扫窗口内解析根又变了(软链再次改指):按漂移交回收路径重建,不把混合口径 // 的解析根写回快照。 if (realpathOrNull(snapshot.workingDir) !== resolvedWorkingDir) return true; + // 重扫窗口内资源根又改指:同上,按漂移交回收路径重建,不写回混合口径。 + if (realpathOrNull(path.join(snapshot.workingDir, '.pi')) !== resolvedPiRoot) return true; snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); snapshot.state.repoRoot = repoRoot; snapshot.state.resolvedWorkingDir = resolvedWorkingDir; + snapshot.state.resolvedPiRoot = resolvedPiRoot; return false; } From 3e0954f587207cfd7e102372d04f9bae9cbe0ef1 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 15:32:42 +0800 Subject: [PATCH 33/45] =?UTF-8?q?fix(pi):=20watch-root=20=E5=9F=BA?= =?UTF-8?q?=E7=BA=BF=E7=BB=9F=E4=B8=80=E6=90=BA=E5=B8=A6=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD,=E6=A0=B9=E6=B2=BB=E4=BB=BB=E6=84=8F?= =?UTF-8?q?=E5=B1=82=E7=BA=A7=E8=BD=AF=E9=93=BE=E6=94=B9=E6=8C=87=E8=87=B4?= =?UTF-8?q?=E7=9B=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 点修三连(workingDir→.pi→.agents)后的根治:快检信号层只比对被盯路径 mtime,被盯路径的解析身份不在信号里 —— 任何一层软链改指同 mtime 的孪生 树都会致盲,逐点枚举永远追不完(Codex P2 族)。改为每个 watch root 基线 统一记 realpath(与 watchRootMtimes 同 key 同批):realpath 含全链路解析, 任意层级改指必改变某个 key 的身份 → 触发重扫;重扫后的路径集合比对本来 就解析正确。resolvedPiRoot 点修字段被吸收删除;resolvedWorkingDir 保留 (scanRoot 刻意不是 watch key)。 回归:新增 `.agents` 链根改指与嵌套 namespace 改指两用例(整秒对齐排 除 Windows utimes 精度截断的判别污染),旧代码下必红、新代码全绿;既有 `.pi` 改指用例经统一机制继续通过。 Assisted-by: Cindy (https://cindy.app) Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 59 +++++++++++++++++++ .../src/agents/pi/project-resource-cli.ts | 44 ++++++++++---- 2 files changed, 91 insertions(+), 12 deletions(-) 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 index 8f224d79da..08015b2aca 100644 --- 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 @@ -407,7 +407,66 @@ describe('piProjectResourcesDrifted', () => { rmSync(piLink); symlinkSync(targetB, piLink, 'junction'); + // 改指后 lexical watch 面与 mtime 全等,唯一信号是 `.pi` 解析身份变化。 expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + + it('retargeting the `.agents` junction to a same-mtime twin tree is drift (uniform resolved identity)', () => { + // 根治回归(Codex P2 族第三击):`.agents` 链根改指。统一解析身份基线后, + // 任意层级改指同 mtime 的孪生树都必然触发,不再需要逐点枚举。 + const targetA = path.join(project, 'agents-a'); + const targetB = path.join(project, 'agents-b'); + const agentsLink = path.join(project, '.agents'); + writeSkill(path.join('agents-a', 'skills'), 'alpha'); + // Windows utimes 精度截断:先整秒对齐 A,快照值与 B 的对齐值才能逐位相等。 + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { + utimesSync(path.join(targetA, ...dir), aligned, aligned); + } + symlinkSync(targetA, agentsLink, 'junction'); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + + // B:同名结构;三层 mtime 与 A 全等(watch 面失明的碰撞前提)。 + writeSkill(path.join('agents-b', 'skills'), 'alpha'); + for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { + utimesSync(path.join(targetB, ...dir), aligned, aligned); + } + rmSync(agentsLink); + symlinkSync(targetB, agentsLink, 'junction'); + + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('retargeting a nested namespace junction to a same-mtime twin tree is drift (any depth)', () => { + // 通用性证明:不是 `.pi`/`.agents` 根,而是嵌套 namespace 级软链改指。 + // rm/symlink 会改 `.pi/skills` 自身 mtime,retarget 后把它恢复到快照值, + // 让解析身份成为唯一信号。 + const targetA = path.join(project, 'ns-a'); + const targetB = path.join(project, 'ns-b'); + const nsLink = path.join(project, '.pi', 'skills', '@scope'); + mkdirSync(path.dirname(nsLink), { recursive: true }); + writeSkill('ns-a', 'alpha'); + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + const skillsDir = path.join(project, '.pi', 'skills'); + for (const dir of [[] as string[], ['alpha']]) { + utimesSync(path.join(targetA, ...dir), aligned, aligned); + } + utimesSync(skillsDir, aligned, aligned); + symlinkSync(targetA, nsLink, 'junction'); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + + writeSkill('ns-b', 'alpha'); + for (const dir of [[] as string[], ['alpha']]) { + utimesSync(path.join(targetB, ...dir), aligned, aligned); + } + rmSync(nsLink); + symlinkSync(targetB, nsLink, 'junction'); + // rm/symlink 弄脏了 `.pi/skills` 的 mtime,恢复到快照值以隔离信号。 + utimesSync(skillsDir, aligned, aligned); + + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); }); 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 1f556fe00c..43be424688 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -219,7 +219,10 @@ export interface PiProjectResourceLaunchSnapshot { * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watchRootMtimes 同批采样 * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ - readonly state: { repoRoot: string; resolvedWorkingDir: string | null; resolvedPiRoot: string | null }; + readonly state: { repoRoot: string; resolvedWorkingDir: string | null }; + /** 每个 watch root 的解析身份(realpath)。基线不只记 mtime:被盯路径的软链改指 + * 同 mtime 的孪生树时,解析身份是唯一信号;与 watchRootMtimes 同 key 同批。 */ + readonly watchRootsResolved: Map; } /** @@ -373,11 +376,19 @@ export function snapshotPiProjectResourceLaunch( // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。 state: { repoRoot, + // 收集器与 watch 面都按解析后的 scanRoot 取物理路径:快照必须同时记住 + // 解析结果,否则 workingDir 经软链启动、软链改指同仓另一目录时,边界与 + // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。scanRoot + // 刻意不是 watch key(不含 workingDir 本身),单独成字段。 resolvedWorkingDir: realpathOrNull(workingDir), - // `.pi` 本体是仓内软链时改指同 mtime 的另一资源树:watch 面取解析后目标的 - // mtime,碰撞时唯一信号是资源根的解析身份(Codex P2)。 - resolvedPiRoot: realpathOrNull(path.join(workingDir, '.pi')), }, + // 每个 watch root 的解析身份:任意层级(`.pi`、`.agents` 链、namespace、单个 + // skill 目录)改指同 mtime 的孪生树时 mtime 面致盲,唯一完备信号是逐 key 的 + // 解析身份(workingDir→`.pi`→`.agents` 三连击后的根治,取代逐点枚举)。realpath + // 含全链路解析,未枚举的嵌套软链同样覆盖。 + watchRootsResolved: new Map( + [...watchRootMtimes.keys()].map((dir) => [dir, realpathOrNull(dir)] as const), + ), }); } @@ -409,10 +420,15 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 解析根变化是唯一信号(Codex P2)。解析失败(悬空)与有值不等同。失败信号。 const resolvedWorkingDir = realpathOrNull(snapshot.workingDir); const resolvedWorkingDirChanged = resolvedWorkingDir !== snapshot.state.resolvedWorkingDir; - // `.pi` 资源根本体改指同 mtime 的另一资源树:watch 面取的是解析后目标的 - // mtime,碰撞时唯一信号是资源根的解析身份(Codex P2)。 - const resolvedPiRoot = realpathOrNull(path.join(snapshot.workingDir, '.pi')); - const resolvedPiRootChanged = resolvedPiRoot !== snapshot.state.resolvedPiRoot; + // 任一 watch root 的解析身份变化(软链改指同 mtime 的孪生树):mtime 面碰撞 + // 时这是唯一信号;realpath 含全链路,任意层级的改指都会落到某个 key 上。 + let resolvedRootChanged = false; + for (const [dir, resolvedAtLaunch] of snapshot.watchRootsResolved) { + if (realpathOrNull(dir) !== resolvedAtLaunch) { + resolvedRootChanged = true; + break; + } + } let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { if (statMtimeMs(dir) !== mtimeAtLaunch) { @@ -420,7 +436,7 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps break; } } - if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedPiRootChanged && !mtimeChanged) return false; + if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedRootChanged && !mtimeChanged) return false; // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 @@ -443,13 +459,17 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 重扫窗口内解析根又变了(软链再次改指):按漂移交回收路径重建,不把混合口径 // 的解析根写回快照。 if (realpathOrNull(snapshot.workingDir) !== resolvedWorkingDir) return true; - // 重扫窗口内资源根又改指:同上,按漂移交回收路径重建,不写回混合口径。 - if (realpathOrNull(path.join(snapshot.workingDir, '.pi')) !== resolvedPiRoot) return true; + // 重扫窗口内解析身份又有变化(任意层级再次改指):按漂移交回收路径重建,不把 + // 混合口径的基线写回快照。 + for (const [dir, resolvedAtSignal] of snapshot.watchRootsResolved) { + if (realpathOrNull(dir) !== resolvedAtSignal) return true; + } snapshot.watchRootMtimes.clear(); for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); + snapshot.watchRootsResolved.clear(); + for (const dir of freshRoots.keys()) snapshot.watchRootsResolved.set(dir, realpathOrNull(dir)); snapshot.state.repoRoot = repoRoot; snapshot.state.resolvedWorkingDir = resolvedWorkingDir; - snapshot.state.resolvedPiRoot = resolvedPiRoot; return false; } From 8a472a3b004d50aaa8505b325ae0605a9f4cc4e7 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 16:13:41 +0800 Subject: [PATCH 34/45] =?UTF-8?q?fix(pi):=20=E7=AA=97=E5=8F=A3=E5=A4=8D?= =?UTF-8?q?=E6=A0=B8=E6=94=B9=E7=94=A8=E6=9C=AC=E8=BD=AE=E9=87=87=E6=A0=B7?= =?UTF-8?q?,=E7=A9=BA=E7=9B=AE=E5=BD=95=E8=90=BD=E5=9C=B0=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E8=AF=AF=E6=8A=A5=E6=BC=82=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile P2:启动时缺失的 .pi/extensions 以解析值 null 入监测表,之后仅创建 空目录时,资源路径集合不变,但窗口复核与启动基线比较,null→path 被误判为 「窗口内再次改指」→ 多余冷启动。 修复:第一遍扫描记录每个 watch root 的本次解析结果,窗口复核与本次采样比 (与 repoRoot/resolvedWorkingDir 两处复核同口径),集合不变则重建基线返回 false。代价:信号循环不再提前 break,多几次 realpath,与 stat 扫描同数量级。 契约澄清并写入函数头:解析身份变化只是触发重扫的信号,永远不是漂移判决。 上一轮「嵌套 namespace 改指=漂移」的断言按此翻转(collector 明文不走进软链 namespace,集合本就不变,该用例此前靠本 bug 才转绿);新增空目录 null→path 用例与其反例(空目录内落扩展文件必须检出)、软链 namespace 换真目录必须检出。 旧代码下两用例红、新代码 28/28 绿;maker-core typecheck 通过。 Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 28 ++++++++++++++++--- .../src/agents/pi/project-resource-cli.ts | 22 +++++++++------ 2 files changed, 37 insertions(+), 13 deletions(-) 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 index 08015b2aca..7481ba37c8 100644 --- 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 @@ -246,6 +246,21 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + it('treats a missing .pi/extensions appearing as an empty dir as no drift (resolution null→path)', () => { + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const baseline = snapshot(); + // 前提:缺失的扩展根已在监测表中,基线解析为 null(Greptile P2) + expect(baseline.watchRootsResolved.get(canon(path.join(project, '.pi', 'extensions')))).toBeNull(); + // 仅创建空目录:资源路径集合仍相同,不得误报漂移触发多余冷启动 + mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); + bumpMtime(path.join(project, '.pi', 'extensions')); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 空目录已纳入盯视:之后真正的扩展落地必须检出 + writeFileSync(path.join(project, '.pi', 'extensions', 'hook.ts'), 'export {};\n'); + bumpMtime(path.join(project, '.pi', 'extensions')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('detects a nearer git boundary appearing after launch (repo root identity)', () => { mkdirSync(path.join(project, 'outer', '.agents', 'skills'), { recursive: true }); writeFileSync(path.join(project, 'outer', '.git'), ''); @@ -439,10 +454,10 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('retargeting a nested namespace junction to a same-mtime twin tree is drift (any depth)', () => { - // 通用性证明:不是 `.pi`/`.agents` 根,而是嵌套 namespace 级软链改指。 - // rm/symlink 会改 `.pi/skills` 自身 mtime,retarget 后把它恢复到快照值, - // 让解析身份成为唯一信号。 + it('retargeting a nested namespace junction to a same-mtime twin tree leaves the set unchanged (identity is signal, not verdict)', () => { + // 通用性验证的另一面:collector 明文不走进软链 namespace(symlinked namespace + // is intentionally not walked),改指前后集合都不含它 —— 按集合契约这不是漂移, + // 不触发多余冷启动;解析身份变化只负责触发重扫(本用例的信号隔离仍成立)。 const targetA = path.join(project, 'ns-a'); const targetB = path.join(project, 'ns-b'); const nsLink = path.join(project, '.pi', 'skills', '@scope'); @@ -467,6 +482,11 @@ describe('piProjectResourcesDrifted', () => { // rm/symlink 弄脏了 `.pi/skills` 的 mtime,恢复到快照值以隔离信号。 utimesSync(skillsDir, aligned, aligned); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 契约的另一端不放松:软链 namespace 换成真目录,集合真正变化,必须检出。 + rmSync(nsLink); + writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); + bumpMtime(skillsDir); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); }); 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 43be424688..60f692b0d5 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -407,9 +407,11 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): * 任何被盯目录的 mtime)。 * 2. 全量重扫,按最终路径集合判定(argv 的输入是集合,不是内容): * - 集合不同 → 漂移,返回 true(不动基线,调用方将回收运行时并重建快照); - * - 集合相同(触碰无关目录 / git init 未截断任何资源)→ 不算漂移,就地重建 - * 整张基线(新建的空 namespace / 空扩展目录纳入盯视)并更新边界持有者, - * 下一次快检恢复零收集。 + * - 集合相同(触碰无关目录 / git init 未截断任何资源 / 缺失目录空壳落地 / + * 不被 collector 枚举的软链 namespace 改指)→ 不算漂移,就地重建整张基线 + * (新建的空 namespace / 空扩展目录纳入盯视)并更新边界持有者,下一次快检 + * 恢复零收集。解析身份变化只是触发重扫的信号,永远不是漂移判决: + * 身份变了而集合不变,说明运行时消费的资源没有变。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { // 本次调用只解析一次 git root,贯穿传给所有收集器;独立探测会在重扫窗口内 @@ -422,12 +424,14 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps const resolvedWorkingDirChanged = resolvedWorkingDir !== snapshot.state.resolvedWorkingDir; // 任一 watch root 的解析身份变化(软链改指同 mtime 的孪生树):mtime 面碰撞 // 时这是唯一信号;realpath 含全链路,任意层级的改指都会落到某个 key 上。 + // 记录本次采样而非只记信号:窗口复核必须与本轮开头比,不能与启动基线比 —— + // 否则空目录从 null→存在 会撞上旧基线被误判为「窗口内再次改指」(Greptile P2)。 + const resolvedNow = new Map(); let resolvedRootChanged = false; for (const [dir, resolvedAtLaunch] of snapshot.watchRootsResolved) { - if (realpathOrNull(dir) !== resolvedAtLaunch) { - resolvedRootChanged = true; - break; - } + const now = realpathOrNull(dir); + resolvedNow.set(dir, now); + if (now !== resolvedAtLaunch) resolvedRootChanged = true; } let mtimeChanged = false; for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { @@ -460,8 +464,8 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps // 的解析根写回快照。 if (realpathOrNull(snapshot.workingDir) !== resolvedWorkingDir) return true; // 重扫窗口内解析身份又有变化(任意层级再次改指):按漂移交回收路径重建,不把 - // 混合口径的基线写回快照。 - for (const [dir, resolvedAtSignal] of snapshot.watchRootsResolved) { + // 混合口径的基线写回快照。与本轮开头采样比(同 repoRoot/resolvedWorkingDir)。 + for (const [dir, resolvedAtSignal] of resolvedNow) { if (realpathOrNull(dir) !== resolvedAtSignal) return true; } snapshot.watchRootMtimes.clear(); From c8ddf4e0f61b7e0f40c566b31c9ef45eedef05a0 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 17:10:27 +0800 Subject: [PATCH 35/45] =?UTF-8?q?fix(pi):=20=E8=BA=AB=E4=BB=BD=E5=9F=BA?= =?UTF-8?q?=E7=BA=BF=E5=85=88=E4=BA=8E=E8=B7=AF=E5=BE=84=E6=94=B6=E9=9B=86?= =?UTF-8?q?=E9=87=87=E6=A0=B7,=E8=A1=A5=E5=8F=97=E9=82=80=E8=80=85/?= =?UTF-8?q?=E5=90=8C=E5=88=BB/local-agent=20=E4=B8=89=E4=B8=AA=E7=9B=B2?= =?UTF-8?q?=E5=8C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对抗审查+Codex P2(4522586100)复核后的四项修正: 1. 启动采样前移(Codex P2):身份基线(resolvedWorkingDir + 逐 key realpath)原先在 snapshotPiProjectResourceLaunch 内采样,晚于 argv 路径收集 —— 窗口内软链改指 同 mtime 孪生树会被固化成一致基线,永久漏检。改为 collectPiProjectResource LaunchWatch 一次遍历同批产出 scanRoot 身份 + 每 key 的 mtime/条目指纹/解析 身份,快照只消费现成样本;重扫重建同样写回同批值,不再补采 realpath。 2. 受邀者(guest)盲区:镜像内新增的技能此前整条排除在漂移检测外(argv 永久冻结 在启动值)。快照条件去掉 !guestRoot,裁剪口径经 restrict 下发到比较处(fresh 先裁剪再比) —— 缺了会拿全量比裁剪基线恒判漂移,回收死循环。 3. 时间戳粒度盲区:NTFS/FAT 同一 tick 内增删,mtime 与基线逐位相等且集合不变则 基线永不刷新,新增资源永久丢失。基线增加 readdir 条目名指纹作第二信号(文件 键/缺失恒 '');变化只作重扫信号,判决仍归集合,不增加正常路径的重扫次数。 4. local-agent 盲区:无头本地 Agent(pi 本地根任务形态)的发送不经过 makerSend Transaction 等六个回收接入点,资源漂移后继续用旧 argv。发送准备窗口(与 instructions 换代重建同一空闲点)接入 hasRecyclableProjectResourceDrift, 漂移时原地 close+start 重建。 顺带:collector 与 watcher 的软链判定统一为 isSymlinkEntry(readdir 把 junction 报成目录的形态口径分叉,watcher 曾可能把 collector 永不枚举的目标树键混入盯视 面);Session.hasProjectResourceDrift 纯转发层并入 hasRecyclableProjectResource Drift(4 层布尔管道收成 3 层);函数头契约改写为三信号口径并写死 「身份基线必须先于路径收集」不变量。 回归:新增 3 用例(启动窗口改指/mtime 孪生、同刻新增/条目指纹、guest 裁剪口径 三段),36/36 绿(31 过 + 5 POSIX-only 于 Windows 跳过);maker-core/desktop typecheck 过;maker/session/pi-startsession-cleanup/local-agent runtime 共 393 用例绿。启动窗口与同刻两缺陷在审计阶段已对旧代码做过独立复现(均为漏检)。 Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/local-agent/runtime.ts | 9 + .../pi-project-resource-drift.test.ts | 121 +++++++++-- packages/maker-core/src/agents/pi/index.ts | 32 +-- .../src/agents/pi/project-resource-cli.ts | 196 ++++++++++++------ packages/maker-core/src/session.ts | 24 +-- 5 files changed, 274 insertions(+), 108 deletions(-) diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts index 3e83df8008..56c2881791 100644 --- a/apps/desktop/src/main/local-agent/runtime.ts +++ b/apps/desktop/src/main/local-agent/runtime.ts @@ -570,6 +570,15 @@ 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; + await previous.close(); + 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/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 index 7481ba37c8..4fcb283cba 100644 --- 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 @@ -15,11 +15,12 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { collectPiProjectResourceCliPaths, - collectPiProjectResourceWatchRootMtimes, + collectPiProjectResourceLaunchWatch, piProjectResourcesDrifted, resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, } from '../project-resource-cli.js'; +import type { PiProjectResourceCliPaths } from '../project-resource-cli.js'; let project = ''; @@ -68,10 +69,11 @@ function bumpMtime(target: string): void { utimesSync(target, t, t); } -function snapshot() { - // 与生产调用点同序:基线先采样,路径后收集(见 snapshotPiProjectResourceLaunch)。 - const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); - return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), watchRootMtimes, resolvePiResourceRepoRoot(project)); +function snapshot(restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { + // 与生产调用点同序:watch 采样(含解析身份)先于路径收集(见 snapshotPiProjectResourceLaunch)。 + const repoRoot = resolvePiResourceRepoRoot(project); + const watch = collectPiProjectResourceLaunchWatch(project, repoRoot); + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project, repoRoot), repoRoot, watch, restrict); } describe('piProjectResourcesDrifted', () => { @@ -131,8 +133,10 @@ describe('piProjectResourcesDrifted', () => { writeFileSync(path.join(project, '.git'), ''); const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); + const nestedRepoRoot = resolvePiResourceRepoRoot(nested); + const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); + nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); writeSkill(path.join('.agents', 'skills'), 'gamma'); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -147,7 +151,7 @@ describe('piProjectResourcesDrifted', () => { writeFileSync(path.join(project, '.git'), ''); const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); - const roots = collectPiProjectResourceWatchRootMtimes(nested); + const roots = collectPiProjectResourceLaunchWatch(nested).mtimes; expect(roots.has(canon(path.join(nested, '.pi')))).toBe(true); expect(roots.has(canon(path.join(nested, '.agents')))).toBe(true); expect(roots.has(canon(path.join(nested, '.agents', 'skills')))).toBe(true); @@ -211,7 +215,7 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'plain'), { recursive: true }); mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: true }); - const roots = collectPiProjectResourceWatchRootMtimes(project); + const roots = collectPiProjectResourceLaunchWatch(project).mtimes; const ns = path.join(project, '.pi', 'skills', '@scope'); expect(roots.has(canon(ns))).toBe(true); expect(roots.has(canon(path.join(ns, 'alpha')))).toBe(true); @@ -223,15 +227,90 @@ describe('piProjectResourcesDrifted', () => { // 生产调用点先采基线后收集路径。基线采样与路径收集之间新增的资源已在集合 // 里且基线较旧:首次快检多一次重扫确认集合一致后刷新基线 —— 既不误报漂移, // 也不会静默漏检(反序才会漏)。 - const watchRootMtimes = collectPiProjectResourceWatchRootMtimes(project); + const repoRoot = resolvePiResourceRepoRoot(project); + const watch = collectPiProjectResourceLaunchWatch(project, repoRoot); writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshotPiProjectResourceLaunch( - project, collectPiProjectResourceCliPaths(project), watchRootMtimes, resolvePiResourceRepoRoot(project)); + project, collectPiProjectResourceCliPaths(project, repoRoot), repoRoot, watch); expect(piProjectResourcesDrifted(baseline)).toBe(false); expect(baseline.watchRootMtimes.get(canon(path.join(project, '.pi', 'skills')))) .toBe(statMtime(path.join(project, '.pi', 'skills'))); }); + it('samples resolved identity before collecting paths (launch-window retarget is drift)', () => { + // 回归(Codex P2,2026-11-10):身份基线若在 argv 收集之后采样,「采基线前的 + // 改指」会被固化成一致基线(mtime 孪生树碰撞时无任何信号)→ 永久漏检。 + // 按生产序复刻:① 采 watch(含解析身份)→ ② 收集 argv → ③ 窗口内改指孪生树 + // → ④ 建快照。快检必须凭身份信号判漂移。 + const realA = path.join(project, 'workspaces', 'real-a'); + const realB = path.join(project, 'workspaces', 'real-b'); + 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 }); + // mtime 孪生:两树各层对齐到整秒,排除 mtime 信号,身份是唯一信号 + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + for (const [root, skill] of [[realA, 'alpha-a'], [realB, 'alpha-b']] as const) { + for (const dir of [root, path.join(root, '.pi'), path.join(root, '.pi', 'skills'), path.join(root, '.pi', 'skills', skill)]) { + utimesSync(dir, aligned, aligned); + } + } + const link = path.join(project, 'wd-link'); + const linkType = process.platform === 'win32' ? 'junction' : 'dir'; + symlinkSync(realA, link, linkType); + const launchRepoRoot = resolvePiResourceRepoRoot(link); + const watch = collectPiProjectResourceLaunchWatch(link, launchRepoRoot); // ① 采 watch + const paths = collectPiProjectResourceCliPaths(link, launchRepoRoot); // ② argv 来自 A + rmSync(link); + symlinkSync(realB, link, linkType); // ③ 窗口内改指 B(mtime 已对齐) + const baseline = snapshotPiProjectResourceLaunch(link, paths, launchRepoRoot, watch); // ④ 建快照 + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('detects a skill added within the same timestamp tick (entry fingerprint signal)', () => { + // NTFS/FAT 时间戳量化:基线采样后同一 tick 内新增,mtime 与基线逐位相等 —— + // 只看 mtime 会永久漏检(集合不变则基线永不刷新)。条目名指纹是第二信号。 + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + const skillsDir = path.join(project, '.pi', 'skills'); + utimesSync(skillsDir, aligned, aligned); + const baseline = snapshot(); + writeSkill(path.join('.pi', 'skills'), 'beta'); + // 显式把 mtime 恢复到基线值,模拟「同一 tick」的量化等值 + utimesSync(skillsDir, aligned, aligned); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + + it('guest restriction: outside-scope set change is not drift (no recycle loop), inside-scope is', () => { + // 受邀者:argv 只含 guestRoot 裁剪后的集合,漂移必须按同一口径比较(fresh 先 + // 裁剪再比)。裁剪缺失时拿全量比裁剪基线,镜像外任何变化恒判漂移 → 回收死 + // 循环;快照缺失(旧行为)时镜像内新增永不生效。 + 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 = canon(path.join(project, 'mirror')) + path.sep; + const restrict = (p: PiProjectResourceCliPaths): PiProjectResourceCliPaths => ({ + skills: Object.freeze(p.skills.filter((s) => s.startsWith(scope))), + promptTemplates: Object.freeze(p.promptTemplates.filter((s) => s.startsWith(scope))), + extensions: Object.freeze([] as readonly string[]), + }); + const launchRepoRoot = resolvePiResourceRepoRoot(wd); + const collected = collectPiProjectResourceCliPaths(wd, launchRepoRoot); + // 前提:全量收集含 mirror 外的技能(链上 .agents 越过 guestRoot) + expect(collected.skills.some((s) => !s.startsWith(scope))).toBe(true); + const watch = collectPiProjectResourceLaunchWatch(wd, launchRepoRoot); + const baseline = snapshotPiProjectResourceLaunch(wd, restrict(collected), launchRepoRoot, watch, restrict); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // mirror 外新增:有信号(链上 .agents 被盯),裁剪口径下集合未变 → 不回收 + writeSkill(path.join('.agents', 'skills'), 'global-2'); + bumpMtime(path.join(project, '.agents')); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // mirror 内新增:受邀者 argv 真会变 → 漂移 + writeSkill(path.join('mirror', 'sub', '.pi', 'skills'), 'beta'); + bumpMtime(path.join(wd, '.pi', 'skills')); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('rebuilds the watch map after an unchanged rescan so new child dirs are watched', () => { mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); const baseline = snapshot(); @@ -267,8 +346,10 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('outer', '.agents', 'skills'), 'outer-skill'); const nested = path.join(project, 'outer', 'sub'); mkdirSync(nested, { recursive: true }); + const nestedRepoRoot = resolvePiResourceRepoRoot(nested); + const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); + nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); expect(piProjectResourcesDrifted(baseline)).toBe(false); // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 mkdirSync(path.join(nested, '.git'), { recursive: true }); @@ -282,8 +363,10 @@ describe('piProjectResourcesDrifted', () => { const nested = path.join(project, 'outer', 'sub'); mkdirSync(path.join(nested, '.pi', 'skills', 'alpha'), { recursive: true }); writeFileSync(path.join(nested, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: t\n---\n'); + const nestedRepoRoot = resolvePiResourceRepoRoot(nested); + const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested), collectPiProjectResourceWatchRootMtimes(nested), resolvePiResourceRepoRoot(nested)); + nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); // 嵌套目录 git init:被截断的上层链没有任何项目资源,集合不变,不应触发回收 mkdirSync(path.join(nested, '.git'), { recursive: true }); expect(piProjectResourcesDrifted(baseline)).toBe(false); @@ -361,12 +444,12 @@ describe('piProjectResourcesDrifted', () => { const hint = resolvePiResourceRepoRoot(project); expect([...collectPiProjectResourceCliPaths(project, hint).skills]) .toEqual([...collectPiProjectResourceCliPaths(project).skills]); - expect([...collectPiProjectResourceWatchRootMtimes(project, hint).keys()]) - .toEqual([...collectPiProjectResourceWatchRootMtimes(project).keys()]); + expect([...collectPiProjectResourceLaunchWatch(project, hint).mtimes.keys()]) + .toEqual([...collectPiProjectResourceLaunchWatch(project).mtimes.keys()]); }); it('missing directories baseline as -1 and compare against real mtimes', () => { - const roots = collectPiProjectResourceWatchRootMtimes(project); + const roots = collectPiProjectResourceLaunchWatch(project).mtimes; expect(roots.get(canon(path.join(project, '.pi')))).toBe(-1); }); it('detects a symlinked workingDir retargeted within the same repo (resolved scan root in drift key)', () => { @@ -381,11 +464,13 @@ describe('piProjectResourcesDrifted', () => { const link = path.join(project, 'wd-link'); const linkType = process.platform === 'win32' ? 'junction' : 'dir'; symlinkSync(realA, link, linkType); + const launchRepoRoot = resolvePiResourceRepoRoot(link); + const launchWatch = collectPiProjectResourceLaunchWatch(link, launchRepoRoot); const baseline = snapshotPiProjectResourceLaunch( link, - collectPiProjectResourceCliPaths(link), - collectPiProjectResourceWatchRootMtimes(link), - resolvePiResourceRepoRoot(link), + collectPiProjectResourceCliPaths(link, launchRepoRoot), + launchRepoRoot, + launchWatch, ); expect(piProjectResourcesDrifted(baseline)).toBe(false); rmSync(link); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 85c2cd6d5c..13f9a8969f 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -245,8 +245,8 @@ import { import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, + collectPiProjectResourceLaunchWatch, emptyPiProjectResourceCliPaths, - collectPiProjectResourceWatchRootMtimes, filterPiProjectCliSkills, piProjectResourceCliArgs, piProjectResourcesDrifted, @@ -4069,15 +4069,18 @@ 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. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 - // watch 基线与 git 边界必须先于路径收集采样(见 snapshotPiProjectResourceLaunch): - // 三样同批且基线在前,采样窗口内新增的资源/边界变化只会让首次快检多一次重扫后 - // 收敛;git root 只解析一次,经 hint 贯穿三样 —— 窗口内 .git 消失不会采出旧根 - // 盯视面配新根路径集合的混合口径。 - const projectResourceRepoRootAtLaunch = loadProjectResourcesInPlace && !guestRoot + // watch 基线(mtime/条目指纹/解析身份)与 git 边界必须先于路径收集采样(见 + // snapshotPiProjectResourceLaunch):身份基线晚于 argv 采集,会把「采基线前的 + // 改指」固化成一致基线,永久漏检(Codex P2,2026-11-10);基线在前则窗口内 + // 新增的资源/边界变化只会让首次快检多一次重扫后收敛。git root 只解析一次, + // 经 hint 贯穿采样与收集 —— 窗口内 .git 消失不会采出旧根盯视面配新根路径 + // 集合的混合口径。受邀者同样建快照(镜像同步进来的新技能必须能检出),裁剪 + // 口径经 restrict 下发,比较对 fresh 做同一裁剪。 + const projectResourceRepoRootAtLaunch = loadProjectResourcesInPlace ? resolvePiResourceRepoRoot(opts.workingDir) : null; - const projectResourceWatchRootMtimes = projectResourceRepoRootAtLaunch - ? collectPiProjectResourceWatchRootMtimes(opts.workingDir, projectResourceRepoRootAtLaunch) + const projectResourceLaunchWatch = projectResourceRepoRootAtLaunch + ? collectPiProjectResourceLaunchWatch(opts.workingDir, projectResourceRepoRootAtLaunch) : null; const collectedProjectResources = loadProjectResourcesInPlace ? guestRoot @@ -4095,11 +4098,16 @@ export class PiAgent extends BaseAgent { } : collectedProjectResources; // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 - // 快照存未经禁用过滤的原始收集结果,与 drift 检测的 fresh collect 同口径; - // 受邀者会话的 collected 已按 guestRoot 裁剪,与全量扫描口径不一致,不参与漂移检测。 - const projectResourceLaunchSnapshot = projectResourceWatchRootMtimes && projectResourceRepoRootAtLaunch + // 快照存未经禁用过滤的原始收集结果(受邀者已按 guestRoot 裁剪),与 drift + // 检测的 fresh collect 经同一 restrict 裁剪后同口径可比;受邀者裁剪缺了会拿 + // 全量比裁剪基线恒判漂移,回收死循环。 + const projectResourceLaunchSnapshot = projectResourceLaunchWatch && projectResourceRepoRootAtLaunch ? snapshotPiProjectResourceLaunch( - opts.workingDir, collectedProjectResources, projectResourceWatchRootMtimes, projectResourceRepoRootAtLaunch) + opts.workingDir, + collectedProjectResources, + projectResourceRepoRootAtLaunch, + projectResourceLaunchWatch, + guestRoot ? (paths) => restrictPiGuestProjectResources(paths, guestRoot) : undefined) : null; // Own the entire managed-skill setup in the existing startup rollback: 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 60f692b0d5..38a5ef874d 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -95,6 +95,13 @@ function isSymlinkDirectory(target: string): boolean { } } +/** readdir 把 Windows junction 报成目录时 Dirent.isSymbolicLink 为 false,需 lstat + * 兜底。collector 与 watcher 必须共用同一判定:口径分叉会让盯视面混入 collector + * 永不枚举的目标树键(无谓重扫 + 基线带脏键)。 */ +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))); } @@ -201,9 +208,20 @@ function statMtimeMs(target: string): number { } } +/** 目录条目名指纹:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 + * 文件键/缺失目录 readdir 失败,恒 ''。变化只作重扫信号,判决仍归路径集合。 */ +function readDirEntryFingerprint(dir: string): string { + try { + return fs.readdirSync(dir).sort().join('\n'); + } catch { + return ''; + } +} + /** - * 启动快照:spawn 时冻结的项目资源清单 + watch root 的 mtime 基线。 - * paths 是未经禁用过滤的原始收集结果(与后续 fresh collect 同口径可比)。 + * 启动快照:spawn 时冻结的项目资源清单 + watch 面基线(mtime/条目指纹/解析身份)。 + * paths 是未经禁用过滤的原始收集结果(受邀者会话已按 guestRoot 裁剪,与后续 + * fresh collect 经同一 restrict 裁剪后同口径可比)。 */ export interface PiProjectResourceLaunchSnapshot { readonly workingDir: string; @@ -217,19 +235,50 @@ export interface PiProjectResourceLaunchSnapshot { /** 启动时认定的 git root 可变持有器:更近的 .git 出现/消失会改变 collector 的枚举链 * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。边界 * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 - * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watchRootMtimes 同批采样 + * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watch 基线同批采样 * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ readonly state: { repoRoot: string; resolvedWorkingDir: string | null }; /** 每个 watch root 的解析身份(realpath)。基线不只记 mtime:被盯路径的软链改指 * 同 mtime 的孪生树时,解析身份是唯一信号;与 watchRootMtimes 同 key 同批。 */ readonly watchRootsResolved: Map; + /** 每个 watch root 的 readdir 条目名指纹:时间戳粒度盲区(同一 tick 内增删, + * mtime 与基线逐位相等)的第二信号;与 watchRootMtimes 同 key 同批。 */ + readonly watchRootEntries: Map; + /** 受邀者裁剪口径(非受邀者恒 null):重扫后的 fresh 集合先经它裁剪再与 paths + * 比较 —— 缺了会拿全量比裁剪基线恒判漂移,回收死循环。 */ + readonly restrict: ((paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) | null; } /** - * 收集漂移快检要盯的目录 mtime 基线。目录集合必须覆盖 collector 实际枚举的 - * 每一层目录:在已存在的子目录内增删条目只改该子目录自身的 mtime,父目录不动, - * 漏盯哪层就在哪层漏检(如已有 namespace 下增删 skill、已有扩展目录内补 index.ts、 - * 已有 skill 目录内删 SKILL.md): + * 启动采样的一次遍历产出:每个 watch key 的三样信号 + scanRoot 解析身份。 + * 整份样本必须先于路径收集采样 —— 身份基线晚于 argv 采集,会把「采基线前的 + * 改指」固化成一致基线,永久漏检(Codex P2,2026-11-10);基线在前则窗口内 + * 不一致只会让首次快检多一次重扫后收敛。 + */ +export interface PiProjectResourceLaunchWatch { + /** workingDir 的解析身份,先于所有键采样(键路径都从它拼出)。 */ + readonly scanRootResolved: string | null; + readonly mtimes: Map; + /** key → readdir 条目名指纹(排序拼接;文件键/缺失恒 '')。时间戳粒度盲区 + * (同一 tick 内增删,mtime 与基线逐位相等)的第二信号;变化只作重扫信号, + * 判决仍归路径集合。 */ + readonly entries: Map; + /** key → realpath 解析身份(缺失 null),与 mtimes 同 key 同批。 */ + readonly resolved: Map; +} + +function recordWatchKey(sample: PiProjectResourceLaunchWatch, target: string): void { + // 解析身份先行:身份与 mtime/条目之间的窗口不一致只会多一次重扫,不会固化。 + sample.resolved.set(target, realpathOrNull(target)); + sample.mtimes.set(target, statMtimeMs(target)); + sample.entries.set(target, readDirEntryFingerprint(target)); +} + +/** + * 收集漂移快检要盯的目录基线(mtime + 条目指纹 + 解析身份,同一次遍历)。目录 + * 集合必须覆盖 collector 实际枚举的每一层目录:在已存在的子目录内增删条目只改 + * 该子目录自身的 mtime,父目录不动,漏盯哪层就在哪层漏检(如已有 namespace 下 + * 增删 skill、已有扩展目录内补 index.ts、已有 skill 目录内删 SKILL.md): * - `/.pi` 本身 + `.pi/skills` / `.pi/prompts` / `.pi/extensions` * - `.pi/skills` 与 `.agents/skills` 各自的两层 skill 树(skills 根、namespace 级、 * namespace 内 skill 级;与 collector 的枚举深度一致,不往更深处看) @@ -237,27 +286,32 @@ export interface PiProjectResourceLaunchSnapshot { * - cwd→git root 链上每级的 `.agents` + `.agents/skills` * 不含 workingDir 本身:往项目根丢无关文件不应触发全量重扫。 */ -export function collectPiProjectResourceWatchRootMtimes(workingDir: string, repoRootHint?: string): Map { - const roots = new Map(); - const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); - if (!isDir(scanRoot)) return roots; +export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRootHint?: string): PiProjectResourceLaunchWatch { + const sample: PiProjectResourceLaunchWatch = { + scanRootResolved: realpathOrNull(workingDir), + mtimes: new Map(), + entries: new Map(), + resolved: new Map(), + }; + const scanRoot = sample.scanRootResolved ?? path.resolve(workingDir); + if (!isDir(scanRoot)) return sample; const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); const piDir = path.join(scanRoot, '.pi'); - roots.set(piDir, statMtimeMs(piDir)); - watchPiSkillTreeMtimes(roots, path.join(piDir, 'skills')); - watchPiPromptTargets(roots, path.join(piDir, 'prompts'), repoRoot); - watchPiExtensionChildMtimes(roots, path.join(piDir, 'extensions')); + recordWatchKey(sample, piDir); + watchPiSkillTreeMtimes(sample, path.join(piDir, 'skills')); + watchPiPromptTargets(sample, path.join(piDir, 'prompts'), repoRoot); + watchPiExtensionChildMtimes(sample, path.join(piDir, 'extensions')); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); - roots.set(agentsDir, statMtimeMs(agentsDir)); - watchPiSkillTreeMtimes(roots, path.join(agentsDir, 'skills')); + recordWatchKey(sample, agentsDir); + watchPiSkillTreeMtimes(sample, path.join(agentsDir, 'skills')); if (current === repoRoot) break; const parent = path.dirname(current); if (parent === current) break; current = parent; } - return roots; + return sample; } /** @@ -266,33 +320,35 @@ export function collectPiProjectResourceWatchRootMtimes(workingDir: string, repo * 目录 mtime 捕获,与 realpath 收集口径一致。跳过 collector 不枚举的子树 * (隐藏/bak、软链 namespace、剪枝名),避免无关变化触发无谓重扫。 */ -function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): void { - roots.set(skillsDir, statMtimeMs(skillsDir)); +function watchPiSkillTreeMtimes(sample: PiProjectResourceLaunchWatch, skillsDir: string): void { + recordWatchKey(sample, skillsDir); if (!isDir(skillsDir)) return; for (const entry of listDir(skillsDir)) { if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(skillsDir, entry.name); - roots.set(childPath, statMtimeMs(childPath)); + recordWatchKey(sample, childPath); const realChild = realpathOrNull(childPath); if (!realChild || !isDir(realChild)) continue; // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 - watchPiSkillManifestTargets(roots, realChild); - if (entry.isSymbolicLink()) continue; + watchPiSkillManifestTargets(sample, realChild); + // 与 collector 同口径判定软链(含 readdir 把 junction 报成目录的形态): + // 软链 namespace collector 明文不枚举,盯视面不得混入目标树内的键。 + if (isSymlinkEntry(entry, childPath)) continue; if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace for (const nested of listDir(realChild)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; const nestedPath = path.join(realChild, nested.name); - roots.set(nestedPath, statMtimeMs(nestedPath)); + recordWatchKey(sample, nestedPath); const realNested = realpathOrNull(nestedPath); if (!realNested || !isDir(realNested)) continue; // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 - watchPiSkillManifestTargets(roots, realNested); + watchPiSkillManifestTargets(sample, realNested); } } } @@ -300,7 +356,7 @@ function watchPiSkillTreeMtimes(roots: Map, skillsDir: string): /** 软链清单本体:SKILL.md/skill.md 为指向仓内目标的软链时,目标移动/删除不改变 * skill 目录自身 mtime,只有盯住解析后的文件才能检出(与 prompts 同款)。悬空链 * 盯链接自身,目标落地即检出。 */ -function watchPiSkillManifestTargets(roots: Map, realFolder: string): void { +function watchPiSkillManifestTargets(sample: PiProjectResourceLaunchWatch, realFolder: string): void { for (const name of ['SKILL.md', 'skill.md']) { const manifestPath = path.join(realFolder, name); let manifestLstat: fs.Stats; @@ -311,24 +367,24 @@ function watchPiSkillManifestTargets(roots: Map, realFolder: str } if (!manifestLstat.isSymbolicLink()) continue; const realManifest = realpathOrNull(manifestPath); - roots.set(realManifest ?? manifestPath, statMtimeMs(realManifest ?? manifestPath)); + recordWatchKey(sample, realManifest ?? manifestPath); } } /** stat 一个 extensions 根及其子目录:已有扩展目录内 index.ts 增删只改子目录 mtime。 */ -function watchPiExtensionChildMtimes(roots: Map, extDir: string): void { - roots.set(extDir, statMtimeMs(extDir)); +function watchPiExtensionChildMtimes(sample: PiProjectResourceLaunchWatch, extDir: string): void { + recordWatchKey(sample, extDir); if (!isDir(extDir)) return; for (const entry of listDir(extDir)) { if (entry.name.startsWith('.')) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(extDir, entry.name); - roots.set(childPath, statMtimeMs(childPath)); + recordWatchKey(sample, childPath); const realChild = realpathOrNull(childPath); if (!realChild || !isDir(realChild)) continue; // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 const realIndex = path.join(realChild, 'index.ts'); - roots.set(realIndex, statMtimeMs(realIndex)); + recordWatchKey(sample, realIndex); } } @@ -338,8 +394,8 @@ function watchPiExtensionChildMtimes(roots: Map, extDir: string) * 但目标文件的移动/删除只改目标处。statSync 跟随软链,目标缺失时为 -1,与 * realpath 收集口径一致。枚举条件与 collector 逐条对应(隐藏/非 .md 跳过)。 */ -function watchPiPromptTargets(roots: Map, promptsDir: string, repoRoot: string): void { - roots.set(promptsDir, statMtimeMs(promptsDir)); +function watchPiPromptTargets(sample: PiProjectResourceLaunchWatch, promptsDir: string, repoRoot: string): void { + recordWatchKey(sample, promptsDir); if (!isDir(promptsDir)) return; for (const entry of listDir(promptsDir)) { if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; @@ -348,47 +404,46 @@ function watchPiPromptTargets(roots: Map, promptsDir: string, re if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) { // 悬空软链(或目标越界):把链接自身入盯视 —— 目标落地时 statSync 解析到 // 新 mtime(未盯视目录里的变化也能触发重扫);普通文件不存在此形态。 - if (entry.isSymbolicLink()) roots.set(entryPath, statMtimeMs(entryPath)); + if (entry.isSymbolicLink()) recordWatchKey(sample, entryPath); continue; } - roots.set(realFile, statMtimeMs(realFile)); + recordWatchKey(sample, realFile); } } /** - * 冻结一份启动快照。watchRootMtimes 与 repoRoot 必须由调用方在收集 paths **之前** - * 采样传入(见 pi/index.ts 调用点):三样同批且基线在前,采样窗口内新增的资源只会 - * 让首次快检多一次重扫后收敛;反过来(先收集后采样)会漏掉窗口内新增的资源,或让 - * 新旧边界与路径集合错配,静默漏检。 + * 冻结一份启动快照。watch 采样(含解析身份与 scanRoot 身份)与 repoRoot 必须由 + * 调用方在收集 paths **之前**采样传入(见 pi/index.ts 调用点):身份基线晚于 argv + * 采集,会把「采基线前的改指」固化成一致基线,永久漏检(Codex P2,2026-11-10); + * 基线在前则窗口内不一致只会让首次快检多一次重扫后收敛。restrict 传受邀者裁剪 + * 口径:比较对 fresh 集合做与启动相同的裁剪。 */ export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, - watchRootMtimes: Map, repoRoot: string, + watch: PiProjectResourceLaunchWatch, + restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths, ): PiProjectResourceLaunchSnapshot { return Object.freeze({ workingDir, paths, - watchRootMtimes, - // 收集器与 watch 面都按解析后的 scanRoot 取物理路径:快照必须同时记住 - // 解析结果,否则 workingDir 经软链启动、软链改指同仓另一目录时,边界与 - // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。 + watchRootMtimes: watch.mtimes, + // scanRoot(workingDir 解析后)刻意不是 watch key(不含 workingDir 本身), + // 解析身份单独成字段;身份出自 watch 采样的最前面 —— 若在这里补采样就退回 + // 「收集后才采身份」的永久漏检窗口(Codex P2)。软链 workingDir 改指同仓 + // 另一目录时,边界与旧物理根 mtime 均不变,这是唯一信号。 state: { repoRoot, - // 收集器与 watch 面都按解析后的 scanRoot 取物理路径:快照必须同时记住 - // 解析结果,否则 workingDir 经软链启动、软链改指同仓另一目录时,边界与 - // 旧物理根 mtime 均不变,快检放行旧 argv(Codex P2,2026-11-10)。scanRoot - // 刻意不是 watch key(不含 workingDir 本身),单独成字段。 - resolvedWorkingDir: realpathOrNull(workingDir), + resolvedWorkingDir: watch.scanRootResolved, }, // 每个 watch root 的解析身份:任意层级(`.pi`、`.agents` 链、namespace、单个 // skill 目录)改指同 mtime 的孪生树时 mtime 面致盲,唯一完备信号是逐 key 的 - // 解析身份(workingDir→`.pi`→`.agents` 三连击后的根治,取代逐点枚举)。realpath - // 含全链路解析,未枚举的嵌套软链同样覆盖。 - watchRootsResolved: new Map( - [...watchRootMtimes.keys()].map((dir) => [dir, realpathOrNull(dir)] as const), - ), + // 解析身份。realpath 含全链路解析,未枚举的嵌套软链同样覆盖。与 mtimes/entries + // 同 key 同批产出(见 collectPiProjectResourceLaunchWatch)。 + watchRootsResolved: watch.resolved, + watchRootEntries: watch.entries, + restrict: restrict ?? null, }); } @@ -399,10 +454,13 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): /** * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。结构性契约: * **每次调用至多一次全量路径收集**。两级信号 → 一次收集 → 一次比较: - * 1. stat 扫描(零收集):所有 watch root 的 mtime 与基线全等(含缺失态 -1)且 - * git 边界未变 → 无漂移;任一不等或有信号 → 进入下一步。信号源: + * 1. 轻量信号扫描(每 key 一次 realpath + stat + readdir,无递归):全部与基线 + * 相等且 git 边界未变 → 无漂移;任一不等 → 进入下一步。信号源: * - watch root mtime 变化(资源增删只改所在目录自身 mtime,基线必须覆盖 * collector 实际枚举的每一层目录); + * - watch root 条目名指纹变化(时间戳粒度盲区:同一 tick 内增删,mtime 与 + * 基线逐位相等,条目名单不同); + * - watch root / workingDir 解析身份变化(软链改指同 mtime 孪生树时唯一信号); * - git 边界变化(更近的 .git 出现/消失会改变 collector 的枚举链,但不动 * 任何被盯目录的 mtime)。 * 2. 全量重扫,按最终路径集合判定(argv 的输入是集合,不是内容): @@ -440,17 +498,27 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps break; } } - if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedRootChanged && !mtimeChanged) return false; + // 条目名指纹:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 + let entriesChanged = false; + for (const [dir, fingerprintAtLaunch] of snapshot.watchRootEntries) { + if (readDirEntryFingerprint(dir) !== fingerprintAtLaunch) { + entriesChanged = true; + break; + } + } + if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedRootChanged && !mtimeChanged && !entriesChanged) return false; // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 // 一起,静默漏检。 - const freshRoots = collectPiProjectResourceWatchRootMtimes(snapshot.workingDir, repoRoot); + const freshRoots = collectPiProjectResourceLaunchWatch(snapshot.workingDir, repoRoot); const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir, repoRoot); + // 受邀者:比较前对 fresh 做与启动相同的裁剪,否则全量比裁剪基线恒判漂移。 + const freshForCompare = snapshot.restrict ? snapshot.restrict(fresh) : fresh; if (!( - samePiResourceList(fresh.skills, snapshot.paths.skills) - && samePiResourceList(fresh.promptTemplates, snapshot.paths.promptTemplates) - && samePiResourceList(fresh.extensions, snapshot.paths.extensions) + samePiResourceList(freshForCompare.skills, snapshot.paths.skills) + && samePiResourceList(freshForCompare.promptTemplates, snapshot.paths.promptTemplates) + && samePiResourceList(freshForCompare.extensions, snapshot.paths.extensions) )) { return true; } @@ -469,9 +537,11 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps if (realpathOrNull(dir) !== resolvedAtSignal) return true; } snapshot.watchRootMtimes.clear(); - for (const [dir, mtime] of freshRoots) snapshot.watchRootMtimes.set(dir, mtime); + for (const [dir, mtime] of freshRoots.mtimes) snapshot.watchRootMtimes.set(dir, mtime); snapshot.watchRootsResolved.clear(); - for (const dir of freshRoots.keys()) snapshot.watchRootsResolved.set(dir, realpathOrNull(dir)); + for (const [dir, resolved] of freshRoots.resolved) snapshot.watchRootsResolved.set(dir, resolved); + snapshot.watchRootEntries.clear(); + for (const [dir, fingerprint] of freshRoots.entries) snapshot.watchRootEntries.set(dir, fingerprint); snapshot.state.repoRoot = repoRoot; snapshot.state.resolvedWorkingDir = resolvedWorkingDir; return false; diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts index 28c34be9e6..31d1b06a3e 100644 --- a/packages/maker-core/src/session.ts +++ b/packages/maker-core/src/session.ts @@ -2301,20 +2301,14 @@ export class Session { } /** - * 盘上项目资源相对运行时启动快照是否已漂移(仅 pi 本地根任务实现,其余 agent 恒 false)。 - */ - hasProjectResourceDrift(): boolean { - return this.handle.hasProjectResourceDrift?.() === true; - } - - /** - * 项目资源漂移且满足回收空闲口径时返回 true。只判定不执行 close:close 必须由 - * 持有 Maker 的调用方走 closeSessionIfCurrent(session, 'runtime-refresh'),让 - * session:closed 带上 Maker 认识的刷新原因 —— 直接 Session.close 绕过 Maker 的 - * closeReasons 登记,IM runner 会按 unexpected 清掉排队中的回合、丢失已接受的 - * 派发。空闲口径与 closeIfIdle 一致:turn 运行中、结束未收口的 turn、换代续接、 - * 手动压缩 / rewind 等宿主排他操作进行中绝不回收。回收后由既有 lazy bootstrap - * 在下次发送时重扫项目资源、重算 argv。 + * 项目资源漂移且满足回收空闲口径时返回 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; @@ -2323,7 +2317,7 @@ export class Session { || this.hasPendingHostOperation()) { return false; } - return this.hasProjectResourceDrift(); + return this.handle.hasProjectResourceDrift?.() === true; } getCurrentTurnId(): string | null { From 916f6ba1a3ef8bd08cbcb6ba82d969371ddb9b15 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 17:47:12 +0800 Subject: [PATCH 36/45] =?UTF-8?q?fix(pi):=20collector=20=E4=B8=8D=E6=9E=9A?= =?UTF-8?q?=E4=B8=BE=E7=9A=84=E9=94=AE=E4=B8=8D=E8=AF=BB=E6=9D=A1=E7=9B=AE?= =?UTF-8?q?=E6=B8=85=E5=8D=95;local-agent=20=E5=8F=AF=E8=A7=81=E5=8F=98?= =?UTF-8?q?=E4=BD=93=E8=B5=B0=20Maker=20=E5=85=B3=E9=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greptile P2(4523063368):条目名指纹的 readdir 跟随软链,.pi/skills 下的软链 namespace(如 @scope)指向仓外大目录时,collector 虽不枚举其目标树, recordWatchKey 仍每次快检读取并排序目标完整条目列表,阻塞桌面主进程。改为按 collector 同一门禁决定是否采条目:软链 namespace/越界子树的键条目基线存 null (快检跳读),解析身份与 mtime 保留(改指/悬空链落地仍可检出);skills/prompts/ extensions 根越界时同样跳读且不再下行枚举(与 collector 的 isWithinRoot 门禁 对齐)。 Codex P1(4523150838):local-agent 可见变体的 Session 由 Maker 托管(在 activeSessions,可带排队回合与暂存附件),漂移重建里直接 Session.close 不登记 原因,会被按 unexpected 丢掉排队回合,未抑制的 onClose 会抢先清理暂存附件。 改为先走 Maker.recyclePiRuntimeIfResourcesDrifted(实例方法自带 runtime-refresh 原因与 rehydrate 抑制窗口);不可见变体不在 activeSessions 恒 false,回退直关。 回归:新增「越界软链 namespace 条目基线为 null + 目标树内部增删不漂移」用例, 漂移套件 37 用例(32 过 + 5 POSIX-only 跳过);maker/session/pi-startsession 378 用例绿;maker-core/desktop typecheck 过。 Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/local-agent/runtime.ts | 11 ++- .../pi-project-resource-drift.test.ts | 25 ++++++ .../src/agents/pi/project-resource-cli.ts | 77 ++++++++++++------- 3 files changed, 84 insertions(+), 29 deletions(-) diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts index 56c2881791..64bf59add6 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 }, @@ -575,7 +575,14 @@ export async function openLocalAgentRuntime( // hasRecyclableProjectResourceDrift,非 pi agent 恒 false 跳过。 if (handle.hasRecyclableProjectResourceDrift()) { const previous = handle; - await previous.close(); + // 可见变体的 Session 由 Maker 托管:必须走 Maker 的 runtime-refresh 关闭 + // (实例方法自带 rehydrate 抑制窗口)。直接 Session.close 不登记原因,会 + // 被按 unexpected 丢掉排队回合,未抑制的 onClose 会在重建前清掉暂存附件 + // (Codex P1,2026-11-10)。不可见变体不在 activeSessions,Maker 回收恒 + // false,回退直关。 + if (!(await maker.recyclePiRuntimeIfResourcesDrifted(previous).catch(() => false))) { + await previous.close(); + } assertCurrent(current); handle = await start(previous.sdkSessionId, current); } 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 index 4fcb283cba..93fbb3c957 100644 --- 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 @@ -311,6 +311,31 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + it('stores null entries baseline for collector-excluded keys (symlink namespace to outside-repo target)', () => { + // Greptile P2:collector 不枚举越界/软链 namespace 子树,条目基线存 null —— + // 快检不 readdir 其目标(readdir 跟随软链,外部大目录完整列表是每条消息一次 + // 的纯开销);改指信号由解析身份承担。 + mkdirSync(path.join(project, 'repo'), { recursive: true }); + writeFileSync(path.join(project, 'repo', '.git'), ''); + writeSkill(path.join('repo', '.pi', 'skills'), 'alpha'); + writeSkill(path.join('outside', 'big'), 'huge'); // repoRoot 外的目标树 + mkdirSync(path.join(project, 'repo', '.pi', 'skills'), { recursive: true }); + symlinkSync(path.join(project, 'outside', 'big'), path.join(project, 'repo', '.pi', 'skills', '@scope'), 'junction'); + const wd = path.join(project, 'repo'); + const launchRepoRoot = resolvePiResourceRepoRoot(wd); + const watch = collectPiProjectResourceLaunchWatch(wd, launchRepoRoot); + // 前提:软链 namespace 键的条目基线为 null(快检将跳读)。键是链接路径本体, + // 不能用 canon 查(canonical 化会把键解析成目标路径) + expect(watch.entries.get(path.join(realpathSync(wd), '.pi', 'skills', '@scope'))).toBeNull(); + const baseline = snapshotPiProjectResourceLaunch( + wd, collectPiProjectResourceCliPaths(wd, launchRepoRoot), launchRepoRoot, watch); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 目标树内部增删:集合不变 → 不漂移(mtime 跟随目标会触发一次重扫后收敛) + writeSkill(path.join('outside', 'big'), 'more'); + bumpMtime(path.join(project, 'outside', 'big')); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + it('rebuilds the watch map after an unchanged rescan so new child dirs are watched', () => { mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); const baseline = snapshot(); 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 38a5ef874d..ba4a42db1b 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -242,8 +242,9 @@ export interface PiProjectResourceLaunchSnapshot { * 同 mtime 的孪生树时,解析身份是唯一信号;与 watchRootMtimes 同 key 同批。 */ readonly watchRootsResolved: Map; /** 每个 watch root 的 readdir 条目名指纹:时间戳粒度盲区(同一 tick 内增删, - * mtime 与基线逐位相等)的第二信号;与 watchRootMtimes 同 key 同批。 */ - readonly watchRootEntries: Map; + * mtime 与基线逐位相等)的第二信号;与 watchRootMtimes 同 key 同批。null = + * collector 不枚举的键(软链 namespace/越界子树),快检跳读。 */ + readonly watchRootEntries: Map; /** 受邀者裁剪口径(非受邀者恒 null):重扫后的 fresh 集合先经它裁剪再与 paths * 比较 —— 缺了会拿全量比裁剪基线恒判漂移,回收死循环。 */ readonly restrict: ((paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) | null; @@ -259,19 +260,22 @@ export interface PiProjectResourceLaunchWatch { /** workingDir 的解析身份,先于所有键采样(键路径都从它拼出)。 */ readonly scanRootResolved: string | null; readonly mtimes: Map; - /** key → readdir 条目名指纹(排序拼接;文件键/缺失恒 '')。时间戳粒度盲区 - * (同一 tick 内增删,mtime 与基线逐位相等)的第二信号;变化只作重扫信号, - * 判决仍归路径集合。 */ - readonly entries: Map; + /** key → readdir 条目名指纹(排序拼接;文件键/缺失恒 '';collector 不枚举的键 + * —— 软链 namespace/越界子树 —— 为 null,快检跳读:readdir 跟随软链,外部大 + * 目录的完整列表是每条消息一次的纯开销)。时间戳粒度盲区(同一 tick 内增删, + * mtime 与基线逐位相等)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ + readonly entries: Map; /** key → realpath 解析身份(缺失 null),与 mtimes 同 key 同批。 */ readonly resolved: Map; } -function recordWatchKey(sample: PiProjectResourceLaunchWatch, target: string): void { +function recordWatchKey(sample: PiProjectResourceLaunchWatch, target: string, enumerateEntries = true): void { // 解析身份先行:身份与 mtime/条目之间的窗口不一致只会多一次重扫,不会固化。 sample.resolved.set(target, realpathOrNull(target)); sample.mtimes.set(target, statMtimeMs(target)); - sample.entries.set(target, readDirEntryFingerprint(target)); + // enumerateEntries=false:collector 不枚举该键的子树(软链 namespace/越界), + // 条目基线存 null,快检跳读(Greptile P2)。 + sample.entries.set(target, enumerateEntries ? readDirEntryFingerprint(target) : null); } /** @@ -298,14 +302,14 @@ export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRoot const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); const piDir = path.join(scanRoot, '.pi'); recordWatchKey(sample, piDir); - watchPiSkillTreeMtimes(sample, path.join(piDir, 'skills')); + watchPiSkillTreeMtimes(sample, repoRoot, path.join(piDir, 'skills')); watchPiPromptTargets(sample, path.join(piDir, 'prompts'), repoRoot); - watchPiExtensionChildMtimes(sample, path.join(piDir, 'extensions')); + watchPiExtensionChildMtimes(sample, repoRoot, path.join(piDir, 'extensions')); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); recordWatchKey(sample, agentsDir); - watchPiSkillTreeMtimes(sample, path.join(agentsDir, 'skills')); + watchPiSkillTreeMtimes(sample, repoRoot, path.join(agentsDir, 'skills')); if (current === repoRoot) break; const parent = path.dirname(current); if (parent === current) break; @@ -320,33 +324,41 @@ export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRoot * 目录 mtime 捕获,与 realpath 收集口径一致。跳过 collector 不枚举的子树 * (隐藏/bak、软链 namespace、剪枝名),避免无关变化触发无谓重扫。 */ -function watchPiSkillTreeMtimes(sample: PiProjectResourceLaunchWatch, skillsDir: string): void { - recordWatchKey(sample, skillsDir); - if (!isDir(skillsDir)) return; +function watchPiSkillTreeMtimes(sample: PiProjectResourceLaunchWatch, repoRoot: string, skillsDir: string): void { + // 与 collector 同一门禁:缺失/越界(repoRoot 外)的 skills 根不枚举 —— 条目 + // 基线存 null(快检跳读;readdir 跟随软链,外部大目录的完整列表是每条消息 + // 一次的纯开销,Greptile P2),下行枚举一并跳过;改指信号由解析身份承担。 + const skillsResolved = realpathOrNull(skillsDir); + const enumerated = !!skillsResolved && isDir(skillsResolved) && isWithinRoot(repoRoot, skillsResolved); + recordWatchKey(sample, skillsDir, enumerated); + if (!enumerated) return; for (const entry of listDir(skillsDir)) { if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(skillsDir, entry.name); - recordWatchKey(sample, childPath); const realChild = realpathOrNull(childPath); - if (!realChild || !isDir(realChild)) continue; + const childInRepo = !!realChild && isDir(realChild) && isWithinRoot(repoRoot, realChild); + // 软链 namespace/越界子树:collector 不枚举其内部,不读条目基线(纯开销); + // 解析身份与 mtime 仍记录(改指/悬空链落地仍能检出)。 + const childIsSymlink = isSymlinkEntry(entry, childPath); + recordWatchKey(sample, childPath, childInRepo && !childIsSymlink); + if (!childInRepo || !realChild) continue; // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 watchPiSkillManifestTargets(sample, realChild); - // 与 collector 同口径判定软链(含 readdir 把 junction 报成目录的形态): - // 软链 namespace collector 明文不枚举,盯视面不得混入目标树内的键。 - if (isSymlinkEntry(entry, childPath)) continue; + if (childIsSymlink) continue; if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace for (const nested of listDir(realChild)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; const nestedPath = path.join(realChild, nested.name); - recordWatchKey(sample, nestedPath); const realNested = realpathOrNull(nestedPath); - if (!realNested || !isDir(realNested)) continue; + const nestedInRepo = !!realNested && isDir(realNested) && isWithinRoot(repoRoot, realNested); + recordWatchKey(sample, nestedPath, nestedInRepo && !isSymlinkEntry(nested, nestedPath)); + if (!nestedInRepo || !realNested) continue; // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 watchPiSkillManifestTargets(sample, realNested); } @@ -372,15 +384,21 @@ function watchPiSkillManifestTargets(sample: PiProjectResourceLaunchWatch, realF } /** stat 一个 extensions 根及其子目录:已有扩展目录内 index.ts 增删只改子目录 mtime。 */ -function watchPiExtensionChildMtimes(sample: PiProjectResourceLaunchWatch, extDir: string): void { - recordWatchKey(sample, extDir); - if (!isDir(extDir)) return; +function watchPiExtensionChildMtimes(sample: PiProjectResourceLaunchWatch, repoRoot: string, extDir: string): void { + // 与 collector 同一门禁:缺失/越界的 extensions 根不枚举(条目基线 null,快检跳读)。 + const extResolved = realpathOrNull(extDir); + const enumerated = !!extResolved && isDir(extResolved) && isWithinRoot(repoRoot, extResolved); + recordWatchKey(sample, extDir, enumerated); + if (!enumerated) return; for (const entry of listDir(extDir)) { if (entry.name.startsWith('.')) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const childPath = path.join(extDir, entry.name); - recordWatchKey(sample, childPath); const realChild = realpathOrNull(childPath); + // collector 只 readdir extensions 自身,不枚举子目录:软链/越界子键不读条目基线。 + recordWatchKey( + sample, childPath, + !!realChild && isDir(realChild) && isWithinRoot(repoRoot, realChild) && !isSymlinkEntry(entry, childPath)); if (!realChild || !isDir(realChild)) continue; // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 const realIndex = path.join(realChild, 'index.ts'); @@ -395,8 +413,11 @@ function watchPiExtensionChildMtimes(sample: PiProjectResourceLaunchWatch, extDi * realpath 收集口径一致。枚举条件与 collector 逐条对应(隐藏/非 .md 跳过)。 */ function watchPiPromptTargets(sample: PiProjectResourceLaunchWatch, promptsDir: string, repoRoot: string): void { - recordWatchKey(sample, promptsDir); - if (!isDir(promptsDir)) return; + // 与 collector 同一门禁:缺失/越界的 prompts 根不枚举(条目基线 null,快检跳读)。 + const promptsResolved = realpathOrNull(promptsDir); + const enumerated = !!promptsResolved && isDir(promptsResolved) && isWithinRoot(repoRoot, promptsResolved); + recordWatchKey(sample, promptsDir, enumerated); + if (!enumerated) return; for (const entry of listDir(promptsDir)) { if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; const entryPath = path.join(promptsDir, entry.name); @@ -499,8 +520,10 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps } } // 条目名指纹:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 + // null = collector 不枚举的键(软链 namespace/越界子树),跳读(Greptile P2)。 let entriesChanged = false; for (const [dir, fingerprintAtLaunch] of snapshot.watchRootEntries) { + if (fingerprintAtLaunch === null) continue; if (readDirEntryFingerprint(dir) !== fingerprintAtLaunch) { entriesChanged = true; break; From 735cc35d16e706901547708ce2d71970da469481 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 18:24:50 +0800 Subject: [PATCH 37/45] =?UTF-8?q?refactor(pi):=20collector=20=E4=B8=8E=20w?= =?UTF-8?q?atcher=20=E5=90=88=E4=B8=80=E4=B8=BA=E5=8D=95=E6=AC=A1=20surfac?= =?UTF-8?q?e=20=E9=81=8D=E5=8E=86,=E7=BB=88=E7=BB=93=E5=8F=A3=E5=BE=84?= =?UTF-8?q?=E5=88=86=E6=AD=A7=E6=97=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对抗审查复核(直链技能漏检 Greptile P2)确认:前三轮的全部盲区(身份晚于收集、 窗口复核比错基线、软链键跳读过头)同源 —— collector 与 watcher 是两套手写遍历, 「watcher 判定 = collector 消费方式」这条不变量只靠注释维持,每个新 case 都是 一个新的分歧点。逐点修补治不了土壤。 本次合一(R1): - collectPiProjectResourceSurface 成为 argv 集合与盯视基线的唯一产出点, 一次遍历同时产出:每个键在 collector 消费它的那一步记录,条目模式按消费 方式派生('full'=readdir 的目录 / 'manifest'=只 stat 清单存在性的软链目标与 已知 skill 目录 / 'none'=不消费)。 - 结构不变量:argv 与基线同批,「基线 ≠ argv 消费的状态」不可能发生; 快检只需检测「盘上 ≠ 基线」。原「先采基线后收集」的时序约定与两处 双调用窗口(spawn 采样、重扫)随之消失。 - collectPiProjectResourceCliPaths / collectPiProjectResourceLaunchWatch 保留为兼容入口(= surface 的两个视图);drift 重扫改用单次 surface 调用。 - index.ts spawn 采样改用单次 surface 调用。 诚实记录:合并过程中测试网当场抓住一次我自己的口径分歧 —— 扩展子键的 Dirent 文件过滤器被机械带入,而 collector 恰恰收集 .ts 文件子键(hook.ts)。 这正是两套遍历时代靠 review 难以及时发现的那类错误。 测试:drift 套件 38 用例全绿(33 过 + 5 POSIX-only 跳过,含直链技能同刻 迁移、越界软链键 null 基线、guest 裁剪、同刻条目指纹、发布前改指); maker/session/pi-startsession-cleanup/local-agent 393 用例绿; maker-core/desktop typecheck 过。 Signed-off-by: Zhang Yunjin --- .../pi-project-resource-drift.test.ts | 94 ++-- packages/maker-core/src/agents/pi/index.ts | 35 +- .../src/agents/pi/project-resource-cli.ts | 444 +++++++++--------- 3 files changed, 300 insertions(+), 273 deletions(-) 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 index 93fbb3c957..c754ada2ff 100644 --- 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 @@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { collectPiProjectResourceCliPaths, collectPiProjectResourceLaunchWatch, + collectPiProjectResourceSurface, piProjectResourcesDrifted, resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, @@ -70,10 +71,9 @@ function bumpMtime(target: string): void { } function snapshot(restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { - // 与生产调用点同序:watch 采样(含解析身份)先于路径收集(见 snapshotPiProjectResourceLaunch)。 - const repoRoot = resolvePiResourceRepoRoot(project); - const watch = collectPiProjectResourceLaunchWatch(project, repoRoot); - return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project, repoRoot), repoRoot, watch, restrict); + // 与生产调用点同口径:surface 一次遍历同批产出基线与路径(结构上不可分离)。 + const surface = collectPiProjectResourceSurface(project); + return snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch, restrict); } describe('piProjectResourcesDrifted', () => { @@ -133,10 +133,9 @@ describe('piProjectResourcesDrifted', () => { writeFileSync(path.join(project, '.git'), ''); const nested = path.join(project, 'sub'); mkdirSync(nested, { recursive: true }); - const nestedRepoRoot = resolvePiResourceRepoRoot(nested); - const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); + const nestedSurface = collectPiProjectResourceSurface(nested); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); + nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); writeSkill(path.join('.agents', 'skills'), 'gamma'); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -223,21 +222,18 @@ describe('piProjectResourcesDrifted', () => { expect(roots.has(canon(path.join(project, '.pi', 'extensions', 'myext')))).toBe(true); }); - it('launch snapshot samples watch roots before path collection (race-safe order)', () => { - // 生产调用点先采基线后收集路径。基线采样与路径收集之间新增的资源已在集合 - // 里且基线较旧:首次快检多一次重扫确认集合一致后刷新基线 —— 既不误报漂移, - // 也不会静默漏检(反序才会漏)。 - const repoRoot = resolvePiResourceRepoRoot(project); - const watch = collectPiProjectResourceLaunchWatch(project, repoRoot); + it('paths and watch table come from one surface walk (self-consistent baseline)', () => { + // argv 与基线出自同一次遍历:基线描述的就是 argv 消费的状态,结构上不可能 + // 不一致;快检只需检测「盘上 ≠ 基线」。 writeSkill(path.join('.pi', 'skills'), 'alpha'); - const baseline = snapshotPiProjectResourceLaunch( - project, collectPiProjectResourceCliPaths(project, repoRoot), repoRoot, watch); + const surface = collectPiProjectResourceSurface(project); + const baseline = snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch); expect(piProjectResourcesDrifted(baseline)).toBe(false); expect(baseline.watchRootMtimes.get(canon(path.join(project, '.pi', 'skills')))) .toBe(statMtime(path.join(project, '.pi', 'skills'))); }); - it('samples resolved identity before collecting paths (launch-window retarget is drift)', () => { + it('retarget between the surface walk and snapshot publish is drift (argv and baseline are same-batch)', () => { // 回归(Codex P2,2026-11-10):身份基线若在 argv 收集之后采样,「采基线前的 // 改指」会被固化成一致基线(mtime 孪生树碰撞时无任何信号)→ 永久漏检。 // 按生产序复刻:① 采 watch(含解析身份)→ ② 收集 argv → ③ 窗口内改指孪生树 @@ -257,12 +253,12 @@ describe('piProjectResourcesDrifted', () => { const link = path.join(project, 'wd-link'); const linkType = process.platform === 'win32' ? 'junction' : 'dir'; symlinkSync(realA, link, linkType); - const launchRepoRoot = resolvePiResourceRepoRoot(link); - const watch = collectPiProjectResourceLaunchWatch(link, launchRepoRoot); // ① 采 watch - const paths = collectPiProjectResourceCliPaths(link, launchRepoRoot); // ② argv 来自 A + // surface 一次遍历:argv 与基线同批,均来自 A —— 生产不可能再出现「基线与 + // 集合不同批」;发布前的改指仍必须由身份信号检出。 + const surface = collectPiProjectResourceSurface(link); rmSync(link); - symlinkSync(realB, link, linkType); // ③ 窗口内改指 B(mtime 已对齐) - const baseline = snapshotPiProjectResourceLaunch(link, paths, launchRepoRoot, watch); // ④ 建快照 + symlinkSync(realB, link, linkType); // 发布前改指 B(mtime 已对齐) + const baseline = snapshotPiProjectResourceLaunch(link, surface.paths, surface.repoRoot, surface.watch); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -294,12 +290,11 @@ describe('piProjectResourcesDrifted', () => { promptTemplates: Object.freeze(p.promptTemplates.filter((s) => s.startsWith(scope))), extensions: Object.freeze([] as readonly string[]), }); - const launchRepoRoot = resolvePiResourceRepoRoot(wd); - const collected = collectPiProjectResourceCliPaths(wd, launchRepoRoot); + const surface = collectPiProjectResourceSurface(wd); + const collected = surface.paths; // 前提:全量收集含 mirror 外的技能(链上 .agents 越过 guestRoot) expect(collected.skills.some((s) => !s.startsWith(scope))).toBe(true); - const watch = collectPiProjectResourceLaunchWatch(wd, launchRepoRoot); - const baseline = snapshotPiProjectResourceLaunch(wd, restrict(collected), launchRepoRoot, watch, restrict); + const baseline = snapshotPiProjectResourceLaunch(wd, restrict(collected), surface.repoRoot, surface.watch, restrict); expect(piProjectResourcesDrifted(baseline)).toBe(false); // mirror 外新增:有信号(链上 .agents 被盯),裁剪口径下集合未变 → 不回收 writeSkill(path.join('.agents', 'skills'), 'global-2'); @@ -311,6 +306,28 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + it('detects a manifest added inside an in-repo direct-linked skill within the same tick', () => { + // 回归(Greptile P2 直链技能):collector 对仓内软链目标消费清单存在性 —— + // 软键条目基线必须取清单存在性而非跳读,否则目标内同刻新增 SKILL.md + // (namespace→skill 迁移)四路信号全盲:目标 mtime 量化等值、链接身份不变、 + // 条目跳读、manifest watcher 只盯软链清单。 + writeFileSync(path.join(project, '.git'), ''); + mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); + mkdirSync(path.join(project, 'target-dir'), { recursive: true }); + const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); + utimesSync(path.join(project, 'target-dir'), aligned, aligned); + symlinkSync(path.join(project, 'target-dir'), path.join(project, '.pi', 'skills', 'foo'), 'junction'); + const baseline = snapshot(); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + // 前提:仓内软键的条目基线是清单存在性指纹('M:' 前缀 + 空清单),不是 null + const linkKey = path.join(realpathSync(project), '.pi', 'skills', 'foo'); + expect(baseline.watchRootEntries.get(linkKey)).toBe('M:'); + // 同一刻新增普通文件 SKILL.md(显式把目标目录 mtime 恢复基线值,隔离 mtime 信号) + writeFileSync(path.join(project, 'target-dir', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); + utimesSync(path.join(project, 'target-dir'), aligned, aligned); + expect(piProjectResourcesDrifted(baseline)).toBe(true); + }); + it('stores null entries baseline for collector-excluded keys (symlink namespace to outside-repo target)', () => { // Greptile P2:collector 不枚举越界/软链 namespace 子树,条目基线存 null —— // 快检不 readdir 其目标(readdir 跟随软链,外部大目录完整列表是每条消息一次 @@ -322,13 +339,11 @@ describe('piProjectResourcesDrifted', () => { mkdirSync(path.join(project, 'repo', '.pi', 'skills'), { recursive: true }); symlinkSync(path.join(project, 'outside', 'big'), path.join(project, 'repo', '.pi', 'skills', '@scope'), 'junction'); const wd = path.join(project, 'repo'); - const launchRepoRoot = resolvePiResourceRepoRoot(wd); - const watch = collectPiProjectResourceLaunchWatch(wd, launchRepoRoot); + const surface = collectPiProjectResourceSurface(wd); // 前提:软链 namespace 键的条目基线为 null(快检将跳读)。键是链接路径本体, // 不能用 canon 查(canonical 化会把键解析成目标路径) - expect(watch.entries.get(path.join(realpathSync(wd), '.pi', 'skills', '@scope'))).toBeNull(); - const baseline = snapshotPiProjectResourceLaunch( - wd, collectPiProjectResourceCliPaths(wd, launchRepoRoot), launchRepoRoot, watch); + expect(surface.watch.entries.get(path.join(realpathSync(wd), '.pi', 'skills', '@scope'))).toBeNull(); + const baseline = snapshotPiProjectResourceLaunch(wd, surface.paths, surface.repoRoot, surface.watch); expect(piProjectResourcesDrifted(baseline)).toBe(false); // 目标树内部增删:集合不变 → 不漂移(mtime 跟随目标会触发一次重扫后收敛) writeSkill(path.join('outside', 'big'), 'more'); @@ -371,10 +386,9 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('outer', '.agents', 'skills'), 'outer-skill'); const nested = path.join(project, 'outer', 'sub'); mkdirSync(nested, { recursive: true }); - const nestedRepoRoot = resolvePiResourceRepoRoot(nested); - const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); + const nestedSurface = collectPiProjectResourceSurface(nested); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); + nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); expect(piProjectResourcesDrifted(baseline)).toBe(false); // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 mkdirSync(path.join(nested, '.git'), { recursive: true }); @@ -388,10 +402,9 @@ describe('piProjectResourcesDrifted', () => { const nested = path.join(project, 'outer', 'sub'); mkdirSync(path.join(nested, '.pi', 'skills', 'alpha'), { recursive: true }); writeFileSync(path.join(nested, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: t\n---\n'); - const nestedRepoRoot = resolvePiResourceRepoRoot(nested); - const nestedWatch = collectPiProjectResourceLaunchWatch(nested, nestedRepoRoot); + const nestedSurface = collectPiProjectResourceSurface(nested); const baseline = snapshotPiProjectResourceLaunch( - nested, collectPiProjectResourceCliPaths(nested, nestedRepoRoot), nestedRepoRoot, nestedWatch); + nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); // 嵌套目录 git init:被截断的上层链没有任何项目资源,集合不变,不应触发回收 mkdirSync(path.join(nested, '.git'), { recursive: true }); expect(piProjectResourcesDrifted(baseline)).toBe(false); @@ -489,13 +502,12 @@ describe('piProjectResourcesDrifted', () => { const link = path.join(project, 'wd-link'); const linkType = process.platform === 'win32' ? 'junction' : 'dir'; symlinkSync(realA, link, linkType); - const launchRepoRoot = resolvePiResourceRepoRoot(link); - const launchWatch = collectPiProjectResourceLaunchWatch(link, launchRepoRoot); + const surface = collectPiProjectResourceSurface(link); const baseline = snapshotPiProjectResourceLaunch( link, - collectPiProjectResourceCliPaths(link, launchRepoRoot), - launchRepoRoot, - launchWatch, + surface.paths, + surface.repoRoot, + surface.watch, ); expect(piProjectResourcesDrifted(baseline)).toBe(false); rmSync(link); diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 13f9a8969f..6b69507431 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -245,7 +245,7 @@ import { import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, - collectPiProjectResourceLaunchWatch, + collectPiProjectResourceSurface, emptyPiProjectResourceCliPaths, filterPiProjectCliSkills, piProjectResourceCliArgs, @@ -4069,24 +4069,19 @@ 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. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 - // watch 基线(mtime/条目指纹/解析身份)与 git 边界必须先于路径收集采样(见 - // snapshotPiProjectResourceLaunch):身份基线晚于 argv 采集,会把「采基线前的 - // 改指」固化成一致基线,永久漏检(Codex P2,2026-11-10);基线在前则窗口内 - // 新增的资源/边界变化只会让首次快检多一次重扫后收敛。git root 只解析一次, - // 经 hint 贯穿采样与收集 —— 窗口内 .git 消失不会采出旧根盯视面配新根路径 - // 集合的混合口径。受邀者同样建快照(镜像同步进来的新技能必须能检出),裁剪 - // 口径经 restrict 下发,比较对 fresh 做同一裁剪。 - const projectResourceRepoRootAtLaunch = loadProjectResourcesInPlace - ? resolvePiResourceRepoRoot(opts.workingDir) + // 项目资源表面(spawn 采样):argv 路径集合与盯视基线出自**同一次遍历** + // (collectPiProjectResourceSurface)—— 结构不变量:基线与 argv 消费的状态 + // 不可能不一致,快检只需检测「盘上 ≠ 基线」。分两次调用会重新造出「集合与 + // 基线不同批」的永久漏检窗口(Codex P2,2026-11-10)。受邀者同样建快照 + // (镜像同步进来的新技能必须能检出),裁剪口径经 restrict 下发,比较对 + // fresh 做同一裁剪。 + const projectResourceSurfaceAtLaunch = loadProjectResourcesInPlace + ? collectPiProjectResourceSurface(opts.workingDir) : null; - const projectResourceLaunchWatch = projectResourceRepoRootAtLaunch - ? collectPiProjectResourceLaunchWatch(opts.workingDir, projectResourceRepoRootAtLaunch) - : null; - const collectedProjectResources = loadProjectResourcesInPlace + const collectedProjectResources = projectResourceSurfaceAtLaunch ? guestRoot - ? restrictPiGuestProjectResources( - collectPiProjectResourceCliPaths(opts.workingDir, projectResourceRepoRootAtLaunch ?? undefined), guestRoot) - : collectPiProjectResourceCliPaths(opts.workingDir, projectResourceRepoRootAtLaunch ?? undefined) + ? restrictPiGuestProjectResources(projectResourceSurfaceAtLaunch.paths, guestRoot) + : projectResourceSurfaceAtLaunch.paths : emptyPiProjectResourceCliPaths(); const projectResourceCli = loadProjectResourcesInPlace ? { @@ -4101,12 +4096,12 @@ export class PiAgent extends BaseAgent { // 快照存未经禁用过滤的原始收集结果(受邀者已按 guestRoot 裁剪),与 drift // 检测的 fresh collect 经同一 restrict 裁剪后同口径可比;受邀者裁剪缺了会拿 // 全量比裁剪基线恒判漂移,回收死循环。 - const projectResourceLaunchSnapshot = projectResourceLaunchWatch && projectResourceRepoRootAtLaunch + const projectResourceLaunchSnapshot = projectResourceSurfaceAtLaunch ? snapshotPiProjectResourceLaunch( opts.workingDir, collectedProjectResources, - projectResourceRepoRootAtLaunch, - projectResourceLaunchWatch, + projectResourceSurfaceAtLaunch.repoRoot, + projectResourceSurfaceAtLaunch.watch, guestRoot ? (paths) => restrictPiGuestProjectResources(paths, guestRoot) : undefined) : null; 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 ba4a42db1b..18eadb7d30 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -106,100 +106,233 @@ function hasSkillFile(dir: string): boolean { return ['SKILL.md', 'skill.md'].some((name) => isFile(path.join(dir, name))); } -function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set): void { - const resolvedDir = realpathOrNull(skillsDir); - if (!resolvedDir || !isDir(resolvedDir) || !isWithinRoot(repoRoot, resolvedDir)) return; +/** + * 项目资源表面 = argv 路径集合 + 盯视基线,出自**同一次遍历**。 + * + * 结构不变量(2026-11-10,取代逐案修补):argv 与基线出自同一遍历,所以「基线 ≠ + * argv 消费的状态」在结构上不可能;快检只需检测「盘上 ≠ 基线」。此前全部盲区 + * (身份晚于收集、窗口复核比错基线、软链键跳读过头)都源于 collector 与 watcher + * 两套手写遍历的分歧 —— 合一后分歧不再可能。每个键的条目模式在遍历点按 collector + * 的消费方式确定:'full'=collector readdir 的目录;'manifest'=collector 只 stat + * SKILL.md/skill.md 存在性的软链目标/已知 skill 目录;'none'=不消费(越界/悬空)。 + */ +export interface PiProjectResourceSurface { + /** 本遍历认定的 git root(枚举链终点;调用方作为快照边界基线传入)。 */ + readonly repoRoot: string; + readonly paths: PiProjectResourceCliPaths; + readonly watch: PiProjectResourceLaunchWatch; +} - const addSkill = (realFolder: string): void => { - const skillMd = ['SKILL.md', 'skill.md'] - .map((name) => path.join(realFolder, name)) - .find(isFile); - const realMd = skillMd ? realpathOrNull(skillMd) : null; - if (realMd && isFile(realMd) && isWithinRoot(repoRoot, realMd)) bucket.add(realFolder); - }; +/** 把一个 skill 目录登记进集合(collector 口径:清单经 realpath 后须在仓内, + * realFolder 本身入集合)。 */ +function addPiSkill(repoRoot: string, realFolder: string, bucket: Set): void { + const skillMd = ['SKILL.md', 'skill.md'] + .map((name) => path.join(realFolder, name)) + .find(isFile); + const realMd = skillMd ? realpathOrNull(skillMd) : null; + if (realMd && isFile(realMd) && isWithinRoot(repoRoot, realMd)) bucket.add(realFolder); +} + +/** + * 走一遍 skills 根的两层树(collector 的枚举 = watcher 的盯视,同一循环): + * 每层先记键(身份/mtime/条目基线,模式按 collector 在此路径的消费方式), + * 再做 collector 的集合判定。 + */ +function walkPiSkillTree( + sample: PiProjectResourceLaunchWatch, + repoRoot: string, + skillsDir: string, + bucket: Set, +): void { + const resolvedDir = realpathOrNull(skillsDir); + const enumerated = !!resolvedDir && isDir(resolvedDir) && isWithinRoot(repoRoot, resolvedDir); + // collector readdir 该根(仓内时)→ 'full';缺失/越界 → 不消费 → 'none' + // (readdir 跟随软链,外部大目录的完整列表是纯开销)。 + recordWatchKey(sample, skillsDir, enumerated ? 'full' : 'none'); + if (!enumerated || !resolvedDir) return; for (const entry of listDir(resolvedDir)) { if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; + if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const candidatePath = path.join(resolvedDir, entry.name); const realFolder = realpathOrNull(candidatePath); - if (!realFolder || !isDir(realFolder) || !isWithinRoot(repoRoot, realFolder)) continue; - if (hasSkillFile(realFolder)) { - addSkill(realFolder); + const folderInRepo = !!realFolder && isDir(realFolder) && isWithinRoot(repoRoot, realFolder); + if (!folderInRepo || !realFolder) { + // collector 不消费(悬空/越界);身份与 mtime 保留 —— 改指/目标落地仍可检出。 + recordWatchKey(sample, candidatePath, 'none'); + continue; + } + const isSymlink = isSymlinkEntry(entry, candidatePath); + const hasManifest = hasSkillFile(realFolder); + // collector 消费方式:软链目标与已知 skill 目录只 stat 清单存在性('manifest', + // namespace↔skill 迁移的同刻信号,不读目标完整列表);将下行枚举的 namespace + // 目录读完整列表('full')。 + recordWatchKey(sample, candidatePath, isSymlink || hasManifest ? 'manifest' : 'full'); + // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, + // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 + // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, + // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 + watchPiSkillManifestTargets(sample, realFolder); + if (hasManifest) { + addPiSkill(repoRoot, realFolder, bucket); continue; } // Direct symlinked Skills remain supported above; a symlinked namespace // could escape the repo or cycle and is intentionally not walked. // lstat must see the unresolved path: a Windows junction may be reported // as a directory by readdir and by the resolved realpath. - const isSymlink = entry.isSymbolicLink() - || (entry.isDirectory() && isSymlinkDirectory(candidatePath)); if (isSymlink || shouldPruneSkillScanDirectory(entry.name)) continue; // At most one namespace/author level: //. for (const nested of listDir(realFolder)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; - const nestedFolder = realpathOrNull(path.join(realFolder, nested.name)); - if (!nestedFolder || !isDir(nestedFolder) || !isWithinRoot(repoRoot, nestedFolder)) continue; - if (hasSkillFile(nestedFolder)) addSkill(nestedFolder); + if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; + const nestedPath = path.join(realFolder, nested.name); + const realNested = realpathOrNull(nestedPath); + const nestedInRepo = !!realNested && isDir(realNested) && isWithinRoot(repoRoot, realNested); + // collector 对嵌套层只 stat 清单存在性(不再下行)→ 仓内一律 'manifest'。 + recordWatchKey(sample, nestedPath, nestedInRepo ? 'manifest' : 'none'); + if (!nestedInRepo || !realNested) continue; + // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 + watchPiSkillManifestTargets(sample, realNested); + if (hasSkillFile(realNested)) addPiSkill(repoRoot, realNested, bucket); } } } -export function collectPiProjectResourceCliPaths(workingDir: string, repoRootHint?: string): PiProjectResourceCliPaths { - if (!workingDir || !path.isAbsolute(workingDir) || !isDir(workingDir)) { - return emptyPiProjectResourceCliPaths(); +/** 走一遍 prompts 根:collector readdir 根、逐文件 realpath 后入集合;watcher 盯 + * 根的条目列表与每个解析后目标(mtime),悬空软链盯链接本体。 */ +function walkPiPromptTargets( + sample: PiProjectResourceLaunchWatch, + repoRoot: string, + promptsDir: string, + bucket: Set, +): void { + const realPrompts = realpathOrNull(promptsDir); + const enumerated = !!realPrompts && isDir(realPrompts) && isWithinRoot(repoRoot, realPrompts); + recordWatchKey(sample, promptsDir, enumerated ? 'full' : 'none'); + if (!enumerated || !realPrompts) return; + for (const entry of listDir(realPrompts)) { + if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; + const entryPath = path.join(realPrompts, entry.name); + const realFile = realpathOrNull(entryPath); + if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) { + // 悬空软链(或目标越界):把链接自身入盯视 —— 目标落地时 statSync 解析到 + // 新 mtime(未盯视目录里的变化也能触发重扫);普通文件不存在此形态。 + if (entry.isSymbolicLink()) recordWatchKey(sample, entryPath); + continue; + } + recordWatchKey(sample, realFile); + bucket.add(realFile); } - const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); - const repoRoot = repoRootHint ?? resolvePiResourceRepoRoot(workingDir); +} + +/** 走一遍 extensions 根:collector readdir 根、子键 realpath 后收 .ts 或 index.ts; + * watcher 盯根的条目列表、子键 mtime 与解析后的 index.ts(缺失态 -1,同刻落地也检出)。 */ +function walkPiExtensionTree( + sample: PiProjectResourceLaunchWatch, + repoRoot: string, + extDir: string, + bucket: Set, +): void { + const realExt = realpathOrNull(extDir); + const enumerated = !!realExt && isDir(realExt) && isWithinRoot(repoRoot, realExt); + recordWatchKey(sample, extDir, enumerated ? 'full' : 'none'); + if (!enumerated || !realExt) return; + for (const entry of listDir(realExt)) { + if (entry.name.startsWith('.')) continue; + const childPath = path.join(realExt, entry.name); + const realChild = realpathOrNull(childPath); + const childInRepo = !!realChild && isWithinRoot(repoRoot, realChild); + // collector 对子键只 stat(文件直接收集;目录再看 index.ts),不 readdir 子目录: + // 子键条目基线一律不读('none'),index.ts 存在性由 realIndex 键盯住(含缺失 + // 态 -1,同刻落地也检出)。 + recordWatchKey( + sample, childPath, + !childInRepo || !isDir(realChild!) || isSymlinkEntry(entry, childPath) ? 'none' : 'full'); + if (!childInRepo || !realChild) continue; + if (isFile(realChild) && realChild.endsWith('.ts')) { + bucket.add(realChild); + continue; + } + if (!isDir(realChild)) continue; + // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 + const indexPath = path.join(realChild, 'index.ts'); + recordWatchKey(sample, indexPath); + const realIndex = realpathOrNull(indexPath); + if (realIndex && isFile(realIndex) && isWithinRoot(repoRoot, realIndex)) { + bucket.add(realIndex); + } + } +} + +/** + * 项目资源表面:argv 路径集合与盯视基线的**唯一产出点**。生产调用方(spawn 采样、 + * 重扫)必须经此一次调用取两样 —— 分两次调用会重新造出「集合与基线不同批」的 + * 永久漏检窗口(Codex P2,2026-11-10)。 + */ +export function collectPiProjectResourceSurface(workingDir: string, repoRootHint?: string): PiProjectResourceSurface { + const watch: PiProjectResourceLaunchWatch = { + scanRootResolved: realpathOrNull(workingDir), + mtimes: new Map(), + entries: new Map(), + resolved: new Map(), + }; const skills = new Set(); const promptTemplates = new Set(); const extensions = new Set(); - - collectSkillDirs(repoRoot, path.join(scanRoot, '.pi', 'skills'), skills); + if (!workingDir || !path.isAbsolute(workingDir) || !isDir(workingDir)) { + return freezePiProjectResourceSurface( + repoRootHint ?? watch.scanRootResolved ?? path.resolve(workingDir), skills, promptTemplates, extensions, watch); + } + const scanRoot = watch.scanRootResolved ?? path.resolve(workingDir); + const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); + const piDir = path.join(scanRoot, '.pi'); + recordWatchKey(watch, piDir); + walkPiSkillTree(watch, repoRoot, path.join(piDir, 'skills'), skills); + walkPiPromptTargets(watch, repoRoot, path.join(piDir, 'prompts'), promptTemplates); + walkPiExtensionTree(watch, repoRoot, path.join(piDir, 'extensions'), extensions); let current = scanRoot; while (true) { - collectSkillDirs(repoRoot, path.join(current, '.agents', 'skills'), skills); + const agentsDir = path.join(current, '.agents'); + recordWatchKey(watch, agentsDir); + walkPiSkillTree(watch, repoRoot, path.join(agentsDir, 'skills'), skills); if (current === repoRoot) break; const parent = path.dirname(current); if (parent === current) break; current = parent; } + return freezePiProjectResourceSurface(repoRoot, skills, promptTemplates, extensions, watch); +} - const realPrompts = realpathOrNull(path.join(scanRoot, '.pi', 'prompts')); - if (realPrompts && isDir(realPrompts) && isWithinRoot(repoRoot, realPrompts)) { - for (const entry of listDir(realPrompts)) { - if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; - const realFile = realpathOrNull(path.join(realPrompts, entry.name)); - if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) continue; - promptTemplates.add(realFile); - } - } - - const realExt = realpathOrNull(path.join(scanRoot, '.pi', 'extensions')); - if (realExt && isDir(realExt) && isWithinRoot(repoRoot, realExt)) { - for (const entry of listDir(realExt)) { - if (entry.name.startsWith('.')) continue; - const realChild = realpathOrNull(path.join(realExt, entry.name)); - if (!realChild || !isWithinRoot(repoRoot, realChild)) continue; - if (isFile(realChild) && realChild.endsWith('.ts')) { - extensions.add(realChild); - continue; - } - if (!isDir(realChild)) continue; - const realIndex = realpathOrNull(path.join(realChild, 'index.ts')); - if (realIndex && isFile(realIndex) && isWithinRoot(repoRoot, realIndex)) { - extensions.add(realIndex); - } - } - } - +function freezePiProjectResourceSurface( + repoRoot: string, + skills: Set, + promptTemplates: Set, + extensions: Set, + watch: PiProjectResourceLaunchWatch, +): PiProjectResourceSurface { return Object.freeze({ - skills: Object.freeze([...skills].sort(comparePiResourcePaths)), - promptTemplates: Object.freeze([...promptTemplates].sort(comparePiResourcePaths)), - extensions: Object.freeze([...extensions].sort(comparePiResourcePaths)), + repoRoot, + paths: Object.freeze({ + skills: Object.freeze([...skills].sort(comparePiResourcePaths)), + promptTemplates: Object.freeze([...promptTemplates].sort(comparePiResourcePaths)), + extensions: Object.freeze([...extensions].sort(comparePiResourcePaths)), + }), + watch, }); } +/** argv 采集的兼容入口(= surface.paths)。生产路径应优先 surface 一次调用。 */ +export function collectPiProjectResourceCliPaths(workingDir: string, repoRootHint?: string): PiProjectResourceCliPaths { + return collectPiProjectResourceSurface(workingDir, repoRootHint).paths; +} + +/** 盯视采样的兼容入口(= surface.watch)。生产路径应优先 surface 一次调用。 */ +export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRootHint?: string): PiProjectResourceLaunchWatch { + return collectPiProjectResourceSurface(workingDir, repoRootHint).watch; +} + function statMtimeMs(target: string): number { try { return fs.statSync(target).mtimeMs; @@ -241,9 +374,8 @@ export interface PiProjectResourceLaunchSnapshot { /** 每个 watch root 的解析身份(realpath)。基线不只记 mtime:被盯路径的软链改指 * 同 mtime 的孪生树时,解析身份是唯一信号;与 watchRootMtimes 同 key 同批。 */ readonly watchRootsResolved: Map; - /** 每个 watch root 的 readdir 条目名指纹:时间戳粒度盲区(同一 tick 内增删, - * mtime 与基线逐位相等)的第二信号;与 watchRootMtimes 同 key 同批。null = - * collector 不枚举的键(软链 namespace/越界子树),快检跳读。 */ + /** 每个 watch root 的条目基线(完整条目名/清单存在性/null 跳读,按 collector + * 消费方式定):时间戳粒度盲区的第二信号;与 watchRootMtimes 同 key 同批。 */ readonly watchRootEntries: Map; /** 受邀者裁剪口径(非受邀者恒 null):重扫后的 fresh 集合先经它裁剪再与 paths * 比较 —— 缺了会拿全量比裁剪基线恒判漂移,回收死循环。 */ @@ -260,109 +392,45 @@ export interface PiProjectResourceLaunchWatch { /** workingDir 的解析身份,先于所有键采样(键路径都从它拼出)。 */ readonly scanRootResolved: string | null; readonly mtimes: Map; - /** key → readdir 条目名指纹(排序拼接;文件键/缺失恒 '';collector 不枚举的键 - * —— 软链 namespace/越界子树 —— 为 null,快检跳读:readdir 跟随软链,外部大 - * 目录的完整列表是每条消息一次的纯开销)。时间戳粒度盲区(同一 tick 内增删, - * mtime 与基线逐位相等)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ + /** key → 条目基线:按 collector 在该路径上的消费方式取 —— readdir 的目录存完整 + * 条目名指纹('L:' 前缀;文件键/缺失恒 'L:');软链目标存清单存在性指纹('M:' + * 前缀,namespace↔skill 迁移的同刻信号,不读完整列表);collector 不消费的键 + * (越界/悬空)为 null,快检跳读。时间戳粒度盲区(同一 tick 内增删,mtime 与 + * 基线逐位相等)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ readonly entries: Map; /** key → realpath 解析身份(缺失 null),与 mtimes 同 key 同批。 */ readonly resolved: Map; } -function recordWatchKey(sample: PiProjectResourceLaunchWatch, target: string, enumerateEntries = true): void { +function recordWatchKey( + sample: PiProjectResourceLaunchWatch, + target: string, + entries: 'full' | 'manifest' | 'none' = 'full', +): void { // 解析身份先行:身份与 mtime/条目之间的窗口不一致只会多一次重扫,不会固化。 sample.resolved.set(target, realpathOrNull(target)); sample.mtimes.set(target, statMtimeMs(target)); - // enumerateEntries=false:collector 不枚举该键的子树(软链 namespace/越界), - // 条目基线存 null,快检跳读(Greptile P2)。 - sample.entries.set(target, enumerateEntries ? readDirEntryFingerprint(target) : null); + // 条目基线按 collector 在该路径上的消费方式取,不按条目类型猜: + // 'full' = collector readdir 的目录,读完整列表; + // 'manifest' = collector 对软链目标只统计 SKILL.md/skill.md 存在性,取清单存在性 + // 指纹(2 次 stat;外部大目录也不拖快检;清单增删 = namespace↔skill + // 迁移,同刻也能检出); + // 'none' = collector 不消费该路径(越界/悬空),基线存 null 快检跳读。 + sample.entries.set(target, fingerprintEntries(target, entries)); } -/** - * 收集漂移快检要盯的目录基线(mtime + 条目指纹 + 解析身份,同一次遍历)。目录 - * 集合必须覆盖 collector 实际枚举的每一层目录:在已存在的子目录内增删条目只改 - * 该子目录自身的 mtime,父目录不动,漏盯哪层就在哪层漏检(如已有 namespace 下 - * 增删 skill、已有扩展目录内补 index.ts、已有 skill 目录内删 SKILL.md): - * - `/.pi` 本身 + `.pi/skills` / `.pi/prompts` / `.pi/extensions` - * - `.pi/skills` 与 `.agents/skills` 各自的两层 skill 树(skills 根、namespace 级、 - * namespace 内 skill 级;与 collector 的枚举深度一致,不往更深处看) - * - `.pi/extensions` 的每个子目录(index.ts 增删只改子目录 mtime) - * - cwd→git root 链上每级的 `.agents` + `.agents/skills` - * 不含 workingDir 本身:往项目根丢无关文件不应触发全量重扫。 - */ -export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRootHint?: string): PiProjectResourceLaunchWatch { - const sample: PiProjectResourceLaunchWatch = { - scanRootResolved: realpathOrNull(workingDir), - mtimes: new Map(), - entries: new Map(), - resolved: new Map(), - }; - const scanRoot = sample.scanRootResolved ?? path.resolve(workingDir); - if (!isDir(scanRoot)) return sample; - const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); - const piDir = path.join(scanRoot, '.pi'); - recordWatchKey(sample, piDir); - watchPiSkillTreeMtimes(sample, repoRoot, path.join(piDir, 'skills')); - watchPiPromptTargets(sample, path.join(piDir, 'prompts'), repoRoot); - watchPiExtensionChildMtimes(sample, repoRoot, path.join(piDir, 'extensions')); - let current = scanRoot; - while (true) { - const agentsDir = path.join(current, '.agents'); - recordWatchKey(sample, agentsDir); - watchPiSkillTreeMtimes(sample, repoRoot, path.join(agentsDir, 'skills')); - if (current === repoRoot) break; - const parent = path.dirname(current); - if (parent === current) break; - current = parent; - } - return sample; +/** 条目基线统一带模式前缀(L:=完整列表,M:=清单存在性),快检按前缀选同一函数 + * 重算 —— 存取同口径,比较不会串档。 */ +function fingerprintEntries(target: string, mode: 'full' | 'manifest' | 'none'): string | null { + if (mode === 'none') return null; + return mode === 'manifest' + ? `M:${readSkillManifestFingerprint(target)}` + : `L:${readDirEntryFingerprint(target)}`; } -/** - * stat 一个 skills 根及其下 collector 实际枚举的两层子目录。statSync 跟随符号 - * 链接:软链 skill 的增删由父目录 mtime 捕获,软链目标内的 SKILL.md 增删由目标 - * 目录 mtime 捕获,与 realpath 收集口径一致。跳过 collector 不枚举的子树 - * (隐藏/bak、软链 namespace、剪枝名),避免无关变化触发无谓重扫。 - */ -function watchPiSkillTreeMtimes(sample: PiProjectResourceLaunchWatch, repoRoot: string, skillsDir: string): void { - // 与 collector 同一门禁:缺失/越界(repoRoot 外)的 skills 根不枚举 —— 条目 - // 基线存 null(快检跳读;readdir 跟随软链,外部大目录的完整列表是每条消息 - // 一次的纯开销,Greptile P2),下行枚举一并跳过;改指信号由解析身份承担。 - const skillsResolved = realpathOrNull(skillsDir); - const enumerated = !!skillsResolved && isDir(skillsResolved) && isWithinRoot(repoRoot, skillsResolved); - recordWatchKey(sample, skillsDir, enumerated); - if (!enumerated) return; - for (const entry of listDir(skillsDir)) { - if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; - const childPath = path.join(skillsDir, entry.name); - const realChild = realpathOrNull(childPath); - const childInRepo = !!realChild && isDir(realChild) && isWithinRoot(repoRoot, realChild); - // 软链 namespace/越界子树:collector 不枚举其内部,不读条目基线(纯开销); - // 解析身份与 mtime 仍记录(改指/悬空链落地仍能检出)。 - const childIsSymlink = isSymlinkEntry(entry, childPath); - recordWatchKey(sample, childPath, childInRepo && !childIsSymlink); - if (!childInRepo || !realChild) continue; - // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, - // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 - // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, - // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 - watchPiSkillManifestTargets(sample, realChild); - if (childIsSymlink) continue; - if (hasSkillFile(realChild)) continue; // skill 目录:collector 不再往里枚举 - if (shouldPruneSkillScanDirectory(entry.name)) continue; // collector 剪枝的 namespace - for (const nested of listDir(realChild)) { - if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; - if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; - const nestedPath = path.join(realChild, nested.name); - const realNested = realpathOrNull(nestedPath); - const nestedInRepo = !!realNested && isDir(realNested) && isWithinRoot(repoRoot, realNested); - recordWatchKey(sample, nestedPath, nestedInRepo && !isSymlinkEntry(nested, nestedPath)); - if (!nestedInRepo || !realNested) continue; - // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 - watchPiSkillManifestTargets(sample, realNested); - } - } +/** 软链目标的清单存在性指纹(namespace↔skill 迁移的同刻信号);文件/缺失恒 ''。 */ +function readSkillManifestFingerprint(dir: string): string { + return ['SKILL.md', 'skill.md'].filter((name) => isFile(path.join(dir, name))).join(','); } /** 软链清单本体:SKILL.md/skill.md 为指向仓内目标的软链时,目标移动/删除不改变 @@ -383,55 +451,6 @@ function watchPiSkillManifestTargets(sample: PiProjectResourceLaunchWatch, realF } } -/** stat 一个 extensions 根及其子目录:已有扩展目录内 index.ts 增删只改子目录 mtime。 */ -function watchPiExtensionChildMtimes(sample: PiProjectResourceLaunchWatch, repoRoot: string, extDir: string): void { - // 与 collector 同一门禁:缺失/越界的 extensions 根不枚举(条目基线 null,快检跳读)。 - const extResolved = realpathOrNull(extDir); - const enumerated = !!extResolved && isDir(extResolved) && isWithinRoot(repoRoot, extResolved); - recordWatchKey(sample, extDir, enumerated); - if (!enumerated) return; - for (const entry of listDir(extDir)) { - if (entry.name.startsWith('.')) continue; - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; - const childPath = path.join(extDir, entry.name); - const realChild = realpathOrNull(childPath); - // collector 只 readdir extensions 自身,不枚举子目录:软链/越界子键不读条目基线。 - recordWatchKey( - sample, childPath, - !!realChild && isDir(realChild) && isWithinRoot(repoRoot, realChild) && !isSymlinkEntry(entry, childPath)); - if (!realChild || !isDir(realChild)) continue; - // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 - const realIndex = path.join(realChild, 'index.ts'); - recordWatchKey(sample, realIndex); - } -} - -/** - * stat 一个 prompts 根及其中 collector 实际接受的每个模板文件的**解析后目标**: - * `.pi/prompts/foo.md` 为仓内符号链接时,链接自身的增删由 prompts 根 mtime 捕获, - * 但目标文件的移动/删除只改目标处。statSync 跟随软链,目标缺失时为 -1,与 - * realpath 收集口径一致。枚举条件与 collector 逐条对应(隐藏/非 .md 跳过)。 - */ -function watchPiPromptTargets(sample: PiProjectResourceLaunchWatch, promptsDir: string, repoRoot: string): void { - // 与 collector 同一门禁:缺失/越界的 prompts 根不枚举(条目基线 null,快检跳读)。 - const promptsResolved = realpathOrNull(promptsDir); - const enumerated = !!promptsResolved && isDir(promptsResolved) && isWithinRoot(repoRoot, promptsResolved); - recordWatchKey(sample, promptsDir, enumerated); - if (!enumerated) return; - for (const entry of listDir(promptsDir)) { - if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; - const entryPath = path.join(promptsDir, entry.name); - const realFile = realpathOrNull(entryPath); - if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) { - // 悬空软链(或目标越界):把链接自身入盯视 —— 目标落地时 statSync 解析到 - // 新 mtime(未盯视目录里的变化也能触发重扫);普通文件不存在此形态。 - if (entry.isSymbolicLink()) recordWatchKey(sample, entryPath); - continue; - } - recordWatchKey(sample, realFile); - } -} - /** * 冻结一份启动快照。watch 采样(含解析身份与 scanRoot 身份)与 repoRoot 必须由 * 调用方在收集 paths **之前**采样传入(见 pi/index.ts 调用点):身份基线晚于 argv @@ -519,25 +538,26 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps break; } } - // 条目名指纹:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 - // null = collector 不枚举的键(软链 namespace/越界子树),跳读(Greptile P2)。 + // 条目基线:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 + // null = collector 不消费的键,跳读;前缀(L:/M:)选与采集同一函数重算。 let entriesChanged = false; for (const [dir, fingerprintAtLaunch] of snapshot.watchRootEntries) { if (fingerprintAtLaunch === null) continue; - if (readDirEntryFingerprint(dir) !== fingerprintAtLaunch) { + const actual = fingerprintAtLaunch.startsWith('M:') + ? `M:${readSkillManifestFingerprint(dir)}` + : `L:${readDirEntryFingerprint(dir)}`; + if (actual !== fingerprintAtLaunch) { entriesChanged = true; break; } } if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedRootChanged && !mtimeChanged && !entriesChanged) return false; - // 重扫与启动同序:先采样 watch 基线,再收集路径 —— 重扫窗口内新增的资源落在 - // 基线之后,下次快检仍会检出;反序(先路径后基线)会把新 mtime 与旧集合固化在 - // 一起,静默漏检。 - const freshRoots = collectPiProjectResourceLaunchWatch(snapshot.workingDir, repoRoot); - const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir, repoRoot); + // 重扫 = 一次 surface 调用:集合与盯视基线同批(与启动同口径),不存在 + // 「基线采完、集合没采到」的窗口。 + const fresh = collectPiProjectResourceSurface(snapshot.workingDir, repoRoot); // 受邀者:比较前对 fresh 做与启动相同的裁剪,否则全量比裁剪基线恒判漂移。 - const freshForCompare = snapshot.restrict ? snapshot.restrict(fresh) : fresh; + const freshForCompare = snapshot.restrict ? snapshot.restrict(fresh.paths) : fresh.paths; if (!( samePiResourceList(freshForCompare.skills, snapshot.paths.skills) && samePiResourceList(freshForCompare.promptTemplates, snapshot.paths.promptTemplates) @@ -560,11 +580,11 @@ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnaps if (realpathOrNull(dir) !== resolvedAtSignal) return true; } snapshot.watchRootMtimes.clear(); - for (const [dir, mtime] of freshRoots.mtimes) snapshot.watchRootMtimes.set(dir, mtime); + for (const [dir, mtime] of fresh.watch.mtimes) snapshot.watchRootMtimes.set(dir, mtime); snapshot.watchRootsResolved.clear(); - for (const [dir, resolved] of freshRoots.resolved) snapshot.watchRootsResolved.set(dir, resolved); + for (const [dir, resolved] of fresh.watch.resolved) snapshot.watchRootsResolved.set(dir, resolved); snapshot.watchRootEntries.clear(); - for (const [dir, fingerprint] of freshRoots.entries) snapshot.watchRootEntries.set(dir, fingerprint); + for (const [dir, fingerprint] of fresh.watch.entries) snapshot.watchRootEntries.set(dir, fingerprint); snapshot.state.repoRoot = repoRoot; snapshot.state.resolvedWorkingDir = resolvedWorkingDir; return false; From 5712876fa4f201f027a814e8c00cc0d1475e02be Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 20:34:32 +0800 Subject: [PATCH 38/45] =?UTF-8?q?fix(pi):=20=E9=A1=B9=E7=9B=AE=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E9=87=87=E6=A0=B7=E4=BA=A4=E9=94=99=E4=B8=8E=E5=9B=9E?= =?UTF-8?q?=E6=94=B6=E5=A4=B1=E8=B4=A5=E7=9A=84=E6=BC=8F=E6=A3=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 采样(argv 与基线):collector 先判清单存在性、再记基线,安装器在这两步之间写入 SKILL.md 会让 argv 漏这条技能而基线已含,快检此后恒等 → 该技能永久不生效。改为 清单存在性与基线条目出自同一次 readdir 采样:交错只可能让 argv 领先基线,下次快检 观察差异后收敛。 回收失败(hook 与 IM 两条投递链):close 抛出时 Session 已停在 error,原逻辑「保持 原样投递」会把轮次发给坏实例、被 ensureActive 拒且永远绕过重建;现在实例不再是 active 时走重建,仍是 active 才原样投递(Codex P2, 2026-11-10)。 Signed-off-by: Zhang Yunjin --- .../__tests__/session-runner.test.ts | 25 +- .../src/main/hook-control/session-runner.ts | 4 +- apps/desktop/src/main/im/shared/turnRunner.ts | 7 +- .../pi-project-resource-drift.test.ts | 47 ++- .../src/agents/pi/project-resource-cli.ts | 325 ++++++++++-------- 5 files changed, 262 insertions(+), 146 deletions(-) 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 a5823f20ec..a9cff77a61 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 @@ -345,8 +345,13 @@ function makePermissionModeFake() { /** fake maker: createSession 返回"send 即接受、随后立刻 done"的会话。 */ function makeFakeSession(id: string) { const permission = makePermissionModeFake(); + let status: 'active' | 'aborting' | 'closed' | 'error' = 'active'; return { id, + getStatus: () => status, + /** 测试注入:模拟 close 失败后 Session 停在 error(回收抛出的同款后果)。 */ + __setStatus: (next: 'active' | 'aborting' | 'closed' | 'error') => { status = next; }, + ...({ instanceId: `instance-${id}` } as { instanceId?: string }), workDir: 'D:/repo', get permissionModeState() { @@ -835,7 +840,7 @@ describe('hook task model selection on next send', () => { }); it('keeps delivering on the live instance when the recycle itself fails', async () => { - // 回收本身失败 → 旧实例仍可用:原样投递(hook 轮次不因回收故障中断)。 + // 回收本身失败但实例仍 active → 原样投递(hook 轮次不因回收故障中断)。 const session = makeFakeSession('sess-new'); session.send.mockResolvedValue({ accepted: true }); fakeMaker.createSession.mockResolvedValueOnce(session); @@ -849,6 +854,24 @@ describe('hook task model selection on next send', () => { 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'); + broken.__setStatus('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 }))) diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts index 211690ce1c..bbed1c1766 100644 --- a/apps/desktop/src/main/hook-control/session-runner.ts +++ b/apps/desktop/src/main/hook-control/session-runner.ts @@ -982,7 +982,9 @@ export function createMakerHookSessionRunner(deps: { try { driftedRecycled = await maker.recyclePiRuntimeIfResourcesDrifted(session); } catch { - // 保持原样投递 + // 回收抛出时 Session 已停在 error(close 失败不回退),旧实例不可用 —— + // 继续投递只会被 ensureActive 拒,必须走重建(Codex P2,2026-11-10)。 + driftedRecycled = session.getStatus() !== 'active'; } if (driftedRecycled) { try { diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index ce77e19147..cd9b871e6b 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1665,7 +1665,12 @@ export function createTurnRunner( driftRecycled = !!(deps.acquirePendingAgentSwitch && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)); } catch (err) { - log.warn('im send: resource-drift recycle failed, sending as-is', + // 两种失败必须分开:close 抛出时 Session 已停在 error(Session.performClose + // 不因异常回退),旧实例不可用 —— 这时继续 send 只会被 ensureActive 抛错, + // runner 永远绑在坏实例上、绕过 createSession 重建路径(Codex P2, + // 2026-11-10)。无 agent-switch 锁的装配不支持重建,保持原样投递。 + driftRecycled = !!deps.acquirePendingAgentSwitch && state.makerSession.getStatus() !== 'active'; + log.warn('im send: resource-drift recycle failed', err instanceof Error ? err.message : String(err)); } if (driftRecycled) { 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 index c754ada2ff..b4752c8926 100644 --- 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 @@ -9,10 +9,11 @@ * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 */ +import fs from 'node:fs'; import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { collectPiProjectResourceCliPaths, collectPiProjectResourceLaunchWatch, @@ -306,7 +307,44 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('detects a manifest added inside an in-repo direct-linked skill within the same tick', () => { + it('keeps argv and baseline consistent when a manifest lands during the walk (no permanent miss)', () => { + // 回归(Greptile P2):「读清单存在性」早于「记基线」时,安装器在这两步之间 + // 写入 SKILL.md → 基线记写后、argv 记写前 → 快检恒等、该 skill 永久不生效。 + // 现在判断输入与基线同一次采样产出,交错只可能让 argv 领先基线(可收敛), + // 不可能落后。 + writeFileSync(path.join(project, '.git'), ''); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + mkdirSync(path.join(project, '.pi', 'skills', 'foo'), { recursive: true }); + const skillsDir = path.join(realpathSync(project), '.pi', 'skills'); + const fooDir = path.join(skillsDir, 'foo'); + const originalReaddir = fs.readdirSync as typeof fs.readdirSync; + let injected = false; + const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => { + // 在「枚举 foo 目录」这一次读之前落地 SKILL.md:模拟安装器与采样的交错。 + if (!injected && String(target) === fooDir) { + injected = true; + writeFileSync(path.join(fooDir, 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); + } + return (originalReaddir as never as (t: fs.PathLike, o?: unknown) => unknown)(target, options); + }) as never); + let surface; + try { + surface = collectPiProjectResourceSurface(project); + } finally { + spy.mockRestore(); + } + expect(injected).toBe(true); + const baseline = snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch); + // 断言「argv 与基线一致」:技能要么被收集,要么基线不含它; + // 两者任一成立都可在后续收敛,唯独不能「argv 漏收而基线已含」。 + const collectedFoo = surface.paths.skills.includes(fooDir); + const baselineHasManifest = (surface.watch.entries.get(fooDir) ?? '').includes('SKILL.md'); + expect(collectedFoo).toBe(true); + expect(baselineHasManifest).toBe(collectedFoo); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + + it('detects a manifest installed between the sample and the decision (per-key single read)', () => { // 回归(Greptile P2 直链技能):collector 对仓内软链目标消费清单存在性 —— // 软键条目基线必须取清单存在性而非跳读,否则目标内同刻新增 SKILL.md // (namespace→skill 迁移)四路信号全盲:目标 mtime 量化等值、链接身份不变、 @@ -319,9 +357,10 @@ describe('piProjectResourcesDrifted', () => { symlinkSync(path.join(project, 'target-dir'), path.join(project, '.pi', 'skills', 'foo'), 'junction'); const baseline = snapshot(); expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 前提:仓内软键的条目基线是清单存在性指纹('M:' 前缀 + 空清单),不是 null + // 前提:仓内软键以完整条目列表为基线('L:' + 空目录),与判断输入同一次 readdir —— + // 而非旧实现的「先读 hasManifest 再记基线」两步窗口 const linkKey = path.join(realpathSync(project), '.pi', 'skills', 'foo'); - expect(baseline.watchRootEntries.get(linkKey)).toBe('M:'); + expect(baseline.watchRootEntries.get(linkKey)).toBe('L:'); // 同一刻新增普通文件 SKILL.md(显式把目标目录 mtime 恢复基线值,隔离 mtime 信号) writeFileSync(path.join(project, 'target-dir', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); utimesSync(path.join(project, 'target-dir'), aligned, aligned); 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 18eadb7d30..7c2f2fdecd 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -79,14 +79,6 @@ function isWithinRoot(root: string, candidate: string): boolean { return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)); } -function listDir(dir: string): fs.Dirent[] { - try { - return fs.readdirSync(dir, { withFileTypes: true }); - } catch { - return []; - } -} - function isSymlinkDirectory(target: string): boolean { try { return fs.lstatSync(target).isSymbolicLink(); @@ -102,19 +94,29 @@ 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))); +/** 从同一次 readdir 的条目里判定 skill 清单存在性(collector 口径:isFile 跟随 + * 软链)。软链清单要先解析目标是否为文件—— 这次读发生在该键基线之后,只会让 + * argv 领先基线,下次快检观察差异后收敛,不会永久漏检。 */ +function skillManifestIn(dir: string, dirents: readonly fs.Dirent[]): boolean { + for (const entry of dirents) { + if (entry.name !== 'SKILL.md' && entry.name !== 'skill.md') continue; + if (entry.isFile()) return true; + if (entry.isSymbolicLink() && isFile(path.join(dir, entry.name))) return true; + } + return false; } /** - * 项目资源表面 = argv 路径集合 + 盯视基线,出自**同一次遍历**。 + * 项目资源表面 = argv 路径集合 + 盯视基线,**同一次遍历**产出。 * - * 结构不变量(2026-11-10,取代逐案修补):argv 与基线出自同一遍历,所以「基线 ≠ - * argv 消费的状态」在结构上不可能;快检只需检测「盘上 ≠ 基线」。此前全部盲区 - * (身份晚于收集、窗口复核比错基线、软链键跳读过头)都源于 collector 与 watcher - * 两套手写遍历的分歧 —— 合一后分歧不再可能。每个键的条目模式在遍历点按 collector - * 的消费方式确定:'full'=collector readdir 的目录;'manifest'=collector 只 stat - * SKILL.md/skill.md 存在性的软链目标/已知 skill 目录;'none'=不消费(越界/悬空)。 + * 结构不变量(逐键,2026-11-10 根因收口):一个键的基线字段与该键上的 argv 判断 + * 出自**同一次采样**(samplePiWatchKey),判断不早于基线、也不另发读。任何采样后 + * 的变化都会被快检观察为差异 → 重扫 → 集合相同则刷新基线后收敛;不存在「基线已 + * 含新状态、argv 还是旧状态」的永久漏检。 + * + * 历史教训:collector 与 watcher 曾是两套手写遍历(口径靠注释),后又只合并了 + * 遍历但保留键内两次读 —— 两次都是同一病根:同一事实产生两次,漂移检测就在两者 + * 之间漏。条目模式由**结构**决定(见 PiWatchEntriesMode),不看内容。 */ export interface PiProjectResourceSurface { /** 本遍历认定的 git root(枚举链终点;调用方作为快照边界基线传入)。 */ @@ -124,19 +126,22 @@ export interface PiProjectResourceSurface { } /** 把一个 skill 目录登记进集合(collector 口径:清单经 realpath 后须在仓内, - * realFolder 本身入集合)。 */ + * realFolder 本身入集合)。此次校验性读发生在该键基线之后 —— 安全方向。 */ function addPiSkill(repoRoot: string, realFolder: string, bucket: Set): void { - const skillMd = ['SKILL.md', 'skill.md'] - .map((name) => path.join(realFolder, name)) - .find(isFile); - const realMd = skillMd ? realpathOrNull(skillMd) : null; - if (realMd && isFile(realMd) && isWithinRoot(repoRoot, realMd)) bucket.add(realFolder); + for (const name of ['SKILL.md', 'skill.md']) { + const manifestPath = path.join(realFolder, name); + if (!isFile(manifestPath)) continue; + const realMd = realpathOrNull(manifestPath); + if (realMd && isWithinRoot(repoRoot, realMd)) { + bucket.add(realFolder); + return; + } + } } /** - * 走一遍 skills 根的两层树(collector 的枚举 = watcher 的盯视,同一循环): - * 每层先记键(身份/mtime/条目基线,模式按 collector 在此路径的消费方式), - * 再做 collector 的集合判定。 + * 走一遍 skills 根的两层树:每个键先采样(基线 + 判断输入),再用采样返回值做 + * collector 的集合判定 —— 全程不再发第二次读。 */ function walkPiSkillTree( sample: PiProjectResourceLaunchWatch, @@ -144,124 +149,90 @@ function walkPiSkillTree( skillsDir: string, bucket: Set, ): void { - const resolvedDir = realpathOrNull(skillsDir); - const enumerated = !!resolvedDir && isDir(resolvedDir) && isWithinRoot(repoRoot, resolvedDir); - // collector readdir 该根(仓内时)→ 'full';缺失/越界 → 不消费 → 'none' - // (readdir 跟随软链,外部大目录的完整列表是纯开销)。 - recordWatchKey(sample, skillsDir, enumerated ? 'full' : 'none'); - if (!enumerated || !resolvedDir) return; + const root = samplePiWatchKey(sample, skillsDir, 'dir', repoRoot); + if (!root.inRepoDir || !root.resolved) return; - for (const entry of listDir(resolvedDir)) { + for (const entry of root.dirents ?? []) { if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; - const candidatePath = path.join(resolvedDir, entry.name); - const realFolder = realpathOrNull(candidatePath); - const folderInRepo = !!realFolder && isDir(realFolder) && isWithinRoot(repoRoot, realFolder); - if (!folderInRepo || !realFolder) { - // collector 不消费(悬空/越界);身份与 mtime 保留 —— 改指/目标落地仍可检出。 - recordWatchKey(sample, candidatePath, 'none'); - continue; - } + const candidatePath = path.join(root.resolved, entry.name); + // 一层子键一律 'dir'(完整条目列表):collector 要么在此收 skill、要么下行 + // 枚举 namespace —— 两条路都依赖该目录的条目集合,只有完整列表能检出同刻新增 + // 的嵌套 skill 目录。模式不依赖 hasManifest(那是旧 bug 的两次读窗口)。 + const child = samplePiWatchKey(sample, candidatePath, 'dir', repoRoot); + if (!child.inRepoDir || !child.resolved) continue; const isSymlink = isSymlinkEntry(entry, candidatePath); - const hasManifest = hasSkillFile(realFolder); - // collector 消费方式:软链目标与已知 skill 目录只 stat 清单存在性('manifest', - // namespace↔skill 迁移的同刻信号,不读目标完整列表);将下行枚举的 namespace - // 目录读完整列表('full')。 - recordWatchKey(sample, candidatePath, isSymlink || hasManifest ? 'manifest' : 'full'); // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 - // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处, - // 跟随后的目录与 skills 根 mtime 都不动,必须先记清单本体再跳过软链目录。 - watchPiSkillManifestTargets(sample, realFolder); - if (hasManifest) { - addPiSkill(repoRoot, realFolder, bucket); + // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处。 + watchPiSkillManifestTargets(sample, child.resolved, repoRoot); + // 判断输入与基线同源(Greptile P2:先 hasManifest 再记基线 → 中间写入的 + // SKILL.md 被固化进基线、argv 漏收 → 永久漏检)。 + if (skillManifestIn(child.resolved, child.dirents ?? [])) { + addPiSkill(repoRoot, child.resolved, bucket); continue; } - // Direct symlinked Skills remain supported above; a symlinked namespace - // could escape the repo or cycle and is intentionally not walked. - // lstat must see the unresolved path: a Windows junction may be reported - // as a directory by readdir and by the resolved realpath. + // 软链 namespace collector 明文不走(可越界/成环);剪枝名同理。 if (isSymlink || shouldPruneSkillScanDirectory(entry.name)) continue; // At most one namespace/author level: //. - for (const nested of listDir(realFolder)) { + for (const nested of child.dirents ?? []) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; - const nestedPath = path.join(realFolder, nested.name); - const realNested = realpathOrNull(nestedPath); - const nestedInRepo = !!realNested && isDir(realNested) && isWithinRoot(repoRoot, realNested); - // collector 对嵌套层只 stat 清单存在性(不再下行)→ 仓内一律 'manifest'。 - recordWatchKey(sample, nestedPath, nestedInRepo ? 'manifest' : 'none'); - if (!nestedInRepo || !realNested) continue; - // 同上层:悬空的嵌套清单(.pi/skills/@scope/foo/SKILL.md 为悬空软链)也要盯住本体 - watchPiSkillManifestTargets(sample, realNested); - if (hasSkillFile(realNested)) addPiSkill(repoRoot, realNested, bucket); + const nestedPath = path.join(child.resolved, nested.name); + // 嵌套层 collector 只 stat 清单存在性、不再下行 → 'skill'(两次 stat)。 + const nestedSample = samplePiWatchKey(sample, nestedPath, 'skill', repoRoot); + if (!nestedSample.inRepoDir || !nestedSample.resolved) continue; + watchPiSkillManifestTargets(sample, nestedSample.resolved, repoRoot); + if (nestedSample.manifest) addPiSkill(repoRoot, nestedSample.resolved, bucket); } } } -/** 走一遍 prompts 根:collector readdir 根、逐文件 realpath 后入集合;watcher 盯 - * 根的条目列表与每个解析后目标(mtime),悬空软链盯链接本体。 */ +/** 走一遍 prompts 根:根的采样条目既进基线也驱动枚举;每个模板以**链接路径** + * 采样(stat 跟随软链:悬空时 mtime=-1,目标落地即变),resolved 直接作为 argv + * 路径 —— 不再单独 realpath 后再比。 */ function walkPiPromptTargets( sample: PiProjectResourceLaunchWatch, repoRoot: string, promptsDir: string, bucket: Set, ): void { - const realPrompts = realpathOrNull(promptsDir); - const enumerated = !!realPrompts && isDir(realPrompts) && isWithinRoot(repoRoot, realPrompts); - recordWatchKey(sample, promptsDir, enumerated ? 'full' : 'none'); - if (!enumerated || !realPrompts) return; - for (const entry of listDir(realPrompts)) { + const root = samplePiWatchKey(sample, promptsDir, 'dir', repoRoot); + if (!root.inRepoDir || !root.resolved) return; + for (const entry of root.dirents ?? []) { if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; - const entryPath = path.join(realPrompts, entry.name); - const realFile = realpathOrNull(entryPath); - if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) { - // 悬空软链(或目标越界):把链接自身入盯视 —— 目标落地时 statSync 解析到 - // 新 mtime(未盯视目录里的变化也能触发重扫);普通文件不存在此形态。 - if (entry.isSymbolicLink()) recordWatchKey(sample, entryPath); - continue; - } - recordWatchKey(sample, realFile); - bucket.add(realFile); + const entryPath = path.join(root.resolved, entry.name); + const target = samplePiWatchKey(sample, entryPath, 'none', repoRoot); + // 悬空/越界目标不收集;链接自身已入盯视(mtime 跟随目标,落地即检出)。 + if (!target.isFile || !target.resolved || !isWithinRoot(repoRoot, target.resolved)) continue; + bucket.add(target.resolved); } } -/** 走一遍 extensions 根:collector readdir 根、子键 realpath 后收 .ts 或 index.ts; - * watcher 盯根的条目列表、子键 mtime 与解析后的 index.ts(缺失态 -1,同刻落地也检出)。 */ +/** 走一遍 extensions 根:根条目同时驱动基线/枚举;子键与 index.ts 以 'none' 采样 + * (文件键;缺失时 mtime=-1 → 同刻落地也必变),判断直接用采样返回值。 */ function walkPiExtensionTree( sample: PiProjectResourceLaunchWatch, repoRoot: string, extDir: string, bucket: Set, ): void { - const realExt = realpathOrNull(extDir); - const enumerated = !!realExt && isDir(realExt) && isWithinRoot(repoRoot, realExt); - recordWatchKey(sample, extDir, enumerated ? 'full' : 'none'); - if (!enumerated || !realExt) return; - for (const entry of listDir(realExt)) { + const root = samplePiWatchKey(sample, extDir, 'dir', repoRoot); + if (!root.inRepoDir || !root.resolved) return; + for (const entry of root.dirents ?? []) { if (entry.name.startsWith('.')) continue; - const childPath = path.join(realExt, entry.name); - const realChild = realpathOrNull(childPath); - const childInRepo = !!realChild && isWithinRoot(repoRoot, realChild); - // collector 对子键只 stat(文件直接收集;目录再看 index.ts),不 readdir 子目录: - // 子键条目基线一律不读('none'),index.ts 存在性由 realIndex 键盯住(含缺失 - // 态 -1,同刻落地也检出)。 - recordWatchKey( - sample, childPath, - !childInRepo || !isDir(realChild!) || isSymlinkEntry(entry, childPath) ? 'none' : 'full'); - if (!childInRepo || !realChild) continue; - if (isFile(realChild) && realChild.endsWith('.ts')) { - bucket.add(realChild); + const childPath = path.join(root.resolved, entry.name); + const child = samplePiWatchKey(sample, childPath, 'none', repoRoot); + if (!child.resolved || !isWithinRoot(repoRoot, child.resolved)) continue; + if (child.isFile && child.resolved.endsWith('.ts')) { + bucket.add(child.resolved); continue; } - if (!isDir(realChild)) continue; - // 软链 index.ts 的目标增删只改目标处,collector 按解析路径收集,盯住解析后的本体。 - const indexPath = path.join(realChild, 'index.ts'); - recordWatchKey(sample, indexPath); - const realIndex = realpathOrNull(indexPath); - if (realIndex && isFile(realIndex) && isWithinRoot(repoRoot, realIndex)) { - bucket.add(realIndex); + if (!child.isDir) continue; + const index = samplePiWatchKey(sample, path.join(child.resolved, 'index.ts'), 'none', repoRoot); + if (index.isFile && index.resolved && isWithinRoot(repoRoot, index.resolved)) { + bucket.add(index.resolved); } } } @@ -288,14 +259,14 @@ export function collectPiProjectResourceSurface(workingDir: string, repoRootHint const scanRoot = watch.scanRootResolved ?? path.resolve(workingDir); const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); const piDir = path.join(scanRoot, '.pi'); - recordWatchKey(watch, piDir); + recordWatchKey(watch, piDir, 'dir', repoRoot); walkPiSkillTree(watch, repoRoot, path.join(piDir, 'skills'), skills); walkPiPromptTargets(watch, repoRoot, path.join(piDir, 'prompts'), promptTemplates); walkPiExtensionTree(watch, repoRoot, path.join(piDir, 'extensions'), extensions); let current = scanRoot; while (true) { const agentsDir = path.join(current, '.agents'); - recordWatchKey(watch, agentsDir); + recordWatchKey(watch, agentsDir, 'dir', repoRoot); walkPiSkillTree(watch, repoRoot, path.join(agentsDir, 'skills'), skills); if (current === repoRoot) break; const parent = path.dirname(current); @@ -392,40 +363,111 @@ export interface PiProjectResourceLaunchWatch { /** workingDir 的解析身份,先于所有键采样(键路径都从它拼出)。 */ readonly scanRootResolved: string | null; readonly mtimes: Map; - /** key → 条目基线:按 collector 在该路径上的消费方式取 —— readdir 的目录存完整 - * 条目名指纹('L:' 前缀;文件键/缺失恒 'L:');软链目标存清单存在性指纹('M:' - * 前缀,namespace↔skill 迁移的同刻信号,不读完整列表);collector 不消费的键 - * (越界/悬空)为 null,快检跳读。时间戳粒度盲区(同一 tick 内增删,mtime 与 - * 基线逐位相等)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ + /** key → 条目基线,由 samplePiWatchKey 与 argv 判断输入同一次采样产出 —— + * 'L:' 完整条目名列表(collector readdir 的目录)/'M:' 清单存在性(collector + * 只 stat SKILL.md/skill.md 的键)/null(collector 不消费)。时间戳粒度盲区 + * (同一 tick 内增删)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ readonly entries: Map; - /** key → realpath 解析身份(缺失 null),与 mtimes 同 key 同批。 */ + /** key → realpath 解析身份(缺失 null),与 mtimes 同键同次采样。 */ readonly resolved: Map; } +/** + * 单键采样模式 = collector 在该路径上到底消费什么。由**结构**决定,不看内容: + * 依赖内容会让「读内容定模式」自身变成新的两次读窗口(2026-11-10 Greptile P2)。 + * - 'dir' collector 会 readdir 的目录 → 完整条目名列表; + * - 'skill' collector 只 stat SKILL.md/skill.md 存在性 → 清单存在性; + * - 'none' collector 不消费(文件/越界/悬空/只 stat 的子键)→ 跳读。 + * 'dir'/'skill' 都由采样器自行门禁:目标须是仓内真实目录,否则指纹为 null —— + * 仓外大目录永远不会被 readdir(每条消息一次的快检不会拖着同步 IO 走路)。 + */ +export type PiWatchEntriesMode = 'dir' | 'skill' | 'none'; + +/** + * 单键采样产出:基线字段 + argv 判断所需的全部输入,均出自这一次采样。 + * + * **不变量(逐键,2026-11-10 根因收口)**:一个键的基线字段与该键上的 argv 判断, + * 必须出自同一次采样;判断不得早于该键的基线,也不得另发读操作。 + * 反例(Greptile P2):先 hasSkillFile() 再记基线,安装器在这两步之间写入 + * SKILL.md → 基线记的是写后状态、argv 还是写前 → 后续快检恒等、该 skill 永久 + * 不生效。只靠注释约束不了,所以判断输入统一由采样返回值提供。 + * + * 采样后发生的任何变化都安全:基线不会比判断更新,快检必然观察差异 → 重扫 → + * 集合相同则刷新基线后收敛(不会永久漏检,最多多一次重扫)。 + */ +export interface PiWatchKeySample { + /** 解析身份(realpath,跟随软链);缺失 null。 */ + readonly resolved: string | null; + /** stat mtime(跟随软链);缺失 -1。 */ + readonly mtime: number; + readonly isFile: boolean; + readonly isDir: boolean; + /** 目标是否仓内真实目录(决定 'dir'/'skill' 是否采指纹)。 */ + readonly inRepoDir: boolean; + /** 'dir' 模式:与条目基线同一次 readdir 的条目;其余 null。 */ + readonly dirents: readonly fs.Dirent[] | null; + /** 'skill' 模式:与清单基线同一次判断的存在性;其余 false。 */ + readonly manifest: boolean; +} + +/** + * 采样一个 watch 键:一次 realpath + 一次 stat + 至多一次内容读,同时写入基线并 + * 返回给调用方做 argv 判断。基线与判断输入同源,**调用方不得对该键另发读**。 + */ +function samplePiWatchKey( + sample: PiProjectResourceLaunchWatch, + target: string, + mode: PiWatchEntriesMode, + repoRoot: string, +): PiWatchKeySample { + // 顺序固定:realpath → stat → 内容。基线先落盘,内容读既进指纹也回给调用方。 + const resolved = realpathOrNull(target); + let stats: fs.Stats | null = null; + try { + stats = fs.statSync(target); + } catch { + stats = null; + } + const isDirectory = stats?.isDirectory() ?? false; + const inRepoDir = isDirectory && !!resolved && isWithinRoot(repoRoot, resolved); + let dirents: readonly fs.Dirent[] | null = null; + let manifest = false; + let fingerprint: string | null = null; + if (mode === 'dir' && inRepoDir) { + try { + dirents = fs.readdirSync(target, { withFileTypes: true }); + } catch { + dirents = null; + } + fingerprint = `L:${(dirents ?? []).map((entry) => entry.name).sort().join('\n')}`; + } else if (mode === 'skill' && inRepoDir) { + const names = ['SKILL.md', 'skill.md'].filter((name) => isFile(path.join(target, name))); + manifest = names.length > 0; + fingerprint = `M:${names.join(',')}`; + } + sample.resolved.set(target, resolved); + sample.mtimes.set(target, stats ? stats.mtimeMs : -1); + sample.entries.set(target, fingerprint); + return { + resolved, + mtime: stats ? stats.mtimeMs : -1, + isFile: stats?.isFile() ?? false, + isDir: isDirectory, + inRepoDir, + dirents, + manifest, + }; +} + +/** 只记基线、不需要判断输入的键(丢弃采样返回值)。repoRoot 必传 —— 默认成 + * 目标的写法会让仓外目录也走进 readdir,等于把性能 P2 重新埋回。 */ function recordWatchKey( sample: PiProjectResourceLaunchWatch, target: string, - entries: 'full' | 'manifest' | 'none' = 'full', + mode: PiWatchEntriesMode, + repoRoot: string, ): void { - // 解析身份先行:身份与 mtime/条目之间的窗口不一致只会多一次重扫,不会固化。 - sample.resolved.set(target, realpathOrNull(target)); - sample.mtimes.set(target, statMtimeMs(target)); - // 条目基线按 collector 在该路径上的消费方式取,不按条目类型猜: - // 'full' = collector readdir 的目录,读完整列表; - // 'manifest' = collector 对软链目标只统计 SKILL.md/skill.md 存在性,取清单存在性 - // 指纹(2 次 stat;外部大目录也不拖快检;清单增删 = namespace↔skill - // 迁移,同刻也能检出); - // 'none' = collector 不消费该路径(越界/悬空),基线存 null 快检跳读。 - sample.entries.set(target, fingerprintEntries(target, entries)); -} - -/** 条目基线统一带模式前缀(L:=完整列表,M:=清单存在性),快检按前缀选同一函数 - * 重算 —— 存取同口径,比较不会串档。 */ -function fingerprintEntries(target: string, mode: 'full' | 'manifest' | 'none'): string | null { - if (mode === 'none') return null; - return mode === 'manifest' - ? `M:${readSkillManifestFingerprint(target)}` - : `L:${readDirEntryFingerprint(target)}`; + samplePiWatchKey(sample, target, mode, repoRoot); } /** 软链目标的清单存在性指纹(namespace↔skill 迁移的同刻信号);文件/缺失恒 ''。 */ @@ -436,7 +478,11 @@ function readSkillManifestFingerprint(dir: string): string { /** 软链清单本体:SKILL.md/skill.md 为指向仓内目标的软链时,目标移动/删除不改变 * skill 目录自身 mtime,只有盯住解析后的文件才能检出(与 prompts 同款)。悬空链 * 盯链接自身,目标落地即检出。 */ -function watchPiSkillManifestTargets(sample: PiProjectResourceLaunchWatch, realFolder: string): void { +function watchPiSkillManifestTargets( + sample: PiProjectResourceLaunchWatch, + realFolder: string, + repoRoot: string, +): void { for (const name of ['SKILL.md', 'skill.md']) { const manifestPath = path.join(realFolder, name); let manifestLstat: fs.Stats; @@ -446,8 +492,9 @@ function watchPiSkillManifestTargets(sample: PiProjectResourceLaunchWatch, realF continue; } if (!manifestLstat.isSymbolicLink()) continue; - const realManifest = realpathOrNull(manifestPath); - recordWatchKey(sample, realManifest ?? manifestPath); + // 目标本体与链接自身各入一键:悬空时 target 为 null 键落到链接本体。 + const target = samplePiWatchKey(sample, manifestPath, 'none', repoRoot); + if (target.resolved) recordWatchKey(sample, target.resolved, 'none', repoRoot); } } From d587ee70af3c9672b9bfb277dbeed314195294fe Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 21:02:11 +0800 Subject: [PATCH 39/45] =?UTF-8?q?test(hook):=20fake=20session=20=E6=94=B9?= =?UTF-8?q?=E7=94=A8=E5=88=9D=E5=A7=8B=E7=8A=B6=E6=80=81=E5=A4=8D=E5=88=BB?= =?UTF-8?q?=20close=20=E5=A4=B1=E8=B4=A5,=E8=A1=A5=E9=BD=90=20getStatus=20?= =?UTF-8?q?=E5=BD=A2=E7=8A=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 回收失败后按实例状态分流(仍 active 才原样投递,否则重建)需要 fake session 带 getStatus:makeFakeSession 改用可选初始状态参数(不再用可变的 __setStatus 注入, 否则 mockImplementationOnce 的返回类型被污染、其余 manual fake 全部不可赋值); 三个 manual fake 同步补 getStatus: () => 'active'。 新增用例:回收抛出且实例已非 active → 必须重建(第二次 createSession), 坏实例不再收到 send —— 对应 Codex P2(4523498648)。 Signed-off-by: Zhang Yunjin --- .../__tests__/session-runner.test.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) 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 a9cff77a61..53c192896c 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,14 +343,15 @@ function makePermissionModeFake() { } /** fake maker: createSession 返回"send 即接受、随后立刻 done"的会话。 */ -function makeFakeSession(id: string) { +function makeFakeSession( + id: string, + status: 'active' | 'aborting' | 'closed' | 'error' = 'active', +) { const permission = makePermissionModeFake(); - let status: 'active' | 'aborting' | 'closed' | 'error' = 'active'; return { id, + // close 失败会让真实 Session 停在 error;测试用初始状态复刻这一后果。 getStatus: () => status, - /** 测试注入:模拟 close 失败后 Session 停在 error(回收抛出的同款后果)。 */ - __setStatus: (next: 'active' | 'aborting' | 'closed' | 'error') => { status = next; }, ...({ instanceId: `instance-${id}` } as { instanceId?: string }), workDir: 'D:/repo', @@ -857,8 +858,7 @@ describe('hook task model selection on next send', () => { 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'); - broken.__setStatus('error'); + const broken = makeFakeSession('sess-new', 'error'); const rebuilt = makeFakeSession('sess-new'); rebuilt.send.mockResolvedValue({ accepted: true }); fakeMaker.createSession.mockResolvedValueOnce(broken).mockResolvedValueOnce(rebuilt); @@ -1796,6 +1796,8 @@ describe('进度快照(turn.progress 链路)', () => { return permission.permissionModeState; }, id, + // 与 makeFakeSession 同形状:生产代码按 getStatus 判定实例是否仍可用。 + getStatus: () => 'active' as const, workDir: 'D:/repo', onEvent( cb: (ev: { @@ -2793,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); @@ -3113,6 +3116,7 @@ describe('交互卡链路(interaction listener 覆盖)', () => { return { ...makePermissionModeFake(), id, + getStatus: () => 'active' as const, workDir: 'D:/repo', onEvent( cb: (ev: { From af6abe80c349b69434ce7e55ca9d44e682ccb93b Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 21:21:16 +0800 Subject: [PATCH 40/45] =?UTF-8?q?fix(im,pi):=20=E5=9B=9E=E6=94=B6=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E5=90=8E=E5=88=B7=E6=96=B0=E8=B7=AF=E5=BE=84=E6=8A=8A?= =?UTF-8?q?=E5=9D=8F=E5=AE=9E=E4=BE=8B=E5=BD=93=E4=B8=8D=E5=AD=98=E5=9C=A8?= =?UTF-8?q?;=E8=BD=AF=E9=93=BE=E4=B8=80=E5=B1=82=E5=9B=9E=E9=80=80?= =?UTF-8?q?=E6=B8=85=E5=8D=95=E9=87=87=E6=A0=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 两条新 review(均为同类病的延伸,非新家族): 1. IM 恢复仍用坏实例(Greptile P2):close 抛出后 Session 停在 error 但仍登记在 activeSessions,上一轮只在 catch 里把 driftRecycled 置真 —— refresh 函数随后 getSession 拿到这个坏实例就直接返回,发送仍会失败。现在 refresh 把 「非 active 或已开始关闭」的实例与「不存在」同等对待,交给 createSession 的 既有 close 重试重建。回归用例:回收抛出且实例 error → 发生第二次 createSession、 坏实例不收到 send。 2. 无关目录拖慢发送(Greptile P2):一层子键上一轮统一 'dir' 采样,仓内软链 namespace 也会保存整份目标目录列表,而 collector 明文不走进它。现在模式只由 结构决定:软链一层 'skill'(两次 stat,仓内大目录也不拖快检)、真实目录 'dir' (完整列表,同刻新增的嵌套 skill 才检得出)。判断输入仍与基线同一次采样, 不重建两次读窗口。回归用例:40 条目软链 namespace 的基线为 'M:',目标内新增 条目不触发回收;真实 skills 根仍为 'L:'。 Signed-off-by: Zhang Yunjin --- .../turnRunnerCompanionRouting.test.ts | 52 +++++++++++++++++++ apps/desktop/src/main/im/shared/turnRunner.ts | 6 +++ .../pi-project-resource-drift.test.ts | 29 +++++++++-- .../src/agents/pi/project-resource-cli.ts | 20 ++++--- 4 files changed, 97 insertions(+), 10 deletions(-) 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 905720413b..2ff2bbf9ba 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts @@ -90,6 +90,8 @@ interface SessionHarness { session: Session; send: ReturnType; emit(event: AgentEvent): void; + /** 复刻 close 失败后的实例状态(仍登记在 activeSessions,但不可用)。 */ + setStatus(next: 'active' | 'error' | 'closed'): void; } function makeSessionHarness(sessionId: string): SessionHarness { @@ -103,12 +105,18 @@ function makeSessionHarness(sessionId: string): SessionHarness { return { accepted: true } as SessionSendResult; }, ); + let status: 'active' | 'error' | 'closed' = 'active'; + let closing = false; const session = { id: sessionId, workDir: '/tmp/wd', agentKind: 'claude-code', instanceId: `${sessionId}-instance`, abort: vi.fn(async () => undefined), + // 回收 close 失败会让真实 Session 停在 error 且仍登记在 activeSessions; + // 生产代码按这两个值决定「复用 / 交给 createSession 重建」。 + getStatus: () => status, + hasStartedClosing: () => closing, send, isTurnRunning: vi.fn(() => false), onEvent(listener: (event: AgentEvent) => void) { @@ -125,6 +133,9 @@ function makeSessionHarness(sessionId: string): SessionHarness { return { session, send, + setStatus(next: 'active' | 'error' | 'closed') { + status = next; + }, emit(event: AgentEvent) { for (const l of [...listeners]) l(event); }, @@ -646,4 +657,45 @@ describe('turnRunner: project-resource drift recycle before IM dispatch', () => // 换实例必须重接广播/落库链路(wireSessionToIpcExternal 按 Session 实例幂等)。 expect(mocks.wireSessionToIpcExternal).toHaveBeenCalledWith(rebuilt.session); }); + + it('rebuilds when the recycle close failed and the old instance is left in error', async () => { + // 回归(Greptile P2):close 失败后旧实例停在 error 但仍登记在 activeSessions。 + // 刷新路径若只认「找不到实例」就会原封不动返回它,后续 send 必挂 —— 必须把 + // error/已开始关闭的实例交给 createSession 的既有 close 重试重建。 + const broken = makeSessionHarness('mimi-main'); + const rebuilt = makeSessionHarness('mimi-main-rebuilt'); + broken.setStatus('error'); + let createCalls = 0; + let rebuiltLive = false; + mocks.getMaker.mockImplementation(() => ({ + getSession: vi.fn((id: string) => (rebuiltLive && id === 'mimi-main' ? rebuilt.session : broken.session)), + on: vi.fn(() => () => undefined), + createSession: vi.fn(async () => { + createCalls += 1; + return createCalls === 1 ? broken.session : rebuilt.session; + }), + // close 抛出:Session 被置为 error,recycle 返回前就抛了。 + recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => { + broken.setStatus('error'); + throw new Error('close boom'); + }), + })); + mocks.dbSelect.mockImplementation(() => ({ + from: () => ({ + where: () => ({ + limit: async () => [{ ...botRows.get('mimi-main'), status: 'active' }], + }), + }), + })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + + expect(createCalls).toBe(2); + expect(broken.send).not.toHaveBeenCalled(); + expect(rebuilt.send).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index cd9b871e6b..5e700fa2d2 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -2048,6 +2048,12 @@ export function createTurnRunner( throw new Error(`session ${sessionId} is not active after deferred agent switch`); } let current = maker.getSession(sessionId); + // close 失败会让实例停在 error、或已开始关闭但仍登记在 activeSessions —— + // 这类实例不可用,按「不存在」处理,交给 createSession 的既有 close 重试重建 + // (Greptile P2,2026-11-10:只认 null 会让刷新原封不动返回坏实例)。 + if (current && (current.getStatus() !== 'active' || current.hasStartedClosing())) { + current = undefined; + } // apply 已提交 DB 但 bootstrap 失败时,直发路径也要像 makerSendTransaction 的 // lazy-create 一样按最新 DB 行自愈,不能退回已关闭的 previous.send()。 if (!current) { 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 index b4752c8926..35f98bf5e0 100644 --- 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 @@ -357,16 +357,39 @@ describe('piProjectResourcesDrifted', () => { symlinkSync(path.join(project, 'target-dir'), path.join(project, '.pi', 'skills', 'foo'), 'junction'); const baseline = snapshot(); expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 前提:仓内软键以完整条目列表为基线('L:' + 空目录),与判断输入同一次 readdir —— - // 而非旧实现的「先读 hasManifest 再记基线」两步窗口 + // 前提:软链一层只采样清单存在性('M:' + 空清单)—— 既不 readdir 目标 + // (仓内大目录也不拖快检),又与判断输入同一次采样(无「先读清单后记基线」窗口) const linkKey = path.join(realpathSync(project), '.pi', 'skills', 'foo'); - expect(baseline.watchRootEntries.get(linkKey)).toBe('L:'); + expect(baseline.watchRootEntries.get(linkKey)).toBe('M:'); // 同一刻新增普通文件 SKILL.md(显式把目标目录 mtime 恢复基线值,隔离 mtime 信号) writeFileSync(path.join(project, 'target-dir', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); utimesSync(path.join(project, 'target-dir'), aligned, aligned); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); + it('samples a symlinked namespace by manifest only, never by full entry list', () => { + // 回归(Greptile P2):一层子键曾一律用 'dir' 采样,仓内软链 namespace 也会 + // 每轮快检 readdir + 排序整个目标目录 —— 而 collector 根本不会走进它。 + writeFileSync(path.join(project, '.git'), ''); + writeSkill(path.join('.pi', 'skills'), 'alpha'); + const big = path.join(project, 'big-namespace'); + mkdirSync(big, { recursive: true }); + for (let i = 0; i < 40; i += 1) mkdirSync(path.join(big, `entry-${i}`), { recursive: true }); + symlinkSync(big, path.join(project, '.pi', 'skills', '@big'), 'junction'); + + const surface = collectPiProjectResourceSurface(project); + const linkKey = path.join(realpathSync(project), '.pi', 'skills', '@big'); + // 基线是清单存在性指纹(不是完整条目列表),快检因此不会遍历 40 个无关条目。 + expect(surface.watch.entries.get(linkKey)).toBe('M:'); + // 真实目录(一层 skill 目录里的 namespace)仍用完整列表,同刻新增才检得出。 + expect(surface.watch.entries.get(path.join(realpathSync(project), '.pi', 'skills'))).toMatch(/^L:/); + const baseline = snapshotPiProjectResourceLaunch( + project, surface.paths, surface.repoRoot, surface.watch); + // 目标目录内新增无关条目:集合不变,不触发回收(且不依赖其完整列表信号)。 + mkdirSync(path.join(big, 'later'), { recursive: true }); + expect(piProjectResourcesDrifted(baseline)).toBe(false); + }); + it('stores null entries baseline for collector-excluded keys (symlink namespace to outside-repo target)', () => { // Greptile P2:collector 不枚举越界/软链 namespace 子树,条目基线存 null —— // 快检不 readdir 其目标(readdir 跟随软链,外部大目录完整列表是每条消息一次 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 7c2f2fdecd..0aa5a03ac6 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -156,19 +156,25 @@ function walkPiSkillTree( if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const candidatePath = path.join(root.resolved, entry.name); - // 一层子键一律 'dir'(完整条目列表):collector 要么在此收 skill、要么下行 - // 枚举 namespace —— 两条路都依赖该目录的条目集合,只有完整列表能检出同刻新增 - // 的嵌套 skill 目录。模式不依赖 hasManifest(那是旧 bug 的两次读窗口)。 - const child = samplePiWatchKey(sample, candidatePath, 'dir', repoRoot); - if (!child.inRepoDir || !child.resolved) continue; + // 模式只由**结构**定(不看内容 —— 读内容定模式会重新造出两次读窗口): + // 软链一层 collector 要么收为直链 skill、要么直接跳过(不走 namespace), + // 只消费清单存在性 → 'skill'(两次 stat;仓内大目录也不拖快检); + // 真实目录 collector 会枚举 namespace → 'dir'(完整列表,同刻新增的嵌套 + // skill 目录才检得出)。 const isSymlink = isSymlinkEntry(entry, candidatePath); + const child = samplePiWatchKey(sample, candidatePath, isSymlink ? 'skill' : 'dir', repoRoot); + if (!child.inRepoDir || !child.resolved) continue; // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处。 watchPiSkillManifestTargets(sample, child.resolved, repoRoot); // 判断输入与基线同源(Greptile P2:先 hasManifest 再记基线 → 中间写入的 - // SKILL.md 被固化进基线、argv 漏收 → 永久漏检)。 - if (skillManifestIn(child.resolved, child.dirents ?? [])) { + // SKILL.md 被固化进基线、argv 漏收 → 永久漏检);软链用采样时的清单存在性, + // 真实目录用采样时的同一次 readdir 条目。 + const hasManifest = isSymlink + ? child.manifest + : skillManifestIn(child.resolved, child.dirents ?? []); + if (hasManifest) { addPiSkill(repoRoot, child.resolved, bucket); continue; } From d2c2612a7558e7daff0980961e4438954d97df94 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 22:13:53 +0800 Subject: [PATCH 41/45] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E5=90=88?= =?UTF-8?q?=E5=B9=B6=E8=A7=A3=E5=86=B2=E7=AA=81=E6=97=B6=E6=95=B4=E5=9D=97?= =?UTF-8?q?=E5=8F=96=E6=9C=AC=E5=9C=B0=E4=BE=A7=E4=B8=A2=E6=8E=89=E7=9A=84?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=E6=94=B9=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 312cbe418b 的合并把若干文件整块保留了本地侧,丢了上游内容(典型:turnRunner.ts 丢 coldCompanion 准备块、turnRunnerCompanionRouting.test.ts 丢冷启动用例、 mobile 跨电脑来源标签、messageSource 的 parseSourceSessionTarget)。按「上游为基 + 只重放本 PR 的漂移回收增量」重建: - turnRunner.ts:恢复上游全文,只重新插入漂移回收块与喊停复核(判定改用 turnTerminalNow() 绕开 CFA 收窄)。 - 18 个非本 PR 文件(renderer/mobile/messageSource/测试)恢复为 upstream/main 版本。 - 内置技能包版本覆盖到 95(合入上游 93 后 94 已对应不同字节,check 报 reused-for-different-bytes)。 - scheduler-host/runner.ts 适配上游 DI:wireSessionToIpc → this.runtime.wireSessionToIpc。 验证:maker-core typecheck 0;desktop typecheck 仅剩上游自带的 7 个错 (codexTerraProxy.integration.test.ts,文件与 upstream 逐字节一致); check:built-in-skills 通过;drift+hook 共 247 用例绿。 Signed-off-by: Zhang Yunjin --- .../turnRunnerCompanionRouting.test.ts | 282 +++++++++++------- .../__tests__/turnRunnerSendOutcome.test.ts | 8 + apps/desktop/src/main/im/shared/turnRunner.ts | 98 ++++-- .../src/main/maker-host/built-in-skills.ts | 2 +- .../components/chat/AutomationOriginBadge.tsx | 22 +- .../components/chat/SessionLinkChip.tsx | 7 +- .../__tests__/AutomationOriginBadge.test.tsx | 24 +- .../embeddedSessionNavigation.test.tsx | 1 + apps/mobile/app/sessions/[sessionId].tsx | 15 +- .../messageSourceLabelsRender.test.tsx | 18 ++ apps/mobile/src/session/MessageRenderer.tsx | 4 +- docs/product-rules/message-source.md | 2 +- .../src/__tests__/messageSource.test.ts | 10 + packages/maker-shared/src/messageSource.ts | 17 +- 14 files changed, 353 insertions(+), 157 deletions(-) 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 2ff2bbf9ba..9ef2374e12 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts @@ -90,8 +90,6 @@ interface SessionHarness { session: Session; send: ReturnType; emit(event: AgentEvent): void; - /** 复刻 close 失败后的实例状态(仍登记在 activeSessions,但不可用)。 */ - setStatus(next: 'active' | 'error' | 'closed'): void; } function makeSessionHarness(sessionId: string): SessionHarness { @@ -105,18 +103,12 @@ function makeSessionHarness(sessionId: string): SessionHarness { return { accepted: true } as SessionSendResult; }, ); - let status: 'active' | 'error' | 'closed' = 'active'; - let closing = false; const session = { id: sessionId, workDir: '/tmp/wd', agentKind: 'claude-code', instanceId: `${sessionId}-instance`, abort: vi.fn(async () => undefined), - // 回收 close 失败会让真实 Session 停在 error 且仍登记在 activeSessions; - // 生产代码按这两个值决定「复用 / 交给 createSession 重建」。 - getStatus: () => status, - hasStartedClosing: () => closing, send, isTurnRunning: vi.fn(() => false), onEvent(listener: (event: AgentEvent) => void) { @@ -133,9 +125,6 @@ function makeSessionHarness(sessionId: string): SessionHarness { return { session, send, - setStatus(next: 'active' | 'error' | 'closed') { - status = next; - }, emit(event: AgentEvent) { for (const l of [...listeners]) l(event); }, @@ -314,6 +303,183 @@ async function runTurn(userId: string, text = 'hello'): Promise { } describe('turnRunner: connection handed to a companion bot', () => { + // Durable transports settle receipts only from dispatch outcomes. Preparation + // must reject before provider start even when there is no TurnState to clean up. + it.each([ + { failure: 'prepare', external: false }, + { failure: 'read', external: false }, + { failure: 'missing', external: false }, + { failure: 'prepare', external: true }, + { failure: 'read', external: true }, + { failure: 'missing', external: true }, + ])('settles cold preparation failure and clears the handed-over ack: %j', async ({ failure, external }) => { + companion.prepareSend.mockImplementation(async () => { + if (failure === 'prepare') throw new Error('MODEL_ROUTE_FAILED'); + if (failure === 'read') vi.mocked(fakeRepo.peekSessionById).mockRejectedValueOnce(new Error('DB_READ_FAILED')); + else vi.mocked(fakeRepo.peekSessionById).mockResolvedValueOnce(null); + return null; + }); + const beforeProviderStart = vi.fn(async () => undefined); + const onEarlyReject = vi.fn(() => true); + const args = { + botContextId: BOT_CONTEXT, userId: OWNER, requesterIsOwner: true, + userMessageId: 'cold-failure', text: 'hello', attachments: [], + ackReactionIdPromise: Promise.resolve('ack'), onEarlyReject, + }; + + if (external) { + await expect(runner.dispatchAgentTurn({ ...args, queueMode: 'external', beforeProviderStart })) + .resolves.toMatchObject({ kind: 'rejected', reason: expect.any(String) }); + expect(onEarlyReject).not.toHaveBeenCalled(); + expect(mocks.im.sendText).not.toHaveBeenCalled(); + } else { + await expect(runner.runAgentTurn(args)).resolves.toBeUndefined(); + expect(onEarlyReject).toHaveBeenCalledOnce(); + } + expect(mocks.im.removeMessageReaction).toHaveBeenCalledWith('cold-failure', 'ack'); + expect(beforeProviderStart).not.toHaveBeenCalled(); + expect(createSessionArgs).toHaveLength(0); + expect(mocks.persistUserMessage).not.toHaveBeenCalled(); + }); + + it('does not reserve a chunked reply for rejected auth or consume it on the next turn', async () => { + const id = 'mimi-main'; + const h = makeSessionHarness(id); + harnesses.set(id, h); + const beginReply = vi.fn(async () => undefined); + const commitFinal = vi.fn(async () => undefined); + runner = createTurnRunner({ + ...fakeAdapter, + channel: 'wecom', + output: { kind: 'chunked-text', im: fakeAdapter.im, beginReply, commitFinal }, + }, fakeRepo, fakeCards, { companion: companion as unknown as ImCompanionRouteDeps }); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'unavailable', providerId: 'disconnected' })); + return null; + }); + + await runTurn(OWNER, 'rejected'); + expect(h.send).not.toHaveBeenCalled(); + expect(beginReply).not.toHaveBeenCalled(); + expect(commitFinal).not.toHaveBeenCalled(); + expect(mocks.im.sendText).toHaveBeenCalledWith(OWNER, expect.stringContaining('unavailable'), expect.anything()); + + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'bot-model', providerId: 'xd' })); + return null; + }); + await runTurn(OWNER, 'accepted'); + expect(h.send).toHaveBeenCalledOnce(); + expect(beginReply).toHaveBeenCalledOnce(); + expect(beginReply.mock.invocationCallOrder[0]!).toBeLessThan(h.send.mock.invocationCallOrder[0]!); + h.emit({ type: 'text', data: { text: 'answer', isFinal: true } } as AgentEvent); + h.emit({ type: 'done', data: {} } as AgentEvent); + await vi.waitFor(() => expect(commitFinal).toHaveBeenCalledOnce()); + expect(commitFinal).toHaveBeenCalledWith(expect.objectContaining({ userId: OWNER, text: 'answer', terminal: 'done' })); + }); + + it.each([ + { userId: OWNER, warm: false }, + { userId: 'g/-100123', warm: false }, + { userId: OWNER, warm: true }, + { userId: 'g/-100123', warm: true }, + ])('uses the newly selected companion route after the old provider disconnects: %j', async ({ userId, warm }) => { + const id = userId === OWNER ? 'mimi-main' : 'lane:im:telegram:777:g:-100123'; + const originalResolve = companion.resolveSession.getMockImplementation()!; + companion.resolveSession.mockImplementation(async (input) => { + const result = await originalResolve(input); + botRows.set(id, rowFor(id, { model: 'old-model', providerId: 'disconnected' })); + return result; + }); + const oldSession = warm ? makeSessionHarness(id) : null; + if (oldSession) harnesses.set(id, oldSession); + const selected = rowFor(id, { model: 'bot-model', providerId: 'xd', sdkSessionId: null }); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, selected); + return null; + }); + const maker = mocks.getMaker(); + const create = maker.createSession.getMockImplementation(); + maker.createSession.mockImplementation(async (args: { id: string; model: string }) => { + // A cold start against the disconnected route must not be attempted. + // Warm createSession calls reuse Maker's existing singleton without booting. + if (!warm) expect(args.model).toBe('bot-model'); + return create(args); + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(userId); + + expect(companion.prepareSend).toHaveBeenCalledWith(id); + expect(harnesses.get(id)!.send).toHaveBeenCalledTimes(1); + expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1); + expect(mocks.im.sendText).not.toHaveBeenCalledWith( + userId, expect.stringContaining('old-model'), expect.anything(), + ); + expect(acquirePendingAgentSwitch).toHaveBeenCalledWith(id, { channelOwned: false }); + }); + + it('checks the landed companion route even if it changed again under the send lock', async () => { + const id = 'mimi-main'; + harnesses.set(id, makeSessionHarness(id)); + acquirePendingAgentSwitch.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'latest-unavailable', providerId: 'disconnected' })); + return () => undefined; + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + + expect(harnesses.get(id)!.send).not.toHaveBeenCalled(); + expect(mocks.persistUserMessage).not.toHaveBeenCalled(); + expect(mocks.im.sendText).toHaveBeenCalledWith( + OWNER, expect.stringContaining('latest-unavailable'), expect.anything(), + ); + }); + + it('queues input while the old companion turn runs and authenticates the new route only at dispatch', async () => { + const id = 'mimi-main'; + const h = makeSessionHarness(id); + harnesses.set(id, h); + botRows.set(id, rowFor(id, { model: 'old-model', providerId: 'disconnected' })); + vi.mocked(h.session.isTurnRunning).mockReturnValue(true); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'bot-model', providerId: 'xd' })); + return null; + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + expect(h.send).not.toHaveBeenCalled(); + expect(companion.prepareSend).not.toHaveBeenCalled(); + expect(mocks.im.sendText).not.toHaveBeenCalled(); + + vi.mocked(h.session.isTurnRunning).mockReturnValue(false); + h.emit({ type: 'done', data: {} } as AgentEvent); + + await vi.waitFor(() => expect(h.send).toHaveBeenCalledTimes(1)); + expect(companion.prepareSend).toHaveBeenCalledWith(id); + expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1); + }); + it('keeps the channel’s own routing for an unbound connection', async () => { binding = null; await runTurn(OWNER, 'first'); @@ -405,6 +571,7 @@ describe('turnRunner: connection handed to a companion bot', () => { // the send lock's own suppression window. The runner must not forget the task. const listeners: Array<(event: MakerEvent) => void> = []; const switched = makeSessionHarness('mimi-main'); + harnesses.set('mimi-main', makeSessionHarness('mimi-main')); let live: Session | undefined; const base = mocks.getMaker() as { createSession: (args: { id?: string }) => Promise; @@ -551,7 +718,8 @@ describe('turnRunner: connection handed to a companion bot', () => { it('replies with a notice and does not send when the bot guard blocks the turn', async () => { companion.prepareSend.mockResolvedValue('Bot 当前未启用,请先恢复 Bot 后再发送消息'); await runTurn(OWNER); - expect(harnesses.get('mimi-main')!.send).not.toHaveBeenCalled(); + expect(harnesses.has('mimi-main')).toBe(false); + expect(createSessionArgs).toHaveLength(0); expect(mocks.im.sendText).toHaveBeenCalledWith( OWNER, expect.stringContaining('伙伴现在接不了消息'), @@ -609,93 +777,3 @@ describe('turnRunner: connection handed to a companion bot', () => { expect(harnesses.get('desktop-sess-1')!.send).toHaveBeenCalledTimes(1); }); }); - -describe('turnRunner: project-resource drift recycle before IM dispatch', () => { - it('rebuilds the runtime from the DB row and dispatches on the rebuilt instance', async () => { - // 回归(MagicLizi P1):IM 直发的「漂移回收 → 按 DB 行重建 → 换实例投递」分支 - // 此前零测试覆盖,是三个 P1 修复(e39f100091/2a35bd8f31/fe45afa803)的共同落点。 - const original = makeSessionHarness('mimi-main'); - const rebuilt = makeSessionHarness('mimi-main-rebuilt'); - let recycleCalledWith: string | undefined; - let createCalls = 0; - // rebuilt 只在回收窗口之后对 getSession 可见:漂移检查前的 agent-switch 复核 - // 也读 getSession,提前暴露会让它抢先把 rebuilt 绑进 state(时序失真)。 - let rebuiltLive = false; - mocks.getMaker.mockImplementation(() => ({ - getSession: vi.fn((id: string) => (rebuiltLive && id === 'mimi-main' ? rebuilt.session : original.session)), - on: vi.fn(() => () => undefined), - createSession: vi.fn(async () => { - createCalls += 1; - return createCalls === 1 ? original.session : rebuilt.session; - }), - recyclePiRuntimeIfResourcesDrifted: vi.fn(async (id: string) => { - recycleCalledWith = id; - rebuiltLive = true; - return true; - }), - })); - // 重建按 DB 行走:refreshSessionAfterPendingAgentSwitch 读 sessions 表。 - mocks.dbSelect.mockImplementation(() => ({ - from: () => ({ - where: () => ({ - limit: async () => [{ ...botRows.get('mimi-main'), status: 'active' }], - }), - }), - })); - runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { - companion: companion as unknown as ImCompanionRouteDeps, - acquirePendingAgentSwitch, - }); - - await runTurn(OWNER); - - // 实现传的是 session 实例(不是 id):必须是回收前的旧实例。 - expect((recycleCalledWith as { id: string } | undefined)?.id).toBe('mimi-main'); - // 旧实例已关闭:投递必须落在重建实例上,而不是把真实原因换成「会话已关闭」。 - expect(original.send).not.toHaveBeenCalled(); - expect(rebuilt.send).toHaveBeenCalledTimes(1); - // 换实例必须重接广播/落库链路(wireSessionToIpcExternal 按 Session 实例幂等)。 - expect(mocks.wireSessionToIpcExternal).toHaveBeenCalledWith(rebuilt.session); - }); - - it('rebuilds when the recycle close failed and the old instance is left in error', async () => { - // 回归(Greptile P2):close 失败后旧实例停在 error 但仍登记在 activeSessions。 - // 刷新路径若只认「找不到实例」就会原封不动返回它,后续 send 必挂 —— 必须把 - // error/已开始关闭的实例交给 createSession 的既有 close 重试重建。 - const broken = makeSessionHarness('mimi-main'); - const rebuilt = makeSessionHarness('mimi-main-rebuilt'); - broken.setStatus('error'); - let createCalls = 0; - let rebuiltLive = false; - mocks.getMaker.mockImplementation(() => ({ - getSession: vi.fn((id: string) => (rebuiltLive && id === 'mimi-main' ? rebuilt.session : broken.session)), - on: vi.fn(() => () => undefined), - createSession: vi.fn(async () => { - createCalls += 1; - return createCalls === 1 ? broken.session : rebuilt.session; - }), - // close 抛出:Session 被置为 error,recycle 返回前就抛了。 - recyclePiRuntimeIfResourcesDrifted: vi.fn(async () => { - broken.setStatus('error'); - throw new Error('close boom'); - }), - })); - mocks.dbSelect.mockImplementation(() => ({ - from: () => ({ - where: () => ({ - limit: async () => [{ ...botRows.get('mimi-main'), status: 'active' }], - }), - }), - })); - runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { - companion: companion as unknown as ImCompanionRouteDeps, - acquirePendingAgentSwitch, - }); - - await runTurn(OWNER); - - expect(createCalls).toBe(2); - expect(broken.send).not.toHaveBeenCalled(); - expect(rebuilt.send).toHaveBeenCalledTimes(1); - }); -}); 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 412136fe70..b588c62f0b 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); @@ -4842,6 +4849,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 3e703975a6..4079c84647 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1064,6 +1064,57 @@ export function createTurnRunner( } target = created.target; } + // A cold companion task must reconcile its saved model before starting an + // agent. Otherwise a disconnected old provider can prevent both wiring and + // the later prepareSend guard from ever applying the new selection. + const coldCompanion = target.botOwned && !sessionStates.has(target.row.id) + && !wiringInFlight.has(target.row.id) && !getMaker().getSession(target.row.id); + if (coldCompanion && deps.companion?.prepareSend) { + let blocked: string | null; + try { + if (target.botOwned?.lane === 'channel') { + coldWiringVendorOptions.set(target.row.id, adapter.buildVendorOptions(userId, target.scopeKey)); + } + blocked = await deps.companion.prepareSend(target.row.id); + if (!blocked) { + const refreshed = await repo.peekSessionById(target.row.id); + if (!refreshed) throw new Error(`companion session ${target.row.id} missing after route preparation`); + target = { ...target, row: refreshed }; + } + } catch (err) { + if (isImAccountScopeClosedError(err)) throw err; + const normalized = normalizeSendError(err); + log.error(`${channel} companion preparation failed before dispatch`, { + kind: 'session-dispatch', + source: 'companion.prepareSend', + sessionId: hashLogSessionId(target.row.id), + reason: normalized.reason, + error: normalized.error, + }); + await waitForAckCleanupBounded(discardHandedOverAck(userMessageId, args.ackReactionIdPromise)); + if (args.queueMode === 'internal') { + try { + const text = ui.agent.sendInternalError(normalized.reason); + const consumed = (await args.onEarlyReject?.(normalized.reason, text)) ?? false; + if (!consumed) await sendTextClaimingOpener(userId, text, target.scopeKey); + } catch { + /* A failed notice must still return a definite pre-dispatch rejection. */ + } + } + return { kind: 'rejected', reason: normalized.reason }; + } finally { + coldWiringVendorOptions.delete(target.row.id); + } + if (blocked) { + const text = ui.agent.companionUnavailable?.(blocked) ?? ui.agent.runtimeError(blocked); + if (args.queueMode === 'internal') { + const consumed = (await args.onEarlyReject?.('companion_unavailable', text)) ?? false; + if (!consumed) await sendTextClaimingOpener(userId, text, target.scopeKey); + } + await discardHandedOverAck(userMessageId, args.ackReactionIdPromise); + return { kind: 'rejected', reason: 'companion_unavailable' }; + } + } const row = target.row; const allowedFileRoots = resolveTurnFileRoots(row.workingDir, row.remoteHostId); let followTarget: ImDefaultRoute | null | undefined = null; @@ -1071,7 +1122,10 @@ export function createTurnRunner( const sharedSession = target.attached || target.notificationReply === true || target.botOwned?.lane === 'canonical'; const authNoticeAttached = target.attached || target.botOwned !== undefined; - if (!target.authChecked) { + // Live companion tasks may still be running on the previous selection. + // Authenticate them after prepareSend + the locked switch at dispatch, not + // against the stale row before their input has even reached the queue. + if (!target.authChecked && (!target.botOwned || coldCompanion)) { // 渠道默认跟随: 本条消息会在 send 锁内切到新默认时, 按新路由检查授权 —— // 否则旧默认坏掉(如供应商断开)时, 消息会先被「缺授权」挡掉, 永远换不过去。 followTarget = @@ -1472,7 +1526,6 @@ export function createTurnRunner( await item.turn.revalidateNotificationReply?.(); await resolveNotificationTarget(rowId, item.turn.scopeKey); } - await beginChunkedReply(item.turn); // 伙伴任务: 与桌面发送同源的伙伴守卫(暂停 / 归档 → 回一句提示不发送), // 再对齐伙伴模型链、刷新能力纪元。要在拿 send 锁之前做 —— 对齐登记的切换 // 意图由下面的锁内应用落实。 @@ -1555,19 +1608,24 @@ export function createTurnRunner( // 失败被吞后这条消息会按旧路由发送 —— 按实际路由补一次授权检查, 旧供应商断开 // 时在这里给出缺授权提示, 而不是进发送流程运行时失败(PR #5155 review P2)。 // 冷路径在接线前已查过一次, 这里兜的是接线后切换才失败 / 热任务的切换失败。 + // 伙伴任务始终在守卫与锁内切换完成后检查实际路由, 不复用入队时的旧选择。 const followAuthRoute = item.turn.followAuthRoute; - if (followAuthRoute) { + if (followAuthRoute || state.botLane) { const landed = await repo.peekSessionById(rowId); - if (landed && !sameImDefaultRoute(routeOfRow(landed), followAuthRoute)) { + if (state.botLane && !landed) { + throw new Error(`companion session ${rowId} missing before route authentication`); + } + if (landed && (state.botLane || (followAuthRoute && !sameImDefaultRoute(routeOfRow(landed), followAuthRoute)))) { const auth = await checkImRouteAuthDetailed(landed, undefined, authCheckDeps()); if (!auth.ok) { + const attached = state.attached || !!state.botLane; const authStatus = { ...auth, agentKind: landed.agentKind, model: landed.model }; if (item.turn.queueMode === 'internal') { const text = - ui.agent.authMissing?.({ ...authStatus, attached: state.attached }) ?? + ui.agent.authMissing?.({ ...authStatus, attached }) ?? ui.agent.apiKeyMissing; const consumed = (await item.onEarlyReject?.('missing_auth', text)) ?? false; - if (!consumed) await replyMissingAuth(userId, authStatus, item.turn.scopeKey, state.attached); + if (!consumed) await replyMissingAuth(userId, authStatus, item.turn.scopeKey, attached); } // 文案已在上面按缺授权发过(外部队列由调用方消费), 这里只走收口。 await handleSendPreDispatchFailure(state, userId, { @@ -1582,6 +1640,10 @@ export function createTurnRunner( } } + // Only claim a passive reply after preparation and route authentication. + // Rejected input must not leave a pending chunked response for the next turn. + await beginChunkedReply(item.turn); + // session-agent-switch:本路径直发 session.send(不经 makerSendTransaction), // 交接注入自己接——切换后首条消息若来自 IM 渠道,新引擎同样需要交接上下文 // (2026-07-20 审计)。落库(persistUserMessage)仍是渠道原文。 @@ -1657,18 +1719,13 @@ export function createTurnRunner( // 项目资源漂移(如会话中途 openspec init):空闲时经 Maker 以 runtime-refresh // 回收运行时,再按 DB 行自愈重建 —— 与桌面发送事务同口径,IM 直发不用旧资源。 // 无 agent-switch 锁的装配不支持关闭后重建,保持原样投递。 - // 两种失败分开:回收本身失败 → 旧实例仍可用,原样投递;回收成功(旧实例 - // 已关)后的重建失败必须上抛 —— 继续用已关闭实例只会把真实原因换成误 - // 导性的「会话已关闭」(2026-11-09 Greptile P2)。 let driftRecycled = false; try { driftRecycled = !!(deps.acquirePendingAgentSwitch && await getMaker().recyclePiRuntimeIfResourcesDrifted(state.makerSession)); } catch (err) { - // 两种失败必须分开:close 抛出时 Session 已停在 error(Session.performClose - // 不因异常回退),旧实例不可用 —— 这时继续 send 只会被 ensureActive 抛错, - // runner 永远绑在坏实例上、绕过 createSession 重建路径(Codex P2, - // 2026-11-10)。无 agent-switch 锁的装配不支持重建,保持原样投递。 + // 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)); @@ -1677,16 +1734,13 @@ export function createTurnRunner( await refreshSessionAfterPendingAgentSwitch(state, state.makerSession.id, userId); log.info('im send: project resources drifted, recycled runtime before dispatch'); } - // 回收+重建是异步窗口:/stop 可能恰好落在其中;喊停后不得再开始执行, - // 与上方 aborted 检查同口径收尾(此时尚未发送,无 chunked 终态章要补)。 - // 经函数读取:上方检查已把控制流收窄到 'done'|'error',但运行时值在回收 - // 窗口内仍可变为 'aborted',需要绕开 CFA 的新鲜读取。 + // 回收+重建是异步窗口:/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); - // beginChunkedReply 早在消息准备期已执行(企微 beginReply 已登记未结束流), - // 与上方停止分支同款补发停止终稿,否则回复永不结束、下一轮终稿错位。 if (output.kind === 'chunked-text' && item.turn.chunkedReplyBegun) { try { await output.commitFinal({ @@ -2048,12 +2102,6 @@ export function createTurnRunner( throw new Error(`session ${sessionId} is not active after deferred agent switch`); } let current = maker.getSession(sessionId); - // close 失败会让实例停在 error、或已开始关闭但仍登记在 activeSessions —— - // 这类实例不可用,按「不存在」处理,交给 createSession 的既有 close 重试重建 - // (Greptile P2,2026-11-10:只认 null 会让刷新原封不动返回坏实例)。 - if (current && (current.getStatus() !== 'active' || current.hasStartedClosing())) { - current = undefined; - } // apply 已提交 DB 但 bootstrap 失败时,直发路径也要像 makerSendTransaction 的 // lazy-create 一样按最新 DB 行自愈,不能退回已关闭的 previous.send()。 if (!current) { 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 6817b87392..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 = 94; +export const BUILT_IN_SKILLS_BUNDLE_VERSION = 95; const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13; export interface BuiltInSkillDescriptor { diff --git a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx index f1c026efc0..6f9b4cbef1 100644 --- a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx +++ b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx @@ -18,9 +18,13 @@ import { isHookSchedulerOrigin, } from '@/lib/messageAutomationOrigin'; import { joinSourceTooltip } from '@/lib/messageSourceLabel'; -import { isCrossDeviceSourceSessionId } from '@cindy/maker-shared/message-source'; +import { parseSourceSessionTarget } from '@cindy/maker-shared/message-source'; import { sessionsStore } from '@/lib/sessionsStore'; import { cn } from '@/lib/utils'; +import { toast } from '@/lib/toast'; + +import { buildSessionDeepLink } from '@/lib/deepLink'; +import { useSessionLinkTarget } from './SessionLinkChip'; import { imLabel } from './HookTaskCard'; @@ -114,16 +118,20 @@ export function AutomationOriginBadge({ const navigationMode = useSessionNavigationMode(); const senderSessionId = automationOrigin.kind === 'session' ? automationOrigin.senderSessionId : undefined; + const sourceTarget = parseSourceSessionTarget(senderSessionId); + const { openTarget: openCrossDeviceTarget } = useSessionLinkTarget( + sourceTarget?.deviceId ? buildSessionDeepLink(sourceTarget.sessionId, { deviceId: sourceTarget.deviceId }) : '', + ); const botProfiles = useBotProfiles(); // 远程任务的来源任务与伙伴资料都在那台设备上,本机同 id 资料不可信(与 BotDirectMessageCard 同口径)。 // 粘滞归属:relay 瞬时重连会清空镜像索引,此窗口内仍要把远程任务当远程处理, // 否则来源任务会被当成本机任务打开。 const hostDeviceId = getStickySessionDeviceId(hostSessionId); - const liveSenderTitle = useLiveSessionTitle(senderSessionId, Boolean(hostDeviceId)); + const liveSenderTitle = useLiveSessionTitle(sourceTarget?.deviceId ? undefined : senderSessionId, Boolean(hostDeviceId)); const senderBot = automationOrigin.kind === 'session' && automationOrigin.senderBotId ? (() => { - const profile = hostDeviceId + const profile = hostDeviceId || sourceTarget?.deviceId ? undefined : botProfiles.find((item) => item.id === automationOrigin.senderBotId); return { @@ -167,8 +175,12 @@ export function AutomationOriginBadge({ if (targetSessionId) { idLines.push(t('chat.userMessage.sourceIds.session', { id: targetSessionId })); } - // 另一台电脑上的来源任务(deviceId::sessionId)不是这里能直接打开的任务:只显示来源与 id。 - open = targetSessionId && !isCrossDeviceSourceSessionId(targetSessionId) + // 带设备的来源复用任务深链导航,支持返回本机及打开尚未同步的远程任务。 + open = sourceTarget?.deviceId + ? () => { + void openCrossDeviceTarget(false).catch(() => toast.error(t('chat.markdownRenderer.openLinkFailed'))); + } + : targetSessionId && sourceTarget ? () => { // 其余来源任务与当前任务在同一台设备上:远程任务的来源任务也在那台设备上。 if (hostDeviceId) remoteProjectsStore.pinSessionOrigin(hostDeviceId, targetSessionId); diff --git a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx index 3173cd1a3e..1e99735e2b 100644 --- a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx +++ b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx @@ -63,7 +63,6 @@ export function useSessionLinkTarget(href: string) { const navigationMode = useSessionNavigationMode(); const reportSessionNavigation = useSessionNavigationIntent(); const target = useMemo(() => parseSessionDeepLinkHref(href), [href]); - const remoteSessions = useRemoteProjectSessions(); const navigationRequestVersionRef = useRef(0); const sessionId = target?.sessionId ?? null; const messageClientId = target?.messageClientId ?? null; @@ -74,10 +73,12 @@ export function useSessionLinkTarget(href: string) { }, [sessionId, messageClientId, targetDeviceId, navigationMode], ); - const remoteSession = remoteSessions.find((s) => - s.id === sessionId && (!targetDeviceId || s.deviceLinkDeviceId === targetDeviceId)) ?? null; const openTarget = async (separate: boolean) => { if (!target || !sessionId) return; + // 只在点击时读一次远程镜像快照:不订阅整份远程任务列表,避免每个链接/来源标签 + // 在列表变化时重渲染并各自扫描(来源标签随长聊天大量挂载)。 + const remoteSession = remoteProjectsStore.getVisibleMergedRemoteSessions().find((s) => + s.id === sessionId && (!targetDeviceId || s.deviceLinkDeviceId === targetDeviceId)) ?? null; const navigationRequestVersion = ++navigationRequestVersionRef.current; const resolveTargetRoute = async () => { let deviceId = targetDeviceId ?? remoteProjectsStore.getSessionDeviceId(sessionId); diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx index 3fcb8bef32..d5bb18d25d 100644 --- a/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx +++ b/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx @@ -1,9 +1,11 @@ // @vitest-environment jsdom -import { fireEvent, render, screen } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ navigate: vi.fn() })); +vi.mock('@/contexts/AuthContext', () => ({ useOptionalAuthDeviceId: () => 'local-device' })); +vi.mock('@/lib/makerTransport', () => ({ getSessionFor: async () => null })); vi.mock('react-router-dom', async (importOriginal) => { const actual = await importOriginal(); @@ -74,17 +76,23 @@ describe('AutomationOriginBadge', () => { expect(screen.getByText('chat.userMessage.sessionSent')).toBeTruthy(); }); - it('shows a task on another computer as a source without offering a broken jump', () => { - const { container } = render( + // Regression: cross-device source labels were inert. Exercise the real link routing hook. + it.each(['dev-A', 'local-device'])('opens a device-qualified source on %s', async (deviceId) => { + const pin = vi.spyOn(remoteProjectsStore, 'pinSessionOrigin'); + pin.mockClear(); + render( , ); - expect(screen.queryByRole('button')).toBeNull(); - expect(screen.getByText('chat.userMessage.sessionSentNamed:Source')).toBeTruthy(); - expect(container.querySelector('[title]')?.getAttribute('title')).toBe( - 'chat.userMessage.sourceIds.session:dev-A::source-task', + const button = screen.getByRole('button'); + expect(button.getAttribute('title')).toBe( + `chat.userMessage.sessionViewSource\nchat.userMessage.sourceIds.session:${deviceId}::source-task`, ); + fireEvent.click(button); + await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/source-task', undefined)); + if (deviceId === 'local-device') expect(pin).not.toHaveBeenCalled(); + else expect(pin).toHaveBeenCalledWith(deviceId, 'source-task'); }); it('lists the source session id under the existing tooltip line', () => { diff --git a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx index cbb5905e10..ae8ddea04b 100644 --- a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx +++ b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx @@ -46,6 +46,7 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({ getSessionDeviceId: () => undefined, remoteProjectsStore: { getSessionDeviceId: () => undefined, + getVisibleMergedRemoteSessions: () => mocks.remoteSessions, pinSessionOrigin: mocks.pinSessionOrigin, }, })); diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx index 9c61ef11f5..ea20db305c 100644 --- a/apps/mobile/app/sessions/[sessionId].tsx +++ b/apps/mobile/app/sessions/[sessionId].tsx @@ -1,3 +1,4 @@ +import { parseSourceSessionTarget } from '@cindy/maker-shared/message-source'; import { TaskArchiveUndoSlot } from '@/session/TaskArchiveUndoNotice'; import { composerRowChrome } from '@/session/composerGeometry'; import { ResizableComposerInputRow } from '@/session/ResizableComposerInputRow'; @@ -10067,12 +10068,20 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S router, ]); - // 「由任务「X」发送」来源标签:工具只在同一设备的任务之间投递,来源任务与当前任务同设备。 + // 跨电脑来源按宿主记录的设备打开;无前缀的历史来源仍属于当前任务所在设备。 const openOriginSession = useCallback((originSessionId: string) => { - if (!deviceId || !originSessionId || originSessionId === sessionId) return; + const target = parseSourceSessionTarget(originSessionId); + const targetDeviceId = target?.deviceId ?? deviceId; + if (!target || !targetDeviceId) return; + if (target.sessionId === sessionId && targetDeviceId === deviceId) return; + const targetDevice = remoteSessionStore.getDeviceIdentity().find((item) => item.deviceId === targetDeviceId); router.push({ pathname: '/sessions/[sessionId]', - params: { sessionId: originSessionId, deviceId, deviceName }, + params: { + sessionId: target.sessionId, + deviceId: targetDeviceId, + deviceName: targetDevice?.name ?? (targetDeviceId === deviceId ? deviceName : targetDeviceId), + }, }); }, [deviceId, deviceName, router, sessionId]); diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx index 0e96626358..6d03767c04 100644 --- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx +++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx @@ -954,3 +954,21 @@ describe("table-heavy assistant replies", () => { }); vi.mock('@/session/RemoteAttachmentPreview', () => ({ RemoteAttachmentPreview: () => null })); + +// Regression: tapping a cross-device source must reach the page's routing callback intact. +it('opens cross-device source labels while redacted sources remain inert', () => { + const onOpenOriginSession = vi.fn(); + const items = buildMobileMessageRenderItems([ + msg('cross', 'go', { origin: { kind: 'session', senderSessionId: 'dev-A::task-1', senderSessionTitle: 'Source' } }), + msg('redacted', 'go', { origin: { kind: 'session' } }), + ], {}).filter(item => item.type === 'message'); + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const host = document.createElement('div'); + const root = createRoot(host); + act(() => root.render()); + const labels = host.querySelectorAll('[data-testid="message.sessionOrigin"]'); + expect(labels.length).toBe(2); + act(() => labels.forEach(label => label.dispatchEvent(new MouseEvent('click', { bubbles: true })))); + expect(onOpenOriginSession).toHaveBeenCalledExactlyOnceWith('dev-A::task-1'); + act(() => root.unmount()); +}); diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx index 7ce817254d..f071e922df 100644 --- a/apps/mobile/src/session/MessageRenderer.tsx +++ b/apps/mobile/src/session/MessageRenderer.tsx @@ -280,7 +280,7 @@ import { useRemoteSessionMessages, } from '@/session/remoteSessionStore'; import { - isCrossDeviceSourceSessionId, + parseSourceSessionTarget, shouldShowSourceDevice, type MessageSourceDevice, type MessageSourcePlugin, @@ -3389,7 +3389,7 @@ function SessionOriginLabel({ idText={sourceIdText(sourceMeta) ?? (senderSessionId ? t('message.renderer.sourceSessionId', { id: senderSessionId }) : undefined)} label={sessionOriginLabel(origin)} - onPress={onOpen && senderSessionId && !isCrossDeviceSourceSessionId(senderSessionId) + onPress={onOpen && senderSessionId && parseSourceSessionTarget(senderSessionId) ? () => onOpen(senderSessionId) : undefined} openHint={t('message.renderer.openSessionOrigin')} diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.md index eb360215e7..67dcc28ace 100644 --- a/docs/product-rules/message-source.md +++ b/docs/product-rules/message-source.md @@ -53,7 +53,7 @@ Agent 用 `send_to_session` 把消息发给另一台电脑上的既有任务时 因此不写 `sourceDevice`。来源任务 id 记为 `deviceId::sessionId`:设备前缀由接收电脑按服务端认证的 控制端设备 id 填写,发送方自带的前缀被拒绝;接收方 Agent 可原样用这个 id 回信。任务标题来自 对端,按不可信文本清洗。它同样只用于归属展示,不是权限判据。 -来源任务不在查看者能直接打开的位置,标签只显示来源与 id,不提供跳转。 +桌面与手机的来源标签可点击:把 `deviceId::sessionId` 拆成设备与任务,按来源设备打开;来源在查看者本机时打开本机任务,尚未同步的远程任务沿既有任务加载流程读取。没有设备前缀的来源仍按当前任务所在设备打开。脱敏后没有任务 ID 的标签保持不可点击。 ## 跨任务委派:发送端判断,正文是原文(2026-11-05) diff --git a/packages/maker-shared/src/__tests__/messageSource.test.ts b/packages/maker-shared/src/__tests__/messageSource.test.ts index 9165d9e3f8..1b659edb5d 100644 --- a/packages/maker-shared/src/__tests__/messageSource.test.ts +++ b/packages/maker-shared/src/__tests__/messageSource.test.ts @@ -4,6 +4,7 @@ import { buildMessageSourceNote, describeMessageSourceSender, isCrossDeviceSourceSessionId, + parseSourceSessionTarget, messageSourceIdEntries, formatSourceRef, promptSafeSourceName, @@ -269,3 +270,12 @@ describe('isCrossDeviceSourceSessionId', () => { } }); }); + +// Routing must preserve the explicit device, while redacted/malformed sources stay inert. +describe('parseSourceSessionTarget', () => { + it('splits a stamped source and preserves same-host legacy ids', () => { + expect(parseSourceSessionTarget('dev-A::task-1')).toEqual({ deviceId: 'dev-A', sessionId: 'task-1' }); + expect(parseSourceSessionTarget('task-1')).toEqual({ sessionId: 'task-1' }); + for (const id of [undefined, '', '::task-1', 'dev-A::']) expect(parseSourceSessionTarget(id)).toBeNull(); + }); +}); diff --git a/packages/maker-shared/src/messageSource.ts b/packages/maker-shared/src/messageSource.ts index 0c96d7efeb..71fe0150a2 100644 --- a/packages/maker-shared/src/messageSource.ts +++ b/packages/maker-shared/src/messageSource.ts @@ -208,14 +208,17 @@ export function messageSourceSenderFromMeta(meta: unknown): MessageSourceSender return undefined; } -/** - * 来源任务在另一台电脑上(Agent 跨电脑发消息时,接收电脑把来源任务 id 记为 - * `deviceId::sessionId`)。它不是本机可打开的任务 id:界面照常显示标签与 id,但不提供跳转。 - */ -export function isCrossDeviceSourceSessionId(sessionId: string | undefined): boolean { - if (!sessionId) return false; +/** 来源任务的设备前缀由接收宿主盖章;跳转时拆开设备与任务,不能把复合 ID 当成本机任务。 */ +export function parseSourceSessionTarget(sessionId: string | undefined): { sessionId: string; deviceId?: string } | null { + if (!sessionId) return null; const split = sessionId.indexOf('::'); - return split > 0 && split < sessionId.length - 2; + if (split < 0) return { sessionId }; + if (split === 0 || split === sessionId.length - 2) return null; + return { deviceId: sessionId.slice(0, split), sessionId: sessionId.slice(split + 2) }; +} + +export function isCrossDeviceSourceSessionId(sessionId: string | undefined): boolean { + return !!parseSourceSessionTarget(sessionId)?.deviceId; } export type MessageSourceIdKind = 'plugin' | 'mcpApp' | 'localApp' | 'teammate' | 'session' | 'automation' | 'member'; From 83c57e495ebb63db327f0ea717697b6a3c3d7b69 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 22:37:02 +0800 Subject: [PATCH 42/45] =?UTF-8?q?test(codex):=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E6=94=B9=E7=94=A8=20desktop=20=E8=A3=85=E9=85=8D=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E5=AF=BC=E5=85=A5=E4=BB=A3=E7=90=86=20API(=E4=BF=AE?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=20typecheck=20=E7=BA=A2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit codexTerraProxy.integration.test.ts 从 '../codex-proxy-host.js' 取 setCodexProxyAuthInjection / ensureCodexProxyReady 等,但该模块只导出 createCodexProxyHost(工厂)与类型 —— 这些 API 由 desktop 装配 codex-proxy-host.desktop.ts 解构导出。上游 main 当前 verify 的 『Typecheck desktop』即挂在这 7 个错上(文件与上游逐字节一致),本 PR CI 因此无法变绿,顺手纠正为导入 desktop 装配。 验证:desktop typecheck 0 错(修改前 7 个)。 Signed-off-by: Zhang Yunjin --- .../maker-host/__tests__/codexTerraProxy.integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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; From 2c9c4ef2e0680845d7d33ec747d711a2fe169bbb Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Tue, 10 Nov 2026 22:38:22 +0800 Subject: [PATCH 43/45] =?UTF-8?q?fix(desktop):=20codexTerraProxy=20?= =?UTF-8?q?=E9=9B=86=E6=88=90=E6=B5=8B=E8=AF=95=E6=94=B9=E7=94=A8=20codex-?= =?UTF-8?q?proxy-host.desktop=20=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #9621 把 codex-proxy-host 拆成共享核心(createCodexProxyHost 工厂)与 codex-proxy-host.desktop 平台绑定后,codexTerraProxy.integration.test.ts 仍在 import 共享核心并调用已不再存在的模块级函数(setCodexProxyAuthInjection / ensureCodexProxyReady / getCodexProxyEndpoint / registerComposed / unregister / disposeCodexProxy / clearCodexProxyAuthInjection),desktop typecheck 自此在 main 上 全红,verify-checks 拦住了所有合并最新 main 的 PR。 修复与仓内其它测试一致:改 import ../codex-proxy-host.desktop.js——桌面侧绑定 仍然按原名导出这些函数(codex-proxy-host.desktop.ts 的 createCodexProxyHost 解构导出),codexAuthInvalidation / codexSmartNamespace / codexProxyHost 等 测试早已走这条路。 验证: - pnpm --dir apps/desktop run typecheck → exit 0(修复前同命令 7 个 TS2339) - vitest 跑该文件 → 2 tests skipped(无 CINDY_TEST_CODEX_BINARY 时的既有行为), collect 正常,import 路径改动不引入加载错误 - eslint 该文件 → 0 problems Signed-off-by: Michael Zhou --- .../maker-host/__tests__/codexTerraProxy.integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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; From dab0ebc8978e4b66693eef15ea23744015c64f74 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 23:10:16 +0800 Subject: [PATCH 44/45] =?UTF-8?q?refactor(pi)!:=20=E5=88=A0=E6=8E=89?= =?UTF-8?q?=E6=BC=82=E7=A7=BB=E6=A3=80=E6=B5=8B=E7=9A=84=E5=9F=BA=E7=BA=BF?= =?UTF-8?q?=E9=95=9C=E5=83=8F,=E5=88=A4=E5=AE=9A=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E9=87=8D=E9=87=87=E9=9B=86=E4=B8=8E=20argv=20=E6=AF=94?= =?UTF-8?q?=E8=BE=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:此前漂移检测维护的第二份「collector 消费什么」的手写描述 —— mtime 基线、 逐 key 条目指纹、逐 key 解析身份、每键采样模式(dir/skill/none)、窗口复核、 repoRoot/resolvedWorkingDir 持有器。六轮 review 的六类漏检全部是这份镜像与 collector 实现之间的分歧: 1. 身份基线晚于 argv 采集 → 窗口内改指被固化成一致基线(Codex P2) 2. 窗口复核与启动基线比 → 空目录 null→path 误判(窗口复核) 3. 软链键一律跳读 → 直链 skill 的清单增删漏检(Greptile P2) 4. 先读清单后记基线 → 安装器交错造成永久漏检(Greptile P2) 5. 剪枝目录按 dir 采样 → node_modules 全列表每条消息一次(Codex P2) 6. 软链 namespace 按 dir 采样 → 仓外大目录全列表(Greptile P2) 而这份镜像并不便宜:快检每 key 3 次 syscall、key 数≈资源数+3×目录链,与 collector 一次采集(每目录 1 readdir + 每资源 3~5 stat)同量级。即:用同等的 IO 换来了一个 永远会分歧的第二描述。 根治:删掉镜像。快照只保留 argv 实际使用的集合与受邀者裁剪口径;判定 = 用同一个 collector 重新采集一次,逐项相等比较。由此: - 没有基线 → 1/2/4 结构上不可能; - 没有采样模式 → 5/6 结构上不可能(剪枝/软链目录根本不进采集); - 采集按 realpath 出路径 → 软链改指(哪怕 mtime 逐位相同)必然改变集合; - 与时间戳无关 → 同一 tick 内的增删不会漏(3 由集合比较天然覆盖)。 净变化:project-resource-cli.ts -494/+116,漂移套件重写为 24 例(去掉全部 bumpMtime —— 那是旧盲区的痕迹)。变异检查:把判定改成恒 false,24 例中 16 例变红。 另含 local-agent 可见变体的回收抛错处置(Codex P2):不再在 Maker 抑制窗口外 裸 close 重试(那会在 start() 恢复同一转录前删掉暂存附件);实例已非 active 才 重建,仍 active 则本轮跳过重建、下条消息再试。 验证:drift 24 + cli 16 + maker/session/hook 590 全绿;maker-core 与 desktop typecheck 均 0 错。 Signed-off-by: Zhang Yunjin --- apps/desktop/src/main/local-agent/runtime.ts | 26 +- .../pi-project-resource-drift.test.ts | 600 +++-------------- packages/maker-core/src/agents/pi/index.ts | 29 +- .../src/agents/pi/project-resource-cli.ts | 612 ++++-------------- 4 files changed, 246 insertions(+), 1021 deletions(-) diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts index 64bf59add6..2a1222a0cc 100644 --- a/apps/desktop/src/main/local-agent/runtime.ts +++ b/apps/desktop/src/main/local-agent/runtime.ts @@ -578,13 +578,29 @@ export async function openLocalAgentRuntime( // 可见变体的 Session 由 Maker 托管:必须走 Maker 的 runtime-refresh 关闭 // (实例方法自带 rehydrate 抑制窗口)。直接 Session.close 不登记原因,会 // 被按 unexpected 丢掉排队回合,未抑制的 onClose 会在重建前清掉暂存附件 - // (Codex P1,2026-11-10)。不可见变体不在 activeSessions,Maker 回收恒 - // false,回退直关。 - if (!(await maker.recyclePiRuntimeIfResourcesDrifted(previous).catch(() => false))) { + // (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); } - assertCurrent(current); - handle = await start(previous.sdkSessionId, current); } if (params.effort !== undefined) { await handle.setEffort(params.effort as Parameters[0]); 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 index 35f98bf5e0..72725c828e 100644 --- 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 @@ -1,34 +1,27 @@ /** * 项目资源漂移检测 —— 纯 fs 单测(不 spawn pi)。 * - * 契约:snapshotPiProjectResourceLaunch 冻结"路径集合 + watch root mtime 基线"; - * piProjectResourcesDrifted 两级判定 —— mtime 全等 → 无漂移(stat 快检,零扫描); - * mtime 变化 → 全量重扫(每次调用至多一次)按路径集合判定(集合相同不回收, - * 路径集合才是 argv 的输入),且就地刷新基线让后续快检恢复零扫描。 - * watch roots 必须覆盖 collector 实际枚举的每一层目录:在已存在子目录内增删 - * 条目只改该子目录自身 mtime,漏盯哪层就在哪层漏检。 + * 契约:启动快照只存「argv 实际使用的路径集合」;piProjectResourcesDrifted 用 + * 同一个 collector 重新采集一遍后逐项比较。**没有任何基线镜像**(无 mtime、无条目 + * 指纹、无逐 key 解析身份),因此不存在「镜像与 collector 分歧」导致的漏检: + * 同一 tick 内的增删、清单后落地、软链改指同 mtime 孪生树都直接反映为集合变化。 + * + * 下面每个用例都不再需要手工推 mtime —— 过去那层依赖正是盲区的来源。 */ -import fs from 'node:fs'; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'; +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, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { collectPiProjectResourceCliPaths, - collectPiProjectResourceLaunchWatch, - collectPiProjectResourceSurface, + type PiProjectResourceCliPaths, piProjectResourcesDrifted, - resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, } from '../project-resource-cli.js'; -import type { PiProjectResourceCliPaths } from '../project-resource-cli.js'; let project = ''; -// Windows CI 无符号链接特权:软链相关用例仅在 POSIX 跑。 -const itPosixOnly = process.platform === 'win32' ? it.skip : it; - beforeEach(() => { project = mkdtempSync(path.join(tmpdir(), 'pi-resource-drift-')); }); @@ -42,39 +35,18 @@ function writeSkill(relativeDir: string, name: string): void { writeFileSync(path.join(project, relativeDir, name, 'SKILL.md'), `---\nname: ${name}\ndescription: test\n---\n`); } -function statMtime(target: string): number { - return statSync(target).mtimeMs; -} - -/** 实现内部以 realpath(scanRoot) 作键前缀、未创建尾段词法拼接(macOS 的 os.tmpdir() 是 /var/folders 软链):断言必须同语义查键,否则键恒缺失(MagicLizi P1 两轮)。canon 向上走到最深存在祖先做 realpath,再把不存在的尾段按原序拼回 —— 对已存在路径等价于 realpathSync。 */ -function canon(target: string): string { - const abs = path.isAbsolute(target) ? target : path.resolve(target); - const missingTail: string[] = []; - let cur = abs; - for (;;) { - try { - return path.join(realpathSync(cur), ...missingTail); - } catch { - const parent = path.dirname(cur); - if (parent === cur) return abs; - missingTail.unshift(path.basename(cur)); - cur = parent; - } - } -} - -// Windows 文件时间戳有粒度(最粗 ~15.6ms):同一 tick 内的连续 mkdir/write 不改 -// 父目录 mtime,快检判不出漂移就不触发重扫 —— 断言依赖漂移判定的步骤必须显式 -// 推 mtime,否则 Windows CI 会偶发假失败(2026-11-08 run 42406651024 实报)。 -function bumpMtime(target: string): void { - const t = new Date(statSync(target).mtimeMs + 50); - utimesSync(target, t, t); -} - +/** 生产调用点同序:快照 = 当前采集结果(采集即 argv)。 */ function snapshot(restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { - // 与生产调用点同口径:surface 一次遍历同批产出基线与路径(结构上不可分离)。 - const surface = collectPiProjectResourceSurface(project); - return snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch, restrict); + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), restrict); +} + +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', () => { @@ -87,18 +59,15 @@ describe('piProjectResourcesDrifted', () => { writeSkill(path.join('.pi', 'skills'), 'alpha'); const baseline = snapshot(); writeSkill(path.join('.pi', 'skills'), 'beta'); - bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('returns to no-drift when the added skill is removed again', () => { + 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'); - bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(true); rmSync(path.join(project, '.pi', 'skills', 'beta'), { recursive: true, force: true }); - bumpMtime(path.join(project, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(false); }); @@ -123,21 +92,17 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('detects a project extension added after launch', () => { + 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 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 nestedSurface = collectPiProjectResourceSurface(nested); - const baseline = snapshotPiProjectResourceLaunch( - nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); - writeSkill(path.join('.agents', 'skills'), 'gamma'); + 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); }); @@ -147,16 +112,14 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('watch roots cover .pi and the .agents ancestor chain', () => { + 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 roots = collectPiProjectResourceLaunchWatch(nested).mtimes; - expect(roots.has(canon(path.join(nested, '.pi')))).toBe(true); - expect(roots.has(canon(path.join(nested, '.agents')))).toBe(true); - expect(roots.has(canon(path.join(nested, '.agents', 'skills')))).toBe(true); - expect(roots.has(canon(path.join(project, '.agents')))).toBe(true); - expect(roots.has(canon(path.join(project, '.agents', 'skills')))).toBe(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)', () => { @@ -188,273 +151,113 @@ describe('piProjectResourcesDrifted', () => { expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('detects index.ts added inside an existing extension dir', () => { - mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: 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(); - writeFileSync(path.join(project, '.pi', 'extensions', 'myext', 'index.ts'), 'export {};\n'); + 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('refreshes the mtime baseline after a rescan finds the same path set', () => { - writeSkill(path.join('.pi', 'skills'), 'alpha'); + 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(); - const skillsDir = path.join(project, '.pi', 'skills'); - const mtimeAtLaunch = baseline.watchRootMtimes.get(canon(skillsDir))!; - // 无关子目录:改了 skills 根 mtime,但不改变路径集合 - mkdirSync(path.join(skillsDir, 'unrelated'), { recursive: true }); expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 基线已就地刷新:下一次快检恢复零扫描,且真实漂移仍能检出 - expect(baseline.watchRootMtimes.get(canon(skillsDir))).toBe(statMtime(skillsDir)); - expect(baseline.watchRootMtimes.get(canon(skillsDir))).not.toBe(mtimeAtLaunch); + writeSkill('ns-b', 'alpha'); + rmSync(path.join(project, '.pi', 'skills', '@scope')); + linkDir(targetB, path.join(project, '.pi', 'skills', '@scope')); expect(piProjectResourcesDrifted(baseline)).toBe(false); - writeSkill(path.join('.pi', 'skills'), 'beta'); - expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('watch roots cover namespace and nested skill levels plus extension child dirs', () => { - writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); - mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'plain'), { recursive: true }); - mkdirSync(path.join(project, '.pi', 'extensions', 'myext'), { recursive: true }); - const roots = collectPiProjectResourceLaunchWatch(project).mtimes; - const ns = path.join(project, '.pi', 'skills', '@scope'); - expect(roots.has(canon(ns))).toBe(true); - expect(roots.has(canon(path.join(ns, 'alpha')))).toBe(true); - expect(roots.has(canon(path.join(ns, 'plain')))).toBe(true); - expect(roots.has(canon(path.join(project, '.pi', 'extensions', 'myext')))).toBe(true); - }); - - it('paths and watch table come from one surface walk (self-consistent baseline)', () => { - // argv 与基线出自同一次遍历:基线描述的就是 argv 消费的状态,结构上不可能 - // 不一致;快检只需检测「盘上 ≠ 基线」。 - writeSkill(path.join('.pi', 'skills'), 'alpha'); - const surface = collectPiProjectResourceSurface(project); - const baseline = snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch); + 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); - expect(baseline.watchRootMtimes.get(canon(path.join(project, '.pi', 'skills')))) - .toBe(statMtime(path.join(project, '.pi', 'skills'))); }); - it('retarget between the surface walk and snapshot publish is drift (argv and baseline are same-batch)', () => { - // 回归(Codex P2,2026-11-10):身份基线若在 argv 收集之后采样,「采基线前的 - // 改指」会被固化成一致基线(mtime 孪生树碰撞时无任何信号)→ 永久漏检。 - // 按生产序复刻:① 采 watch(含解析身份)→ ② 收集 argv → ③ 窗口内改指孪生树 - // → ④ 建快照。快检必须凭身份信号判漂移。 - const realA = path.join(project, 'workspaces', 'real-a'); - const realB = path.join(project, 'workspaces', 'real-b'); + 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 }); - // mtime 孪生:两树各层对齐到整秒,排除 mtime 信号,身份是唯一信号 - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - for (const [root, skill] of [[realA, 'alpha-a'], [realB, 'alpha-b']] as const) { - for (const dir of [root, path.join(root, '.pi'), path.join(root, '.pi', 'skills'), path.join(root, '.pi', 'skills', skill)]) { - utimesSync(dir, aligned, aligned); - } - } - const link = path.join(project, 'wd-link'); - const linkType = process.platform === 'win32' ? 'junction' : 'dir'; - symlinkSync(realA, link, linkType); - // surface 一次遍历:argv 与基线同批,均来自 A —— 生产不可能再出现「基线与 - // 集合不同批」;发布前的改指仍必须由身份信号检出。 - const surface = collectPiProjectResourceSurface(link); - rmSync(link); - symlinkSync(realB, link, linkType); // 发布前改指 B(mtime 已对齐) - const baseline = snapshotPiProjectResourceLaunch(link, surface.paths, surface.repoRoot, surface.watch); + 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('detects a skill added within the same timestamp tick (entry fingerprint signal)', () => { - // NTFS/FAT 时间戳量化:基线采样后同一 tick 内新增,mtime 与基线逐位相等 —— - // 只看 mtime 会永久漏检(集合不变则基线永不刷新)。条目名指纹是第二信号。 + it('does not collect or watch pruned generated dirs (node_modules/dist)', () => { writeSkill(path.join('.pi', 'skills'), 'alpha'); - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - const skillsDir = path.join(project, '.pi', 'skills'); - utimesSync(skillsDir, aligned, aligned); + 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(); - writeSkill(path.join('.pi', 'skills'), 'beta'); - // 显式把 mtime 恢复到基线值,模拟「同一 tick」的量化等值 - utimesSync(skillsDir, aligned, aligned); + 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('guest restriction: outside-scope set change is not drift (no recycle loop), inside-scope is', () => { - // 受邀者:argv 只含 guestRoot 裁剪后的集合,漂移必须按同一口径比较(fresh 先 - // 裁剪再比)。裁剪缺失时拿全量比裁剪基线,镜像外任何变化恒判漂移 → 回收死 - // 循环;快照缺失(旧行为)时镜像内新增永不生效。 + 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 = canon(path.join(project, 'mirror')) + path.sep; - const restrict = (p: PiProjectResourceCliPaths): PiProjectResourceCliPaths => ({ - skills: Object.freeze(p.skills.filter((s) => s.startsWith(scope))), - promptTemplates: Object.freeze(p.promptTemplates.filter((s) => s.startsWith(scope))), + 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 surface = collectPiProjectResourceSurface(wd); - const collected = surface.paths; - // 前提:全量收集含 mirror 外的技能(链上 .agents 越过 guestRoot) - expect(collected.skills.some((s) => !s.startsWith(scope))).toBe(true); - const baseline = snapshotPiProjectResourceLaunch(wd, restrict(collected), surface.repoRoot, surface.watch, restrict); + 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); - // mirror 外新增:有信号(链上 .agents 被盯),裁剪口径下集合未变 → 不回收 writeSkill(path.join('.agents', 'skills'), 'global-2'); - bumpMtime(path.join(project, '.agents')); expect(piProjectResourcesDrifted(baseline)).toBe(false); - // mirror 内新增:受邀者 argv 真会变 → 漂移 writeSkill(path.join('mirror', 'sub', '.pi', 'skills'), 'beta'); - bumpMtime(path.join(wd, '.pi', 'skills')); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); - it('keeps argv and baseline consistent when a manifest lands during the walk (no permanent miss)', () => { - // 回归(Greptile P2):「读清单存在性」早于「记基线」时,安装器在这两步之间 - // 写入 SKILL.md → 基线记写后、argv 记写前 → 快检恒等、该 skill 永久不生效。 - // 现在判断输入与基线同一次采样产出,交错只可能让 argv 领先基线(可收敛), - // 不可能落后。 - writeFileSync(path.join(project, '.git'), ''); - writeSkill(path.join('.pi', 'skills'), 'alpha'); - mkdirSync(path.join(project, '.pi', 'skills', 'foo'), { recursive: true }); - const skillsDir = path.join(realpathSync(project), '.pi', 'skills'); - const fooDir = path.join(skillsDir, 'foo'); - const originalReaddir = fs.readdirSync as typeof fs.readdirSync; - let injected = false; - const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => { - // 在「枚举 foo 目录」这一次读之前落地 SKILL.md:模拟安装器与采样的交错。 - if (!injected && String(target) === fooDir) { - injected = true; - writeFileSync(path.join(fooDir, 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); - } - return (originalReaddir as never as (t: fs.PathLike, o?: unknown) => unknown)(target, options); - }) as never); - let surface; - try { - surface = collectPiProjectResourceSurface(project); - } finally { - spy.mockRestore(); - } - expect(injected).toBe(true); - const baseline = snapshotPiProjectResourceLaunch(project, surface.paths, surface.repoRoot, surface.watch); - // 断言「argv 与基线一致」:技能要么被收集,要么基线不含它; - // 两者任一成立都可在后续收敛,唯独不能「argv 漏收而基线已含」。 - const collectedFoo = surface.paths.skills.includes(fooDir); - const baselineHasManifest = (surface.watch.entries.get(fooDir) ?? '').includes('SKILL.md'); - expect(collectedFoo).toBe(true); - expect(baselineHasManifest).toBe(collectedFoo); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - }); - - it('detects a manifest installed between the sample and the decision (per-key single read)', () => { - // 回归(Greptile P2 直链技能):collector 对仓内软链目标消费清单存在性 —— - // 软键条目基线必须取清单存在性而非跳读,否则目标内同刻新增 SKILL.md - // (namespace→skill 迁移)四路信号全盲:目标 mtime 量化等值、链接身份不变、 - // 条目跳读、manifest watcher 只盯软链清单。 - writeFileSync(path.join(project, '.git'), ''); - mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); - mkdirSync(path.join(project, 'target-dir'), { recursive: true }); - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - utimesSync(path.join(project, 'target-dir'), aligned, aligned); - symlinkSync(path.join(project, 'target-dir'), path.join(project, '.pi', 'skills', 'foo'), 'junction'); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 前提:软链一层只采样清单存在性('M:' + 空清单)—— 既不 readdir 目标 - // (仓内大目录也不拖快检),又与判断输入同一次采样(无「先读清单后记基线」窗口) - const linkKey = path.join(realpathSync(project), '.pi', 'skills', 'foo'); - expect(baseline.watchRootEntries.get(linkKey)).toBe('M:'); - // 同一刻新增普通文件 SKILL.md(显式把目标目录 mtime 恢复基线值,隔离 mtime 信号) - writeFileSync(path.join(project, 'target-dir', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); - utimesSync(path.join(project, 'target-dir'), aligned, aligned); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('samples a symlinked namespace by manifest only, never by full entry list', () => { - // 回归(Greptile P2):一层子键曾一律用 'dir' 采样,仓内软链 namespace 也会 - // 每轮快检 readdir + 排序整个目标目录 —— 而 collector 根本不会走进它。 - writeFileSync(path.join(project, '.git'), ''); - writeSkill(path.join('.pi', 'skills'), 'alpha'); - const big = path.join(project, 'big-namespace'); - mkdirSync(big, { recursive: true }); - for (let i = 0; i < 40; i += 1) mkdirSync(path.join(big, `entry-${i}`), { recursive: true }); - symlinkSync(big, path.join(project, '.pi', 'skills', '@big'), 'junction'); - - const surface = collectPiProjectResourceSurface(project); - const linkKey = path.join(realpathSync(project), '.pi', 'skills', '@big'); - // 基线是清单存在性指纹(不是完整条目列表),快检因此不会遍历 40 个无关条目。 - expect(surface.watch.entries.get(linkKey)).toBe('M:'); - // 真实目录(一层 skill 目录里的 namespace)仍用完整列表,同刻新增才检得出。 - expect(surface.watch.entries.get(path.join(realpathSync(project), '.pi', 'skills'))).toMatch(/^L:/); - const baseline = snapshotPiProjectResourceLaunch( - project, surface.paths, surface.repoRoot, surface.watch); - // 目标目录内新增无关条目:集合不变,不触发回收(且不依赖其完整列表信号)。 - mkdirSync(path.join(big, 'later'), { recursive: true }); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - }); - - it('stores null entries baseline for collector-excluded keys (symlink namespace to outside-repo target)', () => { - // Greptile P2:collector 不枚举越界/软链 namespace 子树,条目基线存 null —— - // 快检不 readdir 其目标(readdir 跟随软链,外部大目录完整列表是每条消息一次 - // 的纯开销);改指信号由解析身份承担。 - mkdirSync(path.join(project, 'repo'), { recursive: true }); - writeFileSync(path.join(project, 'repo', '.git'), ''); - writeSkill(path.join('repo', '.pi', 'skills'), 'alpha'); - writeSkill(path.join('outside', 'big'), 'huge'); // repoRoot 外的目标树 - mkdirSync(path.join(project, 'repo', '.pi', 'skills'), { recursive: true }); - symlinkSync(path.join(project, 'outside', 'big'), path.join(project, 'repo', '.pi', 'skills', '@scope'), 'junction'); - const wd = path.join(project, 'repo'); - const surface = collectPiProjectResourceSurface(wd); - // 前提:软链 namespace 键的条目基线为 null(快检将跳读)。键是链接路径本体, - // 不能用 canon 查(canonical 化会把键解析成目标路径) - expect(surface.watch.entries.get(path.join(realpathSync(wd), '.pi', 'skills', '@scope'))).toBeNull(); - const baseline = snapshotPiProjectResourceLaunch(wd, surface.paths, surface.repoRoot, surface.watch); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 目标树内部增删:集合不变 → 不漂移(mtime 跟随目标会触发一次重扫后收敛) - writeSkill(path.join('outside', 'big'), 'more'); - bumpMtime(path.join(project, 'outside', 'big')); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - }); - - it('rebuilds the watch map after an unchanged rescan so new child dirs are watched', () => { - mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); - const baseline = snapshot(); - // 重扫窗口内新建的空扩展目录:集合未变,但必须从此纳入盯视 - mkdirSync(path.join(project, '.pi', 'extensions', 'newext'), { recursive: true }); - bumpMtime(path.join(project, '.pi', 'extensions')); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - expect(baseline.watchRootMtimes.has(canon(path.join(project, '.pi', 'extensions', 'newext')))).toBe(true); - // 若不重建基线,这里的 index.ts 只改未盯视的新子目录 mtime,永远检不出 - writeFileSync(path.join(project, '.pi', 'extensions', 'newext', 'index.ts'), 'export {};\n'); - bumpMtime(path.join(project, '.pi', 'extensions', 'newext')); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('treats a missing .pi/extensions appearing as an empty dir as no drift (resolution null→path)', () => { - writeSkill(path.join('.pi', 'skills'), 'alpha'); - const baseline = snapshot(); - // 前提:缺失的扩展根已在监测表中,基线解析为 null(Greptile P2) - expect(baseline.watchRootsResolved.get(canon(path.join(project, '.pi', 'extensions')))).toBeNull(); - // 仅创建空目录:资源路径集合仍相同,不得误报漂移触发多余冷启动 - mkdirSync(path.join(project, '.pi', 'extensions'), { recursive: true }); - bumpMtime(path.join(project, '.pi', 'extensions')); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 空目录已纳入盯视:之后真正的扩展落地必须检出 - writeFileSync(path.join(project, '.pi', 'extensions', 'hook.ts'), 'export {};\n'); - bumpMtime(path.join(project, '.pi', 'extensions')); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('detects a nearer git boundary appearing after launch (repo root identity)', () => { + 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 nestedSurface = collectPiProjectResourceSurface(nested); - const baseline = snapshotPiProjectResourceLaunch( - nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); + const baseline = snapshotPiProjectResourceLaunch(nested, collectPiProjectResourceCliPaths(nested)); expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 子目录自己 git init:枚举链截断,outer skill 不再属于本项目边界 mkdirSync(path.join(nested, '.git'), { recursive: true }); - bumpMtime(nested); expect(piProjectResourcesDrifted(baseline)).toBe(true); }); @@ -462,215 +265,20 @@ describe('piProjectResourcesDrifted', () => { mkdirSync(path.join(project, 'outer'), { recursive: true }); writeFileSync(path.join(project, 'outer', '.git'), ''); const nested = path.join(project, 'outer', 'sub'); - mkdirSync(path.join(nested, '.pi', 'skills', 'alpha'), { recursive: true }); - writeFileSync(path.join(nested, '.pi', 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: t\n---\n'); - const nestedSurface = collectPiProjectResourceSurface(nested); - const baseline = snapshotPiProjectResourceLaunch( - nested, nestedSurface.paths, nestedSurface.repoRoot, nestedSurface.watch); - // 嵌套目录 git init:被截断的上层链没有任何项目资源,集合不变,不应触发回收 + 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); - // 边界持有者已就地更新:后续快检恢复零扫描,不再重复重扫判定 - expect(baseline.state.repoRoot).toBe(realpathSync(nested)); - expect(piProjectResourcesDrifted(baseline)).toBe(false); }); - itPosixOnly('detects the resolved symlink target of a prompt template moved away', () => { - // Windows CI 无符号链接特权,本用例仅在 POSIX 跑(见 itPosixOnly)。 - mkdirSync(path.join(project, 'targets'), { recursive: true }); - mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); - writeFileSync(path.join(project, 'targets', 'opsx.md'), '---\ndescription: t\n---\n'); - symlinkSync(path.join(project, 'targets', 'opsx.md'), path.join(project, '.pi', 'prompts', 'foo.md')); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 目标移动/删除不改变 .pi/prompts 自身的 mtime,只有盯住解析后的文件本体才能检出 - rmSync(path.join(project, 'targets', 'opsx.md')); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - itPosixOnly('detects a prompt target materializing behind a dangling symlink', () => { - mkdirSync(path.join(project, '.pi', 'prompts'), { recursive: true }); - mkdirSync(path.join(project, 'elsewhere'), { recursive: true }); - symlinkSync(path.join(project, 'elsewhere', 'target.md'), path.join(project, '.pi', 'prompts', 'foo.md')); - const baseline = snapshot(); - // 悬空软链自身已入盯视:目标落地(改动的是未盯视的 elsewhere 目录)也能检出 - writeFileSync(path.join(project, 'elsewhere', 'target.md'), '---\ndescription: t\n---\n'); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - itPosixOnly('detects the symlink target of a nested skill manifest moved away', () => { - // Windows CI 无符号链接特权,本用例仅在 POSIX 跑(见 itPosixOnly)。 - mkdirSync(path.join(project, 'targets'), { recursive: true }); - mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'alpha'), { recursive: true }); - writeFileSync(path.join(project, 'targets', 'real.md'), '---\nname: alpha\ndescription: t\n---\n'); - symlinkSync(path.join(project, 'targets', 'real.md'), path.join(project, '.pi', 'skills', '@scope', 'alpha', 'SKILL.md')); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 目标移动/删除不改变 skill 目录自身 mtime,只有盯住解析后的清单本体才能检出 - rmSync(path.join(project, 'targets', 'real.md')); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - itPosixOnly('detects a nested skill manifest target materializing behind a dangling symlink', () => { - // 嵌套候选目录的清单是悬空软链时,hasSkillFile 为 false 不入收集,但链接本体 - // 已入盯视:目标落地(改动的 elsewhere 目录未被盯视)也能检出。 - mkdirSync(path.join(project, '.pi', 'skills', '@scope', 'foo'), { recursive: true }); - mkdirSync(path.join(project, 'elsewhere'), { recursive: true }); - symlinkSync(path.join(project, 'elsewhere', 'skill.md'), path.join(project, '.pi', 'skills', '@scope', 'foo', 'SKILL.md')); - const baseline = snapshot(); - writeFileSync(path.join(project, 'elsewhere', 'skill.md'), '---\nname: foo\ndescription: t\n---\n'); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - itPosixOnly('detects a second-level manifest target move for a direct symlinked skill root', () => { - // 直链 skill 根的 SKILL.md 是二级软链:目标删除只改目标处,跟随后的目录与 - // skills 根 mtime 都不变,必须靠清单本体盯视检出。 - mkdirSync(path.join(project, '.pi', 'skills'), { recursive: true }); - mkdirSync(path.join(project, 'real-skill'), { recursive: true }); - mkdirSync(path.join(project, 'targets'), { recursive: true }); - writeFileSync(path.join(project, 'real-skill', 'SKILL.md'), '---\nname: foo\ndescription: t\n---\n'); - symlinkSync(path.join(project, 'real-skill'), path.join(project, '.pi', 'skills', 'foo'), 'dir'); - rmSync(path.join(project, 'real-skill', 'SKILL.md')); - symlinkSync(path.join(project, 'targets', 'real.md'), path.join(project, 'real-skill', 'SKILL.md')); - const baseline = snapshot(); - // 目标落地(悬空链的本体已入盯视,写入后 stat 由 -1 变实值)→ 判漂移 - writeFileSync(path.join(project, 'targets', 'real.md'), '---\nname: foo\ndescription: t\n---\n'); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('collectors honor a shared repoRootHint (launch shares one resolution)', () => { + it('reports collected paths as realpaths so duplicates across roots collapse', () => { writeFileSync(path.join(project, '.git'), ''); writeSkill(path.join('.pi', 'skills'), 'alpha'); - const hint = resolvePiResourceRepoRoot(project); - expect([...collectPiProjectResourceCliPaths(project, hint).skills]) - .toEqual([...collectPiProjectResourceCliPaths(project).skills]); - expect([...collectPiProjectResourceLaunchWatch(project, hint).mtimes.keys()]) - .toEqual([...collectPiProjectResourceLaunchWatch(project).mtimes.keys()]); - }); - - it('missing directories baseline as -1 and compare against real mtimes', () => { - const roots = collectPiProjectResourceLaunchWatch(project).mtimes; - expect(roots.get(canon(path.join(project, '.pi')))).toBe(-1); - }); - it('detects a symlinked workingDir retargeted within the same repo (resolved scan root in drift key)', () => { - // 回归(Codex P2):workingDir 经软链启动、软链改指同仓另一目录时,repoRoot - // 与解析后旧物理根的 mtime 均不变,快检会放行旧 argv。漂移键必须含解析后 - // 的 scanRoot:改指即漂移。junction 在 Windows CI 无特权可用。 - const realA = path.join(project, 'workspaces', 'real-a'); - const realB = path.join(project, 'workspaces', 'real-b'); - 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 }); - const link = path.join(project, 'wd-link'); - const linkType = process.platform === 'win32' ? 'junction' : 'dir'; - symlinkSync(realA, link, linkType); - const surface = collectPiProjectResourceSurface(link); - const baseline = snapshotPiProjectResourceLaunch( - link, - surface.paths, - surface.repoRoot, - surface.watch, - ); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - rmSync(link); - symlinkSync(realB, link, linkType); - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('retargeting the `.pi` junction to a same-mtime twin tree is drift (resolved pi-root identity)', () => { - // 回归(Codex P2):`.pi` 本体是仓内软链时,改指结构相同、mtime 碰巧一致的 - // 另一资源树 —— watch 面取的是解析后目标的 mtime,碰撞时快检放行旧 argv; - // 唯一信号是资源根的解析身份(realpath)。 - const targetA = path.join(project, 'pi-a'); - const targetB = path.join(project, 'pi-b'); - const piLink = path.join(project, '.pi'); - writeSkill(path.join('pi-a', 'skills'), 'alpha'); - // Windows utimes 有精度截断:先把 A 的各层目录对齐到整秒,让快照值与 B 的 - // 对齐值可以逐位相等(mtime 碰撞前提才成立)。 - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { - utimesSync(path.join(targetA, ...dir), aligned, aligned); - } - symlinkSync(targetA, piLink, 'junction'); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - - // B:同名结构、不同内容;目录 mtime 调成与 A 逐层一致(watch 面失明的碰撞前提)。 - // 同名结构:让 mtime 碰撞成为唯一干扰源,解析身份才是本用例的信号。 - writeSkill(path.join('pi-b', 'skills'), 'alpha'); - // 根目录也要对齐:watch 面包含 `.pi` 解析后的目标目录自身。B 的对齐值复用 - // A 的整秒时间,让 watch 面逐位相等(mtime 碰撞前提)。 - for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { - utimesSync(path.join(targetB, ...dir), aligned, aligned); - } - rmSync(piLink); - symlinkSync(targetB, piLink, 'junction'); - - - // 改指后 lexical watch 面与 mtime 全等,唯一信号是 `.pi` 解析身份变化。 - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('retargeting the `.agents` junction to a same-mtime twin tree is drift (uniform resolved identity)', () => { - // 根治回归(Codex P2 族第三击):`.agents` 链根改指。统一解析身份基线后, - // 任意层级改指同 mtime 的孪生树都必然触发,不再需要逐点枚举。 - const targetA = path.join(project, 'agents-a'); - const targetB = path.join(project, 'agents-b'); - const agentsLink = path.join(project, '.agents'); - writeSkill(path.join('agents-a', 'skills'), 'alpha'); - // Windows utimes 精度截断:先整秒对齐 A,快照值与 B 的对齐值才能逐位相等。 - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { - utimesSync(path.join(targetA, ...dir), aligned, aligned); - } - symlinkSync(targetA, agentsLink, 'junction'); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - - // B:同名结构;三层 mtime 与 A 全等(watch 面失明的碰撞前提)。 - writeSkill(path.join('agents-b', 'skills'), 'alpha'); - for (const dir of [[] as string[], ['skills'], ['skills', 'alpha']]) { - utimesSync(path.join(targetB, ...dir), aligned, aligned); - } - rmSync(agentsLink); - symlinkSync(targetB, agentsLink, 'junction'); - - expect(piProjectResourcesDrifted(baseline)).toBe(true); - }); - - it('retargeting a nested namespace junction to a same-mtime twin tree leaves the set unchanged (identity is signal, not verdict)', () => { - // 通用性验证的另一面:collector 明文不走进软链 namespace(symlinked namespace - // is intentionally not walked),改指前后集合都不含它 —— 按集合契约这不是漂移, - // 不触发多余冷启动;解析身份变化只负责触发重扫(本用例的信号隔离仍成立)。 - const targetA = path.join(project, 'ns-a'); - const targetB = path.join(project, 'ns-b'); - const nsLink = path.join(project, '.pi', 'skills', '@scope'); - mkdirSync(path.dirname(nsLink), { recursive: true }); - writeSkill('ns-a', 'alpha'); - const aligned = new Date(Math.floor(Date.now() / 1000) * 1000); - const skillsDir = path.join(project, '.pi', 'skills'); - for (const dir of [[] as string[], ['alpha']]) { - utimesSync(path.join(targetA, ...dir), aligned, aligned); - } - utimesSync(skillsDir, aligned, aligned); - symlinkSync(targetA, nsLink, 'junction'); - const baseline = snapshot(); - expect(piProjectResourcesDrifted(baseline)).toBe(false); - - writeSkill('ns-b', 'alpha'); - for (const dir of [[] as string[], ['alpha']]) { - utimesSync(path.join(targetB, ...dir), aligned, aligned); - } - rmSync(nsLink); - symlinkSync(targetB, nsLink, 'junction'); - // rm/symlink 弄脏了 `.pi/skills` 的 mtime,恢复到快照值以隔离信号。 - utimesSync(skillsDir, aligned, aligned); - - expect(piProjectResourcesDrifted(baseline)).toBe(false); - // 契约的另一端不放松:软链 namespace 换成真目录,集合真正变化,必须检出。 - rmSync(nsLink); - writeSkill(path.join('.pi', 'skills', '@scope'), 'alpha'); - bumpMtime(skillsDir); - expect(piProjectResourcesDrifted(baseline)).toBe(true); + 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/index.ts b/packages/maker-core/src/agents/pi/index.ts index e427234398..71527afed3 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -245,12 +245,10 @@ import { import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, - collectPiProjectResourceSurface, emptyPiProjectResourceCliPaths, filterPiProjectCliSkills, piProjectResourceCliArgs, piProjectResourcesDrifted, - resolvePiResourceRepoRoot, snapshotPiProjectResourceLaunch, } from './project-resource-cli.js'; import { @@ -4069,19 +4067,14 @@ 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. // 受邀者:只要会话目录内的技能与提示词模板,项目扩展不加载(会在本机执行)。 - // 项目资源表面(spawn 采样):argv 路径集合与盯视基线出自**同一次遍历** - // (collectPiProjectResourceSurface)—— 结构不变量:基线与 argv 消费的状态 - // 不可能不一致,快检只需检测「盘上 ≠ 基线」。分两次调用会重新造出「集合与 - // 基线不同批」的永久漏检窗口(Codex P2,2026-11-10)。受邀者同样建快照 - // (镜像同步进来的新技能必须能检出),裁剪口径经 restrict 下发,比较对 - // fresh 做同一裁剪。 - const projectResourceSurfaceAtLaunch = loadProjectResourcesInPlace - ? collectPiProjectResourceSurface(opts.workingDir) - : null; - const collectedProjectResources = projectResourceSurfaceAtLaunch + // 采集只发生这一次:其结果既是 argv 资源段,也是漂移检测的基准。漂移判定 + // 复用同一个 collector 重新采集后逐项比较(见 piProjectResourcesDrifted), + // 不另存任何基线 —— 存基线就等于手写一份「collector 消费什么」的镜像, + // 镜像与实现必然分歧(2026-11-10 六轮漏检全部出在这里)。 + const collectedProjectResources = loadProjectResourcesInPlace ? guestRoot - ? restrictPiGuestProjectResources(projectResourceSurfaceAtLaunch.paths, guestRoot) - : projectResourceSurfaceAtLaunch.paths + ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) + : collectPiProjectResourceCliPaths(opts.workingDir) : emptyPiProjectResourceCliPaths(); const projectResourceCli = loadProjectResourcesInPlace ? { @@ -4093,15 +4086,11 @@ export class PiAgent extends BaseAgent { } : collectedProjectResources; // 启动快照:供运行时空闲时的资源漂移检测(见 handle.hasProjectResourceDrift)。 - // 快照存未经禁用过滤的原始收集结果(受邀者已按 guestRoot 裁剪),与 drift - // 检测的 fresh collect 经同一 restrict 裁剪后同口径可比;受邀者裁剪缺了会拿 - // 全量比裁剪基线恒判漂移,回收死循环。 - const projectResourceLaunchSnapshot = projectResourceSurfaceAtLaunch + // 只存 argv 实际用的集合与受邀者裁剪口径 —— 没有第二份基线。 + const projectResourceLaunchSnapshot = loadProjectResourcesInPlace ? snapshotPiProjectResourceLaunch( opts.workingDir, collectedProjectResources, - projectResourceSurfaceAtLaunch.repoRoot, - projectResourceSurfaceAtLaunch.watch, guestRoot ? (paths) => restrictPiGuestProjectResources(paths, guestRoot) : undefined) : null; 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 0aa5a03ac6..46d983fa89 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -68,17 +68,19 @@ function findNearestGitRoot(workingDir: string): string | null { } } -/** collector 与漂移快检共用的 git 边界解析(同输入必同输出,才能恒等比较)。 */ -export function resolvePiResourceRepoRoot(workingDir: string): string { - const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); - return findNearestGitRoot(scanRoot) ?? scanRoot; -} - function isWithinRoot(root: string, candidate: string): boolean { const relative = path.relative(root, candidate); return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)); } +function listDir(dir: string): fs.Dirent[] { + try { + return fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return []; + } +} + function isSymlinkDirectory(target: string): boolean { try { return fs.lstatSync(target).isSymbolicLink(); @@ -88,456 +90,141 @@ function isSymlinkDirectory(target: string): boolean { } /** readdir 把 Windows junction 报成目录时 Dirent.isSymbolicLink 为 false,需 lstat - * 兜底。collector 与 watcher 必须共用同一判定:口径分叉会让盯视面混入 collector - * 永不枚举的目标树键(无谓重扫 + 基线带脏键)。 */ + * 兜底:软链 namespace 不枚举(可越界/成环)这条规则在 Windows 上也必须成立。 */ function isSymlinkEntry(entry: fs.Dirent, absPath: string): boolean { return entry.isSymbolicLink() || (entry.isDirectory() && isSymlinkDirectory(absPath)); } -/** 从同一次 readdir 的条目里判定 skill 清单存在性(collector 口径:isFile 跟随 - * 软链)。软链清单要先解析目标是否为文件—— 这次读发生在该键基线之后,只会让 - * argv 领先基线,下次快检观察差异后收敛,不会永久漏检。 */ -function skillManifestIn(dir: string, dirents: readonly fs.Dirent[]): boolean { - for (const entry of dirents) { - if (entry.name !== 'SKILL.md' && entry.name !== 'skill.md') continue; - if (entry.isFile()) return true; - if (entry.isSymbolicLink() && isFile(path.join(dir, entry.name))) return true; - } - return false; +function hasSkillFile(dir: string): boolean { + return ['SKILL.md', 'skill.md'].some((name) => isFile(path.join(dir, name))); } /** - * 项目资源表面 = argv 路径集合 + 盯视基线,**同一次遍历**产出。 - * - * 结构不变量(逐键,2026-11-10 根因收口):一个键的基线字段与该键上的 argv 判断 - * 出自**同一次采样**(samplePiWatchKey),判断不早于基线、也不另发读。任何采样后 - * 的变化都会被快检观察为差异 → 重扫 → 集合相同则刷新基线后收敛;不存在「基线已 - * 含新状态、argv 还是旧状态」的永久漏检。 - * - * 历史教训:collector 与 watcher 曾是两套手写遍历(口径靠注释),后又只合并了 - * 遍历但保留键内两次读 —— 两次都是同一病根:同一事实产生两次,漂移检测就在两者 - * 之间漏。条目模式由**结构**决定(见 PiWatchEntriesMode),不看内容。 + * 走一遍 skills 根的两层树(collector 的枚举深度,不往更深处看)。 + * 先判清单(2 次 stat)再决定是否枚举 namespace:skill 目录不必付 readdir 代价。 */ -export interface PiProjectResourceSurface { - /** 本遍历认定的 git root(枚举链终点;调用方作为快照边界基线传入)。 */ - readonly repoRoot: string; - readonly paths: PiProjectResourceCliPaths; - readonly watch: PiProjectResourceLaunchWatch; -} +function collectSkillDirs(repoRoot: string, skillsDir: string, bucket: Set): void { + const resolvedDir = realpathOrNull(skillsDir); + if (!resolvedDir || !isDir(resolvedDir) || !isWithinRoot(repoRoot, resolvedDir)) return; -/** 把一个 skill 目录登记进集合(collector 口径:清单经 realpath 后须在仓内, - * realFolder 本身入集合)。此次校验性读发生在该键基线之后 —— 安全方向。 */ -function addPiSkill(repoRoot: string, realFolder: string, bucket: Set): void { - for (const name of ['SKILL.md', 'skill.md']) { - const manifestPath = path.join(realFolder, name); - if (!isFile(manifestPath)) continue; - const realMd = realpathOrNull(manifestPath); - if (realMd && isWithinRoot(repoRoot, realMd)) { - bucket.add(realFolder); - return; - } - } -} + // 清单经 realpath 后须仍在仓内,否则这个目录不算本项目的 skill。 + const addSkill = (realFolder: string): void => { + const skillMd = ['SKILL.md', 'skill.md'] + .map((name) => path.join(realFolder, name)) + .find(isFile); + const realMd = skillMd ? realpathOrNull(skillMd) : null; + if (realMd && isFile(realMd) && isWithinRoot(repoRoot, realMd)) bucket.add(realFolder); + }; -/** - * 走一遍 skills 根的两层树:每个键先采样(基线 + 判断输入),再用采样返回值做 - * collector 的集合判定 —— 全程不再发第二次读。 - */ -function walkPiSkillTree( - sample: PiProjectResourceLaunchWatch, - repoRoot: string, - skillsDir: string, - bucket: Set, -): void { - const root = samplePiWatchKey(sample, skillsDir, 'dir', repoRoot); - if (!root.inRepoDir || !root.resolved) return; - - for (const entry of root.dirents ?? []) { + for (const entry of listDir(resolvedDir)) { if (entry.name.startsWith('.') || /\.bak\.\d+$/.test(entry.name)) continue; - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; - const candidatePath = path.join(root.resolved, entry.name); - // 模式只由**结构**定(不看内容 —— 读内容定模式会重新造出两次读窗口): - // 软链一层 collector 要么收为直链 skill、要么直接跳过(不走 namespace), - // 只消费清单存在性 → 'skill'(两次 stat;仓内大目录也不拖快检); - // 真实目录 collector 会枚举 namespace → 'dir'(完整列表,同刻新增的嵌套 - // skill 目录才检得出)。 - const isSymlink = isSymlinkEntry(entry, candidatePath); - const child = samplePiWatchKey(sample, candidatePath, isSymlink ? 'skill' : 'dir', repoRoot); - if (!child.inRepoDir || !child.resolved) continue; - // 清单本体无论当前是否解析都盯住:悬空链(目标尚不存在)落地成 skill 时, - // 改动的只是未盯视的目标处,盯住链接自身才能检出(与 prompts 同款)。 - // 直链 skill 根同样适用:其 SKILL.md 为二级软链时,目标移动/删除只改目标处。 - watchPiSkillManifestTargets(sample, child.resolved, repoRoot); - // 判断输入与基线同源(Greptile P2:先 hasManifest 再记基线 → 中间写入的 - // SKILL.md 被固化进基线、argv 漏收 → 永久漏检);软链用采样时的清单存在性, - // 真实目录用采样时的同一次 readdir 条目。 - const hasManifest = isSymlink - ? child.manifest - : skillManifestIn(child.resolved, child.dirents ?? []); - if (hasManifest) { - addPiSkill(repoRoot, child.resolved, bucket); + const candidatePath = path.join(resolvedDir, entry.name); + const realFolder = realpathOrNull(candidatePath); + if (!realFolder || !isDir(realFolder) || !isWithinRoot(repoRoot, realFolder)) continue; + if (hasSkillFile(realFolder)) { + addSkill(realFolder); continue; } - // 软链 namespace collector 明文不走(可越界/成环);剪枝名同理。 - if (isSymlink || shouldPruneSkillScanDirectory(entry.name)) continue; + // Direct symlinked Skills remain supported above; a symlinked namespace + // could escape the repo or cycle and is intentionally not walked. + // lstat must see the unresolved path: a Windows junction may be reported + // as a directory by readdir and by the resolved realpath. + if (isSymlinkEntry(entry, candidatePath)) continue; + if (shouldPruneSkillScanDirectory(entry.name)) continue; // node_modules/dist 等生成目录 // At most one namespace/author level: //. - for (const nested of child.dirents ?? []) { + for (const nested of listDir(realFolder)) { if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue; - if (!nested.isDirectory() && !nested.isSymbolicLink()) continue; - const nestedPath = path.join(child.resolved, nested.name); - // 嵌套层 collector 只 stat 清单存在性、不再下行 → 'skill'(两次 stat)。 - const nestedSample = samplePiWatchKey(sample, nestedPath, 'skill', repoRoot); - if (!nestedSample.inRepoDir || !nestedSample.resolved) continue; - watchPiSkillManifestTargets(sample, nestedSample.resolved, repoRoot); - if (nestedSample.manifest) addPiSkill(repoRoot, nestedSample.resolved, bucket); - } - } -} - -/** 走一遍 prompts 根:根的采样条目既进基线也驱动枚举;每个模板以**链接路径** - * 采样(stat 跟随软链:悬空时 mtime=-1,目标落地即变),resolved 直接作为 argv - * 路径 —— 不再单独 realpath 后再比。 */ -function walkPiPromptTargets( - sample: PiProjectResourceLaunchWatch, - repoRoot: string, - promptsDir: string, - bucket: Set, -): void { - const root = samplePiWatchKey(sample, promptsDir, 'dir', repoRoot); - if (!root.inRepoDir || !root.resolved) return; - for (const entry of root.dirents ?? []) { - if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; - const entryPath = path.join(root.resolved, entry.name); - const target = samplePiWatchKey(sample, entryPath, 'none', repoRoot); - // 悬空/越界目标不收集;链接自身已入盯视(mtime 跟随目标,落地即检出)。 - if (!target.isFile || !target.resolved || !isWithinRoot(repoRoot, target.resolved)) continue; - bucket.add(target.resolved); - } -} - -/** 走一遍 extensions 根:根条目同时驱动基线/枚举;子键与 index.ts 以 'none' 采样 - * (文件键;缺失时 mtime=-1 → 同刻落地也必变),判断直接用采样返回值。 */ -function walkPiExtensionTree( - sample: PiProjectResourceLaunchWatch, - repoRoot: string, - extDir: string, - bucket: Set, -): void { - const root = samplePiWatchKey(sample, extDir, 'dir', repoRoot); - if (!root.inRepoDir || !root.resolved) return; - for (const entry of root.dirents ?? []) { - if (entry.name.startsWith('.')) continue; - const childPath = path.join(root.resolved, entry.name); - const child = samplePiWatchKey(sample, childPath, 'none', repoRoot); - if (!child.resolved || !isWithinRoot(repoRoot, child.resolved)) continue; - if (child.isFile && child.resolved.endsWith('.ts')) { - bucket.add(child.resolved); - continue; - } - if (!child.isDir) continue; - const index = samplePiWatchKey(sample, path.join(child.resolved, 'index.ts'), 'none', repoRoot); - if (index.isFile && index.resolved && isWithinRoot(repoRoot, index.resolved)) { - bucket.add(index.resolved); + const nestedFolder = realpathOrNull(path.join(realFolder, nested.name)); + if (!nestedFolder || !isDir(nestedFolder) || !isWithinRoot(repoRoot, nestedFolder)) continue; + if (hasSkillFile(nestedFolder)) addSkill(nestedFolder); } } } /** - * 项目资源表面:argv 路径集合与盯视基线的**唯一产出点**。生产调用方(spawn 采样、 - * 重扫)必须经此一次调用取两样 —— 分两次调用会重新造出「集合与基线不同批」的 - * 永久漏检窗口(Codex P2,2026-11-10)。 + * 收集 Pi CLI 需要加载的项目资源路径。这是 argv 资源段的**唯一产出点** —— + * 漂移检测也复用同一个函数(见 piProjectResourcesDrifted),所以「检测」与 + * 「实际使用」不可能描述同一份事实两次。 */ -export function collectPiProjectResourceSurface(workingDir: string, repoRootHint?: string): PiProjectResourceSurface { - const watch: PiProjectResourceLaunchWatch = { - scanRootResolved: realpathOrNull(workingDir), - mtimes: new Map(), - entries: new Map(), - resolved: new Map(), - }; +export function collectPiProjectResourceCliPaths(workingDir: string): PiProjectResourceCliPaths { + if (!workingDir || !path.isAbsolute(workingDir) || !isDir(workingDir)) { + return emptyPiProjectResourceCliPaths(); + } + const scanRoot = realpathOrNull(workingDir) ?? path.resolve(workingDir); + const repoRoot = findNearestGitRoot(scanRoot) ?? scanRoot; const skills = new Set(); const promptTemplates = new Set(); const extensions = new Set(); - if (!workingDir || !path.isAbsolute(workingDir) || !isDir(workingDir)) { - return freezePiProjectResourceSurface( - repoRootHint ?? watch.scanRootResolved ?? path.resolve(workingDir), skills, promptTemplates, extensions, watch); - } - const scanRoot = watch.scanRootResolved ?? path.resolve(workingDir); - const repoRoot = repoRootHint ?? (findNearestGitRoot(scanRoot) ?? scanRoot); - const piDir = path.join(scanRoot, '.pi'); - recordWatchKey(watch, piDir, 'dir', repoRoot); - walkPiSkillTree(watch, repoRoot, path.join(piDir, 'skills'), skills); - walkPiPromptTargets(watch, repoRoot, path.join(piDir, 'prompts'), promptTemplates); - walkPiExtensionTree(watch, repoRoot, path.join(piDir, 'extensions'), extensions); + + collectSkillDirs(repoRoot, path.join(scanRoot, '.pi', 'skills'), skills); let current = scanRoot; while (true) { - const agentsDir = path.join(current, '.agents'); - recordWatchKey(watch, agentsDir, 'dir', repoRoot); - walkPiSkillTree(watch, repoRoot, path.join(agentsDir, 'skills'), skills); + collectSkillDirs(repoRoot, path.join(current, '.agents', 'skills'), skills); if (current === repoRoot) break; const parent = path.dirname(current); if (parent === current) break; current = parent; } - return freezePiProjectResourceSurface(repoRoot, skills, promptTemplates, extensions, watch); -} -function freezePiProjectResourceSurface( - repoRoot: string, - skills: Set, - promptTemplates: Set, - extensions: Set, - watch: PiProjectResourceLaunchWatch, -): PiProjectResourceSurface { + const realPrompts = realpathOrNull(path.join(scanRoot, '.pi', 'prompts')); + if (realPrompts && isDir(realPrompts) && isWithinRoot(repoRoot, realPrompts)) { + for (const entry of listDir(realPrompts)) { + if (entry.name.startsWith('.') || !entry.name.endsWith('.md')) continue; + const realFile = realpathOrNull(path.join(realPrompts, entry.name)); + if (!realFile || !isFile(realFile) || !isWithinRoot(repoRoot, realFile)) continue; + promptTemplates.add(realFile); + } + } + + const realExt = realpathOrNull(path.join(scanRoot, '.pi', 'extensions')); + if (realExt && isDir(realExt) && isWithinRoot(repoRoot, realExt)) { + for (const entry of listDir(realExt)) { + if (entry.name.startsWith('.')) continue; + const realChild = realpathOrNull(path.join(realExt, entry.name)); + if (!realChild || !isWithinRoot(repoRoot, realChild)) continue; + if (isFile(realChild) && realChild.endsWith('.ts')) { + extensions.add(realChild); + continue; + } + if (!isDir(realChild)) continue; + const realIndex = realpathOrNull(path.join(realChild, 'index.ts')); + if (realIndex && isFile(realIndex) && isWithinRoot(repoRoot, realIndex)) { + extensions.add(realIndex); + } + } + } + return Object.freeze({ - repoRoot, - paths: Object.freeze({ - skills: Object.freeze([...skills].sort(comparePiResourcePaths)), - promptTemplates: Object.freeze([...promptTemplates].sort(comparePiResourcePaths)), - extensions: Object.freeze([...extensions].sort(comparePiResourcePaths)), - }), - watch, + skills: Object.freeze([...skills].sort(comparePiResourcePaths)), + promptTemplates: Object.freeze([...promptTemplates].sort(comparePiResourcePaths)), + extensions: Object.freeze([...extensions].sort(comparePiResourcePaths)), }); } -/** argv 采集的兼容入口(= surface.paths)。生产路径应优先 surface 一次调用。 */ -export function collectPiProjectResourceCliPaths(workingDir: string, repoRootHint?: string): PiProjectResourceCliPaths { - return collectPiProjectResourceSurface(workingDir, repoRootHint).paths; -} - -/** 盯视采样的兼容入口(= surface.watch)。生产路径应优先 surface 一次调用。 */ -export function collectPiProjectResourceLaunchWatch(workingDir: string, repoRootHint?: string): PiProjectResourceLaunchWatch { - return collectPiProjectResourceSurface(workingDir, repoRootHint).watch; -} - -function statMtimeMs(target: string): number { - try { - return fs.statSync(target).mtimeMs; - } catch { - return -1; - } -} - -/** 目录条目名指纹:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 - * 文件键/缺失目录 readdir 失败,恒 ''。变化只作重扫信号,判决仍归路径集合。 */ -function readDirEntryFingerprint(dir: string): string { - try { - return fs.readdirSync(dir).sort().join('\n'); - } catch { - return ''; - } -} - /** - * 启动快照:spawn 时冻结的项目资源清单 + watch 面基线(mtime/条目指纹/解析身份)。 - * paths 是未经禁用过滤的原始收集结果(受邀者会话已按 guestRoot 裁剪,与后续 - * fresh collect 经同一 restrict 裁剪后同口径可比)。 + * 启动快照 = spawn 时**实际交给 CLI 的资源路径集合** + 比较口径。 + * + * 刻意只有这两样:任何额外的「基线」都是对 collector 消费方式的手写镜像,而镜像 + * 与实现必然随时间分歧(2026-11-10 六轮 review 的六类漏检全部来自这种分歧:身份 + * 采样晚于收集、窗口复核比错基线、软链键跳读过头、清单 TOCTOU、剪枝目录全列表、 + * 软链 namespace 全列表)。没有镜像就没有分歧。 */ export interface PiProjectResourceLaunchSnapshot { readonly workingDir: string; + /** spawn 时 argv 里的资源路径集合。漂移 = 现在采集一遍是否仍等于它。 */ readonly paths: PiProjectResourceCliPaths; - /** - * watch root 的 mtime 基线。Map 值可在重扫确认路径集合未变后就地重建(见 - * piProjectResourcesDrifted),避免 mtime 变化来自无关文件时每条消息重复全量重扫; - * 路径集合与 paths 一样保持启动口径不变。 - */ - readonly watchRootMtimes: Map; - /** 启动时认定的 git root 可变持有器:更近的 .git 出现/消失会改变 collector 的枚举链 - * (.agents 向上走到 repoRoot),而任何被盯目录的 mtime 都不动,必须单独核对。边界 - * 变化只作重扫信号(见 piProjectResourcesDrifted),确认集合未变后就地更新,避免 - * 嵌套目录 git init 在无实际资源变化时多余回收。必须与 watch 基线同批采样 - * (都先于 paths 收集),否则窗口内新旧边界会与路径集合错配。 */ - readonly state: { repoRoot: string; resolvedWorkingDir: string | null }; - /** 每个 watch root 的解析身份(realpath)。基线不只记 mtime:被盯路径的软链改指 - * 同 mtime 的孪生树时,解析身份是唯一信号;与 watchRootMtimes 同 key 同批。 */ - readonly watchRootsResolved: Map; - /** 每个 watch root 的条目基线(完整条目名/清单存在性/null 跳读,按 collector - * 消费方式定):时间戳粒度盲区的第二信号;与 watchRootMtimes 同 key 同批。 */ - readonly watchRootEntries: Map; - /** 受邀者裁剪口径(非受邀者恒 null):重扫后的 fresh 集合先经它裁剪再与 paths - * 比较 —— 缺了会拿全量比裁剪基线恒判漂移,回收死循环。 */ + /** 受邀者裁剪口径(非受邀者 null):fresh 必须先经同一裁剪再比,否则拿全量比 + * 裁剪基线恒判漂移 → 回收死循环。 */ readonly restrict: ((paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) | null; } -/** - * 启动采样的一次遍历产出:每个 watch key 的三样信号 + scanRoot 解析身份。 - * 整份样本必须先于路径收集采样 —— 身份基线晚于 argv 采集,会把「采基线前的 - * 改指」固化成一致基线,永久漏检(Codex P2,2026-11-10);基线在前则窗口内 - * 不一致只会让首次快检多一次重扫后收敛。 - */ -export interface PiProjectResourceLaunchWatch { - /** workingDir 的解析身份,先于所有键采样(键路径都从它拼出)。 */ - readonly scanRootResolved: string | null; - readonly mtimes: Map; - /** key → 条目基线,由 samplePiWatchKey 与 argv 判断输入同一次采样产出 —— - * 'L:' 完整条目名列表(collector readdir 的目录)/'M:' 清单存在性(collector - * 只 stat SKILL.md/skill.md 的键)/null(collector 不消费)。时间戳粒度盲区 - * (同一 tick 内增删)的第二信号;变化只作重扫信号,判决仍归路径集合。 */ - readonly entries: Map; - /** key → realpath 解析身份(缺失 null),与 mtimes 同键同次采样。 */ - readonly resolved: Map; -} - -/** - * 单键采样模式 = collector 在该路径上到底消费什么。由**结构**决定,不看内容: - * 依赖内容会让「读内容定模式」自身变成新的两次读窗口(2026-11-10 Greptile P2)。 - * - 'dir' collector 会 readdir 的目录 → 完整条目名列表; - * - 'skill' collector 只 stat SKILL.md/skill.md 存在性 → 清单存在性; - * - 'none' collector 不消费(文件/越界/悬空/只 stat 的子键)→ 跳读。 - * 'dir'/'skill' 都由采样器自行门禁:目标须是仓内真实目录,否则指纹为 null —— - * 仓外大目录永远不会被 readdir(每条消息一次的快检不会拖着同步 IO 走路)。 - */ -export type PiWatchEntriesMode = 'dir' | 'skill' | 'none'; - -/** - * 单键采样产出:基线字段 + argv 判断所需的全部输入,均出自这一次采样。 - * - * **不变量(逐键,2026-11-10 根因收口)**:一个键的基线字段与该键上的 argv 判断, - * 必须出自同一次采样;判断不得早于该键的基线,也不得另发读操作。 - * 反例(Greptile P2):先 hasSkillFile() 再记基线,安装器在这两步之间写入 - * SKILL.md → 基线记的是写后状态、argv 还是写前 → 后续快检恒等、该 skill 永久 - * 不生效。只靠注释约束不了,所以判断输入统一由采样返回值提供。 - * - * 采样后发生的任何变化都安全:基线不会比判断更新,快检必然观察差异 → 重扫 → - * 集合相同则刷新基线后收敛(不会永久漏检,最多多一次重扫)。 - */ -export interface PiWatchKeySample { - /** 解析身份(realpath,跟随软链);缺失 null。 */ - readonly resolved: string | null; - /** stat mtime(跟随软链);缺失 -1。 */ - readonly mtime: number; - readonly isFile: boolean; - readonly isDir: boolean; - /** 目标是否仓内真实目录(决定 'dir'/'skill' 是否采指纹)。 */ - readonly inRepoDir: boolean; - /** 'dir' 模式:与条目基线同一次 readdir 的条目;其余 null。 */ - readonly dirents: readonly fs.Dirent[] | null; - /** 'skill' 模式:与清单基线同一次判断的存在性;其余 false。 */ - readonly manifest: boolean; -} - -/** - * 采样一个 watch 键:一次 realpath + 一次 stat + 至多一次内容读,同时写入基线并 - * 返回给调用方做 argv 判断。基线与判断输入同源,**调用方不得对该键另发读**。 - */ -function samplePiWatchKey( - sample: PiProjectResourceLaunchWatch, - target: string, - mode: PiWatchEntriesMode, - repoRoot: string, -): PiWatchKeySample { - // 顺序固定:realpath → stat → 内容。基线先落盘,内容读既进指纹也回给调用方。 - const resolved = realpathOrNull(target); - let stats: fs.Stats | null = null; - try { - stats = fs.statSync(target); - } catch { - stats = null; - } - const isDirectory = stats?.isDirectory() ?? false; - const inRepoDir = isDirectory && !!resolved && isWithinRoot(repoRoot, resolved); - let dirents: readonly fs.Dirent[] | null = null; - let manifest = false; - let fingerprint: string | null = null; - if (mode === 'dir' && inRepoDir) { - try { - dirents = fs.readdirSync(target, { withFileTypes: true }); - } catch { - dirents = null; - } - fingerprint = `L:${(dirents ?? []).map((entry) => entry.name).sort().join('\n')}`; - } else if (mode === 'skill' && inRepoDir) { - const names = ['SKILL.md', 'skill.md'].filter((name) => isFile(path.join(target, name))); - manifest = names.length > 0; - fingerprint = `M:${names.join(',')}`; - } - sample.resolved.set(target, resolved); - sample.mtimes.set(target, stats ? stats.mtimeMs : -1); - sample.entries.set(target, fingerprint); - return { - resolved, - mtime: stats ? stats.mtimeMs : -1, - isFile: stats?.isFile() ?? false, - isDir: isDirectory, - inRepoDir, - dirents, - manifest, - }; -} - -/** 只记基线、不需要判断输入的键(丢弃采样返回值)。repoRoot 必传 —— 默认成 - * 目标的写法会让仓外目录也走进 readdir,等于把性能 P2 重新埋回。 */ -function recordWatchKey( - sample: PiProjectResourceLaunchWatch, - target: string, - mode: PiWatchEntriesMode, - repoRoot: string, -): void { - samplePiWatchKey(sample, target, mode, repoRoot); -} - -/** 软链目标的清单存在性指纹(namespace↔skill 迁移的同刻信号);文件/缺失恒 ''。 */ -function readSkillManifestFingerprint(dir: string): string { - return ['SKILL.md', 'skill.md'].filter((name) => isFile(path.join(dir, name))).join(','); -} - -/** 软链清单本体:SKILL.md/skill.md 为指向仓内目标的软链时,目标移动/删除不改变 - * skill 目录自身 mtime,只有盯住解析后的文件才能检出(与 prompts 同款)。悬空链 - * 盯链接自身,目标落地即检出。 */ -function watchPiSkillManifestTargets( - sample: PiProjectResourceLaunchWatch, - realFolder: string, - repoRoot: string, -): void { - for (const name of ['SKILL.md', 'skill.md']) { - const manifestPath = path.join(realFolder, name); - let manifestLstat: fs.Stats; - try { - manifestLstat = fs.lstatSync(manifestPath); - } catch { - continue; - } - if (!manifestLstat.isSymbolicLink()) continue; - // 目标本体与链接自身各入一键:悬空时 target 为 null 键落到链接本体。 - const target = samplePiWatchKey(sample, manifestPath, 'none', repoRoot); - if (target.resolved) recordWatchKey(sample, target.resolved, 'none', repoRoot); - } -} - -/** - * 冻结一份启动快照。watch 采样(含解析身份与 scanRoot 身份)与 repoRoot 必须由 - * 调用方在收集 paths **之前**采样传入(见 pi/index.ts 调用点):身份基线晚于 argv - * 采集,会把「采基线前的改指」固化成一致基线,永久漏检(Codex P2,2026-11-10); - * 基线在前则窗口内不一致只会让首次快检多一次重扫后收敛。restrict 传受邀者裁剪 - * 口径:比较对 fresh 集合做与启动相同的裁剪。 - */ export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, - repoRoot: string, - watch: PiProjectResourceLaunchWatch, restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths, ): PiProjectResourceLaunchSnapshot { - return Object.freeze({ - workingDir, - paths, - watchRootMtimes: watch.mtimes, - // scanRoot(workingDir 解析后)刻意不是 watch key(不含 workingDir 本身), - // 解析身份单独成字段;身份出自 watch 采样的最前面 —— 若在这里补采样就退回 - // 「收集后才采身份」的永久漏检窗口(Codex P2)。软链 workingDir 改指同仓 - // 另一目录时,边界与旧物理根 mtime 均不变,这是唯一信号。 - state: { - repoRoot, - resolvedWorkingDir: watch.scanRootResolved, - }, - // 每个 watch root 的解析身份:任意层级(`.pi`、`.agents` 链、namespace、单个 - // skill 目录)改指同 mtime 的孪生树时 mtime 面致盲,唯一完备信号是逐 key 的 - // 解析身份。realpath 含全链路解析,未枚举的嵌套软链同样覆盖。与 mtimes/entries - // 同 key 同批产出(见 collectPiProjectResourceLaunchWatch)。 - watchRootsResolved: watch.resolved, - watchRootEntries: watch.entries, - restrict: restrict ?? null, - }); + return Object.freeze({ workingDir, paths, restrict: restrict ?? null }); } function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { @@ -545,102 +232,27 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): } /** - * 盘上项目资源相对启动快照是否已漂移(argv 重算后会不同)。结构性契约: - * **每次调用至多一次全量路径收集**。两级信号 → 一次收集 → 一次比较: - * 1. 轻量信号扫描(每 key 一次 realpath + stat + readdir,无递归):全部与基线 - * 相等且 git 边界未变 → 无漂移;任一不等 → 进入下一步。信号源: - * - watch root mtime 变化(资源增删只改所在目录自身 mtime,基线必须覆盖 - * collector 实际枚举的每一层目录); - * - watch root 条目名指纹变化(时间戳粒度盲区:同一 tick 内增删,mtime 与 - * 基线逐位相等,条目名单不同); - * - watch root / workingDir 解析身份变化(软链改指同 mtime 孪生树时唯一信号); - * - git 边界变化(更近的 .git 出现/消失会改变 collector 的枚举链,但不动 - * 任何被盯目录的 mtime)。 - * 2. 全量重扫,按最终路径集合判定(argv 的输入是集合,不是内容): - * - 集合不同 → 漂移,返回 true(不动基线,调用方将回收运行时并重建快照); - * - 集合相同(触碰无关目录 / git init 未截断任何资源 / 缺失目录空壳落地 / - * 不被 collector 枚举的软链 namespace 改指)→ 不算漂移,就地重建整张基线 - * (新建的空 namespace / 空扩展目录纳入盯视)并更新边界持有者,下一次快检 - * 恢复零收集。解析身份变化只是触发重扫的信号,永远不是漂移判决: - * 身份变了而集合不变,说明运行时消费的资源没有变。 + * 盘上项目资源是否已偏离运行时实际使用的 argv。 + * + * 判定 = 用 collector 采集一遍,与快照里的集合逐项相等比较。**没有任何其他信号**: + * - argv 的输入是路径集合,不是内容 → 集合相等即无需回收(改文件内容/在已收集的 + * skill 目录里加文件都不影响 argv); + * - 采集按 realpath 出路径 → 软链改指到别处(哪怕 mtime 逐位相同)必然改变集合; + * - 清单后落地、模板目标移动、扩展目录补 index.ts → 都直接改变集合; + * - 与时间戳无关 → 同一 tick 内的增删不会漏(不需要 mtime 或条目指纹)。 + * + * 代价:每次空闲发送前一次采集(约「每目录 1 readdir + 每资源 3~5 stat」,与过去 + * 那套 mtime/身份快检的 syscall 数量同量级)。这是买「结构上不可能分歧」付的钱; + * 若将来资源规模大到有感知,应当减采集范围,不要恢复基线镜像。 */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { - // 本次调用只解析一次 git root,贯穿传给所有收集器;独立探测会在重扫窗口内 - // 采出不一致的边界+盯视面(.git 消失时 watch 面停在旧根、集合来自新根)。 - const repoRoot = resolvePiResourceRepoRoot(snapshot.workingDir); - const boundaryChanged = repoRoot !== snapshot.state.repoRoot; - // 软链 workingDir 改指同仓另一目录:边界不变、解析后旧物理根的 mtime 不变, - // 解析根变化是唯一信号(Codex P2)。解析失败(悬空)与有值不等同。失败信号。 - const resolvedWorkingDir = realpathOrNull(snapshot.workingDir); - const resolvedWorkingDirChanged = resolvedWorkingDir !== snapshot.state.resolvedWorkingDir; - // 任一 watch root 的解析身份变化(软链改指同 mtime 的孪生树):mtime 面碰撞 - // 时这是唯一信号;realpath 含全链路,任意层级的改指都会落到某个 key 上。 - // 记录本次采样而非只记信号:窗口复核必须与本轮开头比,不能与启动基线比 —— - // 否则空目录从 null→存在 会撞上旧基线被误判为「窗口内再次改指」(Greptile P2)。 - const resolvedNow = new Map(); - let resolvedRootChanged = false; - for (const [dir, resolvedAtLaunch] of snapshot.watchRootsResolved) { - const now = realpathOrNull(dir); - resolvedNow.set(dir, now); - if (now !== resolvedAtLaunch) resolvedRootChanged = true; - } - let mtimeChanged = false; - for (const [dir, mtimeAtLaunch] of snapshot.watchRootMtimes) { - if (statMtimeMs(dir) !== mtimeAtLaunch) { - mtimeChanged = true; - break; - } - } - // 条目基线:时间戳粒度盲区(同一 tick 内增删,mtime 逐位不变)的第二信号。 - // null = collector 不消费的键,跳读;前缀(L:/M:)选与采集同一函数重算。 - let entriesChanged = false; - for (const [dir, fingerprintAtLaunch] of snapshot.watchRootEntries) { - if (fingerprintAtLaunch === null) continue; - const actual = fingerprintAtLaunch.startsWith('M:') - ? `M:${readSkillManifestFingerprint(dir)}` - : `L:${readDirEntryFingerprint(dir)}`; - if (actual !== fingerprintAtLaunch) { - entriesChanged = true; - break; - } - } - if (!boundaryChanged && !resolvedWorkingDirChanged && !resolvedRootChanged && !mtimeChanged && !entriesChanged) return false; - - // 重扫 = 一次 surface 调用:集合与盯视基线同批(与启动同口径),不存在 - // 「基线采完、集合没采到」的窗口。 - const fresh = collectPiProjectResourceSurface(snapshot.workingDir, repoRoot); - // 受邀者:比较前对 fresh 做与启动相同的裁剪,否则全量比裁剪基线恒判漂移。 - const freshForCompare = snapshot.restrict ? snapshot.restrict(fresh.paths) : fresh.paths; - if (!( - samePiResourceList(freshForCompare.skills, snapshot.paths.skills) - && samePiResourceList(freshForCompare.promptTemplates, snapshot.paths.promptTemplates) - && samePiResourceList(freshForCompare.extensions, snapshot.paths.extensions) - )) { - return true; - } - - // 有信号但集合未变:整表重建(新建的空目录/解析后的 prompt 目标纳入盯视) - // 并更新边界持有者,下一次快检恢复零收集。重建后复核边界:重扫窗口内 - // .git 又动了就按漂移交回收路径重建(下次快检从一致的新快照出发), - // 不把混合口径的基线/边界写回快照。 - if (resolvePiResourceRepoRoot(snapshot.workingDir) !== repoRoot) return true; - // 重扫窗口内解析根又变了(软链再次改指):按漂移交回收路径重建,不把混合口径 - // 的解析根写回快照。 - if (realpathOrNull(snapshot.workingDir) !== resolvedWorkingDir) return true; - // 重扫窗口内解析身份又有变化(任意层级再次改指):按漂移交回收路径重建,不把 - // 混合口径的基线写回快照。与本轮开头采样比(同 repoRoot/resolvedWorkingDir)。 - for (const [dir, resolvedAtSignal] of resolvedNow) { - if (realpathOrNull(dir) !== resolvedAtSignal) return true; - } - snapshot.watchRootMtimes.clear(); - for (const [dir, mtime] of fresh.watch.mtimes) snapshot.watchRootMtimes.set(dir, mtime); - snapshot.watchRootsResolved.clear(); - for (const [dir, resolved] of fresh.watch.resolved) snapshot.watchRootsResolved.set(dir, resolved); - snapshot.watchRootEntries.clear(); - for (const [dir, fingerprint] of fresh.watch.entries) snapshot.watchRootEntries.set(dir, fingerprint); - snapshot.state.repoRoot = repoRoot; - snapshot.state.resolvedWorkingDir = resolvedWorkingDir; - return false; + const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); + const compare = snapshot.restrict ? snapshot.restrict(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. */ From 32384197f971377a5de6b2ea82daae9e097efd06 Mon Sep 17 00:00:00 2001 From: Zhang Yunjin Date: Tue, 10 Nov 2026 23:56:46 +0800 Subject: [PATCH 45/45] =?UTF-8?q?fix(pi,im):=20=E5=BF=AB=E7=85=A7=E5=8F=A3?= =?UTF-8?q?=E5=BE=84=E5=90=AB=E5=81=9C=E7=94=A8=E8=BF=87=E6=BB=A4;?= =?UTF-8?q?=E8=A1=A5=20companion=20=E5=81=87=20Maker=20=E7=9A=84=E5=9B=9E?= =?UTF-8?q?=E6=94=B6=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 停用技能触发多余重启(Greptile P2):快照存的是未过滤的采集结果,而 argv 用 的是经 filterPiProjectCliSkills 过滤后的集合 —— 删掉一个从未加载的停用 skill 也会判漂移、白等一次冷启动。改法不是再加一处过滤,而是把「采集 → argv」收成 唯一口径 projectResourceToCliPaths(受邀者裁剪 + 停用过滤,停用清单 spawn 时 冻结),启动与漂移比较共用它;快照里的 restrict 相应更名为 toCliPaths。少一份 口径就少一处可分歧点,和本 PR 的根因修法同向。 回归:停用 skill 删除不漂移、未停用技能新增仍漂移;变异检查(忽略该口径)必红。 2. turnRunnerCompanionRouting 假 Maker 缺 recyclePiRuntimeIfResourcesDrifted: 合并恢复上游测试文件后丢了该桩,漂移回收块在假 Maker 上抛 TypeError 并被 catch 吞掉,后续派发断言全落空(Linux unit tests 4/4 红)。三处 fake 全部补齐。 验证:drift 25 + cli/maker/session/pi-cleanup 418 全绿;maker-core 与 desktop typecheck 均 0 错。 Signed-off-by: Zhang Yunjin --- .../turnRunnerCompanionRouting.test.ts | 3 ++ .../pi-project-resource-drift.test.ts | 25 +++++++++++-- packages/maker-core/src/agents/pi/index.ts | 35 +++++++++---------- .../src/agents/pi/project-resource-cli.ts | 13 +++---- 4 files changed, 50 insertions(+), 26 deletions(-) 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/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 index 72725c828e..90cb716d5e 100644 --- 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 @@ -36,8 +36,8 @@ function writeSkill(relativeDir: string, name: string): void { } /** 生产调用点同序:快照 = 当前采集结果(采集即 argv)。 */ -function snapshot(restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { - return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), restrict); +function snapshot(toCliPaths?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) { + return snapshotPiProjectResourceLaunch(project, collectPiProjectResourceCliPaths(project), toCliPaths); } function real(target: string): string { @@ -226,6 +226,27 @@ describe('piProjectResourcesDrifted', () => { 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 裁剪后的集合,比较必须用同一口径;否则镜像外 // 任何变化恒判漂移 → 回收死循环。 diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index 71527afed3..e14cd9fb0d 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -246,6 +246,7 @@ import { assertPiSpawnArgvFitsPlatform, collectPiProjectResourceCliPaths, emptyPiProjectResourceCliPaths, + type PiProjectResourceCliPaths, filterPiProjectCliSkills, piProjectResourceCliArgs, piProjectResourcesDrifted, @@ -4071,27 +4072,25 @@ export class PiAgent extends BaseAgent { // 复用同一个 collector 重新采集后逐项比较(见 piProjectResourcesDrifted), // 不另存任何基线 —— 存基线就等于手写一份「collector 消费什么」的镜像, // 镜像与实现必然分歧(2026-11-10 六轮漏检全部出在这里)。 - const collectedProjectResources = loadProjectResourcesInPlace - ? guestRoot - ? restrictPiGuestProjectResources(collectPiProjectResourceCliPaths(opts.workingDir), guestRoot) - : collectPiProjectResourceCliPaths(opts.workingDir) - : emptyPiProjectResourceCliPaths(); + // 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 实际用的集合与受邀者裁剪口径 —— 没有第二份基线。 + // 只存 argv 实际用的集合与该口径 —— 没有第二份基线。 const projectResourceLaunchSnapshot = loadProjectResourcesInPlace - ? snapshotPiProjectResourceLaunch( - opts.workingDir, - collectedProjectResources, - guestRoot ? (paths) => restrictPiGuestProjectResources(paths, guestRoot) : undefined) + ? snapshotPiProjectResourceLaunch(opts.workingDir, projectResourceCli, projectResourceToCliPaths) : null; // Own the entire managed-skill setup in the existing startup rollback: 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 46d983fa89..8ce6e9327e 100644 --- a/packages/maker-core/src/agents/pi/project-resource-cli.ts +++ b/packages/maker-core/src/agents/pi/project-resource-cli.ts @@ -214,17 +214,18 @@ export interface PiProjectResourceLaunchSnapshot { readonly workingDir: string; /** spawn 时 argv 里的资源路径集合。漂移 = 现在采集一遍是否仍等于它。 */ readonly paths: PiProjectResourceCliPaths; - /** 受邀者裁剪口径(非受邀者 null):fresh 必须先经同一裁剪再比,否则拿全量比 - * 裁剪基线恒判漂移 → 回收死循环。 */ - readonly restrict: ((paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) | null; + /** 采集 → argv 的唯一口径(受邀者裁剪 + 停用技能过滤)。启动与比较都用它: + * 少了它,受邀者会拿全量比裁剪基线恒判漂移(回收死循环),停用技能的增删会 + * 被当成漂移(白等一次冷启动)。 */ + readonly toCliPaths: ((collected: PiProjectResourceCliPaths) => PiProjectResourceCliPaths) | null; } export function snapshotPiProjectResourceLaunch( workingDir: string, paths: PiProjectResourceCliPaths, - restrict?: (paths: PiProjectResourceCliPaths) => PiProjectResourceCliPaths, + toCliPaths?: (collected: PiProjectResourceCliPaths) => PiProjectResourceCliPaths, ): PiProjectResourceLaunchSnapshot { - return Object.freeze({ workingDir, paths, restrict: restrict ?? null }); + return Object.freeze({ workingDir, paths, toCliPaths: toCliPaths ?? null }); } function samePiResourceList(left: readonly string[], right: readonly string[]): boolean { @@ -247,7 +248,7 @@ function samePiResourceList(left: readonly string[], right: readonly string[]): */ export function piProjectResourcesDrifted(snapshot: PiProjectResourceLaunchSnapshot): boolean { const fresh = collectPiProjectResourceCliPaths(snapshot.workingDir); - const compare = snapshot.restrict ? snapshot.restrict(fresh) : fresh; + const compare = snapshot.toCliPaths ? snapshot.toCliPaths(fresh) : fresh; return !( samePiResourceList(compare.skills, snapshot.paths.skills) && samePiResourceList(compare.promptTemplates, snapshot.paths.promptTemplates)