Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden pending journal reads, scaffold no-clobber, and restore merge-invariant guards
Yuewei-LL85f27704908e
diff --cc apps/desktop/src/main/cindy-brain/GhostManager.tsindex 9f570c4a0b,2d65d685d6..d567e1126c--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@@ -2861,21 -828,11 +2861,25 @@@ export class GhostManager*/async update(lizFilePath: string,- opts?: {+ opts: {+ expectedInstalledApproval: string;+ expectedPackageSha256?: string;+ trustOverride?: GhostHostTrustOverride;++ /** 目录换位完成后、任何通知或运行时收尾前触发。 */++ onPackagePlaced?: () => void;+ },+ ) {+ return this.runExclusiveMutation(() => this.updateUnlocked(lizFilePath, opts));+ }++ private async updateUnlocked(+ lizFilePath: string,+ opts: {+ expectedInstalledApproval: string;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ /** 目录换位完成后、任何通知或运行时收尾前触发。 */+ onPackagePlaced?: () => void;},): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {const parsed = await this.parse(lizFilePath);@@@ -3135,341 -930,10 +3139,342 @@@trust,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),};+ opts?.onPackagePlaced?.();this.options.log?.info('ghost updated', { id: manifest.id, version: manifest.version });- this.options.onChanged?.(this.list());- return { ghost };+ const projected = this.projectCommittedMutationResult(ghost);+ this.options.onChanged?.(projected.list);+ return { ghost: projected.ghost };+ }++ /**+ * 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 批准状态。+ * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。id 必须落在注入的+ * 随包种子清单里(`isTrustedBundledId`)。+ *+ * `markerEnabled` 是安装目录 `.disabled` 兼容镜像的读数,**只往停用方向合并,+ * 不往启用方向翻**:receipt 才是授权事实,镜像文件可被外部因素移除(AV 隔离+ * 恢复/同步冲突解析/手动清理),拿它覆写 receipt 会让用户显式停用的插件在下一轮+ * 对账被静默重新启用 —— 无确认、无审计,且带 skill 槽的插件会随之重新挂进全局+ * 技能链。反方向(镜像说停用、receipt 说启用)必须照办:停用是安全方向,而且+ * 旧客户端只会写镜像文件。重新启用只有用户显式 `setEnabled(true)` 一条路。+ */+ private async publishTrustedBundledSeedUnlocked(+ id: string,+ sourceDirInput: string,+ options: {+ disabled: boolean;+ trust?: typeof CINDY_OFFICIAL_GHOST_TRUST;+ },+ ): Promise<void> {+ if (+ !isValidGhostId(id) ||+ this.options.isTrustedBundledId?.(id) !== true ||+ this.options.isTrustedBundledSource?.(id, sourceDirInput) !== true+ ) {+ throw new Error('builtin seed publish source is not trusted');+ }+ const sourceDir = path.resolve(sourceDirInput);+ if (classifyGhostDirEntrySync(sourceDir) !== 'directory') {+ throw new Error('builtin seed publish source is not a real directory');+ }+ const packageSha256 = await hashApprovedDirectory(sourceDir);+ const root = this.contentRootDir();+ const finalDir = path.join(root, id);+ const rand = crypto.randomBytes(4).toString('hex');+ const stagingDir = path.join(root, `.cindy-installing-${id}-${rand}`);+ const backupDir = path.join(root, `.cindy-updating-${id}-${rand}`);+ let finalKind: GhostDirEntryKind | 'missing';+ try {+ finalKind = classifyGhostDirEntrySync(finalDir);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ finalKind = 'missing';+ }+ if (finalKind !== 'missing' && finalKind !== 'directory') {+ throw new Error('builtin installed path is not a real directory');+ }++ try {+ await copyBundledSeedDirectory(sourceDir, stagingDir);+ if (options.disabled) {+ await fs.promises.writeFile(path.join(stagingDir, DISABLED_MARKER_FILE), '');+ }+ if (options.trust) {+ await fs.promises.writeFile(+ path.join(stagingDir, TRUST_METADATA_FILE),+ `${JSON.stringify(options.trust, null, 2)}\n`,+ );+ }+ if (finalKind === 'missing') {+ await this.receiptStore.writePendingMutation(id, { kind: 'install', packageSha256 });+ this.untrustedApprovals.add(this.isolationKey(id));+ await fs.promises.rename(stagingDir, finalDir);+ return;+ }++ await this.receiptStore.writePendingMutation(id, {+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ phase: 'prepared',+ });+ this.untrustedApprovals.add(this.isolationKey(id));+ await fs.promises.rename(finalDir, backupDir);+ await this.receiptStore.writePendingMutation(id, {+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ phase: 'backed-up',+ });+ await fs.promises.rename(stagingDir, finalDir);+ await this.receiptStore.writePendingMutation(id, {+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ phase: 'published',+ });+ } catch (error) {+ await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);+ const backupKind = await classifyGhostDirEntry(backupDir).catch((entryError) => {+ if ((entryError as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw entryError;+ });+ const publishedKind = await classifyGhostDirEntry(finalDir).catch((entryError) => {+ if ((entryError as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw entryError;+ });+ if (backupKind === 'directory' && publishedKind === null) {+ try {+ await fs.promises.rename(backupDir, finalDir);+ await this.receiptStore.clearPendingMutation(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch {+ // Keep the journal for startup recovery when rollback cannot complete now.+ }+ } else if (backupKind === null && publishedKind === null) {+ try {+ await this.receiptStore.clearPendingMutation(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch {+ // Keep the in-process quarantine while the journal remains.+ }+ }+ throw error;+ }+ }++ async approveTrustedBundledInstall(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean> {+ return this.runExclusiveMutation((mutation) =>+ mutation.approveTrustedBundledInstall(manifest, markerEnabled, options),+ );+ }++ private async approveTrustedBundledInstallUnlocked(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean> {+ if (this.options.isTrustedBundledId?.(manifest.id) !== true) {+ throw new Error(+ `approveTrustedBundledInstall 只服务随包种子插件:${manifest.id} 不在种子清单里`,+ );+ }+ const dir = path.join(this.contentRootDir(), manifest.id);+ if (!options || typeof options.sourceDir !== 'string' || options.sourceDir.trim() === '') {+ throw new Error('approveTrustedBundledInstall requires a verified bundled source directory');+ }+ const sourceDir = path.resolve(options.sourceDir);+ if (sourceDir === path.resolve(dir)) {+ throw new Error('approveTrustedBundledInstall refuses the mutable installed directory');+ }+ if (this.options.isTrustedBundledSource?.(manifest.id, sourceDir) !== true) {+ throw new Error('approveTrustedBundledInstall source is outside the trusted seed roster');+ }+ if (classifyGhostDirEntrySync(sourceDir) !== 'directory') {+ throw new Error('approveTrustedBundledInstall source is not a real directory');+ }+ const sourceManifestPath = resolveGhostContentPathSync(sourceDir, GHOST_MANIFEST_FILE, {+ expect: 'file',+ label: 'bundled manifest',+ });+ const sourceManifestRaw = JSON.parse(fs.readFileSync(sourceManifestPath, 'utf8')) as unknown;+ const sourceManifest = validateGhostManifest(sourceManifestRaw);+ const expectedManifest = validateGhostManifest(manifest);+ if (+ !sourceManifest.ok ||+ !expectedManifest.ok ||+ !isDeepStrictEqual(sourceManifest.manifest, expectedManifest.manifest)+ ) {+ throw new Error('approveTrustedBundledInstall source manifest does not match approval');+ }+ const localeResources = this.readApprovedLocaleResources(sourceDir, manifest);+ const iconDataUrl = this.readInstalledIconDataUrl(sourceDir, manifest) ?? undefined;+ const packageSha256 = await hashApprovedDirectory(sourceDir);+ const skillContentSha256 = await hashApprovedSkillContent(manifest, sourceDir);+ const pendingPublish = this.receiptStore.readPendingMutationSync(manifest.id);+ if (pendingPublish.state === 'invalid' || pendingPublish.state === 'unreadable') {+ throw new Error(`builtin seed publish journal is ${pendingPublish.state}`);+ }+ if (pendingPublish.state === 'valid' && pendingPublish.mutation.kind === 'uninstall') {+ throw new Error('builtin seed publish journal conflicts with uninstall');+ }+ if (+ pendingPublish.state === 'valid' &&+ (pendingPublish.mutation.kind === 'install' || pendingPublish.mutation.kind === 'update') &&+ pendingPublish.mutation.packageSha256 !== packageSha256+ ) {+ throw new Error('builtin seed publish journal does not match immutable source');+ }+ const trust = CINDY_OFFICIAL_GHOST_TRUST;+ const current = this.readApproval(manifest.id);+ // priorEnabled 直接读盘上的 receipt 而不是 readApproval 的投影:进程内隔离态的+ // receipt 不可作授权事实,但"曾经停用"这个位只用于往下拉,是 fail closed 方向,+ // 采纳它只会更保守 —— 否则"隔离 + 镜像同时丢失"的组合会让自愈把插件带回启用。+ const persisted = current.state === 'approved' ? current : this.receiptStore.read(manifest.id);+ const priorEnabled = persisted.state === 'approved' ? persisted.receipt.enabled : undefined;+ const enabled = priorEnabled === undefined ? markerEnabled : markerEnabled && priorEnabled;+ if (enabled !== markerEnabled) {+ // receipt 钉着停用而镜像丢了:把 `.disabled` 补写回去,守住"回滚到旧客户端时+ // 按镜像判启停"的降级承诺。写不进不影响批准事实,receipt 仍是权威。+ try {+ this.writeDisabledMarkerSync(dir);+ } catch (err) {+ this.options.log?.warn('ghost disabled mirror rewrite failed', {+ id: manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ if (+ current.state === 'approved' &&+ isDeepStrictEqual(current.receipt.manifest, manifest) &&+ isDeepStrictEqual(current.receipt.localeResources, localeResources) &&+ isDeepStrictEqual(current.receipt.trust, trust) &&+ isDeepStrictEqual(current.receipt.skillContentSha256, skillContentSha256) &&+ current.receipt.packageSha256 === packageSha256 &&+ current.receipt.iconDataUrl === iconDataUrl+ ) {+ // Receipt equality is not enough for a no-op: the skill snapshot is a+ // separately materialized authorization projection and may have been+ // deleted or modified by an external cleanup/sync process. Re-enter the+ // normal receipt writer when the derived snapshot is unhealthy so the+ // immutable bundled seed can rebuild it without user action.+ const snapshotHealthy =+ (manifest.skill?.items.length ?? 0) === 0 ||+ (await this.receiptStore.skillSnapshotMatchesReceipt(+ current.receipt,+ this.receiptStore.skillSnapshotRoot(manifest.id, current.receipt.revision),+ ));+ if (!snapshotHealthy) {+ await this.receiptStore.write(current.receipt, { skillSourceDir: sourceDir });+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }+ if (current.receipt.enabled !== enabled) {+ await this.receiptStore.write({+ ...current.receipt,+ enabled,+ });+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ return false;+ }+ await this.receiptStore.write(+ createGhostInstallReceipt({+ manifest,+ localeResources,+ enabled,+ trust,+ skillContentSha256,+ packageSha256,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ }),+ { skillSourceDir: sourceDir },+ );+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }++ private async finishTrustedBundledPublish(+ id: string,+ pending: ReturnType<GhostInstallReceiptStore['readPendingMutationSync']>,+ ): Promise<void> {+ if (pending.state === 'missing') return;+ if (pending.state !== 'valid' || pending.mutation.kind === 'uninstall') {+ throw new Error('builtin seed publish journal cannot be committed');+ }+ await this.receiptStore.clearPendingMutation(id);+ if (pending.mutation.kind === 'update') {+ await fs.promises+ .rm(path.join(this.contentRootDir(), pending.mutation.backupDirName), {+ recursive: true,+ force: true,+ })+ .catch(() => undefined);+ }+ }++ /**+ * 撤销 Host 批准。**契约是"调用返回后该插件一定不再被授权运行"**:正常路径删掉+ * receipt 与技能快照;删不掉(状态根不可写等)时退回进程内隔离,不把失败原样抛给+ * 调用方去自己 fail closed —— 那正是上一版留下 fail-open 的地方。+ */+ async removeInstallApproval(id: string): Promise<boolean> {+ return this.runExclusiveMutation((mutation) => mutation.removeInstallApproval(id));+ }++ private async removeInstallApprovalUnlocked(id: string): Promise<boolean> {+ try {+ await this.receiptStore.remove(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ return true;+ } catch (err) {+ this.untrustedApprovals.add(this.isolationKey(id));+ // 这行是"插件已转进程内隔离"的唯一可观测信号,不能因为注入的 logger 没实现+ // error 就静默丢掉 —— 退化到 warn。+ const log = this.options.log;+ (log?.error ?? log?.warn)?.call(+ log,+ 'ghost approval could not be removed; kept untrusted in-process',+ { id, error: err instanceof Error ? err.message : String(err) },+ );+ return false;+ }+ }++ private readApprovedLocaleResources(+ dir: string,+ manifest: GhostManifest,+ ): Record<string, GhostManifestLocaleResource> {+ const resources: Record<string, GhostManifestLocaleResource> = {};+ const realDir = fs.realpathSync(dir);+ for (const localePath of Object.values(manifest.locales ?? {})) {+ if (!localePath) continue;+ // 逐段解析:只 lstat 最终段挡不住"中间段被换成链接"——那会把插件目录之外的+ // JSON 读成已批准的界面文案钉进 receipt。判据与技能目录同源。+ const absPath = resolveGhostContentPathSync(dir, localePath, {+ expect: 'file',+ label: 'bundled locale',+ });+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {+ containWithin: realDir,+ });+ if (bytes === null) throw new Error(`bundled locale missing or oversized: ${localePath}`);+ const raw = JSON.parse(bytes.toString('utf8')) as unknown;+ const validated = validateGhostManifestLocaleResource(raw, manifest);+ if (!validated.ok) throw new Error(`bundled locale invalid: ${localePath}`);+ resources[localePath] = validated.resource;+ }+ return resources;}/** 解压 zip 条目到 staging 目录(install / update 共用;含 zip-slip / bomb 防御)。 */diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 56a791d0c1,9991aad66e..aa50019db2--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@@ -165,3865 -90,428 +165,3868 @@@ async function expectRejectionexpect((result as { rejection: { code: string } }).rejection.code).toBe(code);}-describe('GhostManager · install', () => {- it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {- const manifest = {- ...goodManifest(),- name: 'Base name',- description: 'Base description',- locales: {- en: 'locales/en.json',- 'zh-CN': 'locales/zh-CN.json',- },- };- const locale = (name: string, description: string, toolDescription: string) =>- JSON.stringify({- name,- description,- tools: { do_thing: { description: toolDescription } },- });- const cindy = await makeCindy('localized.cindy', manifest, {- 'locales/en.json': locale('English name', 'English description', 'English tool'),- 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),- });- const result = await manager.install(cindy);- expect(result).toMatchObject({- ghost: {- manifest: {- name: '中文名称',- description: '中文说明',- resolvedLocale: 'zh-CN',- tools: [{ name: 'do_thing', description: '中文工具' }],- },- },- });-- hostLocale = 'ja';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- description: 'English description',- resolvedLocale: 'ja',- tools: [{ name: 'do_thing', description: 'English tool' }],- });- hostLocale = 'fr-FR';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- resolvedLocale: 'en',- });+async function updateGhost(+ cindyPath: string,+ id = 'hello',+): ReturnType<GhostManager['update']> {+ const installed = manager.list().find((ghost) => ghost.manifest.id === id);+ return manager.update(cindyPath, {+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),});+}- it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {- hostLocale = 'en';- const manifest = {- ...goodManifest(),- name: 'Base name',- locales: { en: 'locales/en.json' },- };- const locale = (name: string) =>- JSON.stringify({- name,- tools: { do_thing: { description: 'Localized tool' } },- });- const cindy = await makeCindy('localized-symlink.cindy', manifest, {- 'locales/en.json': locale('Packaged name'),+describe('hashApprovedSkillContent · item.dir 路径段校验', () => {+ it('rejects a link in an intermediate path segment instead of hashing bytes from outside', async () => {+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成软链 / junction 时 OS 会静默穿透,+ // 对最终段 lstat 报的是"真目录、非链接",于是指纹从技能目录之外取字节。首次批准+ // 那条路径的指纹是现算的,外部内容会被钉成"批准字节"再复制成快照,而 frontmatter+ // 一致性校验只看 name/description(manifest 里公开可抄),拦不住。所以这里必须抛错,+ // 不能返回一个哈希。+ const validated = validateGhostManifest({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },});- await manager.install(cindy);- const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');- const outsidePath = path.join(workDir, 'outside-locale.json');- await fs.promises.writeFile(outsidePath, locale('Outside name'));- await fs.promises.rm(localePath);+ if (!validated.ok) throw new Error(validated.reason);++ const base = path.join(workDir, 'plugin');+ const evil = path.join(workDir, 'evil');+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });+ await fs.promises.mkdir(path.join(evil, 'demo'), { recursive: true });+ await fs.promises.writeFile(+ path.join(base, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ );+ await fs.promises.writeFile(+ path.join(evil, 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 正常结构先能算出来,确认用例本身走到了目标代码。+ await expect(hashApprovedSkillContent(validated.manifest, base)).resolves.toHaveProperty(+ 'skills/demo',+ );++ // 把**中间段** skills 换成指向外部的链接。+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });try {- await fs.promises.symlink(outsidePath, localePath, 'file');+ await fs.promises.symlink(+ evil,+ path.join(base, 'skills'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );} catch {- return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。}- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],+ await expect(hashApprovedSkillContent(validated.manifest, base)).rejects.toThrow(+ /path segment is a link/,+ );+ });+});++describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {+ /** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */+ const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({+ ...goodManifest(id),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ });+ const legacySkillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('市场/本地旧安装无感迁移:升级后仍启用、列 approved、写下迁移台账', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 迁移前:没有 receipt → 一律 fail closed(这正是 #1080 被回滚的现场)。+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'legacy-unapproved' } });++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 迁移后:用户什么都没做,插件照旧可用。+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },});+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ });- const localesDir = path.dirname(localePath);- const outsideLocalesDir = path.join(workDir, 'outside-locales');- await fs.promises.rm(localesDir, { recursive: true, force: true });- await fs.promises.mkdir(outsideLocalesDir);+ it('未批准或 receipt 损坏的插件不展示可变 trust 镜像', async () => {+ const forgedTrust = {+ level: 'cindy-official' as const,+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ publisherName: 'Forged publisher',+ reviewerName: 'Forged reviewer',+ };+ await writeLegacyInstall('legacy', goodManifest('legacy'), { trust: forgedTrust });+ await writeLegacyInstall('invalid', goodManifest('invalid'), { trust: forgedTrust });+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });await fs.promises.writeFile(- path.join(outsideLocalesDir, 'en.json'),- locale('Outside parent name'),- );- await fs.promises.symlink(- outsideLocalesDir,- localesDir,- process.platform === 'win32' ? 'junction' : 'dir',+ path.join(workDir, 'ghosts-install-state', 'invalid.json'),+ JSON.stringify({ schemaVersion: 1, id: 'invalid' }),);- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',++ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));+ expect(byId.legacy).toMatchObject({+ approval: { state: 'legacy-unapproved' },+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ });+ expect(byId.invalid).toMatchObject({+ approval: { state: 'invalid' },+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },});+ expect(byId.legacy.trust).not.toHaveProperty('publisherName');+ expect(byId.invalid.trust).not.toHaveProperty('reviewerName');});- it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {- const manifest = {- ...goodManifest(),- locales: { en: 'locales/en.json' },- };- const missing = await makeCindy('locale-missing.cindy', manifest);- await expectRejection(await manager.install(missing), 'file-invalid');+ it('旧安装的停用态被保留:.disabled 镜像 → receipt.enabled=false', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });+ });- const invalid = await makeCindy('locale-invalid.cindy', manifest, {- 'locales/en.json': '{ nope',+ it('信任镜像被保留;缺失时保守降级为 unverified 而不是让迁移失败', async () => {+ await writeLegacyInstall('trusted', goodManifest('trusted'), {+ trust: {+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ publisherName: 'Acme',+ },});- await expectRejection(await manager.install(invalid), 'file-invalid');+ await writeLegacyInstall('bare', goodManifest('bare'), { trust: 'omit' });+ await manager.migrateLegacyApprovalsOnce();+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g]));+ expect(byId.trusted.trust).toMatchObject({ level: 'verified-publisher', publisherName: 'Acme' });+ expect(byId.trusted.enabled).toBe(true);+ // 信任文件缺失不阻断迁移:插件照旧可用,只是展示为 unverified(旧模型读同一文件也如此)。+ expect(byId.bare.trust).toMatchObject({ level: 'unverified' });+ expect(byId.bare.enabled).toBe(true);+ });- const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ it('skill 槽旧安装迁移后:快照建好、字节指纹钉住、对账认可挂链', async () => {+ await writeLegacyInstall('skilled', legacySkillManifest(), { files: legacySkillFiles() });+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ const ghost = manager.list()[0];+ expect(ghost).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(ghost.approvedSkillRoot).toBeTruthy();+ // 迁移出的快照必须能被技能对账认可(字节与 receipt 指纹逐字节对上),否则技能链断。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('全局一次性:台账落地后,新出现的无 receipt 目录不再被迁移(fail closed)', async () => {+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list().find((g) => g.manifest.id === 'first')?.approval.state).toBe('approved');++ // 台账已在。此后再冒出一个没有 receipt 的目录(可能是删了 receipt 想骗迁移,或+ // 真的新拷进来的旧目录)——迁移不再触发,它保持 fail closed。删 receipt 想"从可变+ // 安装目录重建授权"这条路被这道门堵死。+ await writeLegacyInstall('second', goodManifest('second'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('迁移绝不改动安装目录三文件(回滚到旧客户端仍按安装目录判定,§5 兜底第 4 条)', async () => {+ const dir = await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const before = {+ manifest: await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),+ disabled: fs.existsSync(path.join(dir, '.disabled')),+ trust: await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8'),+ };+ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8')).toBe(before.manifest);+ expect(fs.existsSync(path.join(dir, '.disabled'))).toBe(before.disabled);+ expect(await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8')).toBe(before.trust);+ });++ it('manifest 不合法的旧目录不迁移,保持 fail closed,不写出坏 receipt', async () => {+ const dir = path.join(rootDir, 'broken');+ await fs.promises.mkdir(dir, { recursive: true });+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), '{ not valid json');+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.failed).toEqual(['broken']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'broken.json'))).toBe(false);+ });++ it('随包种子 id 跳过迁移(交给 provisioning 的逐字节对账补批准)', async () => {+ const seededManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ isTrustedBundledId: (id) => id === 'hello',});- await expectRejection(await manager.install(unknownTool), 'file-invalid');+ await writeLegacyInstall('hello', goodManifest());+ const outcome = await seededManager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });+ // 没有替它写 receipt:provisioning 才是随包插件的批准入口。+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });- // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。- hostLocale = 'en';- const partial = await makeCindy('locale-partial.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English partial' }),+ it('瞬时状态根 IO 不封门:台账停在 in-progress,下次启动自动续跑治愈', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 第一轮:receipt 落盘的 rename 吃一次 EACCES(模拟杀软/句柄占用的环境抖动)。+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}hello.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);});- expect(await manager.install(partial)).toMatchObject({- ghost: {- manifest: {- name: 'English partial',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],- },- },+ const first = await manager.migrateLegacyApprovalsOnce();+ // 瞬时错不算"内容无效":不进 failed(那会写进 completed 台账永久封门),+ // 记 retryPending、台账停在 in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(ledger.state).toBe('in-progress');+ expect(ledger.pendingIds).toEqual(['hello']);++ // 第二轮(下次启动):环境恢复,自动续跑治愈,不需要用户操作。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ const finalLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string };+ expect(finalLedger.state).toBe('completed');+ });++ it('读 legacy ghost.json 的瞬时 IO(EACCES)判瞬时、不永久封门(P1 回归)', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const realOpenSync = fs.openSync;+ // 只让 <root>/hello/ghost.json 的单句柄安全读取吃一次 EACCES(模拟杀软/句柄占用),+ // 其余照常。+ const spy = vi+ .spyOn(fs, 'openSync')+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (typeof p === 'string' && p.endsWith(path.join('hello', 'ghost.json'))) {+ spy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);+ }) as typeof fs.openSync);++ const first = await manager.migrateLegacyApprovalsOnce();+ // 修复前:readFileSync 的错被包成无 code 的 new Error → 误判确定性 failed →+ // 写进 completed 台账永久封门。修复后:保留 errno → 判瞬时 → retryPending + in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(fs.readFileSync(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ };+ expect(ledger.state).toBe('in-progress');++ // 下轮环境恢复:自动续跑治愈,不需要用户重新确认。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });++ it('legacy .disabled marker IO errors stay pending instead of becoming disabled', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const markerPath = path.join(rootDir, 'hello', '.disabled');+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(markerPath)) {+ spy.mockRestore();+ throw Object.assign(new Error('EIO: marker temporarily unreadable'), { code: 'EIO' });+ }+ return realLstatSync(target, options as never);});- const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {- 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ const first = await manager.migrateLegacyApprovalsOnce();+ expect(first).toMatchObject({ migrated: [], failed: [], retryPending: ['hello'] });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'in-progress',+ pendingIds: ['hello'],});- await expectRejection(await manager.install(aliasedManifest), 'file-invalid');+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'legacy-unapproved' } });++ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });});- it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- const { ghost } = result as { ghost: InstalledGhost };- expect(ghost.manifest.id).toBe('hello');- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);+ it('已有 receipt 瞬时不可读时不从可变安装目录重铸,保留原批准并持久重试', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ // 模拟 #1080 历史状态没有 ledger;receipt 本身只是在本轮被 AV/权限瞬时锁住。+ await fs.promises.rm(migrationLedgerPath());+ const realOpenSync = fs.openSync;+ const openSpy = vi.spyOn(fs, 'openSync');+ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {+ openSpy.mockRestore();+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);+ });- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);- });+ const first = await manager.migrateLegacyApprovalsOnce();- it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {- const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));- const localResult = await manager.install(local);- expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });- await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });+ expect(first).toEqual({ migrated: [], skipped: [], failed: [], retryPending: ['hello'] });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });- const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });- expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });- const receipt = JSON.parse(- await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),- ) as { level?: unknown };- expect(receipt.level).toBe('cindy-official');- expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);- expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');});- it('残缺的官方 receipt 不会被投影为可用的官方 trust', async () => {- const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));- await manager.install(local, { trustOverride: 'cindy-official' });- const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;- delete metadata.publisherName;- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {+ // issue #1243 验收第 4 条的实现形态:schema/编码 bump 后的旧 receipt 判 invalid,+ // 但**首轮迁移**会把它当"已判损坏"从安装目录 backfill 重建 —— 一次内部格式变更+ // 不变成用户重新确认。v1 receipt 从未随任何构建发布,所以不需要专门的 v1 读取器;+ // 未来的 bump 走 §5 的「按旧编码核对 → 原地升级」,见规则文档。+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ // 一份 schemaVersion 过时的 receipt(读取器判 invalid)。+ await fs.promises.writeFile(+ path.join(stateDir, 'hello.json'),+ JSON.stringify({ schemaVersion: 1, id: 'hello', legacy: true }),+ );+ expect(manager.list()[0].approval.state).toBe('invalid');- expect(manager.list()[0]?.trust).toBeUndefined();+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 治愈后为有效批准;用户的停用决定(.disabled)照旧保留。+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });});- it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {- const cindy = await makeCindy('at-resource.cindy', atResourceManifest());- const installed = await manager.install(cindy);+ it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));+ const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');+ const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<- string,- unknown- >;+ // Fixture 模拟曾短暂合入后回滚的 #1080:部分插件已有 v2 receipt,但当时没有+ // legacy migration ledger;同 owner 下其余旧安装仍无 receipt。删除 ledger 只是+ // 构造这份历史状态,不代表安装根攻击者能操作状态根。+ await fs.promises.rm(migrationLedgerPath());+ await writeLegacyInstall('legacy', goodManifest('legacy'));+ await writeLegacyInstall('old-schema', goodManifest('old-schema'), { disabled: true });+ await fs.promises.writeFile(+ path.join(workDir, 'ghosts-install-state', 'old-schema.json'),+ JSON.stringify({ schemaVersion: 1, id: 'old-schema', legacy: true }),+ );- delete metadata.approvedAtResourceProvider;- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' }]);+ const outcome = await manager.migrateLegacyApprovalsOnce();- metadata.approvedAtResourceProvider = { tool: 'other_tool' };- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ expect(outcome.migrated).toEqual(['legacy', 'old-schema']);+ expect(await fs.promises.readFile(approvedReceiptPath, 'utf8')).toBe(approvedReceiptBefore);+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));+ expect(byId.approved.approval.state).toBe('approved');+ expect(byId.legacy).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(byId['old-schema']).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });});- it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest());- const result = await manager.install(cindy, { initiallyEnabled: false });- expect('ghost' in result).toBe(true);- expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);- // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);- // 重新启用即撕掉标记。- await manager.setEnabled('hello', true);- expect(manager.list()[0].enabled).toBe(true);+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const before = await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', 'hello.json'),+ 'utf8',+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]);+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(+ before,+ );});- it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {- const zip = new JSZip();- zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));- zip.file('hello-pack/assets/a.txt', 'a');- const out = path.join(workDir, 'wrapped.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {+ hostLocale = 'en';+ await writeLegacyInstall(+ 'hello',+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },+ { files: { 'locales/en.json': '{ broken json' } },+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。+ expect(outcome.failed).toEqual(['hello']);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });+});- const result = await manager.install(out);- expect('ghost' in result).toBe(true);- // 包裹层被剥掉:内容直接落在 <root>/hello/ 下- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+describe('GhostManager · owner 受管根路径', () => {+ it('允许 userData 祖先通过 symlink/junction 重定位', async () => {+ const physicalUserData = path.join(workDir, 'physical-user-data');+ const linkedUserData = path.join(workDir, 'linked-user-data');+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });+ try {+ await fs.promises.symlink(+ physicalUserData,+ linkedUserData,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }++ const relocated = new GhostManager({+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),+ });++ expect(relocated.list()).toEqual([]);+ });++ it('允许全新 owner 的多层受管根尚未创建', () => {+ const freshOwner = path.join(workDir, 'owners', 'fresh-owner');+ const fresh = new GhostManager({+ getRootDir: () => path.join(freshOwner, 'cindy-brain'),+ getStateDir: () => path.join(freshOwner, 'ghost-install-state'),+ });++ expect(fresh.list()).toEqual([]);+ });++ it('symlinked state root 下已批准插件不被判 invalid(P1 回归)', async () => {+ const physicalUserData = path.join(workDir, 'physical-user-data');+ const linkedUserData = path.join(workDir, 'linked-user-data');+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });+ try {+ await fs.promises.symlink(+ physicalUserData,+ linkedUserData,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }++ const relocated = new GhostManager({+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),+ });+ await relocated.install(await makeCindy('approved.cindy', goodManifest('approved')));++ // receipt 落在 realpath 状态根内;containWithin 必须用 realpath 根,+ // 否则合法 receipt 会被判在根外 → list() 降级成 invalid。+ const listed = relocated.list();+ expect(listed).toHaveLength(1);+ expect(listed[0].approval.state).toBe('approved');+ });++ it('仍拒绝受管根本身是 symlink/junction', async () => {+ const outside = path.join(workDir, 'outside-root');+ const linkedRoot = path.join(workDir, 'linked-root');+ await fs.promises.mkdir(outside, { recursive: true });+ try {+ await fs.promises.symlink(outside, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return;+ }++ expect(+ () =>+ new GhostManager({+ getRootDir: () => linkedRoot,+ getStateDir: () => path.join(workDir, 'state-root'),+ }),+ ).toThrow(/ghost content root is not a real directory/);+ });+});++describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await writeLegacyInstall('bbb', goodManifest('bbb'));+ await manager.migrateLegacyApprovalsOnce();+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa', 'bbb'],+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));++ const outcome = await manager.migrateLegacyApprovalsOnce();+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。+ expect(outcome.migrated).toEqual(['bbb']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ migratedIds: string[];+ };+ expect(ledger.state).toBe('completed');+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);+ });++ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。+ await writeLegacyInstall('ccc', goodManifest('ccc'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa'],+ }),+ );++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['aaa']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.aaa).toBe('approved');+ expect(byId.ccc).toBe('legacy-unapproved');+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');+ });++ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['zzz'],+ }),+ );+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ };+ expect(ledger.state).toBe('in-progress');+ });++ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');+ });++ it.skipIf(process.platform === 'win32')(+ '台账是非普通文件(symlink)→ 门保守关死,不迁也不重写',+ async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ const outside = path.join(workDir, 'ledger-outside.json');+ await fs.promises.writeFile(outside, '{}', 'utf8');+ await fs.promises.symlink(outside, migrationLedgerPath());++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ // 门关死:ledger 未被重写(仍是 symlink 指向外部文件)。+ const st = await fs.promises.lstat(migrationLedgerPath());+ expect(st.isSymbolicLink()).toBe(true);+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{}');+ },+ );++ it.each([+ ['empty pendingIds', []],+ ['non-string pending id', [null]],+ ['path-traversal pending id', ['../x']],+ ['mixed valid and invalid pending ids', ['aaa', '../x']],+ ])('非法 in-progress 台账(%s)保守关门且不被重写成 completed', async (_label, pendingIds) => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const raw = JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds,+ });+ await fs.promises.writeFile(migrationLedgerPath(), raw);++ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe(raw);+ });++ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。+ const marker = path.join(rootDir, 'hello', '.disabled');+ await fs.promises.writeFile(marker, '');+ expect(manager.list()[0].enabled).toBe(false);++ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。+ const realRename = fs.promises.rename;+ const spy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.setEnabled('hello', true);+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(marker)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {+ let stateDir = path.join(workDir, 'owner-a-state');+ const owned = new GhostManager({+ getRootDir: () => rootDir,+ getStateDir: () => stateDir,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('a.cindy', goodManifest()));+ // 撤销失败 → A 的进程内隔离。+ const realRm = fs.promises.rm;+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');+ return realRm(target as never, opts as never);+ });+ try {+ await owned.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }+ expect(owned.list()[0].approval.state).toBe('invalid');++ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,+ // 如实是 legacy-unapproved 而不是 invalid。+ stateDir = path.join(workDir, 'owner-b-state');+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');++ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。+ stateDir = path.join(workDir, 'owner-a-state');+ expect(owned.list()[0].approval.state).toBe('invalid');+ });++ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {+ await writeLegacyInstall('real', goodManifest('real'));+ const outside = path.join(workDir, 'outside-plugin');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));+ try {+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');+ } catch {+ return; // 环境建不了链接则跳过;判据逻辑平台无关。+ }++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['real']);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);+ });+});++describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {+ it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {+ // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,+ // 本地包用户没有市场路线;第三条路必须能不找文件恢复。+ await writeLegacyInstall('hello', goodManifest());+ await manager.migrateLegacyApprovalsOnce();+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');++ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.manifest.id).toBe('hello');+ expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ // 启停镜像同步维护(回滚到旧客户端不错位)。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);+ });++ it('重新确认要求立即启用时,删除停用镜像失败必须拒绝且不提交批准', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(marker)) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }+ return realRm(target, options);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('重新确认要求立即启用时,receipt 提交失败必须恢复原停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ renameSpy.mockRestore();+ }+ });++ it('重新确认不跟随确认后被换成 junction 的安装目录写删停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-'));+ const outsideMarker = path.join(outside, '.disabled');+ await fs.promises.writeFile(outsideMarker, 'sentinel');+ const probe = path.join(workDir, 'reapprove-junction-probe');+ try {+ await fs.promises.symlink(outside, probe, process.platform === 'win32' ? 'junction' : 'dir');+ await fs.promises.rm(probe, { force: true });+ } catch {+ await fs.promises.rm(outside, { recursive: true, force: true });+ return;+ }+ const realInspect = manager.inspectInstalledReapproval.bind(manager);+ const inspectSpy = vi.spyOn(manager, 'inspectInstalledReapproval').mockImplementation(async (ghostId) => {+ const result = await realInspect(ghostId);+ await fs.promises.rm(dir, { recursive: true, force: true });+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ return result;+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(await fs.promises.readFile(outsideMarker, 'utf8')).toBe('sentinel');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ } finally {+ inspectSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('重新确认 receipt 失败回滚前目录被换成 junction 时不得写入外部目标', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const displaced = path.join(rootDir, 'hello-displaced');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-'));+ let linkCreated = false;+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) {+ await realRename(dir, displaced);+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ linkCreated = true;+ } catch {+ await realRename(displaced, dir);+ }+ throw new Error('state root unwritable');+ }+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ if (linkCreated) expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ } finally {+ renameSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),+ );+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it.each(['skill', 'locale', 'icon', 'trust'] as const)(+ '确认间隙 %s 批准投影被换 → 拒绝重新确认',+ async (kind) => {+ const manifest = {+ ...goodManifest(),+ author: 'Original author',+ icon: 'assets/icon.png',+ locales: { en: 'locales/en.json' },+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ };+ await writeLegacyInstall('hello', manifest, {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ if (kind === 'skill') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',+ );+ } else if (kind === 'locale') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'locales', 'en.json'),+ JSON.stringify({ name: 'Replaced name' }),+ );+ } else if (kind === 'icon') {+ await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');+ } else {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ publisherName: 'Different publisher',+ }),+ );+ }++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ },+ );++ it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ });+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await guarded.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const inspected = await manager.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');+ });++ it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {+ await writeLegacyInstall('hello', goodManifest(), {+ trust: {+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.trust.level).toBe('unverified');+ });+});++describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect(manager.list()[0].enabled).toBe(true);++ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。+ const realRename = fs.promises.rename;+ const renameSpy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).includes('ghosts-install-state')) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(false);+ } finally {+ renameSpy.mockRestore();+ }+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(restarted.list()[0].enabled).toBe(false);+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {+ const nested = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ ],+ },+ };+ const files = {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ };+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ const ghost = manager.list()[0];+ expect(ghost.approval.state).toBe('approved');+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {+ await writeLegacyInstall(+ 'skilled',+ {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ ],+ },+ },+ {+ files: {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ },+ },+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });++ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。+ await writeLegacyInstall('hello', goodManifest());+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ });++ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('P0-2:首次批准先提交 migration ledger,落账失败时不留下有效 receipt', async () => {+ const renameTargets: string[] = [];+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ const target = String(to);+ renameTargets.push(target);+ if (target.endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ renameSpy.mockRestore();+ }++ expect(renameTargets.some((target) => target.endsWith('.legacy-migration.json'))).toBe(true);+ expect(renameTargets.some((target) => target.endsWith(`${path.sep}hello.json`))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ // Ledger commit failed before the receipt became visible, so the install+ // transaction rolls back the final directory as well; no ghost is listed.+ expect(manager.list()).toEqual([]);+ });++ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {+ const finalDir = path.join(rootDir, 'hello');+ const pendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const realRename = fs.promises.rename;+ const realRm = fs.promises.rm;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EBUSY: installed directory locked'), { code: 'EBUSY' });+ }+ return realRm(target, options);+ });+ try {+ await expect(manager.install(await makeCindy('a.cindy', goodManifest()))).resolves.toMatchObject(+ { rejection: { code: 'io' } },+ );+ } finally {+ renameSpy.mockRestore();+ rmSpy.mockRestore();+ }++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);++ const migration = await manager.migrateLegacyApprovalsOnce();+ expect(migration.migrated).toEqual([]);+ expect(migration.skipped).toContain('hello');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingPath)).toBe(false);+ });++ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const realReaddir = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {+ if (String(dir) === rootDir) {+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });+ }+ return realReaddir(dir, opts);+ }) as never);+ try {+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 环境恢复后下一轮照常迁移。+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ });++ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {+ // 台账已落(首轮迁移空跑一个插件)。+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ await writeLegacyInstall('planted', goodManifest('planted'));+ const out = await manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ );+ expect(out.migrated).toEqual(['recovered']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.recovered).toBe('approved');+ expect(byId.planted).toBe('legacy-unapproved');+ });++ it.each(['manifest', 'disabled', 'trust', 'locale', 'skill'] as const)(+ '恢复 backfill 在 %s 批准投影漂移时保持 fail closed',+ async (kind) => {+ const manifest = {+ ...goodManifest('recovered'),+ icon: 'assets/icon.png',+ locales: { en: 'locales/en.json' },+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ };+ await writeLegacyInstall('recovered', manifest, {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',+ },+ });+ const expected = await recoveredProjectionOptions('recovered');+ const dir = path.join(rootDir, 'recovered');+ if (kind === 'manifest') {+ await fs.promises.writeFile(+ path.join(dir, 'ghost.json'),+ JSON.stringify({+ ...manifest,+ tools: [+ { name: 'do_thing', description: '做点事' },+ { name: 'new_thing', description: 'New privileged tool' },+ ],+ }),+ );+ } else if (kind === 'disabled') {+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');+ } else if (kind === 'trust') {+ await fs.promises.writeFile(+ path.join(dir, '.cindy-trust.json'),+ JSON.stringify({+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ }),+ );+ } else if (kind === 'locale') {+ await fs.promises.writeFile(+ path.join(dir, 'locales', 'en.json'),+ JSON.stringify({ name: 'Replaced name' }),+ );+ } else {+ await fs.promises.writeFile(+ path.join(dir, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',+ );+ }++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ },+ );++ it('keeps legacy approval backfill eligible when the optional icon cannot be read', async () => {+ await writeLegacyInstall(+ 'recovered',+ {+ ...goodManifest('recovered'),+ icon: 'assets/icon.png',+ },+ {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ },+ },+ );+ const realOpenSync = fs.openSync;+ const spy = vi+ .spyOn(fs, 'openSync')+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (+ typeof p === 'string' &&+ p.endsWith(path.join('recovered', 'assets', 'icon.png'))+ ) {+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);+ }) as typeof fs.openSync);++ try {+ const result = await readLegacyGhostApprovalProjection(path.join(rootDir, 'recovered'), 'recovered');+ expect(result.projection.iconDataUrl).toBeUndefined();+ } finally {+ spy.mockRestore();+ }+ });++ it('恢复 backfill 不跟随被换成 junction 的插件根目录', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const expected = await recoveredProjectionOptions('recovered');+ const installedDir = path.join(rootDir, 'recovered');+ const externalDir = path.join(workDir, 'external-recovered');+ await fs.promises.rename(installedDir, externalDir);+ await fs.promises.symlink(externalDir, installedDir, 'junction');++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json'))).toBe(false);+ });++ it('closes the recovery ledger when a queued id is already approved', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['hello'],+ }),+ );++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['hello'],+ { expectedApprovalProjectionSha256ById: {} },+ ),+ ).resolves.toEqual({+ migrated: [],+ failed: [],+ });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'completed',+ });+ });++ it('keeps a target-only legacy recovery without a frozen projection fail closed', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ { expectedApprovalProjectionSha256ById: {} },+ ),+ ).resolves.toEqual({+ migrated: [],+ failed: ['recovered'],+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ await fs.promises.rm(migrationLedgerPath());+ const realOpenSync = fs.openSync;+ const openSpy = vi.spyOn(fs, 'openSync');+ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {+ openSpy.mockRestore();+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });+ }+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);+ });++ expect(+ await manager.backfillRecoveredLegacyGhosts(+ ['hello'],+ await recoveredProjectionOptions('hello'),+ ),+ ).toEqual({+ migrated: [],+ failed: [],+ });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });+ });++ it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });++ const expected = await recoveredProjectionOptions('recovered');+ const first = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(first).toEqual({ migrated: [], failed: [] });+ const pendingLedger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(pendingLedger.state).toBe('in-progress');+ expect(pendingLedger.pendingIds).toEqual(['recovered']);++ const second = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(second.migrated).toEqual(['recovered']);+ const completedLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ expect(completedLedger.state).toBe('completed');+ expect(completedLedger.pendingIds).toBeUndefined();+ });++ it('persists recovered ids before the first receipt write starts', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ let queueSeenBeforeReceipt = false;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ const ledger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ queueSeenBeforeReceipt =+ ledger.state === 'in-progress' && ledger.pendingIds?.includes('recovered') === true;+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });++ try {+ await manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ );+ } finally {+ renameSpy.mockRestore();+ }+ expect(queueSeenBeforeReceipt).toBe(true);+ });++ it('does not overwrite an existing recovery queue when the migration ledger is unreadable', async () => {+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const originalLedger = {+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['existing'],+ };+ // 台账经 bounded no-follow 读取,超上限即视为不可读(不再用 unbounded+ // readFileSync)。构造一个超限 ledger,验证门保守关死且 recovery queue 不被覆盖。+ const oversizedLedger = {+ ...originalLedger,+ migratedIds: Array.from({ length: 900 }, (_, i) => `pad-${'x'.repeat(120)}-${i}`),+ };+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify(oversizedLedger),+ );+ await writeLegacyInstall('recovered', goodManifest('recovered'));++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ ),+ ).rejects.toThrow(+ /ledger exists but is unreadable/,+ );+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(+ oversizedLedger,+ );+ });++ it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {+ await manager.install(+ await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),+ );+ await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));+ const inspected = await manager.inspectInstalledReapproval('clasher');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const result = await manager.reapproveInstalled('clasher', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');+ });++ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {+ await writeLegacyInstall('brokered', {+ ...goodManifest('brokered'),+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'token',+ source: 'oauth',+ oauth: { tokenBroker: 'github' },+ },+ ],+ },+ });+ const inspected = await manager.inspectInstalledReapproval('brokered');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.previouslyEnabled).toBe(false);+ });++ it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const realRename = fs.promises.rename;+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ // staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。+ if (path.resolve(String(to)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EPERM: dir locked'), { code: 'EPERM' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const bumped = await makeCindy('b.cindy', { ...goodManifest(), version: '1.0.1' });+ const result = await updateGhost(bumped);+ expect('rejection' in result).toBe(true);+ if (!('rejection' in result)) return;+ expect(result.rejection.code).toBe('io');+ expect(result.rejection.code === 'io' && result.rejection.rollbackFailed).toBe(true);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ spy.mockRestore();+ }+ });+});++describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {+ const pendingMarkerPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */+ const freshManager = () =>+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。+ await writeLegacyInstall('hello', goodManifest());+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),+ );++ const recovered = freshManager(); // 构造期恢复:删掉未完成安装+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ const outcome = await recovered.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象+ });++ it('keeps a committed builtin restore successful and retries tombstone clearing from its journal', async () => {+ trustedBundledIds.add('hello');+ const clearBuiltinTombstone = vi+ .fn<(id: string) => void>()+ .mockImplementationOnce(() => {+ throw new Error('state root temporarily unavailable');+ })+ .mockImplementation(() => undefined);+ const restoringManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ const installed = await restoringManager.install(+ await makeCindy('builtin-restore.cindy', goodManifest()),+ );++ expect('ghost' in installed).toBe(true);+ expect(restoringManager.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath(), 'utf8'))).toMatchObject({+ kind: 'install',+ clearBuiltinTombstone: true,+ });++ const recoveredAfterClearFailure = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(recoveredAfterClearFailure.list()[0]).toMatchObject({+ approval: { state: 'approved' },+ });+ });++ it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ await fs.promises.rm(finalDir, { recursive: true, force: true });+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: 'f'.repeat(64),+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('非法 pending marker 会阻断 orphan backup 启发式,不删除待人工恢复的 backup', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '..\\outside',+ }),+ );++ const recovered = freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalid pending marker filename blocks orphan-backup heuristics', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ const invalidMarker = path.join(path.dirname(pendingMarkerPath()), '.pending-BAD!.json');+ await fs.promises.writeFile(invalidMarker, '{}');++ const recovered = freshManager();+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(invalidMarker)).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker JSON 为 null 时按 invalid 保留现场,不让构造期恢复崩溃', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.writeFile(pendingMarkerPath(), 'null');++ const recovered = freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('状态根 journal 扫描 EACCES 时跳过全部恢复启发式,任何现场都不动', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.mkdir(stagingDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ if (path.resolve(String(target)) === path.resolve(stateRoot)) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ // 未提交 update 已先移除 final;backup 不可读时保留整笔 journal,+ // 因而此刻 final 仍缺失,等待下次可读时再由 recovery 收敛。+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(stagingDir)).toBe(true);+ });++ it('journal root unreadable blocks the whole owner even when installed ids cannot be enumerated yet', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ const resolved = path.resolve(String(target));+ if (resolved === path.resolve(stateRoot) || resolved === path.resolve(rootDir)) {+ throw Object.assign(new Error('EACCES: managed root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);++ let recovered: GhostManager;+ try {+ recovered = freshManager();+ } finally {+ spy.mockRestore();+ }++ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker 读取 EACCES 时保留 marker/final/backup,不降级到 orphan cleanup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );- const realReadFileSync = fs.readFileSync;- const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {++ // readPendingMutationSync now uses readBoundedFileNoFollowSync (single-handle++ // open+stat+read) instead of lstat+readFileSync. Inject EACCES at openSync++ // so the bounded reader surfaces the unreadable state through its normal path.++ const realOpenSync = fs.openSync;++ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath())) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }- return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);- }) as typeof fs.readFileSync);++ return (realOpenSync as (...args: unknown[]) => unknown)(target, ...rest);++ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ });++ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),+ );+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);+ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('已提交 update 的 receipt lstat EACCES 时保留 final/backup/receipt/journal', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ }),+ );+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);+ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('update backup lstat EACCES 时保留整笔 journal,不清 marker 继续猜恢复', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(backupDir)) {+ throw Object.assign(new Error('EACCES: backup locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ const backupName = '.cindy-updating-hello-abcdef12';+ const finalDir = path.join(rootB, 'hello');+ await fs.promises.mkdir(path.join(rootB, backupName), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, backupName, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, backupName, 'main.js'), 'old');+ await fs.promises.mkdir(stateB, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateB, '.pending-hello.json'),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getLocale: () => hostLocale,+ });+ activeRoot = rootB;+ activeState = stateB;+ expect(owned.list().map((ghost) => ghost.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootB, backupName))).toBe(false);+ });++ it('排队中的 mutation 在 owner 代际变化后拒绝执行', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });++ let markStarted!: () => void;+ let releaseFirst!: () => void;+ const started = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const first = owned.runExclusiveMutation(async () => {+ markStarted();+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ });+ await started;++ const second = owned.runExclusiveMutation(async () => {+ await fs.promises.mkdir(activeRoot, { recursive: true });+ await fs.promises.writeFile(path.join(activeRoot, 'queued-write'), 'must not run');+ });+ const rejected = expect(second).rejects.toThrow(/owner context changed/);+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ releaseFirst();++ await first;+ await rejected;+ expect(fs.existsSync(path.join(rootA, 'queued-write'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'queued-write'))).toBe(false);+ });++ it('执行中的独占 mutation 钉住 owner 内容根与状态根,不把后半段写进新 owner', async () => {+ const rootA = path.join(workDir, 'owned-a');+ const rootB = path.join(workDir, 'owned-b');+ const stateA = path.join(workDir, 'owned-state-a');+ const stateB = path.join(workDir, 'owned-state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('owned.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootB, 'hello'), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, 'hello', 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, 'hello', 'main.js'), 'owner-b');++ await owned.runExclusiveMutation(async (mutation) => {+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ expect(await mutation.uninstall('hello', { notify: false })).toEqual({ ok: true });+ });++ expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'hello', 'main.js'))).toBe(true);+ expect(owned.list().find((ghost) => ghost.manifest.id === 'hello')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';++ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );++ freshManager(); // 构造期恢复:未提交 → 回滚到 backup+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ revision: string;+ };+ const backupName = '.cindy-updating-hello-abcdef34';+ await fs.promises.mkdir(path.join(rootDir, backupName));+ await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: committedReceipt.packageSha256,+ receiptRevision: committedReceipt.revision,+ backupDirName: backupName,+ phase: 'published',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');+ });++ it('same-hash backed-up update restores the only backup instead of deleting it', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const receipt = JSON.parse(receiptBefore) as { packageSha256: string };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0011';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '11111111-1111-4111-8111-111111111111',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('same-hash backed-up update rolls back a final whose receipt revision is still old', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0022';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(path.join(finalDir, 'new.txt'), 'uncommitted');+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '22222222-2222-4222-8222-222222222222',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(finalDir, 'new.txt'))).toBe(false);+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('legacy install marker with an old same-hash receipt and no final stays isolated', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: receipt.packageSha256,+ }),+ );++ freshManager();+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(manager.list()).toEqual([]);+ });++ it('卸载先撤批准再删目录:删目录失败时不留"孤立 approved receipt + 目录在"(防借尸还魂)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect(manager.list()[0].approval.state).toBe('approved');+ // 让内容目录的 rm 失败(模拟句柄占用),但放行 receipt/快照的 rm。+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation((async (p: fs.PathLike, ...rest: unknown[]) => {+ if (String(p) === path.join(rootDir, 'hello')) {+ rmSpy.mockRestore();+ const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;+ err.code = 'EBUSY';+ throw err;+ }+ return (realRm as (...a: unknown[]) => Promise<void>)(p, ...rest);+ }) as typeof fs.promises.rm);++ const res = await manager.uninstall('hello');+ await expectRejection(res, 'io');+ // 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报+ // legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('卸载崩在撤批准之后、删目录之前:恢复据 uninstall 标记删净残留目录', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 模拟崩溃现场:receipt 已撤(revoke 先行),目录还在,uninstall 标记在。+ await fs.promises.rm(receiptPath(), { force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);++ freshManager(); // 构造期恢复+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('卸载崩在撤批准之前:恢复据 uninstall 标记把 receipt 与目录都删净', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 崩在写标记之后、撤批准之前:receipt 与目录都还在。+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(receiptPath())).toBe(true);++ freshManager();+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');+ const result = await manager.setEnabled('foo', false);+ await expectRejection(result, 'not-installed');+ });++ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const dir = path.join(rootDir, 'hello');+ const outside = path.join(workDir, 'outside-target');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.rm(dir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。+ }+ const result = await manager.setEnabled('hello', false);+ await expectRejection(result, 'not-installed');+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ });+});++describe('GhostManager · update pre-rename recovery', () => {+ it('marker 落盘但尚未 rename 时保留旧 final 与 receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(stagingDir, { recursive: true });+ const stateReceiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {+ packageSha256?: string;+ };+ await fs.promises.writeFile(+ statePendingPath,+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '.cindy-updating-hello-deadbeef',+ phase: 'prepared',+ oldPackageSha256: receipt.packageSha256,+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(stateReceiptPath)).toBe(true);+ expect(fs.existsSync(statePendingPath)).toBe(false);+ expect(fs.existsSync(stagingDir)).toBe(false);+ });+});++describe('GhostManager · install', () => {+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ description: 'Base description',+ locales: {+ en: 'locales/en.json',+ 'zh-CN': 'locales/zh-CN.json',+ },+ };+ const locale = (name: string, description: string, toolDescription: string) =>+ JSON.stringify({+ name,+ description,+ tools: { do_thing: { description: toolDescription } },+ });+ const cindy = await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': locale('English name', 'English description', 'English tool'),+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),+ });+ const result = await manager.install(cindy);+ expect(result).toMatchObject({+ ghost: {+ manifest: {+ name: '中文名称',+ description: '中文说明',+ resolvedLocale: 'zh-CN',+ tools: [{ name: 'do_thing', description: '中文工具' }],+ },+ },+ });++ hostLocale = 'ja';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ description: 'English description',+ resolvedLocale: 'ja',+ tools: [{ name: 'do_thing', description: 'English tool' }],+ });+ hostLocale = 'fr-FR';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ resolvedLocale: 'en',+ });+ });++ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {+ hostLocale = 'en';+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ locales: { en: 'locales/en.json' },+ };+ const locale = (name: string) =>+ JSON.stringify({+ name,+ tools: { do_thing: { description: 'Localized tool' } },+ });+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {+ 'locales/en.json': locale('Packaged name'),+ });+ await manager.install(cindy);+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');+ const outsidePath = path.join(workDir, 'outside-locale.json');+ await fs.promises.writeFile(outsidePath, locale('Outside name'));+ await fs.promises.rm(localePath);+ try {+ await fs.promises.symlink(outsidePath, localePath, 'file');+ } catch {+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。+ }++ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: 'Localized tool' }],+ });++ const localesDir = path.dirname(localePath);+ const outsideLocalesDir = path.join(workDir, 'outside-locales');+ await fs.promises.rm(localesDir, { recursive: true, force: true });+ await fs.promises.mkdir(outsideLocalesDir);+ await fs.promises.writeFile(+ path.join(outsideLocalesDir, 'en.json'),+ locale('Outside parent name'),+ );+ await fs.promises.symlink(+ outsideLocalesDir,+ localesDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ });+ });++ it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {+ const manifest = {+ ...goodManifest(),+ locales: { en: 'locales/en.json' },+ };+ const missing = await makeCindy('locale-missing.cindy', manifest);+ await expectRejection(await manager.install(missing), 'file-invalid');++ const invalid = await makeCindy('locale-invalid.cindy', manifest, {+ 'locales/en.json': '{ nope',+ });+ await expectRejection(await manager.install(invalid), 'file-invalid');++ const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ });+ await expectRejection(await manager.install(unknownTool), 'file-invalid');++ // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。+ hostLocale = 'en';+ const partial = await makeCindy('locale-partial.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English partial' }),+ });+ expect(await manager.install(partial)).toMatchObject({+ ghost: {+ manifest: {+ name: 'English partial',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: '做点事' }],+ },+ },+ });++ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ });+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');+ });++ it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ const { ghost } = result as { ghost: InstalledGhost };+ expect(ghost.manifest.id).toBe('hello');+ expect(ghost.dir).toBe(path.join(rootDir, 'hello'));+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);+ });++ it('returns the quarantined projection when install journal cleanup fails', async () => {+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ let result: Awaited<ReturnType<GhostManager['install']>>;+ try {+ result = await manager.install(await makeCindy('valid.cindy', goodManifest()));+ } finally {+ clearSpy.mockRestore();+ }+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed install projection');+ expect(result.ghost).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ });++ it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {+ const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));+ const localResult = await manager.install(local);+ expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });+ await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });++ const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });+ expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });+ const receipt = JSON.parse(+ await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),+ ) as { level?: unknown };+ expect(receipt.level).toBe('cindy-official');+ expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);+ expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ });++ it('可变 trust 镜像损坏不会覆盖有效的官方 Host receipt', async () => {+ const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));+ await manager.install(local, { trustOverride: 'cindy-official' });+ const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;+ delete metadata.publisherName;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);++ expect(manager.list()[0]?.trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ });++ it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {+ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());+ const installed = await manager.install(cindy);++ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<+ string,+ unknown+ >;++ delete metadata.approvedAtResourceProvider;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' }]);++ metadata.approvedAtResourceProvider = { tool: 'other_tool' };+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ });++ it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest());+ const result = await manager.install(cindy, { initiallyEnabled: false });+ expect('ghost' in result).toBe(true);+ expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);+ // 重新启用即撕掉标记。+ await manager.setEnabled('hello', true);+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {+ const zip = new JSZip();+ zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));+ zip.file('hello-pack/assets/a.txt', 'a');+ const out = path.join(workDir, 'wrapped.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));++ const result = await manager.install(out);+ expect('ghost' in result).toBe(true);+ // 包裹层被剥掉:内容直接落在 <root>/hello/ 下+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+ });++ it('源文件不存在 → source-not-found', async () => {+ await expectRejection(+ await manager.install(path.join(workDir, 'nope.cindy')),+ 'source-not-found',+ );+ });++ it('不是 zip 的文件 → file-invalid', async () => {+ const bad = path.join(workDir, 'bad.cindy');+ await fs.promises.writeFile(bad, 'this is not a zip');+ await expectRejection(await manager.install(bad), 'file-invalid');+ });++ it('缺 ghost.json → file-invalid', async () => {+ const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('ghost.json 不是合法 JSON → file-invalid', async () => {+ const zip = new JSZip();+ zip.file('ghost.json', '{ not json');+ const out = path.join(workDir, 'badjson.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ await expectRejection(await manager.install(out), 'file-invalid');+ });++ it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {+ const cindy = await makeCindy('decl.cindy', {+ schemaVersion: 1,+ id: 'legacy',+ name: '老声明型',+ version: '1.0.0',+ kind: 'declaration',+ panel: { title: '静态面板', body: '一段文字' },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ const manifest = {+ ...goodManifest(),+ slots: ['node'],+ tools: undefined,+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ };+ const cindy = await makeCindy('missing-node.cindy', manifest);+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(+ '包不能自带主机保留文件 %s',+ async (reservedFile) => {+ const cindy = await makeCindy('reserved.cindy', goodManifest(), {+ [reservedFile]: '{}',+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: {+ code: 'file-invalid',+ reason: expect.stringContaining('主机保留文件'),+ },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ },+ );++ it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {+ const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装+ expect(onChanged).not.toHaveBeenCalled();+ });++ // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。+ it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(+ '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',+ async (entryName) => {+ // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字+ // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。+ const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });+ const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {+ [entryName]: evilManifest,+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(onChanged).not.toHaveBeenCalled();+ },+ );++ it('重复装入同 id → already-installed,原安装不受影响', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', goodManifest())),+ 'already-installed',+ );+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {+ await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),+ 'command-conflict',+ );+ expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘+ const ok = await manager.install(+ await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),+ );+ expect('ghost' in ok).toBe(true);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ });+});++describe('GhostManager · uninstall', () => {+ it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello');+ expect('ok' in result).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0]).toEqual([]);+ });++ it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello', { notify: false });++ expect('ok' in result).toBe(true);+ expect(manager.list()).toEqual([]);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('persists builtin tombstone intent before removing approval or installed bytes', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).toHaveBeenCalledWith('hello');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });++ it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');++ await expect(+ manager.uninstall('hello', { notify: false, recordBuiltinTombstone: false }),+ ).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).not.toHaveBeenCalled();+ expect(manager.list()).toEqual([]);+ });++ it('keeps builtin uninstall journal and bytes quarantined when tombstone persistence fails', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ const error = new Error('access denied') as NodeJS.ErrnoException;+ error.code = 'EACCES';+ throw error;+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toMatchObject({+ rejection: { code: 'io' },+ });++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ manifest: { id: 'hello' },+ enabled: false,+ approval: { state: 'invalid' },+ });+ expect(+ JSON.parse(+ await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', '.pending-hello.json'),+ 'utf8',+ ),+ ),+ ).toMatchObject({ kind: 'uninstall', builtinTombstone: true });+ });++ it('recovers a crashed builtin uninstall by persisting its tombstone before deletion', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateDir, '.pending-hello.json'),+ `${JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'uninstall',+ builtinTombstone: true,+ })}\n`,+ );+ const recoveredTombstone = vi.fn(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ recordBuiltinTombstone: recoveredTombstone,+ });++ expect(recoveredTombstone).toHaveBeenCalledWith('hello');+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(stateDir, '.pending-hello.json'))).toBe(false);+ });++ it('卸未装的 id → not-installed', async () => {+ const result = await manager.uninstall('ghost');+ expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ });++ it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ const sibling = path.join(workDir, 'victim');+ await fs.promises.mkdir(sibling);+ for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {+ const result = await manager.uninstall(id);+ expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ }+ expect(fs.existsSync(sibling)).toBe(true);+ });++ it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {+ const cindy = await makeCindy('a.cindy', goodManifest());+ await manager.install(cindy);+ await manager.uninstall('hello');+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });+});++describe('GhostManager · list', () => {+ it('根目录不存在 → 空清单(不报错)', () => {+ expect(manager.list()).toEqual([]);+ });++ it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 手工捏三个坏目录+ await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));+ await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));+ await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');+ await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));+ await fs.promises.writeFile(+ path.join(rootDir, 'wrong-name', 'ghost.json'),+ JSON.stringify(goodManifest('other-id')),+ );+ // 隐藏目录(staging 残留形态)也不进清单+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });++ it('多意识按 id 排序', async () => {+ await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));+ await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ });+});++describe('GhostManager · Host approval receipt', () => {+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */+ const realCopyFile = fs.promises.copyFile;+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ const writeBundledSource = async (+ manifest: InstalledGhost['manifest'],+ files: Record<string, string> = { 'main.js': '// bundled seed' },+ ): Promise<{ sourceDir: string }> => {+ const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);+ await fs.promises.rm(sourceDir, { recursive: true, force: true });+ await fs.promises.mkdir(sourceDir, { recursive: true });+ trustedBundledIds.add(manifest.id);+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(manifest));+ for (const [relativePath, content] of Object.entries(files)) {+ const target = path.join(sourceDir, relativePath);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ await fs.promises.writeFile(target, content);+ }+ return { sourceDir };+ };++ /** 带 skill 槽的清单 + 配套包内文件(技能快照相关用例共用)。 */+ const skillManifest = (): Record<string, unknown> => ({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ });+ const skillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const before = manager.list()[0];+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(path.dirname(receiptPath())).not.toBe(rootDir);++ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ version: '99.0.0',+ slots: ['node'],+ node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },+ }),+ );+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ }),+ );++ const after = manager.list()[0];+ expect(after.manifest).toEqual(before.manifest);+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录+ // 影响,镜像也不能把插件往"启用"方向翻。+ expect(after.enabled).toBe(false);+ expect(after.trust).toEqual(before.trust);+ expect(after.approval.state).toBe('approved');++ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {+ const legacyDir = path.join(rootDir, 'hello');+ await fs.promises.mkdir(legacyDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(legacyDir, 'ghost.json'),+ JSON.stringify(goodManifest()),+ );+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ const reviewed = await updateGhost(+ await makeCindy('reviewed.cindy', { ...goodManifest(), version: '2.0.0' }),+ );+ expect(reviewed).toMatchObject({+ ghost: {+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ },+ });++ await fs.promises.writeFile(receiptPath(), '{ broken');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('rejects an update when the approved revision changed after review', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const staleApproval = ghostInstallApprovalToken(manager.list()[0].approval);+ const v2 = await makeCindy('v2.cindy', {+ ...goodManifest(),+ version: '2.0.0',+ });+ const first = await manager.update(v2, {+ expectedInstalledApproval: staleApproval,+ });+ expect(first).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });++ const v3 = await makeCindy('v3.cindy', {+ ...goodManifest(),+ version: '3.0.0',+ });+ await expectRejection(+ await manager.update(v3, {+ expectedInstalledApproval: staleApproval,+ }),+ 'state-changed',+ );+ expect(manager.list()[0].manifest.version).toBe('2.0.0');+ });++ it('quarantines an update while the new directory is published but receipt is not committed', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const originalRename = fs.promises.rename;+ let releasePublish!: () => void;+ let publishStarted!: () => void;+ const publishStartedPromise = new Promise<void>((resolve) => {+ publishStarted = resolve;+ });+ const publishGate = new Promise<void>((resolve) => {+ releasePublish = resolve;+ });+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(from).includes('.cindy-installing-hello-')) {+ const result = await originalRename(from, to);+ publishStarted();+ await publishGate;+ return result;+ }+ return originalRename(from, to);+ });+ try {+ const updatePromise = manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ await publishStartedPromise;+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ releasePublish();+ expect('ghost' in (await updatePromise)).toBe(true);+ } finally {+ releasePublish();+ renameSpy.mockRestore();+ }+ });++ it('keeps a committed update quarantined until its durable journal is cleared', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ try {+ const result = await manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed update projection');+ expect(result.ghost).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(manager.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ clearSpy.mockRestore();+ }++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('removes the receipt and approved skill snapshots on uninstall', async () => {+ const manifest = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ };+ const cindy = await makeCindy('skill.cindy', manifest, {+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ await manager.install(cindy);+ const listed = manager.list()[0];+ expect(listed.approvedSkillRoot).toBeTruthy();+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);++ await manager.uninstall('skilled');+ expect(fs.existsSync(receiptPath('skilled'))).toBe(false);+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);+ });++ it('keeps an uninstall journal when receipt cleanup fails after content removal', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ await fs.promises.rm(receiptPath());+ await fs.promises.mkdir(receiptPath());+ await fs.promises.writeFile(path.join(receiptPath(), 'blocked'), 'x');++ const result = await manager.uninstall('hello');++ expect(result).toEqual({ ok: true });+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(+ true,+ );+ await fs.promises.rm(receiptPath(), { recursive: true, force: true });+ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('keeps disabling possible when the approved skill snapshot is gone, and rebuilds it on enable', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 外部把快照删掉:停用是安全方向,必须仍然成功,不能把插件卡在既不能用也不能关。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });++ // 重新启用时从当前安装目录重建快照,不需要用户重新走一次确认。+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ const healed = manager.list()[0];+ expect(healed.enabled).toBe(true);+ expect(healed.approvedSkillRoot).toBe(snapshotRoot);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('refuses to rebuild an enable-time snapshot from install bytes that drifted from the approved manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 安装目录里的 SKILL.md 与批准 manifest 声明的 description 不再一致,快照也没了:+ // 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户+ // 没看过的技能指令。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Silently widened skill\n---\n\nTampered instructions\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('prunes skill snapshots left behind by superseded approval revisions', async () => {+ await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));+ const firstSnapshot = manager.list()[0].approvedSkillRoot!;+ const snapshotParent = path.dirname(firstSnapshot);++ await updateGhost(+ await makeCindy(+ 'skill-v2.cindy',+ { ...skillManifest(), version: '2.0.0' },+ skillFiles(),+ ),+ 'skilled',+ );+ const secondSnapshot = manager.list()[0].approvedSkillRoot!;++ expect(secondSnapshot).not.toBe(firstSnapshot);+ expect(await fs.promises.readdir(snapshotParent)).toEqual([+ path.basename(secondSnapshot),+ ]);+ });++ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。+ const external = path.join(workDir, 'external-data');+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。+ await fs.promises.rm(idDir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 环境建不了链接则跳过;判定逻辑平台同源。+ }++ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。+ await manager.setEnabled('skilled', false);+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);+ // 外部目录里也不应多出任何被"发布"进去的快照字节。+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);+ });++ it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const installedSkillMd = path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md');+ // 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准+ // manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,+ // 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份+ // 读进内存。+ await fs.promises.writeFile(+ installedSkillMd,+ `---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n${'padding '.repeat(+ GHOST_SKILL_MD_MAX_BYTES / 4,+ )}`,+ );+ expect((await fs.promises.lstat(installedSkillMd)).size).toBeGreaterThan(+ GHOST_SKILL_MD_MAX_BYTES,+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),+ '#!/bin/sh\necho injected\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to follow a link planted inside the skill directory when rebuilding', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const outside = path.join(workDir, 'outside-skill');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'bytes from outside the skill dir');+ // Windows junction 不需要管理员权限即可创建,是本平台成本最低的一条"把技能目录+ // 之外的字节拉进批准快照"的路子。判据不能建立在 Dirent 类型位的实现细节上,+ // 所以这条用例把行为钉住:planted link 一律拒,快照不落地。+ try {+ await fs.promises.symlink(+ outside,+ path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。+ }+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ // 状态根里不该出现任何来自技能目录之外的字节(含崩溃残留的 .tmp)。+ const stateRoot = manager.approvalStateRoot();+ const leaked: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const child = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(child);+ else if (entry.name === 'leak.txt') leaked.push(child);+ }+ };+ if (fs.existsSync(stateRoot)) walk(stateRoot);+ expect(leaked).toEqual([]);+ });++ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, tampered, 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ try {+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ } finally {+ spy.mockRestore();+ }+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;+ try {+ result = await manager.setEnabled('skilled', true);+ } finally {+ spy.mockRestore();+ }+ await expectRejection(result, 'io');+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成+ // 行为钉住、测不出重排。+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(+ /exceeds \d+ bytes/,+ );+ expect(swapped).toBe(1);+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('keeps an install unusable when a stale approval cannot be revoked', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":+ // removeInstallApproval 的契约是返回后一定不再被授权运行。+ const spy = vi+ .spyOn(fs.promises, 'rm')+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ try {+ await manager.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。+ await fs.promises.writeFile(+ snapshotSkillMd,+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');+ });++ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ tampered,+ );++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('bundled unchanged approval repairs a deleted skill snapshot without toggling enabled state', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ const snapshotRoot = listed.approvedSkillRoot!;+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, listed.enabled, source),+ ).toBe(true);+ expect(manager.list()[0].enabled).toBe(listed.enabled);+ const repairedSnapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(+ await fs.promises.readFile(+ path.join(repairedSnapshotRoot, 'skills', 'demo', 'SKILL.md'),+ 'utf8',+ ),+ ).toContain('Approved instructions');+ });++ it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),+ ) as Record<string, unknown>;+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。+ delete receipt.skillContentSha256;+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalidates a schema v1 receipt instead of trusting its legacy content digests', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ // v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。+ receipt.schemaVersion = 1;+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('revoking approval fails the install closed, and a later bundled approval heals it', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;++ // 随包对账在换入新种子字节后写批准失败时走的收敛动作:撤掉陈旧批准。+ // 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。+ await manager.removeInstallApproval('hello');++ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ // 下一轮启动对账重新补批准即自愈,不需要用户介入。+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },+ });+ });++ it('uses the immutable bundled source directory when minting the approval receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);+ trustedBundledIds.add(approvedManifest.id);+ await fs.promises.mkdir(sourceDir, { recursive: true });+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));+ await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');++ const unsafeCall = manager.approveTrustedBundledInstall as unknown as (+ manifest: InstalledGhost['manifest'],+ markerEnabled: boolean,+ ) => Promise<boolean>;+ await expect(unsafeCall.call(manager, approvedManifest, true)).rejects.toThrow(+ /verified bundled source directory/,+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: path.join(rootDir, approvedManifest.id),+ }),+ ).rejects.toThrow(/mutable installed directory/);+ const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);+ await fs.promises.mkdir(arbitrarySourceDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(arbitrarySourceDir, 'ghost.json'),+ JSON.stringify(approvedManifest),+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: arbitrarySourceDir,+ }),+ ).rejects.toThrow(/trusted seed roster/);++ expect(+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),+ ).toBe(true);+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ const sourcePackageSha256 = receipt.packageSha256;+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);+ });++ it('publishes bundled replacements through the pending journal and commits on receipt write', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const { sourceDir } = await writeBundledSource(approvedManifest, {+ 'main.js': 'immutable replacement bytes',+ });+ const stateRoot = manager.approvalStateRoot();+ const pendingPath = path.join(stateRoot, '.pending-hello.json');++ await manager.runExclusiveMutation(async (mutation) => {+ expect(await mutation.removeInstallApproval('hello')).toBe(true);+ await mutation.publishTrustedBundledSeed('hello', sourceDir, { disabled: false });+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(true);+ await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ });++ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(+ 'immutable replacement bytes',+ );+ expect(fs.existsSync(pendingPath)).toBe(false);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');+ });++ it('keeps a receipt-pinned disable when the .disabled mirror was lost, and rewrites the mirror', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);++ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(false);+ expect(manager.list()[0].enabled).toBe(false);+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('源文件不存在 → source-not-found', async () => {- await expectRejection(- await manager.install(path.join(workDir, 'nope.cindy')),- 'source-not-found',- );- });+ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);- it('不是 zip 的文件 → file-invalid', async () => {- const bad = path.join(workDir, 'bad.cindy');- await fs.promises.writeFile(bad, 'this is not a zip');- await expectRejection(await manager.install(bad), 'file-invalid');+ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);});- it('缺 ghost.json → file-invalid', async () => {- const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });- await expectRejection(await manager.install(cindy), 'file-invalid');- });+ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));- it('ghost.json 不是合法 JSON → file-invalid', async () => {- const zip = new JSZip();- zip.file('ghost.json', '{ not json');- const out = path.join(workDir, 'badjson.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));- await expectRejection(await manager.install(out), 'file-invalid');+ // 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:+ // 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。+ const bumped = { ...approvedManifest, version: '1.0.1' };+ expect(+ await manager.approveTrustedBundledInstall(+ bumped,+ true,+ await writeBundledSource(bumped),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ manifest: { version: '1.0.1' },+ });+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {- const cindy = await makeCindy('decl.cindy', {- schemaVersion: 1,- id: 'legacy',- name: '老声明型',- version: '1.0.0',- kind: 'declaration',- panel: { title: '静态面板', body: '一段文字' },+ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠+ // "唯一调用者是随包对账"这条纪律。+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: () => false,});- await expectRejection(await manager.install(cindy), 'file-invalid');+ const validated = validateGhostManifest(goodManifest());+ if (!validated.ok) throw new Error(validated.reason);+ await expect(+ guarded.approveTrustedBundledInstall(+ validated.manifest,+ true,+ await writeBundledSource(validated.manifest),+ ),+ ).rejects.toThrow(/种子清单/);});- it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {+ hostLocale = 'en';const manifest = {...goodManifest(),- slots: ['node'],- tools: undefined,- node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ locales: { en: 'locales/en.json' },};- const cindy = await makeCindy('missing-node.cindy', manifest);- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ await manager.install(+ await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'Approved English name' }),+ }),+ );+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ receipt.localeResources = {};+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },});- await expectRejection(await manager.install(cindy), 'file-invalid');});+});- it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(- '包不能自带主机保留文件 %s',- async (reservedFile) => {- const cindy = await makeCindy('reserved.cindy', goodManifest(), {- [reservedFile]: '{}',- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: {- code: 'file-invalid',- reason: expect.stringContaining('主机保留文件'),- },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- },- );-- it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {- const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装- expect(onChanged).not.toHaveBeenCalled();+describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必须拒装)', () => {+ it('staging→final 发布后、首次校验前换掉 SKILL.md → 拒装,篡改字节不成为批准事实', async () => {+ const cindy = await makeCindy('skill.cindy', {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ }, {+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ // 故障注入:staging→final 的 rename 真实执行后,立刻在 finalDir 里改写 SKILL.md+ // 正文 —— 模拟"发布与首次 hash 之间"的本机进程篡改窗口。+ const realRename = fs.promises.rename;+ const finalDir = path.join(rootDir, 'skilled');+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ await realRename(from, to);+ if (String(to) === finalDir) {+ spy.mockRestore();+ await fs.promises.writeFile(+ path.join(finalDir, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ }+ });+ try {+ const result = await manager.install(cindy);+ // 修复前:指纹从被篡改的 finalDir 首读,篡改字节自洽地成为 receipt 指纹与+ // 快照,install 返回 ok。修复后:指纹来自包投影,快照对账发现字节不符 → 拒装。+ expect('rejection' in result, JSON.stringify(result)).toBe(true);+ } finally {+ spy.mockRestore();+ }+ // 拒装收尾:不留半截安装,也没有任何批准事实落盘。+ expect(manager.list()).toHaveLength(0);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'skilled.json')),+ ).toBe(false);});+});- // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。- it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(- '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',- async (entryName) => {- // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字- // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。- const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });- const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {- [entryName]: evilManifest,- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(onChanged).not.toHaveBeenCalled();- },- );-- it('重复装入同 id → already-installed,原安装不受影响', async () => {+describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {+ it('final 缺位 + 唯一 backup → 下次启动自动搬回,插件不凭空消失', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();- await expectRejection(- await manager.install(await makeCindy('b.cindy', goodManifest())),- 'already-installed',+ // 模拟崩溃现场:final→backup 已发生,staging→final 没来得及。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-abcdef01'),);- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(onChanged).not.toHaveBeenCalled();- });+ // 崩溃前 list() 视角:插件消失(点目录被跳过)—— 这正是要修的现场。+ expect(manager.list()).toHaveLength(0);- it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {- await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));- await expectRejection(- await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),- 'command-conflict',- );- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(- await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),- );- expect('ghost' in ok).toBe(true);- expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ // "重启":新建 manager,构造期恢复扫描搬回。receipt 从未更新过,恢复后+ // receipt 与内容完全一致,等价于那次更新从未发生。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(restarted.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);});-});-describe('GhostManager · uninstall', () => {- it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ it('final 是普通文件时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.writeFile(finalDir, 'unexpected file');- const result = await manager.uninstall('hello');- expect('ok' in result).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(manager.list()).toEqual([]);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0]).toEqual([]);+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });++ expect((await fs.promises.lstat(finalDir)).isFile()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ it('final 是 junction/链接时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();-- const result = await manager.uninstall('hello', { notify: false });+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ const outsideDir = path.join(workDir, 'outside-final-target');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(outsideDir, { recursive: true });+ try {+ await fs.promises.symlink(outsideDir, finalDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // Windows 环境未授予建链接权限时跳过;生产判据仍由 lstat 钉住。+ }- expect('ok' in result).toBe(true);- expect(manager.list()).toEqual([]);- expect(onChanged).not.toHaveBeenCalled();- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('卸未装的 id → not-installed', async () => {- const result = await manager.uninstall('ghost');- expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ expect((await fs.promises.lstat(finalDir)).isSymbolicLink()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {- await fs.promises.mkdir(rootDir, { recursive: true });- const sibling = path.join(workDir, 'victim');- await fs.promises.mkdir(sibling);- for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {- const result = await manager.uninstall(id);- expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ it('final lstat EACCES 时不删除唯一 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EACCES: final path locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ } finally {+ spy.mockRestore();}- expect(fs.existsSync(sibling)).toBe(true);- });- it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {- const cindy = await makeCindy('a.cindy', goodManifest());- await manager.install(cindy);- await manager.uninstall('hello');- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(finalDir)).toBe(false);});-});-describe('GhostManager · list', () => {- it('根目录不存在 → 空清单(不报错)', () => {- expect(manager.list()).toEqual([]);+ it('final 在位的陈旧 backup 与 staging 残留 → 回收;同 id 多个 backup 不猜、原样保留', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-abcdef01'), { recursive: true });+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-hello-deadbeef'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-installing-hello-deadbeef'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);++ // 多 backup 且 final 缺位:不猜哪份是对的,原样保留等人工处理。+ await fs.promises.rename(path.join(rootDir, 'hello'), path.join(rootDir, '.cindy-updating-hello-11111111'));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-22222222'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-22222222'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);});- it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- // 手工捏三个坏目录- await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));- await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));- await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');- await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));- await fs.promises.writeFile(- path.join(rootDir, 'wrong-name', 'ghost.json'),- JSON.stringify(goodManifest('other-id')),+ it('id 是另一个 id 的 `-` 前缀(hello / hello-x)各留唯一 backup → 两者都搬回,不因前缀误判互相拖累(P1)', async () => {+ // 回归:siblings 统计曾用 startsWith(`.cindy-updating-${id}-`) 前缀匹配,+ // `.cindy-updating-hello-<hex>` 是 `.cindy-updating-hello-x-<hex>` 的前缀,+ // 于是处理 hello 时把 hello-x 的 backup 也算进来 → siblings 变 2 → 判"多备份+ // 留待人工" → hello 崩溃后持续消失。修复后按解析 id 精确比对,两者各自恢复。+ await manager.install(await makeCindy('a.cindy', goodManifest('hello')));+ await manager.install(await makeCindy('b.cindy', goodManifest('hello-x')));+ // 两个插件都卡在"final→backup 已发生,staging→final 未完成"的崩溃现场,+ // 且各自只有唯一 backup(合法可恢复的场景)。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-11111111'),+ );+ await fs.promises.rename(+ path.join(rootDir, 'hello-x'),+ path.join(rootDir, '.cindy-updating-hello-x-22222222'),);- // 隐藏目录(staging 残留形态)也不进清单- await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('多意识按 id 排序', async () => {- await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));- await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ // 两者都应搬回 final,backup 清空 —— hello 不能被 hello-x 的存在拖成"消失"。+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello-x', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-x-22222222'))).toBe(false);});});@@@ -4349,8 -726,13 +4352,17 @@@ describe('GhostManager · update(原位await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));onChanged.mockClear();- const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }, { 'new.txt': 'v2' });- const result = await updateGhost(v2);+ const v2 = await makeCindy(+ 'v2.cindy',+ { ...goodManifest(), version: '2.0.0' },+ { 'new.txt': 'v2' },+ );+ const onPackagePlaced = vi.fn();- const result = await manager.update(v2, { onPackagePlaced });++ const installed = manager.list().find((g) => g.manifest.id === 'hello');++ const result = await manager.update(v2, {++ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),++ onPackagePlaced,++ });expect('ghost' in result, JSON.stringify(result)).toBe(true);const { ghost } = result as { ghost: InstalledGhost };expect(ghost.manifest.version).toBe('2.0.0');diff --cc apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex 955d74b06a,b2fe650cf9..beccb2c987--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@@ -60,18 -59,51 +60,63 @@@ describe('market Ghost session boundaryexpect(body).toContain('releaseMutation?.();');});+ it('fails owner-scoped plugin reads closed while an account boundary is pending', () => {+ const start = source.indexOf('function availableGhosts(): InstalledGhost[] {');+ const end = source.indexOf('\n}', start);+ const body = source.slice(start, end);+ expect(body).toContain('if (isAppSessionBoundaryPending()) return [];');+ expect(source).toContain(+ 'return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;',+ );+ expect(source.match(/getGhost: findAvailableGhost/g)?.length ?? 0).toBeGreaterThanOrEqual(3);+ expect(source).toContain('return findAvailableGhost(id)?.manifest.name ?? null;');+ });++ it('allows explicit local replacement and detaches market routing before landing', () => {+ const updateStart = source.indexOf(+ "ipcMain.handle('ghosts:update'",+ );+ const updateEnd = source.indexOf(+ "ipcMain.handle('ghosts:pick-file'",+ updateStart,+ );+ const body = source.slice(updateStart, updateEnd);++ const ledgerReadIndex = body.indexOf(+ 'marketLedger.installationForGhost(inspected.manifest.id)',+ );+ const captureIndex = body.indexOf('const mutationOwner = captureGhostMutationOwner();');+ const ledgerBindIndex = body.indexOf('const marketLedger = getPluginMarketLedger().bind(');+ const inspectIndex = body.indexOf('await manager.inspect(lizFilePath)');+ const leaseIndex = body.indexOf('const releaseMutation = beginGhostMutation(mutationOwner);');+ const detachDecisionIndex = body.indexOf(+ 'const detachMarketRecord = Boolean(marketRecord?.installed)',+ );+ const runtimeStopIndex = body.indexOf('runtime.stop(inspected.manifest.id)');+ const managerUpdateIndex = body.indexOf('result = await manager.update(');+ const detachIndex = body.indexOf(+ 'marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject)',+ );++ expect(captureIndex).toBeGreaterThan(-1);+ expect(ledgerBindIndex).toBeGreaterThan(captureIndex);+ expect(ledgerBindIndex).toBeLessThan(inspectIndex);+ expect(leaseIndex).toBeGreaterThan(inspectIndex);+ expect(ledgerReadIndex).toBeGreaterThan(leaseIndex);+ expect(detachDecisionIndex).toBeGreaterThan(ledgerReadIndex);+ expect(detachIndex).toBeGreaterThan(detachDecisionIndex);+ expect(runtimeStopIndex).toBeGreaterThan(detachIndex);+ expect(managerUpdateIndex).toBeGreaterThan(runtimeStopIndex);+ expect(body).toContain('marketLedger.isDefaultInstallSuppressed(');+ expect(body).toContain('marketLedger.restoreInstallation(');+ expect(body).toContain('suppressed: marketRecordWasSuppressed');+ expect(body).toContain('onPackagePlaced: () => {');+ expect(body).toContain('packagePlaced = true;');+ expect(body).toContain('if (!packagePlaced) {\n restoreMarketRecord();');+ expect(body).toContain('releaseMutation();');+ expect(body).not.toContain('GHOST_SOURCE_CONFLICT');+ });+it('runs the final market callback before both initial install and update placement', () => {const installStart = source.indexOf('async function installOrUpdateMarketGhostPackageLocked(',diff --cc apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.tsindex 5b3c257821,0000000000..890ee58d4fmode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts+++ b/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts@@@ -1,133 -1,0 +1,146 @@@+import fs from 'node:fs';+import path from 'node:path';++import {+ sameForgeScaffoldParentIdentity,+ type ForgeScaffoldParentIdentity,+} from './forgeScaffoldIdentity.js';++interface Request {+ expectedParent: ForgeScaffoldParentIdentity;+ targetName: string;+ files: Array<{ path: string; base64: string }>;+}++interface ParentPortLike {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}++const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;+if (!parentPort) throw new Error('Forge scaffold worker missing parentPort');++function send(message: unknown): void {+ parentPort?.postMessage(message);+}++function samePath(left: string, right: string): boolean {+ const normalize = (value: string) => {+ const resolved = path.resolve(value);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+ };+ return normalize(left) === normalize(right);+}++function hasCode(error: unknown, code: string): boolean {+ return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);+}++async function verifyParent(expected: Request['expectedParent']): Promise<void> {+ const stats = await fs.promises.lstat('.', { bigint: true });+ if (!sameForgeScaffoldParentIdentity(stats, expected)) {+ throw new Error('Forge scaffold parent identity changed');+ }+ const real = await fs.promises.realpath('.');+ if (!samePath(real, expected.realPath)) throw new Error('Forge scaffold parent path changed');+}++function safeRelative(relative: string): boolean {+ if (!relative || relative.includes('\0') || path.isAbsolute(relative)) return false;+ const normalized = path.normalize(relative);+ return normalized !== '..' && !normalized.startsWith(`..${path.sep}`);+}++async function run(request: Request): Promise<void> {+ if (+ !request ||+ typeof request.targetName !== 'string' ||+ request.targetName !== path.basename(request.targetName) ||+ request.targetName === '.' ||+ request.targetName === '..' ||+ !Array.isArray(request.files) ||+ request.files.length > 32 ||+ request.files.some((file) => !file || !safeRelative(file.path) || typeof file.base64 !== 'string')+ ) {+ throw new Error('Invalid Forge scaffold worker request');+ }+ await verifyParent(request.expectedParent);++ try {+ await fs.promises.lstat(request.targetName);+ send({ ok: false, errorCode: 'TARGET_EXISTS', message: '目标已经存在,不会覆盖' });+ return;+ } catch (error) {+ if (!hasCode(error, 'ENOENT')) throw error;+ }++ let staging: string | null = null;+ try {+ staging = await fs.promises.mkdtemp(`.${request.targetName}-scaffold-`);+ for (const file of request.files) {+ const target = path.join(staging, file.path);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL |+ (fs.constants.O_NOFOLLOW ?? 0);+ const handle = await fs.promises.open(target, flags, 0o600);+ try {+ await handle.writeFile(Buffer.from(file.base64, 'base64'));+ await handle.sync();+ } finally {+ await handle.close();+ }+ }+ await verifyParent(request.expectedParent);+ const stagingStat = await fs.promises.lstat(staging);+ if (!stagingStat.isDirectory() || stagingStat.isSymbolicLink()) {+ throw new Error('Forge scaffold staging directory changed');+ }++ // Re-check target existence immediately before rename. On POSIX,++ // rename(staging, target) atomically replaces an existing directory, so++ // a concurrent process that creates the target between the initial ENOENT++ // check and the rename call would have its just-created directory silently++ // replaced. This second lstat shrinks the window to the sub-call gap++ // between lstat and rename.++ try {++ await fs.promises.lstat(request.targetName);++ send({ ok: false, errorCode: 'TARGET_EXISTS', message: '目标已经存在,不会覆盖' });++ return;++ } catch (error) {++ if (!hasCode(error, 'ENOENT')) throw error;++ }+ try {+ await fs.promises.rename(staging, request.targetName);+ } catch (error) {+ if (hasCode(error, 'EEXIST') || hasCode(error, 'ENOTEMPTY')) {+ send({ ok: false, errorCode: 'TARGET_EXISTS', message: '目标已经存在,不会覆盖' });+ return;+ }+ throw error;+ }+ staging = null;+ await verifyParent(request.expectedParent);+ send({ ok: true });+ } finally {+ if (staging) {+ try {+ const stat = await fs.promises.lstat(staging);+ if (stat.isDirectory() && !stat.isSymbolicLink()) {+ await fs.promises.rm(staging, { recursive: true, force: true });+ }+ } catch {+ // Keep the boundary fail-closed; never retry cleanup through an unknown path.+ }+ }+ }+}++let handled = false;+send({ type: 'ready' });+parentPort.on('message', (event) => {+ const message = event.data as { type?: unknown; request?: Request };+ if (handled || message?.type !== 'scaffold' || !message.request) return;+ handled = true;+ run(message.request).catch((error) => {+ send({ ok: false, errorCode: 'INTERNAL', message: error instanceof Error ? error.message : String(error) });+ });+});diff --cc apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex c4fe1ab255,0000000000..4e4d950741mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@@ -1,1170 -1,0 +1,1170 @@@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';++import {+ GHOST_LOCALE_MAX_BYTES,+ GHOST_SKILL_MD_MAX_BYTES,+ isValidGhostId,+ validateGhostManifest,+ validateGhostManifestLocaleResource,+ type GhostManifest,+ type GhostManifestLocaleResource,+ type GhostTrustInfo,+} from '../../shared/ghost.js';+import {+ classifyGhostDirEntry,+ classifyGhostDirEntrySync,+ collectGhostContentFiles,+ hashGhostContentFiles,+ isRegularGhostDirEntry,+ resolveGhostContentPath,+} from './ghostContentTree.js';+import { isPathInsideDir } from './dirDeposit.js';+import { checkSkillMdConsistency } from './skillSlot.js';++// v2 pairs receipts with the unambiguous ghostContentTree framing. Keeping v1+// readable would let an old ambiguous digest authorize a snapshot under the+// new verifier, so old receipts intentionally fail closed and require approval+// to be written again.+const RECEIPT_SCHEMA_VERSION = 2;+const MAX_RECEIPT_BYTES = 2 * 1024 * 1024;+const MAX_PENDING_MUTATION_BYTES = 64 * 1024;+const MAX_ICON_DATA_URL_BYTES = 768 * 1024;+const MAX_MIGRATION_LEDGER_BYTES = 64 * 1024;+/**+ * 受管 icon 快照的完整形态:声明的图片 mime + 严格 base64 载荷。载荷字符集也要+ * 校验 —— 只认前缀会让被改写的 receipt 把任意字符串塞进 renderer 的 img src。+ */+const ICON_DATA_URL_RE = /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/;++/**+ * 一次明确批准的插件安装事实;只允许 Host 写入安装目录之外的状态根。+ *+ * receipt 钉住的是**授权事实**(批准过的 manifest / trust / 启停 / revision)。+ * 它不保证安装目录里的内容字节此后一直没被改过 —— 逻辑页代码仍从可变的安装+ * 目录加载,只有技能目录因为越出沙箱而被拷成快照。+ */+export interface GhostInstallReceipt {+ schemaVersion: typeof RECEIPT_SCHEMA_VERSION;+ id: string;+ revision: string;+ manifest: GhostManifest;+ localeResources: Record<string, GhostManifestLocaleResource>;+ enabled: boolean;+ trust: GhostTrustInfo;+ /**+ * 批准时点的来源指纹,仅供审计与人工比对:市场/本地包是 `.cindy` 文件哈希,+ * 随包种子是内容目录哈希。**运行时不校验它**,不要据此认为安装内容持续完整。+ */+ packageSha256?: string;+ /**+ * 按 skill item 目录钉住的批准字节指纹(`item.dir` → sha256)。声明了 skill 槽+ * 时逐项必填,没声明时是空对象。+ *+ * 这一项**是运行期判据**,与只作审计用的 `packageSha256` 不同:快照缺失需要从+ * 可变安装目录重建时,必须先重算并逐字节对上才允许重建。少了它,改写 SKILL.md+ * 正文或往技能目录塞辅助文件就能在一次"启用"里被固化成已批准快照并全局挂链,+ * 而 frontmatter 一致性校验只看 name/description,拦不住这类漂移。+ */+ skillContentSha256: Record<string, string>;+ iconDataUrl?: string;+}++export type GhostInstallReceiptReadResult =+ | { state: 'approved'; receipt: GhostInstallReceipt }+ | { state: 'legacy-unapproved' }+ | { state: 'invalid'; reason: string };++export type GhostInstallReceiptRecoveryReadResult =+ | { state: 'approved'; receipt: GhostInstallReceipt }+ | { state: 'missing' }+ | { state: 'invalid'; reason: string }+ | { state: 'unreadable'; reason: string };++/**+ * 一次性 legacy 迁移的落地台账。存在即表示"本机已跑过一轮从旧安装布局 backfill+ * receipt 的迁移"——此后任何缺失 receipt 都按删除/损坏 fail closed,不再触发迁移。+ *+ * 它是迁移的**全局一次性门**(见 `GhostManager.migrateLegacyApprovalsOnce`):没有+ * 这道门,删掉某个 receipt 就能骗一次"从当前可变安装目录重建授权",而安装目录可被+ * 同权限进程改写。ledger 门是充分守卫——能删 ledger 的进程本就能直接往状态根写一份+ * 结构合法的伪造 receipt(§7 已登记"状态根无写保护"缺口),迁移路径严格弱于它。+ */+export interface GhostLegacyMigrationLedger {+ version: 1;+ /** 迁移完成时刻(ISO)。仅审计,不参与判定。 */+ migratedAt: string;+ /** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"用户确认过"与"迁移来的"。 */+ migratedIds: string[];+ /**+ * 迁移读不出核心事实而 fail closed 的 id(坏 manifest / 技能目录含链接等)。+ * 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新确认恢复入口。+ */+ failedIds?: string[];+ /**+ * 迁移状态机,缺省按 `completed` 读(与旧台账兼容)。+ *+ * `in-progress` 在**首个 backfill 动笔之前**原子落盘,记下本轮要迁的完整 id 清单+ * (`pendingIds`)。这是崩溃安全的关键:迁移中途崩溃/断电时,receipt 首写自动落+ * 台账的守卫(见 `write`)不会把门焊死 —— 下次启动看到 `in-progress` 就按+ * `pendingIds` 续跑,已写出 receipt 的 id 自然跳过,全部处理完才原子改写成+ * `completed`。清单钉死在动笔前,续跑**只认清单内的 id**:迁移窗口期间新装再删+ * receipt 的 id 不在清单里,骗不到续跑重铸。+ */+ state?: 'in-progress' | 'completed';+ /** 仅 `in-progress`:本轮待迁 id 全集(动笔前钉死)。 */+ pendingIds?: string[];+}++/**+ * 装入/更新事务的提交日志(状态根内,崩溃后仍在)。用来消除「目录已 rename、receipt+ * 还没写」这段崩溃窗口:+ * - install:崩溃留下"有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法+ * 区分 —— 全新 owner 首个安装崩在这里,下轮迁移会把它(含崩溃窗口内被同权限进程+ * 改写的 manifest)当存量批准掉,用户确认的是 A、被授权的是 B。+ * - update:`final→backup`、`staging→final`、写 receipt 三步;第二三步之间崩溃留下+ * "新字节 + 旧 receipt",恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧批准+ * 跑新代码"。+ *+ * 新 marker 用 `receiptRevision` 作为本次事务的提交 nonce,避免更新前后包 hash 相同+ * 时把旧 receipt 误认成本次提交。`packageSha256` 与 phase 只用于兼容旧 marker;无法+ * 区分新旧 receipt 时必须走保守恢复方向,不得删除唯一 backup。+ */+export type GhostPendingMutation =+ | {+ kind: 'install';+ packageSha256: string;+ /** Revision of the receipt this transaction intends to publish. */+ receiptRevision?: string;+ clearBuiltinTombstone?: boolean;+ }+ | {+ kind: 'update';+ packageSha256: string;+ backupDirName: string;+ /** Revision of the receipt this transaction intends to publish. */+ receiptRevision?: string;+ /** Durable phase for distinguishing pre-rename crashes from swapped content. */+ phase?: 'prepared' | 'backed-up' | 'published';+ /** Hash of the previously approved bytes, when an approval existed. */+ oldPackageSha256?: string;+ }+ // uninstall 不带 packageSha256:它的提交信号不是"receipt 写到某版本",而是"receipt ++ // 内容目录都已移除"。恢复见到它就把两者删干净(顺序无关,幂等)。+ | { kind: 'uninstall'; builtinTombstone?: boolean };++export type GhostPendingMutationReadResult =+ | { state: 'valid'; mutation: GhostPendingMutation }+ | { state: 'missing' }+ | { state: 'invalid'; reason: string }+ | { state: 'unreadable'; reason: string };++export type GhostPendingMutationListResult =+ { state: 'ok'; ids: string[]; blocked: boolean } | { state: 'unreadable'; reason: string };++/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */+export class GhostInstallReceiptStore {+ constructor(private readonly getRootDir: () => string) {}++ rootDir(): string {+ return path.resolve(this.getRootDir());+ }++ read(id: string): GhostInstallReceiptReadResult {+ const result = this.readForRecovery(id);+ if (result.state === 'approved') return result;+ if (result.state === 'missing') return { state: 'legacy-unapproved' };+ return { state: 'invalid', reason: result.reason };+ }++ /** Recovery must not confuse transient state-root IO with missing/corrupt approval state. */+ readForRecovery(id: string): GhostInstallReceiptRecoveryReadResult {+ const receiptPath = this.receiptPath(id);+ let bytes: Buffer | null;+ try {+ bytes = readBoundedFileNoFollowSync(receiptPath, MAX_RECEIPT_BYTES, {+ containWithin: this.rootDir(),+ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { state: 'missing' };+ }+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }+ if (!bytes) {+ return { state: 'invalid', reason: 'receipt 不是普通文件或超过大小上限' };+ }+ const text = bytes.toString('utf8');+ let parsed: unknown;+ try {+ parsed = JSON.parse(text) as unknown;+ } catch (error) {+ return { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };+ }+ const validated = validateReceipt(parsed, id);+ return validated.ok+ ? { state: 'approved', receipt: validated.receipt }+ : { state: 'invalid', reason: validated.reason };+ }++ /**+ * 写入批准事实。`skillSourceDir` 是快照缺失时的取字节来源:装入/更新传新+ * 内容目录,纯状态改写(启停)传当前安装目录即可自愈。+ *+ * `requireSkillSnapshot: false` 用于**必须成功的收敛方向**(停用):快照+ * 已被外部删掉时不该把插件卡在"既不能用也不能关"的状态,此时按无 skill+ * 落链继续写批准事实,由对账撤掉链接。+ */+ async write(+ receipt: GhostInstallReceipt,+ options: { skillSourceDir?: string; requireSkillSnapshot?: boolean } = {},+ ): Promise<void> {+ const validated = validateReceipt(receipt, receipt.id);+ if (!validated.ok)+ throw new Error(`refusing to write invalid ghost receipt: ${validated.reason}`);++ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ try {+ await this.ensureSkillSnapshot(receipt, options.skillSourceDir);+ } catch (error) {+ if (options.requireSkillSnapshot !== false) throw error;+ }+ // Migration ledger 是 receipt 对外生效的前置提交记录。正常装入/更新若先写+ // receipt、后 best-effort 落 ledger,会自然制造“有效 receipt + 无 ledger”的+ // mixed 状态;下一版既不能安全判断其它无 receipt 目录是 legacy 还是被删批准。+ // legacy migration/recovery 已在首个 backfill 前写好 in-progress,因此这里仅在+ // **完全没有** ledger 时先写 completed,且失败必须阻断 receipt 提交。+ if (!this.hasMigrationLedger()) {+ await this.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'completed',+ });+ }+ const target = this.receiptPath(receipt.id);+ const temp = path.join(+ root,+ `.${receipt.id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify(receipt, null, 2)}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ await this.pruneStaleSkillSnapshots(receipt);+ }++ async remove(id: string): Promise<void> {+ const receiptPath = this.receiptPath(id);+ const receiptKind = await classifyCleanupEntry(receiptPath);+ if (receiptKind === 'missing') {+ // ENOENT is already-clean and must remain idempotent.+ } else if (receiptKind !== 'file') {+ throw new Error(`ghost receipt path is not a regular file: ${receiptPath}`);+ } else {+ await fs.promises.rm(receiptPath, { force: true });+ }+ // Validate both managed snapshot path segments before recursive deletion.+ // Missing segments mean cleanup is already complete; links, non-directories,+ // and transient IO failures remain observable so the caller keeps its journal.+ const snapshotPath = await this.assertManagedSnapshotParent(id, { createMissing: false });+ if (!snapshotPath) return;+ await fs.promises.rm(snapshotPath, {+ recursive: true,+ force: true,+ });+ }++ /** `remove` 的同步版:启动恢复(构造期同步)收尾未完成卸载用,判据同 `remove`。 */+ removeSync(id: string): void {+ const receiptPath = this.receiptPath(id);+ const receiptKind = classifyCleanupEntrySync(receiptPath);+ if (receiptKind === 'missing') {+ // ENOENT is already-clean and must remain idempotent.+ } else if (receiptKind !== 'file') {+ throw new Error(`ghost receipt path is not a regular file: ${receiptPath}`);+ } else {+ fs.rmSync(receiptPath, { force: true });+ }+ const snapshotPath = this.assertManagedSnapshotParentSync(id, { createMissing: false });+ if (!snapshotPath) return;+ fs.rmSync(snapshotPath, { recursive: true, force: true });+ }++ skillSnapshotRoot(id: string, revision: string): string {+ if (!isValidGhostId(id) || !isRevision(revision)) {+ throw new Error('invalid ghost skill snapshot identity');+ }+ return path.join(this.rootDir(), 'skill-snapshots', id, revision);+ }++ /**+ * 快照父路径(`<状态根>/skill-snapshots/<id>`)的逐段遏制断言。+ *+ * 任何 readdir / mkdir / rename / rm 之前都必须过这道:父段被同权限进程换成+ * junction/链接时,这些操作会**穿透**到状态根之外 —— 把 §7 登记的「状态根可写→+ * 可伪造批准」升级成「任意外部目录删除/写入」,是一次真实的权限升级(已在+ * Windows 上实测复现)。判据与 ghostContentTree 同源:逐段 lstat、链接一律拒,+ * 最后再 realpath 对账"物理路径仍在状态根内"(状态根自身的祖先允许是链接 ——+ * relocated home 场景,所以以 realpath(root) 为基准而不是词法路径)。+ *+ * `createMissing`:装入/更新路径按需补建缺失段;prune/remove 等回收路径不建,+ * 段缺失(ENOENT)返回 null 表示"没有可回收对象"。段存在但不是真目录一律抛错,+ * 由调用方决定 fail closed 还是跳过 —— 绝不带着可疑父段继续动盘。+ */+ private async assertManagedSnapshotParent(+ id: string,+ opts: { createMissing: boolean },+ ): Promise<string | null> {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');+ const root = this.rootDir();+ let current = root;+ for (const segment of ['skill-snapshots', id]) {+ current = path.join(current, segment);+ let kind: Awaited<ReturnType<typeof classifyGhostDirEntry>> | null;+ try {+ kind = await classifyGhostDirEntry(current);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ kind = null;+ }+ if (kind === null) {+ if (!opts.createMissing) return null;+ // 非 recursive:上一段刚验证过是真目录,逐段建才不会静默沿着链接铺路。+ await fs.promises.mkdir(current);+ continue;+ }+ if (kind !== 'directory') {+ throw new Error(+ `skill snapshot path segment is not a real directory: ${segment} (${kind})`,+ );+ }+ }+ const [realRoot, realParent] = await Promise.all([+ fs.promises.realpath(root),+ fs.promises.realpath(current),+ ]);+ if (!isPathInsideDir(realRoot, realParent)) {+ throw new Error('skill snapshot parent escaped the approval state root');+ }+ return current;+ }++ private assertManagedSnapshotParentSync(+ id: string,+ opts: { createMissing: boolean },+ ): string | null {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');+ const root = this.rootDir();+ let current = root;+ for (const segment of ['skill-snapshots', id]) {+ current = path.join(current, segment);+ let kind: ReturnType<typeof classifyGhostDirEntrySync> | null;+ try {+ kind = classifyGhostDirEntrySync(current);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ kind = null;+ }+ if (kind === null) {+ if (!opts.createMissing) return null;+ fs.mkdirSync(current);+ continue;+ }+ if (kind !== 'directory') {+ throw new Error(+ `skill snapshot path segment is not a real directory: ${segment} (${kind})`,+ );+ }+ }+ const realRoot = fs.realpathSync(root);+ const realParent = fs.realpathSync(current);+ if (!isPathInsideDir(realRoot, realParent)) {+ throw new Error('skill snapshot parent escaped the approval state root');+ }+ return current;+ }++ /** 迁移台账路径。点开头,不会与任何合法 ghost id 的 `<id>.json` receipt 撞名。 */+ private migrationLedgerPath(): string {+ return path.join(this.rootDir(), '.legacy-migration.json');+ }++ /** 读迁移台账(缺失/损坏返回 null;追加 id 时用,判定门只看 hasMigrationLedger)。 */+ readMigrationLedger(): GhostLegacyMigrationLedger | null {+ try {+ // 与 receipt 同源:no-follow + 限量 + realpath 根内复核。FIFO / symlink 到+ // 无界大文件必须在 parse 前就被拒绝,否则启动路径(migrationDoorClosed)+ // 会阻塞或分配无界内存,而不是把台账按不可读关门。+ const bytes = readBoundedFileNoFollowSync(+ this.migrationLedgerPath(),+ MAX_MIGRATION_LEDGER_BYTES,+ { containWithin: this.rootDir() },+ );+ if (bytes === null) return null;+ const raw = JSON.parse(+ bytes.toString('utf8'),+ ) as GhostLegacyMigrationLedger;+ if (+ !raw ||+ raw.version !== 1 ||+ typeof raw.migratedAt !== 'string' ||+ !isValidUniqueGhostIdArray(raw.migratedIds)+ ) {+ return null;+ }+ if (raw.state !== undefined && raw.state !== 'in-progress' && raw.state !== 'completed') {+ return null;+ }+ if (raw.failedIds !== undefined && !isValidUniqueGhostIdArray(raw.failedIds)) return null;+ if (+ raw.state === 'in-progress' &&+ (!isValidUniqueGhostIdArray(raw.pendingIds) || raw.pendingIds.length === 0)+ ) {+ return null;+ }+ if (raw.state !== 'in-progress' && raw.pendingIds !== undefined) return null;+ return raw;+ } catch {+ return null;+ }+ }++ /**+ * 迁移门是否已关死。三种情况:+ * - 无台账 → 开(首轮迁移 / legacy 恢复流程的留门);+ * - 台账 `in-progress` → 开(上一轮中途崩溃,按 pendingIds 续跑);+ * - 台账 `completed` / 无 state(旧格式)/ **存在但读不出** → 关。+ * 损坏台账按"关"处理是刻意的保守方向:台账由原子 temp+rename 写出,自然损坏面+ * 趋近于零;能改坏它的进程与 §7「可直接伪造合法 receipt」同类,把门放开反而是+ * 给这类进程送一条重铸授权的路。调用方发现"存在但读不出"应记 error 日志。+ */+ migrationDoorClosed(): boolean {+ if (!this.hasMigrationLedger()) return false;+ const ledger = this.readMigrationLedger();+ return ledger === null || ledger.state !== 'in-progress';+ }++ /** 是否已跑过一轮 legacy 迁移(全局一次性门;存在即按"已跑"处理,宁可不再迁)。 */+ hasMigrationLedger(): boolean {+ try {+ // 只要路径存在就视为已迁,不论它是普通文件还是 symlink / FIFO / 设备节点:+ // 把非普通 ledger 判成"不存在"会让迁移门重开,允许从当前可变安装目录重铸授权。+ fs.lstatSync(this.migrationLedgerPath());+ return true;+ } catch (error) {+ // ENOENT = 从未迁过,可以迁;其它错误(权限等)= 状态未知,保守当作"已迁",+ // 绝不因为读不动 ledger 就把迁移(=从可变安装目录重建授权)再放开一次。+ return (error as NodeJS.ErrnoException).code !== 'ENOENT';+ }+ }++ async writeMigrationLedger(ledger: GhostLegacyMigrationLedger): Promise<void> {+ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ const target = this.migrationLedgerPath();+ const temp = path.join(+ root,+ `.legacy-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify(ledger, null, 2)}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ }++ /** 事务标记路径。点开头,不与 `<id>.json` receipt 或 `.legacy-migration.json` 撞名。 */+ private pendingMutationPath(id: string): string {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for pending mutation path');+ return path.join(this.rootDir(), `.pending-${id}.json`);+ }++ /** 事务开始:装入/更新 rename 动盘**之前**落标记(原子 temp+rename;re-begin 覆盖)。 */+ async writePendingMutation(id: string, entry: GhostPendingMutation): Promise<void> {+ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ const target = this.pendingMutationPath(id);+ const temp = path.join(+ root,+ `.pending-${id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify({ version: 1, id, ...entry })}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ }++ /** 事务提交:receipt 写成功后清标记。删不动只多留一份标记,下轮恢复幂等重判。 */+ async clearPendingMutation(id: string): Promise<void> {+ await fs.promises.rm(this.pendingMutationPath(id), { force: true });+ }++ /** 同步清标记(启动恢复在构造期同步跑,不能留 fire-and-forget 的异步删除)。 */+ clearPendingMutationSync(id: string): void {+ fs.rmSync(this.pendingMutationPath(id), { force: true });+ }++ readPendingMutationSync(id: string): GhostPendingMutationReadResult {+ let raw: Record<string, unknown>;+ const markerPath = this.pendingMutationPath(id);++ let bytes: Buffer | null;+ try {- const stat = fs.lstatSync(markerPath);- if (!stat.isFile() || stat.size > MAX_PENDING_MUTATION_BYTES) {- return { state: 'invalid', reason: 'journal is not a regular file or exceeds size limit' };- }++ // Single-handle bounded read: the earlier lstat+readFileSync pair had a++ // TOCTOU window where a FIFO/symlink/huge file could replace the journal++ // between the two calls. readBoundedFileNoFollowSync opens, stats, and++ // reads from the same handle with O_NONBLOCK so a FIFO/device blocks++ // neither the open nor the subsequent read.++ bytes = readBoundedFileNoFollowSync(markerPath, MAX_PENDING_MUTATION_BYTES, {++ containWithin: this.rootDir(),++ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { state: 'missing' };+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }- let text: string;- try {- text = fs.readFileSync(markerPath, 'utf8');- } catch (error) {- return {- state: 'unreadable',- reason: error instanceof Error ? error.message : String(error),- };++ if (!bytes) {++ return { state: 'invalid', reason: 'journal is not a regular file or exceeds size limit' };+ }++ const text = bytes.toString('utf8');+ let parsed: unknown;+ try {+ parsed = JSON.parse(text) as unknown;+ } catch (error) {+ return { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { state: 'invalid', reason: 'journal must be an object' };+ }+ raw = parsed as Record<string, unknown>;+ if (raw.version !== 1 || raw.id !== id) {+ return { state: 'invalid', reason: 'journal version/id mismatch' };+ }+ if (raw.kind === 'uninstall') {+ if (raw.builtinTombstone !== undefined && typeof raw.builtinTombstone !== 'boolean') {+ return { state: 'invalid', reason: 'journal builtinTombstone is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'uninstall',+ ...(raw.builtinTombstone === true ? { builtinTombstone: true } : {}),+ },+ };+ }+ if (typeof raw.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(raw.packageSha256)) {+ return { state: 'invalid', reason: 'journal packageSha256 is invalid' };+ }+ if (raw.kind === 'install') {+ if (+ raw.receiptRevision !== undefined &&+ (typeof raw.receiptRevision !== 'string' || !isRevision(raw.receiptRevision))+ ) {+ return { state: 'invalid', reason: 'journal receiptRevision is invalid' };+ }+ if (+ raw.clearBuiltinTombstone !== undefined &&+ typeof raw.clearBuiltinTombstone !== 'boolean'+ ) {+ return { state: 'invalid', reason: 'journal clearBuiltinTombstone is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'install',+ packageSha256: raw.packageSha256,+ ...(typeof raw.receiptRevision === 'string'+ ? { receiptRevision: raw.receiptRevision }+ : {}),+ ...(raw.clearBuiltinTombstone === true ? { clearBuiltinTombstone: true } : {}),+ },+ };+ }+ if (+ raw.kind === 'update' &&+ typeof raw.backupDirName === 'string' &&+ isManagedBackupDirName(id, raw.backupDirName)+ ) {+ const phase = raw.phase === undefined ? undefined : raw.phase;+ if (+ phase !== undefined &&+ phase !== 'prepared' &&+ phase !== 'backed-up' &&+ phase !== 'published'+ ) {+ return { state: 'invalid', reason: 'journal update phase is invalid' };+ }+ const oldPackageSha256 = raw.oldPackageSha256;+ const receiptRevision = raw.receiptRevision;+ if (+ receiptRevision !== undefined &&+ (typeof receiptRevision !== 'string' || !isRevision(receiptRevision))+ ) {+ return { state: 'invalid', reason: 'journal receiptRevision is invalid' };+ }+ if (+ oldPackageSha256 !== undefined &&+ (typeof oldPackageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(oldPackageSha256))+ ) {+ return { state: 'invalid', reason: 'journal oldPackageSha256 is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'update',+ packageSha256: raw.packageSha256,+ backupDirName: raw.backupDirName,+ ...(receiptRevision !== undefined ? { receiptRevision } : {}),+ ...(phase !== undefined ? { phase } : {}),+ ...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),+ },+ };+ }+ return { state: 'invalid', reason: 'journal kind/backupDirName is invalid' };+ }++ /** 状态根里所有未清的事务标记 id(启动恢复用)。 */+ listPendingMutationIdsSync(): GhostPendingMutationListResult {+ let names: string[];+ try {+ names = fs.readdirSync(this.rootDir());+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { state: 'ok', ids: [], blocked: false };+ }+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }+ const ids: string[] = [];+ let blocked = false;+ for (const name of names) {+ const match = /^\.pending-(.+)\.json$/.exec(name);+ if (!match) continue;+ if (isValidGhostId(match[1])) ids.push(match[1]);+ else blocked = true;+ }+ return { state: 'ok', ids, blocked };+ }++ private receiptPath(id: string): string {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for receipt path');+ return path.join(this.rootDir(), `${id}.json`);+ }++ private async ensureSkillSnapshot(+ receipt: GhostInstallReceipt,+ skillSourceDir: string | undefined,+ ): Promise<void> {+ const items = receipt.manifest.skill?.items ?? [];+ if (items.length === 0) return;+ const target = this.skillSnapshotRoot(receipt.id, receipt.revision);+ // 父段遏制必须先于**任何**对 target 的操作:lstat/rm/rename 都会穿透被换成+ // junction 的父段,读写到状态根之外(见 assertManagedSnapshotParent 头注释)。+ const parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: true });+ if (!parent) throw new Error('skill snapshot parent unavailable');+ let existing: fs.Stats | null;+ try {+ existing = await fs.promises.lstat(target);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ existing = null;+ }+ if (existing) {+ if (!existing.isDirectory()) {+ throw new Error('approved skill snapshot target is not a directory');+ }+ // 快照已存在**不等于**它还是被批准的那份字节:状态根里的目录同样可被同权限+ // 进程改写,而主 Agent 是顺着共享技能链接持续读它的。所以这里必须重算,+ // 不能像上一版那样直接早退信任它。+ if (await this.skillSnapshotMatchesReceipt(receipt, target)) return;+ // 对不上的快照一律不可信:删掉,退回下面的重建路径 —— 重建本身仍要过安装+ // 目录的字节校验,所以"损坏快照"能自愈,"安装字节已漂移"仍然拒。+ await fs.promises.rm(target, { recursive: true, force: true });+ }+ if (!skillSourceDir) {+ throw new Error('approved skill snapshot is missing');+ }+ const temp = path.join(+ parent,+ `.${receipt.revision}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.mkdir(temp, { recursive: false });++ // 顺序是安全要点,不要改回"先校验源目录、再复制":源目录随时可被同权限进程+ // 改写,校验和复制各读一次就有一个可换字节的窗口,复制出来的快照可能不是被+ // 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节+ // 做全部权威校验**,校验通过才 rename 就位。+ // 清单允许嵌套的 skill dir(如 skills/foo 与 skills/foo/bar —— 校验只拒重复,+ // 不拒前缀嵌套)。祖先目录的整树复制已经带上了嵌套项的字节,再按嵌套项复制一次+ // 会撞上 COPYFILE_EXCL 直接失败 —— 那会让一份合法清单在装入/更新/迁移/重新确认+ // 四条路上全军覆没(§5 红线)。按深度排序、祖先先复制,已覆盖的嵌套项跳过复制;+ // 指纹校验仍逐 item 进行(嵌套项的根就在祖先拷出的树里)。大小写折叠比较,+ // 与清单查重同口径。+ const copiedRoots: string[] = [];+ const itemsByDepth = [...items].sort(+ (a, b) => a.dir.split('/').length - b.dir.split('/').length,+ );+ for (const item of itemsByDepth) {+ const dirFold = item.dir.toLowerCase();+ if (copiedRoots.some((root) => dirFold === root || dirFold.startsWith(`${root}/`))) {+ continue;+ }+ // 与算指纹同一个解析入口:逐段确认真目录,挡住"中间段被换成链接"这条从技能+ // 目录之外取字节的路子。两侧必须共用,否则一侧穿透、一侧不穿透,复制的和+ // 算指纹的就不是同一组字节。+ const source = await resolveGhostContentPath(skillSourceDir, item.dir, {+ expect: 'directory',+ label: 'approved skill',+ });+ // 复制前的便宜预检:只为早失败、少做无用功(避免整份拷一个超大 SKILL.md)。+ // **这不是安全边界** —— 它读的是可变源目录,结论随时可能过期,真正说话的是+ // 下面对 temp 的校验。+ const sourceSkillMdStat = await fs.promises+ .lstat(path.join(source, 'SKILL.md'))+ .catch(() => null);+ if (+ sourceSkillMdStat &&+ (!sourceSkillMdStat.isFile() || sourceSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES)+ ) {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,+ );+ }+ await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));+ copiedRoots.push(dirFold);+ }++ // 权威校验一律针对 temp:此刻这些字节已经脱离可变安装目录,复制期间被换过也+ // 会在这里暴露。**尺寸上限必须排在算指纹之前** —— 源目录那道预检不是安全边界+ // (预检后可被换成超大文件),若先算指纹就等于上限在权威路径上一次都没生效。+ for (const item of items) {+ const copiedSkillMdPath = path.join(temp, ...item.dir.split('/'), 'SKILL.md');+ // 包一层领域错误:这一段现在排在算指纹之前,SKILL.md 缺失时若直接抛裸 ENOENT,+ // 日志里就看不出是"技能内容被动过"这件事(只有被篡改时才可达,两种写法都+ // fail closed,纯粹为可读性)。+ const copiedSkillMdStat = await fs.promises.lstat(copiedSkillMdPath).catch((error) => {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is unreadable in the snapshot: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ });+ if (!copiedSkillMdStat.isFile() || copiedSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES) {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,+ );+ }+ }+ // 指纹判定走与"接受既有快照""发布后复核"同一个 helper:同一判据只有一份实现,+ // 否则三处各写一遍、日后只改其中一处,就是这条链路前几轮反复出问题的形态。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, temp))) {+ throw new Error(+ `approved skill content for ${receipt.id} no longer matches the bytes approved at install time`,+ );+ }+ for (const item of items) {+ // 指纹相符已经蕴含 frontmatter 一致(批准时点那份过过这道校验),这里重跑一遍+ // 是防止钉指纹那条路径本身有 bug,并给出更具体的错误。+ const consistencyError = checkSkillMdConsistency(+ await fs.promises.readFile(path.join(temp, ...item.dir.split('/'), 'SKILL.md'), 'utf8'),+ item,+ );+ if (consistencyError) {+ throw new Error(`approved skill ${item.dir} is inconsistent: ${consistencyError}`);+ }+ }++ await fs.promises.rename(temp, target);++ // rename 之前 temp 位于状态根内、同权限进程仍可改写它,所以就位之后再核一遍:+ // 这一步把"校验通过 → rename"之间那段窗口收掉 —— 在那段里被换过的字节到这里+ // 会暴露,并且不会留在盘上。+ //+ // 残留窗口(已知、未关):这次核对之后、主 Agent 顺着共享技能链接读取之前,快照+ // 仍可被改写。要真正关掉需要给状态根写保护或在消费侧校验,都不在本函数范围内;+ // 该缺口已正式登记在 docs/dev-rules/plugin-security-and-authoring.md 第 6 节+ // (与"内容根字节可变"是两条并列的不同缺口)。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, target))) {+ await fs.promises.rm(target, { recursive: true, force: true }).catch(() => undefined);+ throw new Error('approved skill snapshot changed while being published');+ }+ } finally {+ await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);+ }+ }++ /**+ * 快照目录里的字节是否仍等于 receipt 钉住的批准指纹。+ *+ * 三处调用共用同一判据(接受既有快照 / 复制后发布前 / 发布后复核) —— 这类判定散落+ * 多处再各写一遍,就是本 PR 前几轮反复出问题的成因。读不动或含非普通条目一律按+ * 不匹配处理:调用方对"不匹配"的收敛动作都是删掉重建或拒绝,始终 fail closed。+ */+ async skillSnapshotMatchesReceipt(+ receipt: GhostInstallReceipt,+ snapshotDir: string,+ ): Promise<boolean> {+ const actual = await hashApprovedSkillContent(receipt.manifest, snapshotDir).catch(() => null);+ if (!actual) return false;+ return (receipt.manifest.skill?.items ?? []).every(+ (item) => actual[item.dir] === receipt.skillContentSha256[item.dir],+ );+ }++ /**+ * 回收同一插件下非当前 revision 的技能快照与崩溃残留的 `.tmp` 目录。+ *+ * 只在新 receipt 已经原子提交之后跑:此刻旧 revision 已不是批准事实,留着+ * 就是每次更新泄漏一份完整拷贝。共享技能根里指向旧 revision 的链接会因此+ * 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 槽来说,短暂"技能不可+ * 用"是正确的收敛方向,留着旧批准版本继续生效不是。+ *+ * best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。+ */+ private async pruneStaleSkillSnapshots(receipt: GhostInstallReceipt): Promise<void> {+ // 父段遏制先行:`<id>` 段被换成 junction 时,readdir 会列出外部目录的条目、+ // 随后的逐项 recursive rm 就会把**外部目录的内容**删掉(Windows 实测可复现)。+ // 回收是 best-effort:父段可疑就整体跳过,绝不带着可疑父段动盘。+ let parent: string | null;+ try {+ parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: false });+ } catch {+ return;+ }+ if (!parent) return;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(parent, { withFileTypes: true });+ } catch {+ return;+ }+ await Promise.all(+ entries+ .filter((entry) => entry.name !== receipt.revision)+ .map((entry) =>+ fs.promises+ .rm(path.join(parent, entry.name), { recursive: true, force: true })+ .catch(() => undefined),+ ),+ );+ }+}++function isValidUniqueGhostIdArray(value: unknown): value is string[] {+ return (+ Array.isArray(value) &&+ value.every((id) => isValidGhostId(id)) &&+ new Set(value).size === value.length+ );+}++function isManagedBackupDirName(id: string, name: string): boolean {+ return new RegExp(`^\\.cindy-updating-${escapeRegExp(id)}-[0-9a-f]{8}$`).test(name);+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++type CleanupEntryKind = 'missing' | 'file' | 'directory' | 'link' | 'other';++async function classifyCleanupEntry(absPath: string): Promise<CleanupEntryKind> {+ try {+ return await classifyGhostDirEntry(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+}++function classifyCleanupEntrySync(absPath: string): CleanupEntryKind {+ try {+ return classifyGhostDirEntrySync(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+}++/**+ * 迁移专用:读旧安装目录里的 `.cindy-trust.json` 信任镜像。#1080 之前授权事实就散在+ * 安装目录三文件里,升级迁移要从它们重建等价 receipt。+ *+ * 缺失/损坏/非普通文件一律返回 `null` —— trust 只是**展示与来源信号**(能力由 manifest+ * slot 授予,不由 trust 等级授予),读不出时调用方用保守默认(`unverified`)而不是让整个+ * 迁移失败:旧模型读的也是同一个文件,缺了同样显示不出 verified,不比旧模型少展示什么。+ *+ * `cindy-official` 一律**封顶拒收**(按镜像损坏处理):官方档只该由 provisioning 在与+ * 随包种子逐字节对账后授予,而本函数的两个调用方(legacy 迁移 / 从已装目录重新确认)都+ * 只服务非随包插件 —— 非随包目录里出现官方档镜像本身就不可信,照抄会让确认卡/列表把+ * 一个可变目录里的插件展示成「Cindy 官方」。+ */+export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {+ const file = path.join(dir, '.cindy-trust.json');+ try {+ const realDir = fs.realpathSync(dir);+ const bytes = readBoundedFileNoFollowSync(file, MAX_RECEIPT_BYTES, { containWithin: realDir });+ if (bytes === null) return null;+ try {+ const trust = validateTrust(JSON.parse(bytes.toString('utf8')));+ if (!trust || trust.level === 'cindy-official') return null;+ return trust;+ } catch {+ return null;+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EIO') throw error;+ return null;+ }+}++export function createGhostInstallReceipt(input: {+ manifest: GhostManifest;+ localeResources: Record<string, GhostManifestLocaleResource>;+ enabled: boolean;+ trust: GhostTrustInfo;+ /** 由 `hashApprovedSkillContent` 从**这次批准的内容目录**现算,不可沿用旧值。 */+ skillContentSha256: Record<string, string>;+ packageSha256?: string;+ revision?: string;+ iconDataUrl?: string;+}): GhostInstallReceipt {+ return {+ schemaVersion: RECEIPT_SCHEMA_VERSION,+ id: input.manifest.id,+ revision: input.revision ?? crypto.randomUUID(),+ manifest: input.manifest,+ localeResources: input.localeResources,+ enabled: input.enabled,+ trust: input.trust,+ skillContentSha256: input.skillContentSha256,+ ...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),+ ...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),+ };+}++/**+ * 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。+ *+ * 判据全部取自 `ghostContentTree`(路径逐段解析 + 条目类型判定 + 指纹格式),与+ * 快照拷贝侧 `copyRegularDirectory`、安装目录漂移指纹 `hashApprovedDirectory`、+ * 随包种子指纹 `fingerprintDirContent` 共用同一份实现。差异只有显式策略:技能+ * 目录**不跳过点开头条目**(技能指令可以引用目录里的任意文件,漏掉一类就是漏掉+ * 一条改写通道),非普通条目一律拒。+ */+export async function hashApprovedSkillContent(+ manifest: GhostManifest,+ sourceDir: string | undefined,+): Promise<Record<string, string>> {+ const items = manifest.skill?.items ?? [];+ if (items.length === 0) return {};+ if (!sourceDir) throw new Error('skill content hash requires a source directory');+ const result: Record<string, string> = {};+ for (const item of items) {+ const itemRoot = await resolveGhostContentPath(sourceDir, item.dir, {+ expect: 'directory',+ label: 'approved skill',+ });+ const tree = await collectGhostContentFiles(itemRoot, {+ dotEntries: 'include',+ nonRegular: 'throw',+ label: `approved skill ${item.dir}`,+ });+ result[item.dir] = await hashGhostContentFiles(itemRoot, tree.files, tree.rootIdentity);+ }+ return result;+}++function validateReceipt(+ raw: unknown,+ expectedId: string,+): { ok: true; receipt: GhostInstallReceipt } | { ok: false; reason: string } {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ return { ok: false, reason: 'receipt 必须是对象' };+ }+ const value = raw as Record<string, unknown>;+ if (value.schemaVersion !== RECEIPT_SCHEMA_VERSION) {+ return { ok: false, reason: 'receipt schemaVersion 不受支持' };+ }+ if (value.id !== expectedId || !isValidGhostId(expectedId)) {+ return { ok: false, reason: 'receipt id 与安装目录不一致' };+ }+ if (typeof value.revision !== 'string' || !isRevision(value.revision)) {+ return { ok: false, reason: 'receipt revision 不合法' };+ }+ const manifestResult = validateGhostManifest(value.manifest);+ if (!manifestResult.ok || manifestResult.manifest.id !== expectedId) {+ return {+ ok: false,+ reason: manifestResult.ok ? 'receipt manifest id 不一致' : manifestResult.reason,+ };+ }+ if (typeof value.enabled !== 'boolean') {+ return { ok: false, reason: 'receipt enabled 不合法' };+ }+ const trust = validateTrust(value.trust);+ if (!trust) return { ok: false, reason: 'receipt trust 不合法' };+ if (+ value.packageSha256 !== undefined &&+ (typeof value.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.packageSha256))+ ) {+ return { ok: false, reason: 'receipt packageSha256 不合法' };+ }+ // 技能字节指纹是运行期判据,必填且键集必须与清单声明严格一致 —— 留"字段缺失就+ // 跳过校验"的可选口子等于给漂移留一条绕过路径。receipt 格式尚未随任何版本发布,+ // 不存在需要兼容的旧 receipt。+ const skillContentSha256: Record<string, string> = {};+ {+ const raw = value.skillContentSha256;+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ return { ok: false, reason: 'receipt skillContentSha256 不合法' };+ }+ const expectedDirs = (manifestResult.manifest.skill?.items ?? [])+ .map((item) => item.dir)+ .sort();+ const actualDirs = Object.keys(raw as Record<string, unknown>).sort();+ if (+ expectedDirs.length !== actualDirs.length ||+ expectedDirs.some((dir, index) => dir !== actualDirs[index])+ ) {+ return { ok: false, reason: 'receipt skillContentSha256 与 manifest 声明不一致' };+ }+ for (const [dir, digest] of Object.entries(raw as Record<string, unknown>)) {+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {+ return { ok: false, reason: `receipt skillContentSha256 不合法:${dir}` };+ }+ skillContentSha256[dir] = digest;+ }+ }+ if (+ value.iconDataUrl !== undefined &&+ (typeof value.iconDataUrl !== 'string' ||+ Buffer.byteLength(value.iconDataUrl, 'utf8') > MAX_ICON_DATA_URL_BYTES ||+ !ICON_DATA_URL_RE.test(value.iconDataUrl))+ ) {+ return { ok: false, reason: 'receipt iconDataUrl 不合法' };+ }+ if (+ !value.localeResources ||+ typeof value.localeResources !== 'object' ||+ Array.isArray(value.localeResources)+ ) {+ return { ok: false, reason: 'receipt localeResources 不合法' };+ }+ const expectedLocalePaths = [+ ...new Set(Object.values(manifestResult.manifest.locales ?? {})),+ ].sort();+ const actualLocalePaths = Object.keys(value.localeResources as Record<string, unknown>).sort();+ if (+ expectedLocalePaths.length !== actualLocalePaths.length ||+ expectedLocalePaths.some((localePath, index) => localePath !== actualLocalePaths[index])+ ) {+ return { ok: false, reason: 'receipt localeResources 与 manifest 声明不一致' };+ }+ const localeResources: Record<string, GhostManifestLocaleResource> = {};+ for (const [localePath, resource] of Object.entries(+ value.localeResources as Record<string, unknown>,+ )) {+ if (Buffer.byteLength(JSON.stringify(resource), 'utf8') > GHOST_LOCALE_MAX_BYTES) {+ return { ok: false, reason: `receipt locale 超过大小上限:${localePath}` };+ }+ const validated = validateGhostManifestLocaleResource(resource, manifestResult.manifest);+ if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };+ localeResources[localePath] = validated.resource;+ }+ return {+ ok: true,+ receipt: {+ schemaVersion: RECEIPT_SCHEMA_VERSION,+ id: expectedId,+ revision: value.revision,+ manifest: manifestResult.manifest,+ localeResources,+ enabled: value.enabled,+ trust,+ skillContentSha256,+ ...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),+ ...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),+ },+ };+}++function isRevision(value: string): boolean {+ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);+}++async function copyRegularDirectory(source: string, target: string): Promise<void> {+ // 类型判据与 hashApprovedSkillContent 同源(ghostContentTree):两侧必须同形,+ // 否则指纹算的和快照拷的可能不是同一组字节。+ if ((await classifyGhostDirEntry(source)) !== 'directory') {+ throw new Error(`skill source is not a directory: ${source}`);+ }+ await fs.promises.mkdir(target, { recursive: true });+ const entries = await fs.promises.readdir(source, { withFileTypes: true });+ for (const entry of entries) {+ const from = path.join(source, entry.name);+ const to = path.join(target, entry.name);+ const kind = await classifyGhostDirEntry(from);+ if (!isRegularGhostDirEntry(kind)) {+ throw new Error(+ `skill snapshot rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${from}`,+ );+ }+ if (kind === 'directory') {+ await copyRegularDirectory(from, to);+ } else {+ await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);+ }+ }+}++function validateTrust(raw: unknown): GhostTrustInfo | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const value = raw as Record<string, unknown>;+ if (+ !['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(+ String(value.level),+ ) ||+ typeof value.publisherSigned !== 'boolean' ||+ typeof value.publisherVerified !== 'boolean' ||+ typeof value.reviewed !== 'boolean'+ ) {+ return null;+ }+ const optionalStrings = ['publisherName', 'publisherKeyId', 'reviewerName'] as const;+ for (const key of optionalStrings) {+ if (value[key] !== undefined && typeof value[key] !== 'string') return null;+ }+ if (value.unknownReviewer !== undefined && typeof value.unknownReviewer !== 'boolean') {+ return null;+ }+ return value as unknown as GhostTrustInfo;+}diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 2db7e06288,c49f1e09cf..54d3ac6350--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -48,12 -45,11 +48,15 @@@ importtype GhostVideoResultParams,type InstalledGhost,} from '../../shared/ghost.js';- import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';+ import type {+ PluginMarketItemSource,+ PluginMarketPackageReviewFacts,+ } from '../../shared/pluginMarket.js';import { getAppCapabilities } from '../appCapabilities.js';+import {+ isGhostSkillProjectionBoundaryStableForOwner,+ withGhostSkillProjectionReconcile,+} from '../authBoundaryQuarantine.js';import {activeOwnerScopeKey,getActiveDataOwnerPushStamp,@@@ -86,10 -79,14 +89,15 @@@ importprovisionBuiltinGhosts,readBuiltinTombstones,recordBuiltinTombstone,+ renameBuiltinTombstone,type ProvisionIdentity,} from './builtinGhostProvisioner.js';- import { getAccessToken, getAuthState, onAuthStateChange } from '../authManager.js';+ import {+ getAccessToken,+ getAuthState,+ getCurrentUserId,+ onAuthStateChange,+ } from '../authManager.js';import { serverApiFetch } from '../serverApiClient.js';import { getClientEndpoint } from '../clientEndpointsService.js';import { createGhostOauthBrokerClient } from './ghostOauthBroker.js';@@@ -4162,14 -3847,14 +4174,16 @@@ export async function installOrUpdateMaexpected: {ghostId: string;version: string;+ /** receipt 模型并发护栏:更新分支比对 receipt 派生 token(与 main 硬化叠加,决策 A)。 */+ expectedInstalledApproval?: string;/**- * 安装前实际展示给用户的 manifest。真实包若声明了未展示权限,会在- * 落盘前暂停并把同一份已验证包交给上层复核。+ * 手动首装确认真实包、同来源更新仅在真实包扩权时确认;默认安装只把+ * 市场目录 manifest 当作 fail-closed 权限上限。目录 manifest 不记作批准。*/- reviewedManifest?: GhostManifest;- /** 经来源账本摘要认证的已装清单;缺失时不得回退到可变运行时清单。 */+ permissionPolicy?:+ | { mode: 'manual'; sourceType: PluginMarketItemSource }+ | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };+ /** 安装锁内从当前已落位包读取的 canonical 权限基线。 */permissionBaselineManifest?: GhostManifest;/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */approvedPackageSha256?: string;@@@ -4192,8 -3879,9 +4208,10 @@@ async function installOrUpdateMarketGhoexpected: {ghostId: string;version: string;+ expectedInstalledApproval?: string;- reviewedManifest?: GhostManifest;+ permissionPolicy?:+ | { mode: 'manual'; sourceType: PluginMarketItemSource }+ | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };permissionBaselineManifest?: GhostManifest;approvedPackageSha256?: string;reviewedBaseline?: string;@@@ -4219,24 -3909,8 +4239,24 @@@? 'cindy-official': undefined;requireGhostAvailableForActiveSession(expected.ghostId);+ /**+ * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。+ *+ * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,+ * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。+ * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`+ * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是+ * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着+ * 它装进来,用户**从没审过就多出一个常驻能力面**。+ *+ * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包+ * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。+ * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。+ * (token broker 授权校验由下方 rejectUnauthorizedTokenBroker(canonicalManifest) 统一执行,+ * 原 receipt 分支在此处的硬中止已被本可恢复复核取代,见约束文档 §11 整合任务①。)+ */const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);- if (expected.reviewedManifest) {+ if (expected.permissionPolicy) {const baselineManifest = expected.permissionBaselineManifest ?? null;const installedBaseline = baselineManifest? ghostPermissionBaselineKey(baselineManifest)@@@ -4309,30 -3996,32 +4342,44 @@@getGhostAgentSlot().clearGhost(expected.ghostId);getGhostErrandSlot().clearGhost(expected.ghostId);let result: Awaited<ReturnType<typeof manager.update>>;+ let packagePlaced = false;try {- // 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。+ // 与首装分支同一口径:钉住 inspect 时校验过的包字节。receipt 模型下更新必须+ // 绑定 receipt token(决策 A:与 main 的 sha 钉扎叠加),否则并发批准变更绕不过去。+ if (!expected.expectedInstalledApproval) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin approval state was not bound to the market update',+ );+ }result = await manager.update(cindyFilePath, {expectedPackageSha256: inspected.packageSha256,+ expectedInstalledApproval: expected.expectedInstalledApproval,...(trustOverride ? { trustOverride } : {}),+ onPackagePlaced: () => {+ packagePlaced = true;+ expected.onPackagePlacedInLock?.();+ },});} catch (error) {- spawnIfResident(installed);- throw error;+ if (!packagePlaced) {+ spawnIfResident(installed);+ throw error;+ }+ const placed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);+ if (!placed) throw error;+ log.warn('market ghost post-placement notification failed', {+ ghostId: expected.ghostId,+ error: error instanceof Error ? error.message : String(error),+ });+ result = { ghost: placed };}if ('rejection' in result) {- spawnIfResident(installed);+ // 回滚失败 = 安装目录可能已是新字节或缺失,"旧版本还在"不成立,不得按旧+ // InstalledGhost 重启运行时(P1:那会拿旧批准跑未知字节)。+ if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {+ spawnIfResident(installed);+ }throwInstallError(result.rejection);}runtime.resetFuse(expected.ghostId);@@@ -5592,12 -5266,10 +5639,15 @@@ export function registerGhostIpc(): voi) {throwIpcError('INVALID_PARAMS', 'expectedPackageSha256 must come from ghosts:inspect');}- const mutationOwner = captureGhostMutationOwner();+ if (!isGhostInstallApprovalToken(expectedInstalledApproval)) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedInstalledApproval must come from ghosts:list',+ );+ }+ const marketLedger = getPluginMarketLedger().bind(+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),+ );const inspected = await manager.inspect(lizFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);assertGhostSupportsCurrentCindy(inspected.canonicalManifest);@@@ -5606,56 -5278,126 +5656,128 @@@}rejectReservedGhostId(inspected.manifest.id);rejectUnauthorizedTokenBroker(inspected.manifest);- // 与市场装入/本地装入/卸载共用按 ghostId 的互斥:换目录期间同 id 的其它- // 装入/卸载不得插入(否则并发装入会与本次 rename 竞争、留下不一致态)。- return withGhostInstallLock(inspected.manifest.id, async () => {- const releaseMutation = beginGhostMutation(mutationOwner);- try {+ // 从熄灯到换版收尾整段持 owner 租约:熄灯之后每一步都在改"当前 owner"的插件世界,+ // 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。租约在锁外,+ // 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。+ const releaseMutation = beginGhostMutation(mutationOwner);+ try {+ return await withGhostInstallLock(inspected.manifest.id, async () => {const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);- runtime.stop(inspected.manifest.id);- getGhostNodeRuntimeBroker().stop(inspected.manifest.id);- getGhostAgentSlot().clearGhost(inspected.manifest.id);- getGhostErrandSlot().clearGhost(inspected.manifest.id);- let result: Awaited<ReturnType<typeof manager.update>>;- try {- result = await manager.update(lizFilePath, {- expectedPackageSha256,- expectedInstalledApproval,- });- } catch (err) {- // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)- if (previousGhost) spawnIfResident(previousGhost);- throw err;- }- if ('rejection' in result) {- // 回滚失败时安装目录状态未知(可能是新字节/缺失),不按"旧版本还在"重启。- if (- previousGhost &&- !(result.rejection.code === 'io' && result.rejection.rollbackFailed)- ) {- spawnIfResident(previousGhost);+ let marketRecord: PluginMarketInstallationRecord | null;+ let marketInstallSubject: string | null = null;+ let marketRecordWasSuppressed = false;+ try {+ marketRecord = marketLedger.installationForGhost(inspected.manifest.id);+ if (+ marketRecord?.installed &&+ (marketRecord.source === 'market' || marketRecord.source === 'legacy-adopted')+ ) {+ marketInstallSubject = getCurrentUserId() ?? mutationOwner.dataOwnerId;+ marketRecordWasSuppressed = marketInstallSubject+ ? marketLedger.isDefaultInstallSuppressed(+ marketInstallSubject,+ marketRecord.pluginId,+ )+ : false;+ }+ } catch (error) {+ log.warn('failed to verify Plugin provenance before local update', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');}- throwInstallError(result.rejection);- }- runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账- const store = getLayoutStore();- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);- if (docked) {- const applied = store.setLayout(docked);- if ('rejection' in applied) {- log.warn('ghost panel dock rejected', {- id: result.ghost.manifest.id,- reason: applied.rejection,+ // 用户已在本地包确认流程中明确选择了这份真实包:同 id 可以原位替换,+ // 市场来源不是永久所有权。替换前先切断旧市场更新路由;落位失败再恢复,+ // 全程不清理 Secret、KV、偏好或其它按 ghostId 保存的用户状态。+ const detachMarketRecord = Boolean(marketRecord?.installed);+ const restoreMarketRecord = (): void => {+ if (!detachMarketRecord || !marketRecord) return;+ try {+ marketLedger.restoreInstallation(+ marketRecord,+ marketInstallSubject+ ? {+ userId: marketInstallSubject,+ suppressed: marketRecordWasSuppressed,+ }+ : undefined,+ );+ } catch (error) {+ // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户+ // 明确选择的本地包。用户仍可从任一市场显式替换同 ID 插件。+ log.error('failed to restore Plugin market provenance after local update failure', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ };+ if (detachMarketRecord) {+ try {+ // 先持久化切断自动更新路由,再改真实包。账本不可写时不触碰包,+ // 避免同 manifest 的本地代码被旧市场静默覆盖。+ marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject);+ } catch (error) {+ restoreMarketRecord();+ log.warn('failed to detach Plugin market provenance before local update', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');+ }+ }+ runtime.stop(inspected.manifest.id);+ getGhostNodeRuntimeBroker().stop(inspected.manifest.id);+ getGhostAgentSlot().clearGhost(inspected.manifest.id);+ getGhostErrandSlot().clearGhost(inspected.manifest.id);+ let result: Awaited<ReturnType<typeof manager.update>>;+ let packagePlaced = false;+ try {+ result = await manager.update(lizFilePath, {+ expectedPackageSha256,++ expectedInstalledApproval,+ onPackagePlaced: () => {+ packagePlaced = true;+ },+ });+ } catch (err) {+ if (!packagePlaced) {+ restoreMarketRecord();+ // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)+ if (previousGhost) spawnIfResident(previousGhost);+ throw err;+ }+ const placed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);+ if (!placed) throw err;+ log.warn('local ghost post-placement notification failed', {+ ghostId: inspected.manifest.id,+ error: err instanceof Error ? err.message : String(err),});+ result = { ghost: placed };}- }- spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火- return { ghost: result.ghost };+ if ('rejection' in result) {+ restoreMarketRecord();+ if (previousGhost) spawnIfResident(previousGhost);+ throwInstallError(result.rejection);+ }+ runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账+ const store = getLayoutStore();+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);+ if (docked) {+ const applied = store.setLayout(docked);+ if ('rejection' in applied) {+ log.warn('ghost panel dock rejected', {+ id: result.ghost.manifest.id,+ reason: applied.rejection,+ });+ }+ }+ spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火+ return { ghost: result.ghost };- } finally {- releaseMutation();- }- });+ });+ } finally {+ releaseMutation();+ }});// 设置页「装入意识…」第一步:系统文件选择框(按 .cindy 过滤),只选不装。diff --cc apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 0121040c1a,4e6eb43574..5706381564--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@@ -97,8 -78,13 +97,13 @@@ importpluginMarketCustomIconProjectionToken,pluginMarketCustomIconSourceToken,} from '../../../shared/pluginMarket';-import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';+import type { MarketSourceConfig } from '../../../shared/pluginMarket';- import { PluginMarketLedger, ghostManifestDigest } from '../ledger';+ import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';+ import {+ PluginMarketLedger,+ ghostManifestDigest,+ type PluginMarketInstallationRecord,+ } from '../ledger';import { PluginMarketService } from '../service';import { MarketSourceManager } from '../sources';import { MarketSourceStore } from '../sources/store';@@@ -1041,18 -1099,13 +1119,14 @@@ describe('PluginMarketService 自定义roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);- runtime.install.mockResolvedValue({- manifest: ghostManifest('alpha'),- dir: '/ghosts/alpha',- enabled: true,- });+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));const pluginId = customMarketPluginId('team-lib', 'alpha');- // 以 detail 下发的归一化 manifest 作为“用户审阅内容”,与安装侧重读结果逐字比对。- const reviewed = await h.service.detail(pluginId);+ // detail 的目录 manifest 只用于预览;安装权限由 Main 随后解析真实包。- await h.service.detail(pluginId);++ const detail = await h.service.detail(pluginId);const result = await h.service.install(pluginId, {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,});expect(result.ghost?.manifest.id).toBe('alpha');expect(runtime.install).toHaveBeenCalledTimes(1);@@@ -1069,123 -1122,6 +1143,128 @@@});});+ it('requires full review for an unapproved custom update and carries its receipt token to commit', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },+ ]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const installedManifest = ghostManifest('alpha', '1.0.0');+ const installedDir = path.join(root, 'installed-alpha');+ fs.mkdirSync(installedDir, { recursive: true });+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));+ runtime.ghosts = [+ {+ manifest: installedManifest,+ dir: installedDir,+ enabled: true,+ approval: { state: 'legacy-unapproved' },+ },+ ];+ h.ledger.upsertInstallation({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-08-01T00:00:00.000Z',+ sourceKey: marketSourceKey({ type: 'local', path: dir }),+ manifestDigest: ghostManifestDigest(installedManifest),+ });+ runtime.install.mockResolvedValue({+ manifest: ghostManifest('alpha', '2.0.0'),+ dir: installedDir,+ enabled: true,+ });+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);++ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: reviewed.releaseId,+ expectedManifest: reviewed.manifest,+ expectedInstalledApproval: 'legacy-unapproved',+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();++ await h.service.install(pluginId, {+ expectedReleaseId: reviewed.releaseId,+ expectedManifest: reviewed.manifest,+ expectedInstalledApproval: 'legacy-unapproved',+ allowPermissionExpansion: true,+ reviewedBaseline: ghostPermissionBaselineKey(installedManifest as GhostManifest),+ });+ expect(runtime.install).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ expectedInstalledApproval: 'legacy-unapproved' }),+ );++ // 非 approved 安装无批准基线:目标包全部权限都必须重新确认,++ // 不让可变安装目录的 ghost.json 冒充权限基线。++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );+ });++ it('rejects a custom update when the receipt changes during packaging', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const installedManifest = ghostManifest('alpha');+ const installedDir = path.join(root, 'installed-alpha');+ fs.mkdirSync(installedDir, { recursive: true });+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));+ h.ledger.upsertInstallation({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-08-01T00:00:00.000Z',+ sourceKey: marketSourceKey({ type: 'local', path: dir }),+ manifestDigest: ghostManifestDigest(installedManifest),+ });+ const calls = { n: 0 };+ runtime.listSequence = () => {+ calls.n += 1;+ return [+ {+ manifest: installedManifest,+ dir: installedDir,+ enabled: true,+ approval:+ calls.n >= 2+ ? { state: 'invalid' as const }+ : {+ state: 'approved' as const,+ revision: '00000000-0000-4000-8000-000000000001',+ },+ },+ ];+ };+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);++ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: reviewed.releaseId,+ expectedManifest: reviewed.manifest,+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ });+it('custom market 即使自报 cindy-github 也不会获得 server-market 官方标记', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-github-'));roots.push(root);@@@ -1197,17 -1133,18 +1276,19 @@@enabled: true,});const pluginId = customMarketPluginId('team-lib', 'cindy-github');- const reviewed = await h.service.detail(pluginId);- await h.service.detail(pluginId);++ const detail = await h.service.detail(pluginId);await h.service.install(pluginId, {-- expectedReleaseId: customMarketReleaseId('team-lib', 'cindy-github', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "cindy-github", "1.0.0"),++ expectedManifest: detail.manifest,});- expect(runtime.install.mock.calls[0]?.[1]).toEqual({+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({ghostId: 'cindy-github',version: '1.0.0',+ permissionPolicy: { mode: 'manual', sourceType: 'local-market' },});+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('officialCindyGithub');});it('rejects install when the reviewed release no longer matches', async () => {@@@ -1226,27 -1162,27 +1306,48 @@@expect(runtime.install).not.toHaveBeenCalled();});+ it('uses the packaged manifest when the catalog preview changed before install', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ // 用户审阅之后,本地 ghost.json 保持 id/version 不变但新增权限声明。+ const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');+ const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };+ fs.writeFileSync(ghostFile, JSON.stringify(tampered));+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));++ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: detail.releaseId,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });+ expect(runtime.install).toHaveBeenCalledTimes(1);+ });++ it('rejects install when the manifest changed after permission review', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ // 用户审阅之后,本地 ghost.json 保持 id/version 不变但新增权限声明。+ const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');+ const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };+ fs.writeFileSync(ghostFile, JSON.stringify(tampered));++ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: detail.releaseId,+ expectedManifest: detail.manifest,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ });+it('rejects install when the account switches during packaging', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);@@@ -1378,16 -1357,64 +1522,71 @@@source: 'market',installed: true,updatedAt: '2026-07-30T02:00:00.000Z',- });+ } satisfies PluginMarketInstallationRecord;+ h.ledger.upsertInstallation(previousRecord);- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,}),).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });- expect(runtime.install).not.toHaveBeenCalled();+ runtime.install.mockImplementationOnce(async (_file, options) => {+ options.beforeCommitInLock?.();+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });+ throw new Error('placement failed');+ });+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,+ }),+ ).rejects.toThrow('placement failed');+ expect(h.ledger.installationForGhost('alpha')).toEqual(previousRecord);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(false);+ runtime.install.mockImplementationOnce(async (_file, options) => {+ options.beforeCommitInLock?.();+ options.onPackagePlacedInLock?.();+ throw new Error('notification failed after placement');+ });+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,+ }),+ ).rejects.toThrow('notification failed after placement');+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });+ expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(true);+ runtime.install.mockImplementationOnce(async (_file, options) => {+ options.beforeCommitInLock?.();+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });+ return {+ manifest: ghostManifest('alpha'),+ dir: '/ghosts/replaced-alpha',+ enabled: true,+ };+ });+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ permissionBaselineManifest: current.manifest,+ });+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ source: 'local-market',+ installed: true,+ });});it('lets the user choose between uninstalled custom sources with the same ghostId', async () => {@@@ -1417,11 -1440,10 +1612,11 @@@'not-installed',]);- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,}),).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });expect(runtime.install).toHaveBeenCalledTimes(1);@@@ -1432,17 -1454,12 +1627,13 @@@roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);- runtime.install.mockResolvedValue({- manifest: ghostManifest('server-plugin'),- dir: '/ghosts/server-plugin',- enabled: true,- });+ runtime.install.mockResolvedValue(installedGhost(root, 'server-plugin'));- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));- await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));await expect(h.service.install(customMarketPluginId('team-lib', 'server-plugin'), {-- expectedReleaseId: customMarketReleaseId('team-lib', 'server-plugin', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "server-plugin", "1.0.0"),++ expectedManifest: detail.manifest,}),).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });expect(runtime.install).toHaveBeenCalledTimes(1);@@@ -1517,13 -1533,9 +1707,9 @@@roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);- runtime.install.mockResolvedValue({- manifest: ghostManifest('alpha'),- dir: '/ghosts/alpha',- enabled: true,- });+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));const pluginId = customMarketPluginId('team-lib', 'alpha');- const reviewed = await h.service.detail(pluginId);- await h.service.detail(pluginId);++ const detail = await h.service.detail(pluginId);const realList = MarketSourceStore.prototype.list;let reads = 0;@@@ -1537,8 -1549,7 +1723,8 @@@try {await expect(h.service.install(pluginId, {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,}),).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });expect(runtime.install).toHaveBeenCalledTimes(1);@@@ -1555,7 -1566,7 +1741,7 @@@const rivalDir = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);const pluginId = customMarketPluginId('team-lib', 'alpha');- const reviewed = await h.service.detail(pluginId);- await h.service.detail(pluginId);++ const detail = await h.service.detail(pluginId);// 落位期间(installOrUpdateMarketGhostPackage 还在 await 包检查)另一窗口尝试// 变更来源配置。自定义安装提交段持有来源锁,这次 addSource 必须排在落位后,@@@ -1578,12 -1590,10 +1765,11 @@@});const installing = h.service.install(pluginId, {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,});// runtime.install 只会在 beforeCommit 复核之后、SOURCE_MUTATION_KEY 仍被持有时调用。- // 用显式 barrier 等到这个时刻,不能靠固定毫秒数猜测打包是否已经完成:CI 负载下- // 打包超过等待时间时,rival 会先拿锁,测试反而正确地收到 ALREADY_EXISTS。+ // 用显式 barrier 等到这个时刻,不能靠固定毫秒数猜测打包是否已经完成。await installEntered;let addSourceSettled = false;const adding = h.service@@@ -1640,15 -1654,22 +1830,24 @@@const snapshot = await h.service.snapshot();expect(snapshot.items[0]?.installState).toBe('conflict');- // 安装:同样被拒,恶意/无关仓库不能借同名市场"更新"别人装出来的插件。- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ // 用户明确点击该条目后可以替换;成功落位后才切换后续更新路由。- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "2.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,}),- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });- expect(runtime.install).not.toHaveBeenCalled();+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ permissionBaselineManifest: current.manifest,+ });+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({+ sourceKey: marketSourceKey({ type: 'local', path: dirB }),+ version: '2.0.0',+ installed: true,+ });});it('rejects the install when the source vanishes before the commit point', async () => {@@@ -1657,7 -1678,7 +1856,7 @@@const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);const pluginId = customMarketPluginId('team-lib', 'alpha');- const reviewed = await h.service.detail(pluginId);- await h.service.detail(pluginId);++ const detail = await h.service.detail(pluginId);// 打包期间另一窗口移除了该来源(移除先拿 SOURCE_MUTATION_KEY 删配置,租约只// 保住目录字节)。用"入口发现之后 store.get 开始返回 null"精确模拟这个时序:@@@ -1675,8 -1696,7 +1874,8 @@@try {await expect(h.service.install(pluginId, {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,}),).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });expect(runtime.install).not.toHaveBeenCalled();@@@ -1723,15 -1751,22 +1930,25 @@@const snapshot = await h.service.snapshot();expect(snapshot.items[0]?.installState).toBe('conflict');- // 安装:同样被拒,来源的更新不能覆盖用户降级期间自己装的包。- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ // 列表不把它当自动更新,但用户显式选择后可以替换。- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {-- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),- expectedManifest: reviewed.manifest,++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "2.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ allowPermissionExpansion: true,+ allowSourceReplacement: true,}),- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });- expect(runtime.install).not.toHaveBeenCalled();+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ permissionBaselineManifest: replacedManifest,+ });+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({+ sourceKey: marketSourceKey({ type: 'local', path: dir }),+ version: '2.0.0',+ installed: true,+ });});it('masks failure details with a generation error when the account switches mid-operation', async () => {@@@ -1905,14 -1950,20 +2132,21 @@@await expect(h.service.install(item.id, {expectedReleaseId: item.currentRelease.id,- expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,}),- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });- expect(h.api.download).not.toHaveBeenCalled();- expect(runtime.install).not.toHaveBeenCalled();+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });- expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: current.manifest,- });++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );+ expect(h.ledger.installationForGhost('server-plugin')).toMatchObject({+ pluginId: item.id,+ source: 'market',+ installed: true,+ });});- it('adopts a matching install after a lost ledger write instead of dead-ending in conflict', async () => {+ it('recovers a lost ledger write through an explicit install without automatic adoption', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);@@@ -1923,26 -1974,30 +2157,31 @@@fs.mkdirSync(installedDir, { recursive: true });fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(ghostManifest('alpha')));runtime.ghosts = [{ manifest: ghostManifest('alpha'), dir: installedDir, enabled: true }];-- // 列表:不能标 conflict(UI 会禁用安装,用户连修复入口都没有);投影成可安装。- const snapshot = await h.service.snapshot();- expect(snapshot.items[0]?.installState).toBe('not-installed');-- // 安装 = 收养:完整重装 + 补写溯源,自愈完成。runtime.install.mockResolvedValue({manifest: ghostManifest('alpha'),- dir: installedDir,+ dir: '/ghosts/recovered-alpha',enabled: true,});- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- await h.service.install(customMarketPluginId('team-lib', 'alpha'), {- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- expectedManifest: reviewed.manifest,- expectedInstalledApproval: APPROVED_INSTALL_TOKEN,-+ // 列表不根据内容相同自动推断来源;用户显式点击后可以原位恢复路由。+ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]?.installState).toBe('conflict');+- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),++ expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "1.0.0"),++ expectedManifest: detail.manifest,++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ allowSourceReplacement: true,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ permissionBaselineManifest: ghostManifest('alpha'),});expect(h.ledger.installationForGhost('alpha')).toMatchObject({- installed: true,+ pluginId: customMarketPluginId('team-lib', 'alpha'),source: 'local-market',+ installed: true,});});diff --cc apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 18ef368f0f,492673adc9..2fb68bd24f--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@@ -168,23 -153,13 +168,26 @@@ function summary(overrides: Partial<Vis};}+function detail(+ item = summary(),+ slots: ['notify'] | ['notify', 'fs'] = ['notify'],+): VisiblePluginDetail {+ return {+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: manifest(item.ghostId, item.currentRelease.version, slots),+ },+ };+}+- function reviewedInstallOptions(item: VisiblePluginSummary) {+ function reviewedInstallOptions(+ item: VisiblePluginSummary,+ allowSourceReplacement = false,+ ) {return {expectedReleaseId: item.currentRelease.id,- expectedManifest: manifest(item.ghostId, item.currentRelease.version),+ allowSourceReplacement,};}@@@ -593,18 -617,33 +645,36 @@@ describe('PluginMarketService migratioconst { ghost } = await h.service.install(item.id, reviewedInstallOptions(item));- expect(runtime.install).toHaveBeenCalledWith(- expect.stringMatching(/\.cindy$/),- {- ghostId: 'cindy-test',- version: '1.0.0',- reviewedManifest: manifest(),- },- );+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {+ ghostId: 'cindy-test',+ version: '1.0.0',+ permissionPolicy: { mode: 'manual', sourceType: 'server' },+ });- expect(h.api.listAll).not.toHaveBeenCalled();++ // 安装入口用目录 summary 做 detail 身份绑定(防止把 A 的确认导向 B 的内容),++ // 因此手动安装也会先取一次目录,但不做任何 listAll 之外的多余请求。++ expect(h.api.listAll).toHaveBeenCalledTimes(1);// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。expect(ghost?.enabled).toBe(true);});+ it('installs the explicitly selected official entry when another entry shares its ghostId', async () => {+ const selected = summary();+ const other = summary({ id: `c${'b'.repeat(24)}`, name: 'Other Listing' });+ runtime.install.mockResolvedValue({+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ });+ const h = harness([selected, other]);++ await expect(+ h.service.install(selected.id, reviewedInstallOptions(selected)),+ ).resolves.toMatchObject({ ghost: { manifest: { id: selected.ghostId } } });+ expect(h.api.detail).toHaveBeenCalledWith(selected.id);- expect(h.api.listAll).not.toHaveBeenCalled();++ // 安装入口用目录 summary 绑定 detail 身份,共享 ghostId 的另一条目也一并取回。++ expect(h.api.listAll).toHaveBeenCalledTimes(1);+ });+it('server-market 只为 cindy-github 安装显式传 Host 官方身份', async () => {const github = summary({ ghostId: 'cindy-github' });runtime.install.mockResolvedValue({@@@ -1007,13 -1071,47 +1109,56 @@@});expect((await h.service.snapshot()).items[0]?.installState).toBe('conflict');- await expect(h.service.install(item.id, reviewedInstallOptions(item, true))).rejects.toThrow(- 'placement failed',- );+ await expect(- h.service.install(item.id, reviewedInstallOptions(item)),- ).rejects.toThrow('[ALREADY_EXISTS]');- expect(runtime.install).not.toHaveBeenCalled();++ h.service.install(item.id, {++ ...reviewedInstallOptions(item, true),++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ }),++ ).rejects.toThrow('placement failed');+ expect(h.ledger.installationForGhost(item.ghostId)).toEqual(previousRecord);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);+ runtime.install.mockImplementationOnce(async (_file, options) => {+ options.beforeCommitInLock?.();+ options.onPackagePlacedInLock?.();+ throw new Error('notification failed after placement');+ });- await expect(h.service.install(item.id, reviewedInstallOptions(item, true))).rejects.toThrow(- 'notification failed after placement',- );++ await expect(++ h.service.install(item.id, {++ ...reviewedInstallOptions(item, true),++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ }),++ ).rejects.toThrow('notification failed after placement');+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);+ runtime.install.mockImplementationOnce(async (_file, options) => {+ options.beforeCommitInLock?.();+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });+ return {+ manifest: manifest(item.ghostId, '2.0.0', ['notify']),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ };+ });+ await expect(- h.service.install(item.id, reviewedInstallOptions(item, true)),++ h.service.install(item.id, {++ ...reviewedInstallOptions(item, true),++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ }),+ ).resolves.toMatchObject({+ ghost: { manifest: { version: '2.0.0' } },+ });- expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: installed,- });++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ pluginId: item.id,+ source: 'market',+ version: '2.0.0',+ installed: true,+ });});- it('does not trust an installed manifest as the permission baseline without a digest', async () => {- it('uses the actual installed manifest as the permission baseline for a legacy record', async () => {++ it('does not trust a mutable install manifest as the permission baseline without a matching ledger digest', async () => {const item = summary({currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },});@@@ -1035,12 -1133,11 +1180,14 @@@version: '1.0.0',});- await h.service.install(item.id, reviewedInstallOptions(item));-- expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: installed,+ await h.service.install(item.id, {+ ...reviewedInstallOptions(item),+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,});+- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );});it('installs and enables a public defaultInstall package in local mode', async () => {@@@ -1675,8 -1854,9 +1942,10 @@@});const h = harness([item]);- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[NOT_FOUND]');+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(+ '[NOT_FOUND]',+ );+ expect(h.api.detail).not.toHaveBeenCalled();expect(runtime.install).not.toHaveBeenCalled();});@@@ -2136,8 -2325,19 +2414,22 @@@installed: false,});- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[ALREADY_EXISTS]');- expect(runtime.install).not.toHaveBeenCalled();+ await expect(- h.service.install(item.id, reviewedInstallOptions(item, true)),++ h.service.install(item.id, {++ ...reviewedInstallOptions(item, true),++ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ }),+ ).resolves.toMatchObject({+ ghost: { manifest: { id: item.ghostId } },+ });- expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: manifest(),- });++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ pluginId: item.id,+ source: 'market',+ installed: true,+ });});it('does not overwrite a local plugin that appears while an official package downloads', async () => {@@@ -2413,7 -2452,7 +2707,7 @@@expect(runtime.install).toHaveBeenCalledTimes(1);});- it('does not trust the current installed package without a digest after download', async () => {- it('re-reads the actual installed package as the permission baseline after download', async () => {++ it('rejects a stale installed manifest as the permission baseline after download when the ledger digest no longer matches', async () => {const item = summary({currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },});@@@ -2430,15 -2469,9 +2724,11 @@@dir: '/userData/cindy-brain/cindy-test',enabled: true,});+ // 下载窗口期(锁外复核已通过之后)本地 ghosts:update 把已装换成只有 notify+ // 的包——此刻目标包相对当前已装多出 fs,而这条从没被审阅过。- const downloadMock = vi.mocked(- (await import('../download.js')).downloadVerifiedPlugin,- );+ const downloadMock = vi.mocked((await import('../download.js')).downloadVerifiedPlugin);downloadMock.mockImplementationOnce(async () => {- runtime.ghosts = [- { manifest: currentInstalled, dir: installedDir, enabled: true },- ];+ runtime.ghosts = [{ manifest: currentInstalled, dir: installedDir, enabled: true }];});const h = harness([item]);h.ledger.upsertInstallation({@@@ -2446,13 -2479,12 +2736,21 @@@releaseId: 'release-1',version: '1.0.0',});- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({++ // 下载窗口期目标包相对"当前实际已装"多出 fs,且这条基线在本次安装前从没被++ // 审阅过:合并后的 Main 侧扩权闸要求显式 allowPermissionExpansion 才放行,++ // 同时权限基线必须取下载后重读的真实运行包(不是审阅时刻的 runtime manifest)。+ await expect(+ h.service.install(item.id, {+ ...reviewedInstallOptions(item),+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,++ allowPermissionExpansion: true,+ }),- ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');++ ).resolves.toMatchObject({+ ghost: { manifest: { version: '2.0.0' } },+ });- expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: currentInstalled,- });++ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(++ 'permissionBaselineManifest',++ );});it('rejects an update when the installed target disappears during download', async () => {diff --cc apps/desktop/src/main/plugin-market/install.tsindex a77d43f266,261d4ee217..9443a6c7f7--- a/apps/desktop/src/main/plugin-market/install.ts+++ b/apps/desktop/src/main/plugin-market/install.ts@@@ -16,9 -16,12 +16,13 @@@ import { app } from 'electron'import {validateGhostManifest,+ type GhostManifest,type InstalledGhost,} from '../../shared/ghost.js';+ import type {+ PluginMarketItemSource,+ PluginMarketPackageReviewFacts,+ } from '../../shared/pluginMarket.js';import {installOrUpdateMarketGhostPackage,rejectReservedGhostIdForCustomMarket,@@@ -54,9 -57,13 +58,16 @@@ function sanitizeInstallDetail(messageexport async function installCustomMarketPlugin(input: {pluginDir: string;- expected: GhostManifest;++ expected?: GhostManifest;+ /** 更新时把审阅所绑定的 Host receipt token 贯穿到最终安装出口。 */+ expectedInstalledApproval?: string;+ expectedGhostId: string;+ expectedVersion: string;+ sourceType: Extract<PluginMarketItemSource, 'git-market' | 'local-market'>;+ permissionBaselineManifest?: PluginMarketPackageReviewFacts['manifest'];+ reviewPackagePermissions?: (+ facts: PluginMarketPackageReviewFacts,+ ) => Promise<boolean>;/*** 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。* 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须@@@ -151,33 -171,57 +175,79 @@@sanitizeInstallDetail(packed.message),);}+ // 唯一防篡改防线:比对实际打进包的 manifest,而非打包前磁盘上的 ghost.json。+ // 堵住"前置比对通过后、打包读取文件前"目录被改(保持 id/version 却新增+ // 权限声明)的窗口——装的就是 packed.manifest,必须以它为准。- if (JSON.stringify(packed.manifest) !== JSON.stringify(input.expected)) {++ // expected 只在校验流程显式提供了用户审阅过的清单时做防篡改比对;++ // 来源隔离路径(permissionPolicy)由 expectedGhostId/expectedVersion +++ // permissionBaselineManifest 在装出前复核。++ if (++ input.expected !== undefined &&++ JSON.stringify(packed.manifest) !== JSON.stringify(input.expected)++ ) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin changed after permission review',+ );+ }+ const permissionPolicy = { mode: 'manual' as const, sourceType: input.sourceType };+ // 装出前最后防线:打包期间账号、所选来源或运行时插件状态都可能已变化。+ // 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。- const commit = async (): Promise<InstalledGhost> => {- await input.beforeCommit?.();- // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,- // 不再进入官方市场“下载真实包后复核”的分支。- const installed = await installOrUpdateMarketGhostPackage(tempPath, {- ghostId: validated.manifest.id,- version: validated.manifest.version,- ...(input.expectedInstalledApproval- ? { expectedInstalledApproval: input.expectedInstalledApproval }- : {}),- });- // 溯源写入与落位同锁(见 afterCommit 注释)。- await input.afterCommit?.();- return installed;+ const commit = async (+ approval?: Pick<PluginMarketPackageReviewFacts, 'packageSha256' | 'installedBaseline'>,+ ): Promise<InstalledGhost> => {+ const run = async (): Promise<InstalledGhost> => {+ await input.beforeCommit?.();++ // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,++ // 不再进入官方市场“下载真实包后复核”的分支。+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {+ // Main 会从真实临时包再次解析并与所选市场条目的身份核对;不能使用+ // 打包前活目录里的值,否则目录在打包窗口变化时会把另一个插件装入。+ ghostId: input.expectedGhostId,+ version: input.expectedVersion,+ permissionPolicy,+ ...(input.permissionBaselineManifest+ ? { permissionBaselineManifest: input.permissionBaselineManifest }+ : {}),++ ...(input.expectedInstalledApproval++ ? { expectedInstalledApproval: input.expectedInstalledApproval }++ : {}),+ ...(approval+ ? {+ approvedPackageSha256: approval.packageSha256,+ ...(approval.installedBaseline !== null+ ? { reviewedBaseline: approval.installedBaseline }+ : {}),+ }+ : {}),+ ...(input.beforePackagePlacement+ ? { beforeCommitInLock: input.beforePackagePlacement }+ : {}),+ ...(input.onPackagePlaced+ ? { onPackagePlacedInLock: input.onPackagePlaced }+ : {}),+ });+ // 溯源写入与落位同锁(见 afterCommit 注释)。+ await input.afterCommit?.(installed, packed.manifest);+ return installed;+ };+ return input.withCommitLock ? input.withCommitLock(run) : run();};- return await (input.withCommitLock ? input.withCommitLock(commit) : commit());++ let review: PluginMarketPackageReviewFacts;+ try {+ // 首装或扩权会在任何运行时写入前暂停;无扩权更新则在同一锁内直接落位。+ return await commit();+ } catch (error) {+ if (!(error instanceof GhostPackagePermissionReviewRequiredError)) throw error;+ review = error.review;+ }+ const approved = await input.reviewPackagePermissions?.(review);+ if (approved !== true) return null;++ // 确认返回后重新取得来源/ghost 锁,复核来源、当前安装基线与真实包 SHA。+ // 确认期间不持锁,取消或窗口销毁可立即结束并清理临时包。+ return await commit(review);} finally {await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);}diff --cc apps/desktop/src/main/plugin-market/registerIpc.tsindex 6a3a0eb799,e15203c38a..77d42897f0--- a/apps/desktop/src/main/plugin-market/registerIpc.ts+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@@ -3,8 -3,8 +3,9 @@@ import os from 'node:os'import { ipcMain, type WebContents } from 'electron';import { isIpcError } from '../../shared/ipc-errors.js';+import { isGhostInstallApprovalToken, type GhostManifest } from '../../shared/ghost.js';import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';+ import { getActiveDataOwnerPushStamp } from '../appSessionState.js';import {sendToTrustedAppWindows,setGhostUninstallLedgerPreparer,@@@ -156,39 -167,20 +168,45 @@@ export function registerPluginMarketIpctypeof options === 'object' && options !== null? (options as {expectedReleaseId?: unknown;+ expectedInstalledApproval?: unknown;+ expectedManifest?: unknown;+ allowPermissionExpansion?: unknown;+ reviewedBaseline?: unknown;+ allowSourceReplacement?: unknown;}): null;const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');+ const expectedInstalledApproval = obj?.expectedInstalledApproval;+ if (+ expectedInstalledApproval !== undefined &&+ !isGhostInstallApprovalToken(expectedInstalledApproval)+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedInstalledApproval must come from ghosts:list',+ );+ }+ const expectedManifest = requireObject(obj?.expectedManifest);+ const allowPermissionExpansion = obj?.allowPermissionExpansion === true;+ // 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。+ const reviewedBaseline =+ typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;+ const allowSourceReplacement = obj?.allowSourceReplacement;+ if (typeof allowSourceReplacement !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'allowSourceReplacement must be a boolean');+ }return invokePluginMarket(() =>service().install(requireString(pluginId, 'pluginId'),{expectedReleaseId,+ expectedManifest: expectedManifest as unknown as GhostManifest,+ ...(expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval }+ : {}),+ allowPermissionExpansion,+ ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),+ allowSourceReplacement,},(facts) =>packagePermissionReviewBridge.request(diff --cc apps/desktop/src/main/plugin-market/service.tsindex 581ab62bbb,2e40fb964b..bfaeb4f148--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@@ -95,8 -92,7 +95,8 @@@ const log = createLogger('plugin-markettype PackagePermissionReviewer = (facts: PluginMarketPackageReviewFacts) => Promise<boolean>;class SilentUpgradeBusyError extends Error {}- class SilentUpgradeStaleBaselineError extends Error {}class SilentDefaultInstallCancelledError extends Error {}++class SilentUpgradeStaleBaselineError extends Error {}/*** 来源增删改的互斥键。自定义市场安装的提交段也要拿这把锁,保证所选来源从@@@ -114,31 -110,8 +114,21 @@@*/const SOURCE_MUTATION_KEY = 'market-sources';const CUSTOM_ICON_PROJECTION_TOKEN_RE = /^[a-f0-9]{16}$/;+ const CUSTOM_MARKET_SNAPSHOT_TIMEOUT_MS = 3_000;- /**- * 扩权批准的原子复核:Renderer 的 allowPermissionExpansion 只代表「用户对- * **某一份**已装 manifest 与目标包之间的差异点过同意」。它到达这里之前有一段- * 往返窗口,期间「从文件更新」等路径可能整体替换已装 manifest(ghosts.update()- * 没有版本单调性检查),那份同意就不再对应现实——继续放行等于让旧批准覆盖- * 相对新 manifest 的全部新增权限。- *- * 所以带审阅基线来的批准,必须在安装锁内、真正放行扩权之前,拿**当前**已装- * manifest 重算指纹比对;不一致就拒绝这次批准,由 Renderer 回到重新审阅。- * 基线缺席时保持既有行为(旧版本 Renderer / 首装无基线可比),不新增拒绝面。- */+function assertReviewedBaselineFresh(+ installed: GhostManifest,+ reviewedBaseline: string | undefined,+): void {+ if (reviewedBaseline === undefined) return;+ if (ghostPermissionBaselineKey(installed) !== reviewedBaseline) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Installed Plugin permissions changed after review; re-review required',+ );+ }+}+function captureMarketOwner(): ActiveAppSession {const session = getActiveAppSession();if (@@@ -267,14 -253,32 +270,24 @@@ interface CustomMarketEntryiconKey: string | null;}- /**- * 已安装插件的 locale 无关 manifest 摘要。运行时 `InstalledGhost.manifest` 是- * **按当前界面语言本地化后的**(GhostManager.readInstalledLocalizedManifest),- * 拿它算摘要会让"切换应用语言"被误判成"包被替换"。所以摘要一律来自安装目录的- * 原始 ghost.json,并过同一 validateGhostManifest 再规范化——与写入侧(发现层的- * plugin.manifest,同为校验器输出)同口径。读不出/校验不过返回 null,视为不匹配- * (fail 向 conflict,安全方向)。- */+ interface CustomMarketDiscovery {+ entries: CustomMarketEntry[];+ unavailableSourceNames: string[];+ }++ interface CustomMarketDiscoveryProgress {+ entries: CustomMarketEntry[];+ settledSourceNames: Set<string>;+ unavailableSourceNames: Set<string>;+ }++ export interface PluginMarketSnapshotOptions {+ /** Renderer 目录请求先返回;默认安装/升级在同一 owner 上后台补做。 */+ deferDefaultReconciliation?: boolean;+ /** 延后对账完成(成功或失败)后通知 IPC 层刷新一次性提示。 */+ onDeferredReconciliationSettled?: () => void;+ }+-/**- * 已安装插件的 locale 无关 manifest 摘要。运行时 `InstalledGhost.manifest` 是- * **按当前界面语言本地化后的**(GhostManager.readInstalledLocalizedManifest),- * 拿它算摘要会让"切换应用语言"被误判成"包被替换"。所以摘要一律来自安装目录的- * 原始 ghost.json,并过同一 validateGhostManifest 再规范化——与写入侧(发现层的- * plugin.manifest,同为校验器输出)同口径。读不出/校验不过返回 null,视为不匹配- * (fail 向 conflict,安全方向)。- *//*** 展示投影用:剥掉控制字符(保留换行/制表)与双向文本控制符。只作用于送往* Renderer 的市场条目字段,不改动 manifest 本体(校验/摘要仍以原文为准)。@@@ -638,20 -673,9 +682,19 @@@ export class PluginMarketService}this.requireConfigured();return this.runForOwner(async (owner) => {++ // 本地(免账号)模式只对 public 插件暴露详情;目录 summary 也是 detail 身份++ // 绑定的依据,服务端返回的 id/ghostId/scope 与请求不一致时必须拒,防止把++ // A 的详情内容(含权限清单)呈现给请求 B 的 Renderer。+ const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);+ requireSameMarketOwner(owner);+ const summary = catalog.find((candidate) => candidate.id === pluginId);+ if (!summary) {+ throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');+ }const plugin = await this.api.detail(pluginId);requireSameMarketOwner(owner);- // 详情响应必须与请求的 pluginId 绑定:server 换身份会让用户审阅到别的插件- // (receipt 分支保留的安全绑定,与 main 的跨来源去重叠加)。+ assertDetailMatchesSummary(summary, plugin);- if (owner.mode === 'local' && plugin.scope !== 'public') {- throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');- }+ requirePluginVisibleForOwner(owner, plugin);const compatible = validateGhostManifest(plugin.currentRelease.manifest);if (!compatible.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');@@@ -834,31 -858,15 +877,27 @@@const ledger = this.ledgerForOwner(owner);return this.withMutation(pluginId, async () => {requireSameMarketOwner(owner);++ // 安装必须先经目录可见性闸:本地(免账号)模式只允许 public 插件,未通过++ // 可见性的条目在调用 detail 之前就要拒掉,不能把组织私有插件的详情拉下来。++ // 目录 summary 也是 detail 身份绑定的依据:detail 自报的 id/ghostId/scope/++ // 发布必须与用户确认时看到的那份 summary 一致,否则 A 的确认会被导向 B 的内容。+ const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);+ requireSameMarketOwner(owner);- const selected = catalog.find((plugin) => plugin.id === pluginId);++ const selected = catalog.find((candidate) => candidate.id === pluginId);+ if (!selected) {+ throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');+ }- if (catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1) {- throwIpcError('ALREADY_EXISTS', 'Multiple market Plugins use the same Plugin ID');- }const plugin = await this.api.detail(pluginId);requireSameMarketOwner(owner);- // 绑定到用户确认时看的那份目录 summary:id 与 ghostId 都必须一致 —— 可见性- // 判定与 ghostId 唯一性判定都是基于 selected 做的,detail 换身份就全绕过了。++ // 详情响应必须与请求的 pluginId 绑定:server 换身份会让用户审阅到别的插件。+ assertDetailMatchesSummary(selected, plugin);+ requirePluginVisibleForOwner(owner, plugin);if (plugin.currentRelease.id !== options.expectedReleaseId) {- throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');}const compatible = validateGhostManifest(plugin.currentRelease.manifest);- const reviewed = validateGhostManifest(options.expectedManifest);- if (- !compatible.ok ||- !reviewed.ok ||- ghostManifestDigest(compatible.manifest) !== ghostManifestDigest(reviewed.manifest)- ) {- throwIpcError('PRECONDITION_FAILED', 'Plugin manifest changed after permission review');+ if (!compatible.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}if (!manifestSupportsCurrentCindy(compatible.manifest)) {throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');@@@ -870,15 -878,9 +909,17 @@@plugin,{expectedInstalled: Boolean(existing),+ reviewedManifest: compatible.manifest,+ ...(options.expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval: options.expectedInstalledApproval }+ : {}),+ allowPermissionExpansion: options.allowPermissionExpansion === true,- reviewPackagePermissions,+ ...(options.reviewedBaseline !== undefined+ ? { reviewedBaseline: options.reviewedBaseline }+ : {}),+ permissionPolicy: { mode: 'manual', sourceType: 'server' },+ reviewPackagePermissions,+ allowSourceReplacement: options.allowSourceReplacement === true,},owner,ledger,@@@ -1115,56 -1105,40 +1144,69 @@@const reviewInstalledDigest = existing? installedGhostRawManifestDigest(existing.dir): null;- const ownsInstall = Boolean(- existing &&- currentRecord?.installed &&- currentRecord.pluginId === pluginId &&- currentRecord.sourceKey === sourceKey &&- currentRecord.manifestDigest != null &&- currentRecord.manifestDigest === reviewInstalledDigest,- );- // 收养:运行时已装内容的声明与本来源候选**完全一致**(原始 manifest 摘要- // 相等)时,允许在没有有效账本记录的情况下重装并补写溯源。这是"包已落位- // 但账本写失败"(文件锁/磁盘错)后的唯一自愈入口——否则该插件永久 conflict、- // 更新永被拒。安全性:收养走完整重装,落位字节来自本来源的包,且用户刚在- // 确认框审阅过同一份 manifest;声明有任何差异都收养不了。- const adoptable = Boolean(+ const currentRecord = ledger.installationForGhost(plugin.ghostId);+ const matchesSelectedRoute = Boolean(existing &&- !ownsInstall &&- reviewInstalledDigest === ghostManifestDigest(plugin.manifest),+ currentRecord?.installed &&+ currentRecord.pluginId === pluginId &&+ currentRecord.sourceKey === sourceKey &&+ currentRecord.manifestDigest != null &&+ currentRecord.manifestDigest === reviewInstalledDigest,);- if (existing && !ownsInstall && !adoptable) {+ if (existing && !matchesSelectedRoute && options.allowSourceReplacement !== true) {throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');}+ const assertCustomReviewApproved = (installedNow: InstalledGhost | null): void => {+ if (!installedNow) return;+ if (options.expectedInstalledApproval === undefined) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin approval state was not bound to the market update',+ );+ }+ if (ghostInstallApprovalToken(installedNow.approval) !== options.expectedInstalledApproval) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin approval state changed after permission review',+ );+ }+ const requiresFullReview =+ installedNow.approval.state !== 'approved' ||+ diffInstalledGhostPermissionItems(installedNow, plugin.manifest).added.length > 0;+ if (!requiresFullReview) return;+ if (options.allowPermissionExpansion !== true) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');+ }+ assertReviewedBaselineFresh(installedNow.manifest, options.reviewedBaseline);+ };+ // 无有效 receipt 时不信现场 manifest:目标包全部权限都必须重新确认。+ assertCustomReviewApproved(existing ?? null);+ // 来源只决定后台更新路由,不是 ghostId 的永久所有权。只有详情页明确+ // 选择“替换”才允许原地切换来源;普通更新和“全部更新”必须保持当前路由。+ // 权限基线始终取当前真实安装,避免换源绕过扩权确认。- const permissionBaselineManifest = existing- ? installedGhostRawManifest(existing.dir)- : null;++ // 只在已批准安装时给出基线:非 approved 的安装无批准基线,++ // 目标包全部权限都必须重新确认,与官方市场路径 (commitDownloadedPackage) 一致。++ const permissionBaselineManifest =++ existing && existing.approval.state === 'approved'++ ? installedGhostRawManifest(existing.dir)++ : null;+ let replacedRoute: PluginMarketInstallationRecord | null = null;+ let replacedRouteWasSuppressed = false;+ let packageLanded = false;requireSameMarketOwner(owner);const ghost = await installCustomMarketPlugin({pluginDir: plugin.dir,+ expected: options.expectedManifest,+ expectedGhostId: plugin.ghostId,+ expectedVersion: plugin.version,+ sourceType: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',+ reviewPackagePermissions: async (facts) => {+ requireSameMarketOwner(owner);+ const approved = await reviewPackagePermissions?.(facts);+ requireSameMarketOwner(owner);+ return approved === true;+ },+ ...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),beforeCommit: async () => {requireSameMarketOwner(owner);// 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿@@@ -1197,11 -1171,32 +1239,36 @@@if (current && installedGhostRawManifestDigest(current.dir) !== reviewInstalledDigest) {throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');}+ // raw manifest 摘要不含 Host receipt;内容未变但批准态失效同样必须拒绝+ // 旧确认,并在下一轮按无批准基线展示全部权限。+ assertCustomReviewApproved(current ?? null);},+ expectedInstalledApproval: options.expectedInstalledApproval,+ beforePackagePlacement: () => {+ const record = ledger.installationForGhost(plugin.ghostId);+ const routeStillMatches = Boolean(+ existing &&+ record?.installed &&+ record.pluginId === pluginId &&+ record.sourceKey === sourceKey &&+ record.manifestDigest != null &&+ record.manifestDigest === reviewInstalledDigest,+ );+ if (existing && !routeStillMatches && options.allowSourceReplacement !== true) {+ throwIpcError('PRECONDITION_FAILED', 'Installed Plugin source changed');+ }+ if (existing && record?.installed && !routeStillMatches) {+ replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(+ ledger,+ record,+ defaultInstallSubject(owner),+ );+ replacedRoute = record;+ }+ },+ onPackagePlaced: () => {+ packageLanded = true;+ },// 复核与落位的双重互斥:// - SOURCE_MUTATION_KEY:beforeCommit 返回后包检查还要跑一段,期间不能// 让来源被增删,否则复核结论在落位前过期。@@@ -1412,17 -1468,19 +1540,28 @@@private async installDetail(plugin: VisiblePluginSummary | VisiblePluginDetail,options: {+ /** 手动安装时已向用户展示;默认安装时作为自动授权的目录权限上限。 */+ reviewedManifest?: GhostManifest;+ allowPermissionExpansion?: boolean;+ /** receipt 模型的并发护栏:比对 receipt 派生 token,状态变更即拒(与 main 硬化叠加)。 */+ expectedInstalledApproval?: string;+ /** 安装前权限确认所依据的已装权限指纹。 */+ reviewedBaseline?: string;- /** 真实包比展示清单多权限时,在当前安装事务内立即询问发起窗口。 */+ /** 手动安装确认真实包;默认安装只使用目录 manifest 作为 fail-closed 上限。 */+ permissionPolicy?:+ | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }+ | {+ mode: 'cap';+ manifest: GhostManifest;+ sourceType: PluginMarketItem['sourceType'];+ };+ /** 真实包需要确认时,在当前安装事务内立即询问发起窗口。 */reviewPackagePermissions?: PackagePermissionReviewer;- beforeCommitInLock?: () => void;+ /** 用户明确点击安装时,允许所选市场包原地替换其它来源的同 id 插件。 */+ allowSourceReplacement?: boolean;++ /** 静默升级时基线不匹配是否按陈旧基线拒绝(不静默覆盖用户已审阅的基线)。 */+ silentBaselineMismatch?: boolean;+ beforeCommitInLock?: () => void;/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */expectedInstalled: boolean;} = { expectedInstalled: false },@@@ -1437,38 -1495,21 +1576,49 @@@.list().find((ghost) => ghost.manifest.id === plugin.ghostId);const currentRecord = ledger.installationForGhost(plugin.ghostId);- if (existing && !serverMarketOwnsInstalledGhost(plugin.id, existing, currentRecord)) {+ if (+ existing &&+ !options.allowSourceReplacement &&+ !serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord)+ ) {throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');}+ // 受体并发护栏(TOCTOU):仅当调用方**显式**带来了确认时捕获的批准令牌才核对。+ // 令牌是更新/恢复入口在渲染确认框那一刻钉下的当前受体;它对不上 = 确认往返+ // 窗口里批准被换过,拒绝用旧同意批新包。自动播种/迁移/首装(不带令牌)不受此闸,+ // 各自的 expectedInstalled / 所有权 / reviewedBaseline 门负责它们的关切。+ if (existing) {+ if (options.expectedInstalledApproval === undefined) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin approval state was not bound to the market update',+ );+ }+ if (ghostInstallApprovalToken(existing.approval) !== options.expectedInstalledApproval) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin approval state changed after permission review');+ }+ }+ const reviewedManifest = options.reviewedManifest+ ? validateGhostManifest(options.reviewedManifest)+ : null;+ if (reviewedManifest && !reviewedManifest.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');+ }+ const permissionCap =+ options.permissionPolicy?.mode === 'cap'+ ? validateGhostManifest(options.permissionPolicy.manifest)+ : null;+ if (permissionCap && !permissionCap.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');+ }+ this.assertServerPreviewExpansionApproved(+ existing ?? null,+ reviewedManifest?.manifest,+ options.allowPermissionExpansion,+ options.reviewedBaseline,+ options.silentBaselineMismatch,+ );const download = await this.api.download(plugin.id, plugin.currentRelease.id);requireSameMarketOwner(owner);if (@@@ -1495,14 -1536,19 +1645,26 @@@plugin,{expectedInstalled: options.expectedInstalled,+ ...(options.expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval: options.expectedInstalledApproval }+ : {}),+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),+ allowPermissionExpansion: options.allowPermissionExpansion,+ reviewedBaseline: options.reviewedBaseline,- beforeCommitInLock: options.beforeCommitInLock,+ silentBaselineMismatch: options.silentBaselineMismatch,+ ...(options.permissionPolicy+ ? {+ permissionPolicy:+ options.permissionPolicy.mode === 'cap' && permissionCap?.ok+ ? {+ ...options.permissionPolicy,+ manifest: permissionCap.manifest,+ }+ : options.permissionPolicy,+ }+ : {}),+ allowSourceReplacement: options.allowSourceReplacement,+ beforeCommitInLock: options.beforeCommitInLock,},owner,ledger,@@@ -1518,16 -1564,21 +1680,28 @@@plugin,{expectedInstalled: options.expectedInstalled,+ ...(options.expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval: options.expectedInstalledApproval }+ : {}),+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),+ allowPermissionExpansion: options.allowPermissionExpansion,+ reviewedBaseline: options.reviewedBaseline,++ silentBaselineMismatch: options.silentBaselineMismatch,+ ...(options.permissionPolicy+ ? {+ permissionPolicy:+ options.permissionPolicy.mode === 'cap' && permissionCap?.ok+ ? {+ ...options.permissionPolicy,+ manifest: permissionCap.manifest,+ }+ : options.permissionPolicy,+ }+ : {}),approvedPackageSha256: error.review.packageSha256,approvedPackageBaseline: error.review.installedBaseline,+ allowSourceReplacement: options.allowSourceReplacement,beforeCommitInLock: options.beforeCommitInLock,- silentBaselineMismatch: options.silentBaselineMismatch,},owner,ledger,@@@ -1543,14 -1594,17 +1717,22 @@@tempPath: string,plugin: VisiblePluginSummary | VisiblePluginDetail,options: {- reviewedManifest?: GhostManifest;- allowPermissionExpansion?: boolean;- reviewedBaseline?: string;+ permissionPolicy?:+ | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }+ | {+ mode: 'cap';+ manifest: GhostManifest;+ sourceType: PluginMarketItem['sourceType'];+ };approvedPackageSha256?: string;approvedPackageBaseline?: string | null;+ expectedInstalledApproval?: string;- beforeCommitInLock?: () => void;++ reviewedManifest?: GhostManifest;++ allowPermissionExpansion?: boolean;++ reviewedBaseline?: string;+ silentBaselineMismatch?: boolean;+ allowSourceReplacement?: boolean;+ beforeCommitInLock?: () => void;expectedInstalled: boolean;},owner: ActiveAppSession,@@@ -1602,14 -1634,29 +1785,40 @@@const installedRawManifest = installedNow? installedGhostRawManifest(installedNow.dir): null;- // 权限基线是当前真正运行的包,不是 ledger 中的来源摘要。更新路由已由- // 上面的 serverRecordMatchesInstalledGhost 单独判断;把两者捆绑会让旧记录- // 因缺摘要被当成首次安装,升级时无端要求重新批准全部权限。- const permissionBaselineManifest = installedRawManifest;++ // 权限基线只在已批准安装时给出:非 approved (legacy-unapproved/invalid)++ // 无批准基线,目标包全部权限都必须重新确认,不能让旧确认带出的基线被++ // 当成"已审阅过"。approved 安装的基线取当前真实运行包(不是 ledger 摘要),++ // 更新路由由上方 serverRecordMatchesInstalledGhost 单独判断。++ // 经来源账本摘要认证的已装清单;缺失时不得回退到可变运行时清单。++ // currentRecordNow 是 provenance ledger 的记录(允许 source replacement 时不比对++ // pluginId,但不影响摘要链——来源可以不同,安装目录的字节身份仍需与已记录摘要一致)。+ const permissionBaselineManifest =+ installedNow?.approval.state === 'approved' &&+ installedRawManifest &&+ currentRecordNow?.installed &&+ (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&+ currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)+ ? installedRawManifest+ : null;+ const replacingSource = Boolean(+ installedNow &&+ options.allowSourceReplacement &&+ currentRecordNow?.installed &&+ !serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow),+ );+ let routeDetached = false;+ let replacedRouteWasSuppressed = false;+ let packageLanded = false;+ const detachPreviousRoute = (): void => {+ options.beforeCommitInLock?.();+ if (!replacingSource || !currentRecordNow) return;+ replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(+ ledger,+ currentRecordNow,+ defaultInstallSubject(owner),+ );+ routeDetached = true;+ };const installed = await installOrUpdateMarketGhostPackage(tempPath, {ghostId: plugin.ghostId,version: plugin.currentRelease.version,@@@ -1628,10 -1675,26 +1837,29 @@@: {}),}: {}),+ ...(options.expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval: options.expectedInstalledApproval }+ : {}),- ...(options.beforeCommitInLock ? { beforeCommitInLock: options.beforeCommitInLock } : {}),+ ...(options.beforeCommitInLock || replacingSource+ ? { beforeCommitInLock: detachPreviousRoute }+ : {}),+ ...(replacingSource+ ? {+ onPackagePlacedInLock: () => {+ packageLanded = true;+ },+ }+ : {}),+ }).catch((error) => {+ if (routeDetached && !packageLanded && currentRecordNow) {+ this.restoreMarketRouteAfterFailedReplacement(+ ledger,+ currentRecordNow,+ defaultInstallSubject(owner),+ replacedRouteWasSuppressed,+ );+ }+ throw error;});await this.withCapturedLedgerMutation(ledger, () => {ledger.upsertInstallation(recordFrom(plugin, 'market', installed));@@@ -2060,27 -2084,32 +2294,32 @@@});return;}- const installed = await this.installDetail(- detail,- {- expectedInstalled: true,- permissionPolicy: {- mode: 'cap',- manifest: reviewedManifest.manifest,- sourceType: 'server',- },- beforeCommitInLock: () => {- if (- hasPendingGhostCalls(summary.ghostId) ||- hasRunningGhostErrand(summary.ghostId) ||- hasRunningGhostCindyWork(summary.ghostId)- ) {- throw new SilentUpgradeBusyError('Plugin is busy');- }- },+ const installed = await this.installDetail(detail, {+ expectedInstalled: true,+ reviewedManifest: reviewedManifest.manifest,+ allowPermissionExpansion: true,+ reviewedBaseline,+ expectedInstalledApproval: ghostInstallApprovalToken(freshInstalled.approval),+ silentBaselineMismatch: true,++ permissionPolicy: {++ mode: 'cap',++ manifest: reviewedManifest.manifest,++ sourceType: 'server',+ },- owner,- ledger,- );+ beforeCommitInLock: () => {+ if (+ hasPendingGhostCalls(summary.ghostId) ||+ hasRunningGhostErrand(summary.ghostId) ||+ hasRunningGhostCindyWork(summary.ghostId)+ ) {+ throw new SilentUpgradeBusyError('Plugin is busy');+ }+ },+ }, owner, ledger);if (installed) {const addedPermissions = freshInstalled- ? diffGhostPermissionItems(freshInstalled.manifest, reviewedManifest.manifest).added- .map(({ key, labelKey, labelArgs }) => ({+ ? diffGhostPermissionItems(freshInstalled.manifest, installed.manifest).added.map(+ ({ key, labelKey, labelArgs }) => ({key,labelKey,...(labelArgs ? { labelArgs } : {}),diff --cc apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 9f5ddc84ac,6b8df45bcd..b6e8414472--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@@ -802,12 -791,7 +813,14 @@@ export function GhostPluginPage()[],);- // 目录详情只用于发现与预览;点击更新后由 Main 下载真实包并完成唯一确认。+ // 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做+ // 权限 diff,经用户确认后才安装,不做静默升级。+ //+ // 同版本的 `installed` 也走这里:缺少批准状态的存量安装靠"用市场包重装同一+ // release"恢复,此时权限 diff 会把目标包的全部权限当新增项逐条列出。+ // 所有来源先展示详情清单;官方包下载后仍以真实包清单兜底发现额外权限。++ // 原位更新不切换来源(#2043):点击后详情若已不再是 update-available 则如实++ // 提示状态变化,install 一律 allowSourceReplacement: false。const handleMarketUpdate = useCallback(async (ghostId: string) => {const marketItem = marketByGhostId.get(ghostId);@@@ -827,31 -808,17 +840,43 @@@try {const next = await window.electronAPI.pluginMarket.detail(marketItem.pluginId);if (!isMarketBusyLeaseActive(marketBusyLease)) return;- if (next.installState !== 'update-available') {++ // 来源隔离 + 状态新鲜度(#2043):重取详情后若已不再是可更新/可重审的++ // 目标(conflict 换源、已装已批准等),如实提示状态变化并刷新,不静默继续。++ // `installed` 且未批准的同版本恢复仍放行(见 marketReviewTargetsInstalledGhost)。++ if (++ next.installState !== 'update-available' &&++ !marketReviewTargetsInstalledGhost(next, installedGhost?.approval.state)++ ) {+ toast.error(t('settings.ghosts.market.errors.stateChanged'));+ await refreshMarket();+ return;+ }+ const diff = diffMarketUpdatePermissionItems(installedGhost, next.manifest);+ const approved = await confirm({+ title: t('settings.ghosts.updateConfirm.title', { name: next.name }),+ description: t('settings.ghosts.updateConfirm.body', {+ from: installedGhost?.manifest.version ?? next.version,+ to: next.version,+ }),+ content: <GhostUpdateReview diff={diff} />,+ maxWidth: 520,+ confirmText: t('settings.ghosts.updateConfirm.confirm'),+ cancelText: t('settings.ghosts.updateConfirm.cancel'),+ });+ if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;const options: PluginMarketInstallOptions = {expectedReleaseId: next.releaseId,+ expectedManifest: next.manifest,+ expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),+ allowPermissionExpansion: diff.added.length > 0,+ ...(installedGhost+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }+ : {}),++ // 原位更新不切换来源(#2043):只有冲突替换显式走 runMarketInstallFlow。+ allowSourceReplacement: false,};const ghost = await installReviewedMarketPackage({- detail: next,- lease: marketBusyLease,+ pluginId: next.pluginId,options,});if (!ghost) return;@@@ -1204,55 -1145,13 +1230,56 @@@await refreshMarket();return;}- if (!isMarketBusyLeaseActive(marketBusyLease)) return;+ const diff = isUpdate+ ? diffMarketUpdatePermissionItems(installedGhost!, marketDetail.manifest)+ : null;+ const confirmed = await confirm({+ title: isUpdate+ ? t('settings.ghosts.updateConfirm.title', { name: marketDetail.name })+ : t('settings.ghosts.market.installConfirmTitle', {+ name: marketDetail.name,+ }),+ description: isUpdate+ ? t('settings.ghosts.market.updateConfirmDescription')+ : t(+ marketDetail.sourceType === 'server'+ ? 'settings.ghosts.market.installConfirmDescription'+ : 'settings.ghosts.market.customInstallConfirmDescription',+ ),+ content: isUpdate ? (+ <GhostUpdateReview diff={diff!} />+ ) : (+ <GhostPermissionList items={ghostPermissionItems(marketDetail.manifest)} />+ ),+ maxWidth: 520,+ confirmText: isUpdate+ ? t('settings.ghosts.updateConfirm.confirm')+ : t('settings.ghosts.market.install'),+ cancelText: isUpdate+ ? t('settings.ghosts.updateConfirm.cancel')+ : t('settings.ghosts.installConfirm.cancel'),+ autoFocusConfirm: true,+ });+ if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;const options: PluginMarketInstallOptions = {expectedReleaseId: marketDetail.releaseId,+ expectedManifest: marketDetail.manifest,+ ...(isUpdate && installedGhost+ ? { expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval) }+ : {}),+ ...(isUpdate && diff!.added.length > 0+ ? {+ allowPermissionExpansion: true,+ ...(installedGhost+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }+ : {}),+ }+ : {}),++ // 来源隔离(#2043):仅用户显式选择的冲突替换允许切换来源;更新与原位安装不切换。+ allowSourceReplacement: marketDetail.installState === 'conflict',};const ghost = await installReviewedMarketPackage({- detail: marketDetail,- lease: marketBusyLease,+ pluginId: marketDetail.pluginId,options,});if (!ghost) return;diff --cc apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.tsindex e0cd937c2d,8805662d83..a55c59672f--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts@@@ -1,7 -1,7 +1,13 @@@/**- * Regression coverage for the module-level update-all batch controller:- * uninstall guards, reviewed-manifest passthrough, cancellation handling,- * baseline drift recovery, and batch state surviving page unmount.- * Regression coverage for the module-level update-all controller.- * Permission review is intentionally absent here: every row delegates to the- * Main-owned real-package transaction and this module owns progress only.++ * Regression coverage for the module-level update-all batch controller.++ *++ * Two feature sets are exercised together:++ * - needs-confirm approval binding: rows whose approval is missing/invalid or++ * whose target expands permissions stop for explicit review (approve/skip),++ * including receipt/baseline drift recovery and batch state surviving unmount.++ * - source isolation (#2043): the batch only updates `update-available`++ * packages, never replaces a source, and auto-installs carry++ * `allowSourceReplacement: false`.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md* @vitest-environment jsdom*/@@@ -79,29 -63,29 +85,49 @@@ function marketItem(overrides: Partial<};}+ function detail(overrides: Partial<PluginMarketDetail> = {}): PluginMarketDetail {+ const item = marketItem(overrides);+ return {+ ...item,+ manifest: manifest({ id: item.ghostId, version: item.version }),+ readme: null,+ ...overrides,+ } as PluginMarketDetail;+ }+const detailMock = vi.fn<(pluginId: string) => Promise<PluginMarketDetail>>();- const installMock = vi.fn(async () => ({ ghost: { manifest: manifest({}) } }) as never);+ const installMock = vi.fn();+const DEFAULT_APPROVAL_TOKEN = 'approved:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';++function stubDetail(overrides: {+ manifest: GhostManifest;+ sourceType: PluginMarketDetail['sourceType'];+}): void {+ detailMock.mockResolvedValue({+ ...marketItem({ sourceType: overrides.sourceType }),+ manifest: overrides.manifest,+ readme: null,+ } as unknown as PluginMarketDetail);+}++async function waitForSettledBatch(): Promise<void> {+ await vi.waitFor(() => {+ const state = getUpdateAllBatchState();+ expect(state.running).toBe(false);+ expect(state.rows?.some((row) => row.status === 'pending')).toBe(false);+ });+}+ async function waitForFinishedBatch(): Promise<void> {+ await vi.waitFor(() => {+ const current = getUpdateAllBatchState();+ expect(current.running).toBe(false);+ expect(+ current.rows?.some((row) => row.status === 'pending' || row.status === 'installing'),+ ).toBe(false);+ });+ }+beforeEach(() => {__resetUpdateAllBatchForTest();dataOwnerTesting.reset();@@@ -119,1050 -102,182 +144,1247 @@@});describe('updateAllController', () => {+ it('skips rows whose plugin was uninstalled mid-batch instead of reinstalling', async () => {+ installedGhosts = [];+ stubDetail({ manifest: manifest({}), sourceType: 'server' });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ expect(installMock).not.toHaveBeenCalled();+ });++ it('serially delegates every row with only its current release precondition', async () => {+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });+ detailMock.mockImplementation(async (pluginId) =>+ pluginId === 'plugin-a'+ ? detail()+ : detail({+ pluginId: 'plugin-b',+ ghostId: 'ghost-b',+ releaseId: 'release-b2',+ version: '2.1.0',+ }),+ );++ startUpdateAllBatch([+ marketItem(),+ marketItem({+ pluginId: 'plugin-b',+ ghostId: 'ghost-b',+ releaseId: 'release-b2',+ version: '2.1.0',+ }),+ ]);+ await waitForFinishedBatch();+++ // 自动安装路径同时绑定批准基线、回传审阅清单并携带来源隔离标志。+ expect(installMock.mock.calls).toEqual([- ['plugin-a', { expectedReleaseId: 'release-2', allowSourceReplacement: false }],- ['plugin-b', { expectedReleaseId: 'release-b2', allowSourceReplacement: false }],++ [++ 'plugin-a',++ {++ expectedReleaseId: 'release-2',++ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,++ expectedManifest: expect.anything(),++ allowSourceReplacement: false,++ },++ ],++ [++ 'plugin-b',++ {++ expectedReleaseId: 'release-b2',++ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,++ expectedManifest: expect.anything(),++ allowSourceReplacement: false,++ },++ ],+ ]);+ expect(getUpdateAllBatchState().rows?.map((row) => row.status)).toEqual([+ 'done',+ 'done',+ ]);+ });++ it('binds an automatic update to the installed receipt approval revision', async () => {+ const revision = '11111111-1111-4111-8111-111111111111';+ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.0' }),+ approval: { state: 'approved', revision },+ },+ ];+ const targetManifest = manifest({});+ stubDetail({ manifest: targetManifest, sourceType: 'server' });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: `approved:${revision}`,+ expectedManifest: targetManifest,++ allowSourceReplacement: false,+ });+ });++ it.each(['legacy-unapproved', 'invalid'] as const)(+ 'requires a full permission review for a %s install even when its live manifest matches',+ async (approvalState) => {+ const samePermissions = manifest({+ version: '1.0.0',+ network: { hosts: ['api.example.com'] },+ });+ installedGhosts = [{ manifest: samePermissions, approval: { state: approvalState } }];+ const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({+ manifest: targetManifest,+ sourceType: 'server',+ });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ const held = getUpdateAllBatchState().rows?.[0];+ expect(held).toMatchObject({+ status: 'needs-confirm',+ reviewedApproval: approvalState,+ });+ expect(held?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);+ expect(held?.permissionDiff?.unchanged).toEqual([]);+ expect(installMock).not.toHaveBeenCalled();++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: approvalState,+ expectedManifest: targetManifest,+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ },+ );++ it('requires an explicit confirmation for an unapproved plugin with no optional capabilities', async () => {+ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.0' }),+ approval: { state: 'legacy-unapproved' },+ },+ ];+ stubDetail({ manifest: manifest({}), sourceType: 'server' });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ reviewedApproval: 'legacy-unapproved',+ permissionDiff: { removed: [], unchanged: [] },+ });+ expect(getUpdateAllBatchState().rows?.[0]?.permissionDiff?.added).toEqual([+ expect.objectContaining({ kind: 'code' }),+ ]);+ expect(installMock).not.toHaveBeenCalled();+ });++ it('invalidates an approved review when its receipt becomes invalid before confirmation', async () => {+ const revision = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.0' }),+ approval: { state: 'approved', revision },+ },+ ];+ const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({+ manifest: targetManifest,+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.0' }),+ approval: { state: 'invalid' },+ },+ ];+ await approveUpdateExpansion('plugin-a');++ const rereview = getUpdateAllBatchState().rows?.[0];+ expect(rereview).toMatchObject({+ status: 'needs-confirm',+ staleReview: false,+ reviewedApproval: 'invalid',+ });+ expect(rereview?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);+ expect(installMock).not.toHaveBeenCalled();++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: 'invalid',+ expectedManifest: targetManifest,+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ });++ it('holds server preview permission expansion for approval', async () => {+ const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({ manifest: targetManifest, sourceType: 'server' });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ releaseId: 'release-2',+ expectedManifest: targetManifest,+ });++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenLastCalledWith(+ 'plugin-a',+ expect.objectContaining({ expectedManifest: targetManifest }),+ );+ });++ it('marks a transaction cancelled in Main as skipped', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'server' });+ installMock.mockResolvedValueOnce({ cancelled: true } as never);++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ });++ it('marks a Main-side permission cancellation as skipped', async () => {+ installMock.mockResolvedValueOnce({ cancelled: true });++ startUpdateAllBatch([marketItem()]);+ await waitForFinishedBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ });++ it('skips a plugin removed before its row starts', async () => {+ installedGhosts = [];++ startUpdateAllBatch([marketItem()]);+ await waitForFinishedBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ expect(installMock).not.toHaveBeenCalled();+ });++ it('settles a release already installed by another flow without downloading again', async () => {+ detailMock.mockResolvedValueOnce(detail({ installState: 'installed' }));++ startUpdateAllBatch([marketItem()]);+ await waitForFinishedBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ expect(installMock).not.toHaveBeenCalled();+ });++ it('passes the reviewed manifest back when approving a non-server expansion', async () => {+ const nextManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({ manifest: nextManifest, sourceType: 'git-market' });++ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();++ const held = getUpdateAllBatchState().rows?.[0];+ expect(held?.status).toBe('needs-confirm');+ expect(held?.expectedManifest).toBe(nextManifest);++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: nextManifest,+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('passes expectedManifest when approving a server-source expansion', async () => {+ const revision = '22222222-2222-4222-8222-222222222222';+ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.0' }),+ approval: { state: 'approved', revision },+ },+ ];+ const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({+ manifest: targetManifest,+ sourceType: 'server',+ });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ await approveUpdateExpansion('plugin-a');++ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: `approved:${revision}`,+ expectedManifest: targetManifest,+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ });++ it('turns approval into a skip when the plugin was uninstalled while waiting', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ installedGhosts = [];+ await approveUpdateExpansion('plugin-a');++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ expect(installMock).not.toHaveBeenCalled();+ });++ it('recomputes the diff when an external update replaced the permission baseline', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // 「从文件更新」把插件装成了第三个版本,且它已自带原先要审的 network 权限:+ // 审阅过的 diff 与 allowPermissionExpansion 都不再对应现实。+ installedGhosts = [+ {+ manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }),+ approval: {+ state: 'approved',+ revision: '33333333-3333-4333-8333-333333333333',+ },+ },+ ];+ reconcileUpdateAllBatch();+ const held = getUpdateAllBatchState().rows?.[0];+ expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true, fromVersion: '1.0.5' });+ expect(held?.permissionDiff).toBeUndefined();++ await approveUpdateExpansion('plugin-a');+ // 相对当前已装 manifest 已无扩权 → 按普通更新安装,不带 allowPermissionExpansion。+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: 'approved:33333333-3333-4333-8333-333333333333',+ expectedManifest: expect.any(Object),+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('keeps the row held for re-review when the recomputed diff still expands permissions', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 外部装成第三个版本且权限面变了(多了 fs),但仍不含目标版本要新增的+ // network —— 基线失效触发重算,重算结果依旧是扩权。+ installedGhosts = [{ manifest: manifest({ version: '1.0.5', slots: ['fs'] }) }];+ reconcileUpdateAllBatch();+ await approveUpdateExpansion('plugin-a');++ const row = getUpdateAllBatchState().rows?.[0];+ expect(row).toMatchObject({ status: 'needs-confirm', staleReview: false, fromVersion: '1.0.5' });+ expect(row?.permissionDiff?.added.length).toBeGreaterThan(0);+ // 重算后仍是扩权:停在当前批次等待用户重新确认,不提前调用安装。+ expect(installMock).not.toHaveBeenCalled();+ });++ it('recomputes on baseline drift even before reconcile flagged the row', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 外部更新已落地但 reconcile 还没跑(竞态窗口):版本比较必须兜住,+ // 不得拿旧 diff 换来的 allowPermissionExpansion 安装。+ installedGhosts = [+ { manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }) },+ ];+ await approveUpdateExpansion('plugin-a');++ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: expect.any(Object),+ });+ });++ it('invalidates the review when a same-version manifest swap widened permissions', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // 「从文件更新」换入**同版本**但权限更宽的 manifest:版本号完全看不出来,+ // 沿用旧审阅会把 fs 这条从未审阅的权限一并放行。+ installedGhosts = [{ manifest: manifest({ version: '1.0.0', slots: ['fs'] }) }];+ reconcileUpdateAllBatch();+ const held = getUpdateAllBatchState().rows?.[0];+ expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });+ expect(held?.permissionDiff).toBeUndefined();++ await approveUpdateExpansion('plugin-a');+ // 相对新基线仍是扩权 → 回到预览权限确认,绝不沿用旧批准或提前安装。+ expect(installMock).not.toHaveBeenCalled();+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ staleReview: false,+ });+ });++ it('keeps the review valid when only the version moved but permissions are identical', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 权限面完全没变,只是版本号动了:审阅结论仍然成立,不该逼用户重审。+ installedGhosts = [{ manifest: manifest({ version: '1.0.4' }) }];+ reconcileUpdateAllBatch();+ const kept = getUpdateAllBatchState().rows?.[0];+ expect(kept).toMatchObject({ status: 'needs-confirm', fromVersion: '1.0.4' });+ expect(kept?.staleReview).toBeFalsy();+ expect(kept?.permissionDiff?.added.length).toBeGreaterThan(0);++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: expect.any(Object),+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ });++ it('voids the batch when the data owner changes during the detail round-trip', async () => {+ let releaseDetail: (() => void) | undefined;+ detailMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseDetail = () => {+ setDataOwnerGeneration('owner-b');+ resolve({+ ...marketItem({}),+ manifest: manifest({}),+ readme: null,+ } as unknown as PluginMarketDetail);+ };+ }),+ );++ startUpdateAllBatch([marketItem({})]);+ await vi.waitFor(() => expect(releaseDetail).toBeDefined());+ releaseDetail?.();+ await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));++ // 旧账号发起的批次在身份切换后整体作废,不得写入新账号数据。+ expect(getUpdateAllBatchState().rows).toBeNull();+ expect(installMock).not.toHaveBeenCalled();+ });++ it('skips a queued update that changed to a source conflict before its turn', async () => {+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });+ let resolveFirstInstall: (() => void) | undefined;+ installMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirstInstall = () => resolve({ ghost: { manifest: manifest() } });+ }),+ );+ detailMock.mockImplementation(async (pluginId) =>+ pluginId === 'plugin-a'+ ? detail()+ : detail({+ pluginId: 'plugin-b',+ ghostId: 'ghost-b',+ installState: 'conflict',+ }),+ );++ startUpdateAllBatch([+ marketItem(),+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ ]);+ await vi.waitFor(() => expect(resolveFirstInstall).toBeDefined());+ resolveFirstInstall?.();+ await waitForFinishedBatch();++ expect(installMock).toHaveBeenCalledTimes(1);+ expect(getUpdateAllBatchState().rows?.[1]?.status).toBe('skipped');+ });++ it('keeps ordinary install failures as terminal failed rows', async () => {+ installMock.mockRejectedValueOnce(new Error('network down'));++ startUpdateAllBatch([marketItem()]);+ await waitForFinishedBatch();++ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'failed',+ errorText: 'settings.ghosts.market.errors.generic',+ });+ });++ it('voids the whole batch when its data owner changes during detail loading', async () => {+ let resolveDetail: ((value: PluginMarketDetail) => void) | undefined;+ detailMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveDetail = resolve;+ }),+ );++ startUpdateAllBatch([marketItem()]);+ await vi.waitFor(() => expect(resolveDetail).toBeDefined());+ setDataOwnerGeneration('owner-b');+ resolveDetail?.(detail());+ await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));++ expect(getUpdateAllBatchState().rows).toBeNull();+ expect(installMock).not.toHaveBeenCalled();+ });++ it('keeps running until the post-batch market refresh finishes', async () => {+ let resolveRefresh: (() => void) | undefined;+ setUpdateAllBatchHooks({+ refreshMarket: () =>+ new Promise<void>((resolve) => {+ resolveRefresh = resolve;+ }),+ });++ startUpdateAllBatch([marketItem()]);+ await vi.waitFor(() => expect(resolveRefresh).toBeDefined());+ expect(getUpdateAllBatchState().running).toBe(true);++ startUpdateAllBatch([+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ ]);+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual([+ 'plugin-a',+ ]);++ resolveRefresh?.();+ await waitForFinishedBatch();+ expect(toast.success).toHaveBeenCalledTimes(1);+ });++ it('reconciles a pending row removed while an earlier row is installing', async () => {+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });+ let resolveInstall: (() => void) | undefined;+ installMock.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveInstall = () => resolve({ ghost: { manifest: manifest() } });+ }),+ );+ detailMock.mockImplementation(async (pluginId) =>+ pluginId === 'plugin-a'+ ? detail()+ : detail({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ );++ startUpdateAllBatch([+ marketItem(),+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ ]);+ await vi.waitFor(() => expect(resolveInstall).toBeDefined());+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];+ reconcileUpdateAllBatch();+ expect(getUpdateAllBatchState().rows?.[1]?.status).toBe('skipped');++ resolveInstall?.();+ await waitForFinishedBatch();+ expect(installMock).toHaveBeenCalledTimes(1);+ });+++ it('reconcile settles held rows updated externally and voids stale-owner batches', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // 目标 release 已落账(市场快照报 installed)→ 待确认行收束为完成。+ installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];+ reconcileUpdateAllBatch([marketItem({ installState: 'installed' })]);+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ expect(installMock).not.toHaveBeenCalled();++ // 账号切换后对账直接作废整批。+ startUpdateAllBatch([]);+ setDataOwnerGeneration('owner-b');+ reconcileUpdateAllBatch();+ expect(getUpdateAllBatchState().rows).toBeNull();+ });++ it('does not settle as done when a same-version foreign release was installed', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 「从文件更新」装了同版本但**不是目标 release** 的包:版本号看着到位,+ // 但 main 侧 record.releaseId 对不上,市场仍报 update-available。+ installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];+ reconcileUpdateAllBatch([marketItem({ installState: 'update-available' })]);+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ await approveUpdateExpansion('plugin-a');+ // 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。+ expect(installMock).toHaveBeenCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: expect.any(Object),+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('re-reads the installed manifest after detail() instead of trusting the pre-await snapshot', async () => {+ // 审阅基线:已装带 network,目标包在此之上多出 fs → 用户审的是 fs 这一条。+ installedGhosts = [+ { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },+ ];+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // detail() 往返期间「从文件更新」把已装换成**不带 network** 的包:此刻目标包+ // 相对当前已装多出 network + fs,而 network 用户从没审过。批准必须以+ // detail 之后的事实判断,拿 await 前捕获的快照会直接放行。+ detailMock.mockImplementation(async () => {+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];+ return {+ ...marketItem({}),+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),+ readme: null,+ } as unknown as PluginMarketDetail;+ });++ await approveUpdateExpansion('plugin-a');+ expect(installMock).not.toHaveBeenCalled();+ const row = getUpdateAllBatchState().rows?.[0];+ expect(row?.status).toBe('needs-confirm');+ // 新差异按当前事实重算,把没审过的 network 也摆出来。+ expect(row?.permissionDiff?.added.length).toBeGreaterThan(1);+ });++ it('returns a Main-side baseline rejection to re-review instead of a terminal failure', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // Main 在安装锁内用当前已装 manifest 复核后否决了这次批准。+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('[PRECONDITION_FAILED] baseline changed'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] baseline changed',+ }),+ );++ await approveUpdateExpansion('plugin-a');+ const row = getUpdateAllBatchState().rows?.[0];+ // 「事实已变,请重新审阅」而不是「更新失败」——终态失败会让用户失去入口。+ // 手里的 detail 已被 Main 否决,不能拿它出确认内容:丢弃旧差异 + 标记过期,+ // 下次批准重新取详情。+ expect(row?.status).toBe('needs-confirm');+ expect(row?.staleReview).toBe(true);+ expect(row?.permissionDiff).toBeUndefined();+ expect(row?.errorText).toBeUndefined();+ });++ it('holds running through the post-approval refresh so no second batch can start', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().running).toBe(false);++ let releaseRefresh: (() => void) | undefined;+ setUpdateAllBatchHooks({+ refreshMarket: () =>+ new Promise<void>((resolve) => {+ releaseRefresh = resolve;+ }),+ });++ const approving = approveUpdateExpansion('plugin-a');+ await vi.waitFor(() => expect(releaseRefresh).toBeDefined());+ // 刷新还没回来:页面手里仍是旧的 update-available 快照,必须挡住第二批。+ expect(getUpdateAllBatchState().running).toBe(true);+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);++ releaseRefresh?.();+ await approving;+ expect(getUpdateAllBatchState().running).toBe(false);+ });++ it('serialises concurrent approvals and only settles after the last one', async () => {+ const expanding = manifest({ network: { hosts: ['api.example.com'] } });+ detailMock.mockImplementation(async (pluginId) =>+ ({+ ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),+ manifest: expanding,+ readme: null,+ }) as unknown as PluginMarketDetail,+ );+ installedGhosts = [+ { manifest: manifest({ version: '1.0.0' }) },+ { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },+ ];+ startUpdateAllBatch([+ marketItem({}),+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ ]);+ await waitForSettledBatch();+ expect(+ getUpdateAllBatchState().rows?.every((row) => row.status === 'needs-confirm'),+ ).toBe(true);++ // 两次安装都卡住,用来观察是否并发。+ const installGate: Array<() => void> = [];+ let concurrentPeak = 0;+ let active = 0;+ installMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ active += 1;+ concurrentPeak = Math.max(concurrentPeak, active);+ installGate.push(() => {+ active -= 1;+ resolve({ ghost: { manifest: expanding } } as never);+ });+ }),+ );+ let refreshCalls = 0;+ setUpdateAllBatchHooks({+ refreshMarket: async () => {+ refreshCalls += 1;+ },+ });++ // 用户连点两个「同意」。+ const first = approveUpdateExpansion('plugin-a');+ const second = approveUpdateExpansion('plugin-b');++ await vi.waitFor(() => expect(installGate.length).toBe(1));+ // 串行:第二个必须排队,不能与第一个同时在装。+ expect(concurrentPeak).toBe(1);+ expect(getUpdateAllBatchState().running).toBe(true);++ installGate[0]?.();+ await first;+ // 第一个结束时还有在途批准 → 不许提前释放闸门、不许提前报完成。+ expect(getUpdateAllBatchState().running).toBe(true);+ expect(refreshCalls).toBe(0);++ await vi.waitFor(() => expect(installGate.length).toBe(2));+ installGate[1]?.();+ await second;++ // 最后一个结束才收尾:刷新一次、释放 running、报一次完成。+ expect(concurrentPeak).toBe(1);+ expect(getUpdateAllBatchState().running).toBe(false);+ expect(refreshCalls).toBe(1);+ expect(vi.mocked(toast.success)).toHaveBeenCalledTimes(1);+ });++ it('skips a row whose target release was already installed by the single-item flow', async () => {+ // 用户在批次启动前用卡片的单项更新装了同一个 release;本批次拿的是那之前的+ // 市场快照,仍标 update-available。runner 取详情后必须发现已落账并跳过。+ detailMock.mockResolvedValue({+ ...marketItem({ installState: 'installed' }),+ manifest: manifest({ version: '1.1.0' }),+ readme: null,+ } as unknown as PluginMarketDetail);++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ expect(installMock).not.toHaveBeenCalled();+ });++ it('holds a runner row for re-review instead of failing it on PRECONDITION_FAILED', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'git-market' });+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',+ }),+ );++ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();++ const row = getUpdateAllBatchState().rows?.[0];+ // 自动安装路径遇到前置条件变化 → 可恢复的待重审,不是终态失败。+ expect(row).toMatchObject({ status: 'needs-confirm', staleReview: true });+ expect(row?.errorText).toBeUndefined();+ expect(row?.permissionDiff).toBeUndefined();+ });++ it('lets a held runner row be re-reviewed and approved through to completion', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'git-market' });+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',+ }),+ );++ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();++ const held = getUpdateAllBatchState().rows?.[0];+ expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });+ // 关键:待重审行必须带着目标 release,否则 approve 的入口守卫会直接返回,+ // 用户点「重新审阅」毫无反应,该项在本批次里永远走不下去。+ expect(held?.releaseId).toBe('release-2');++ // 点「重新审阅」→ 重取详情、按当前事实重算(已无扩权)→ 装上收尾。+ await approveUpdateExpansion('plugin-a');++ expect(installMock).toHaveBeenLastCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: expect.anything(),+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('fails instead of holding when there is no target release to re-review', async () => {+ // detail 拿得到、但 install 前置条件失败且行上没有 releaseId 的极端情形:+ // 用 detail 报 installed 之外的路径构造——这里直接验证 hold 的防御分支,+ // 保证不会产出「点不动的 needs-confirm 死行」。+ detailMock.mockResolvedValue({+ ...marketItem({ releaseId: '' }),+ manifest: manifest({}),+ readme: null,+ } as unknown as PluginMarketDetail);+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] gone',+ }),+ );++ startUpdateAllBatch([marketItem({ releaseId: '' })]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');+ });++ it('still fails the row on non-precondition install errors', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'server' });+ installMock.mockRejectedValueOnce(new Error('network down'));++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 真失败仍然是失败:不能把所有错误都变成"再审一次"。+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');+ });++ it('re-reviews instead of failing when a custom source swaps the manifest under the plain update path', async () => {+ // 自定义市场源:审阅基线含 network,目标包在此之上多出 fs。+ installedGhosts = [+ { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },+ ];+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),+ sourceType: 'git-market',+ });+ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // 批准时外部把已装换成同样带 fs 的包 → 重算后已无扩权,走普通更新分支;+ // 但市场源又以同版本改了 manifest,Main 因 expectedManifest 不匹配拒绝。+ detailMock.mockImplementation(async () => {+ installedGhosts = [+ {+ manifest: manifest({+ version: '1.0.0',+ network: { hosts: ['api.example.com'] },+ slots: ['fs'],+ }),+ },+ ];+ return {+ ...marketItem({ sourceType: 'git-market' }),+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),+ readme: null,+ } as unknown as PluginMarketDetail;+ });+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',+ }),+ );++ await approveUpdateExpansion('plugin-a');++ const row = getUpdateAllBatchState().rows?.[0];+ // 并发事实变化 → 回到重新审阅,不是终态失败(否则用户失去本项入口)。+ expect(row?.status).toBe('needs-confirm');+ expect(row?.errorText).toBeUndefined();+ });++ it('drops the stale detail when a same-release manifest swap rejects the approval', async () => {+ const reviewedManifest = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({ manifest: reviewedManifest, sourceType: 'git-market' });+ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ expectedManifest: reviewedManifest,+ });++ // 竞态:detail() 返回的仍是审阅时那份(所以 renderer 侧判定审阅有效),+ // 但在 install 到达 Main 之前,自定义源在**同一 releaseId 下**换了 manifest,+ // Main 因 expectedManifest 对不上拒绝。此刻手里这份 detail 已经不对了。+ const swappedManifest = manifest({+ network: { hosts: ['api.example.com', 'evil.example.com'] },+ });+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',+ }),+ );++ await approveUpdateExpansion('plugin-a');++ const held = getUpdateAllBatchState().rows?.[0];+ // 旧差异与旧 manifest 必须丢弃并标记过期,否则下次批准会再提交同一份+ // 过期的 expectedManifest,循环失败。+ expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });+ expect(held?.permissionDiff).toBeUndefined();+ expect(held?.expectedManifest).toBeUndefined();++ // 再次批准:此时详情已能取到源上的新 manifest → 相对当前已装仍是扩权 →+ // 用**新** manifest 重新出确认内容。+ detailMock.mockResolvedValue({+ ...marketItem({ sourceType: 'git-market' }),+ manifest: swappedManifest,+ readme: null,+ } as unknown as PluginMarketDetail);+ await approveUpdateExpansion('plugin-a');+ const rereviewed = getUpdateAllBatchState().rows?.[0];+ expect(rereviewed).toMatchObject({ status: 'needs-confirm', staleReview: false });+ expect(rereviewed?.expectedManifest).toBe(swappedManifest);++ // 用户同意新差异 → 带新 manifest 装上,推进到完成,不再循环。+ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenLastCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,+ expectedManifest: swappedManifest,+ allowPermissionExpansion: true,+ reviewedBaseline: expect.any(String),+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('never treats a missing expectedManifest as a valid review for custom sources', async () => {+ const reviewed = manifest({ network: { hosts: ['api.example.com'] } });+ stubDetail({ manifest: reviewed, sourceType: 'git-market' });+ startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);+ await waitForSettledBatch();++ // 第一次批准被 Main 拒 → 行被清成 expectedManifest: undefined + staleReview。+ installMock.mockRejectedValueOnce(+ Object.assign(new Error('precondition'), {+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',+ }),+ );+ await approveUpdateExpansion('plugin-a');+ expect(getUpdateAllBatchState().rows?.[0]?.expectedManifest).toBeUndefined();++ // 重新审阅 → 再批准,全程必须带上当前 expectedManifest。缺失被短路成+ // 「审阅仍有效」的话,这里会不带该字段安装,主进程直接 INVALID_PARAMS。+ await approveUpdateExpansion('plugin-a');+ await approveUpdateExpansion('plugin-a');++ expect(installMock).toHaveBeenLastCalledWith(+ 'plugin-a',+ expect.objectContaining({ expectedManifest: reviewed }),+ );+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('voids an approval whose detail returned after the account switched', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 详情请求停在半空,期间切到账号 B(页面的作废 effect 还没跑,代际未变)。+ let releaseDetail: (() => void) | undefined;+ detailMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseDetail = () => {+ setDataOwnerGeneration('owner-b');+ resolve({+ ...marketItem({}),+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ readme: null,+ } as unknown as PluginMarketDetail);+ };+ }),+ );+ const approval = approveUpdateExpansion('plugin-a');+ await vi.waitFor(() => expect(releaseDetail).toBeDefined());++ // 账号 B 装着同 id 的插件:旧批准绝不能读它的 manifest、更不能装它。+ installedGhosts = [{ manifest: manifest({ version: '2.0.0' }) }];+ releaseDetail?.();+ await approval;++ expect(installMock).not.toHaveBeenCalled();+ expect(getUpdateAllBatchState().rows).toBeNull();+ });++ it('does not make a new generation approval wait behind the previous one', async () => {+ const expanding = manifest({ network: { hosts: ['api.example.com'] } });+ detailMock.mockImplementation(async (pluginId) =>+ ({+ ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),+ manifest: expanding,+ readme: null,+ }) as unknown as PluginMarketDetail,+ );+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 账号 A 的批准卡在安装里(永不 resolve)。+ const stuck: Array<() => void> = [];+ installMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ stuck.push(() => resolve({ ghost: { manifest: expanding } } as never));+ }),+ );+ const oldApproval = approveUpdateExpansion('plugin-a');+ await vi.waitFor(() => expect(stuck.length).toBe(1));++ // 切账号 → 新批次(新代际)。+ setDataOwnerGeneration('owner-b');+ reconcileUpdateAllBatch();+ installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');++ // 新代际的批准不该排在账号 A 那个仍然卡着的安装后面:它必须立刻开跑。+ const newApproval = approveUpdateExpansion('plugin-b');+ await vi.waitFor(() => expect(stuck.length).toBe(2));++ stuck[1]?.();+ await newApproval;+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');++ // 收尾:放行旧代际那个安装,它轮到时因代际失效不会改写当前批次。+ stuck[0]?.();+ await oldApproval;+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });++ it('never rebinds a queued approval onto the batch that replaced it', async () => {+ const expanding = manifest({ network: { hosts: ['api.example.com'] } });+ detailMock.mockImplementation(async (pluginId) =>+ ({+ ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),+ manifest: expanding,+ readme: null,+ }) as unknown as PluginMarketDetail,+ );+ installedGhosts = [+ { manifest: manifest({ version: '1.0.0' }) },+ { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },+ ];+ startUpdateAllBatch([+ marketItem({}),+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ ]);+ await waitForSettledBatch();++ // 首项安装卡住,第二项的批准排在队列里等。+ const gate: Array<() => void> = [];+ installMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ gate.push(() => resolve({ ghost: { manifest: expanding } } as never));+ }),+ );+ const first = approveUpdateExpansion('plugin-a');+ const queued = approveUpdateExpansion('plugin-b');+ await vi.waitFor(() => expect(gate.length).toBe(1));++ // 安装进行中切换账号 + 新账号启动自己的批次(同样含 plugin-b 待确认项)。+ setDataOwnerGeneration('owner-b');+ reconcileUpdateAllBatch();+ installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);+ await waitForSettledBatch();+ const newBatchRow = getUpdateAllBatchState().rows?.[0];+ expect(newBatchRow).toMatchObject({ pluginId: 'plugin-b', status: 'needs-confirm' });++ const installsBeforeDrain = installMock.mock.calls.length;+ // 旧队列项这时才轮到执行:它属于上一个代际/账号,必须整体作废,+ // 绝不能改绑到新批次里同 pluginId 的待确认项上并直接安装。+ gate[0]?.();+ await first;+ await queued;++ expect(installMock.mock.calls.length).toBe(installsBeforeDrain);+ // 新批次的待确认项原封不动,仍等用户在新账号下自己批准。+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ pluginId: 'plugin-b',+ status: 'needs-confirm',+ });+ });++ it('never lets a superseded runner write into the batch that replaced it', async () => {+ // 账号 A 的 detail() 停在半空。+ let releaseDetail: ((value: PluginMarketDetail) => void) | undefined;+ detailMock.mockImplementation(+ () =>+ new Promise<PluginMarketDetail>((resolve) => {+ releaseDetail = resolve;+ }),+ );+ startUpdateAllBatch([marketItem({})]);+ await vi.waitFor(() => expect(releaseDetail).toBeDefined());++ // 切到账号 B 并启动 B 自己的批次(旧批次已被作废 + 代际接管)。+ setDataOwnerGeneration('owner-b');+ reconcileUpdateAllBatch();+ expect(getUpdateAllBatchState().rows).toBeNull();+ detailMock.mockResolvedValue({+ ...marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ manifest: manifest({ id: 'ghost-b' }),+ readme: null,+ } as unknown as PluginMarketDetail);+ installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);++ // A 的请求这时才失败返回:不得把失败写进 B、不得消费 B 的 pending 行、+ // 不得提前清掉 B 的 running。+ releaseDetail?.(undefined as unknown as PluginMarketDetail);+ await waitForSettledBatch();++ const rows = getUpdateAllBatchState().rows ?? [];+ expect(rows.map((row) => row.pluginId)).toEqual(['plugin-b']);+ expect(rows[0]?.status).not.toBe('failed');+ expect(installMock).toHaveBeenCalledWith('plugin-b', expect.objectContaining({}));+ });++ it('settles without reinstalling once the target release is actually on record', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });+ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 目标 release 已落账:detail 报 installed,批准直接收束不重复下载。+ installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];+ detailMock.mockResolvedValue({+ ...marketItem({ installState: 'installed' }),+ manifest: manifest({ version: '1.1.0', network: { hosts: ['api.example.com'] } }),+ readme: null,+ } as unknown as PluginMarketDetail);++ // 已落账的早退分支同样要走统一收尾:刷新市场快照 + 完成 toast,+ // 不留旧快照和悬空的未完成提示。+ const refreshMarket = vi.fn(async () => undefined);+ setUpdateAllBatchHooks({ refreshMarket });++ await approveUpdateExpansion('plugin-a');+ expect(installMock).not.toHaveBeenCalled();+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ expect(refreshMarket).toHaveBeenCalledTimes(1);+ expect(toast.success).toHaveBeenCalledWith('settings.ghosts.updateAll.doneToast');+ });++ it('holds running until the post-batch refresh settles so no second batch overlaps', async () => {+ let releaseRefresh: (() => void) | undefined;+ setUpdateAllBatchHooks({+ refreshMarket: () =>+ new Promise<void>((resolve) => {+ releaseRefresh = resolve;+ }),+ });+ stubDetail({ manifest: manifest({}), sourceType: 'server' });++ startUpdateAllBatch([marketItem({})]);+ await vi.waitFor(() => expect(releaseRefresh).toBeDefined());++ // 刷新还没回来:running 必须仍为 true,旧 runner 的收尾不能让第二批插进来。+ expect(getUpdateAllBatchState().running).toBe(true);+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);++ releaseRefresh?.();+ await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));+ });++ it('keeps pending confirmations readable after the page unsubscribes (unmount)', async () => {+ stubDetail({+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ sourceType: 'server',+ });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ // 模块级状态与页面订阅无关:卸载(无订阅者)后快照仍保留待确认行,+ // 重新进页可以直接恢复批准/跳过入口。+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');+ });});diff --cc apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.tsindex a213dea302,f32a67eae2..4a42ab80f4--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts@@@ -80,13 -79,11 +80,15 @@@ describe('batch transitions', () =>expect(next[1].status).toBe('pending');});- it('settles when nothing auto-advances, finishes only after confirms resolve', () => {- it('finishes only after every serial row reaches a terminal state', () => {++ it('finishes only after every row reaches a terminal state, including needs-confirm', () => {let next = updateRow(rows, 'p1', { status: 'done' });+ next = updateRow(next, 'p2', { status: 'installing' });+ expect(isBatchFinished(next)).toBe(false);++ next = updateRow(next, 'p2', { status: 'needs-confirm' });- // needs-confirm 不再自动推进,但用户还没处理 → settled 而未 finished。+ expect(isBatchSettled(next)).toBe(true);+ expect(isBatchFinished(next)).toBe(false);+next = updateRow(next, 'p2', { status: 'skipped' });expect(isBatchFinished(next)).toBe(true);expect(batchSummary(next)).toEqual({ done: 1, skipped: 1, failed: 0 });diff --cc apps/desktop/src/renderer/features/plugin/lib/updateAllController.tsindex d7528df490,4bd8fb96ad..b1f7059b30--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts@@@ -1,15 -1,9 +1,18 @@@/*** Window-level controller for the "update all plugins" batch flow.*- * The controller owns only batch progress and serial execution. Permission- * review belongs to the Main-owned real-package transaction; no catalog- * manifest or parallel approval state is retained here.+ * Inputs: the market update snapshot plus user approve/skip actions.+ * Outputs: a subscribable batch snapshot for the Plugin page and the+ * serial install IPC calls.+ *+ * 为什么在组件外:批次可以在用户关掉弹窗、离开 /plugins 后继续跑+ * (「后台继续」语义),待确认的扩权项也必须在回到插件页后仍然保留+ * 批准/跳过入口——状态生命周期必须长于页面组件,所以照+ * useInstalledGhosts 的先例做成模块级单例 store。真实包复核返回期间若+ * 已装权限基线漂移,保留目标 release 并退回可恢复的重新审阅状态。++ *++ * 来源隔离(#2043):批次只原位更新 `update-available` 的市场包;conflict /++ * 其它来源状态不在这里静默替换来源,install 一律 `allowSourceReplacement: false`。* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/@@@ -229,11 -123,7 +232,14 @@@ export function startUpdateAllBatch(marvoid runQueue(generation);}-/** 串行执行,每个 install() 自己在 Main 中下载、确认并提交同一真实包。 */+/**+ * 批量 runner:串行走「取详情 → 权限 diff → 无扩权直接装 / 有扩权停待确认」。+ * 全程以启动时捕获的 `generation` 为准:任一 await 之后代际若已失效+ * (批次被作废或被新批次接管),立即停手——不写状态、不消费队列、不收尾。++ *++ * 来源隔离(#2043):非 `update-available` 的详情(conflict / 其它状态)不在++ * 批量里静默替换来源,按跳过收束;自动安装路径一律 `allowSourceReplacement: false`。+ */async function runQueue(generation: number): Promise<void> {if (state.running || !isGenerationCurrent(generation)) return;emit({ ...state, running: true });@@@ -267,56 -148,39 +273,67 @@@patchRow(generation, next.pluginId, { status: 'done' });continue;}++ // 来源隔离(#2043):批量更新只原位替换 update-available 的市场包;++ // conflict / 其它来源状态不在这里静默切换来源,按跳过收束。+ if (detail.installState !== 'update-available') {+ patchRow(generation, next.pluginId, { status: 'skipped' });+ continue;+ }- const installed = readInstalledGhostsSnapshot().find(- (ghost) => ghost.manifest.id === next.ghostId,- );- if (!installed) {+ const installedGhost = installedGhostOf(next.ghostId);+ if (!installedGhost) {+ // 批量期间插件已被卸载:绝不拿市场 manifest 兜底继续安装+ // (那会把用户刚卸载的插件重新装回来),该行按跳过收束。patchRow(generation, next.pluginId, { status: 'skipped' });continue;}+ const installedManifest = installedGhost.manifest;+ const reviewedApproval = ghostInstallApprovalToken(installedGhost.approval);+ const diff = diffInstalledGhostPermissionItems(installedGhost, detail.manifest);+ if (installedGhost.approval.state !== 'approved' || diff.added.length > 0) {+ // 扩权不自动放行;没有有效 receipt 时也不存在可沿用的批准基线,+ // 即使目标包没有权限项仍要停下来完成一次明确确认。+ patchRow(generation, next.pluginId, {+ status: 'needs-confirm',+ releaseId: detail.releaseId,+ permissionDiff: diff,+ // 审阅基线绑定权限指纹而非版本号:同版本换 manifest 也能识别。+ reviewedBaseline: ghostPermissionBaselineKey(installedManifest),+ reviewedApproval,+ expectedManifest: detail.manifest,+ });+ continue;+ }+ patchRow(generation, next.pluginId, {- fromVersion: installed.manifest.version,++ fromVersion: installedManifest.version,+ toVersion: detail.version,+ });const result = await window.electronAPI.pluginMarket.install(next.pluginId, {expectedReleaseId: detail.releaseId,+ expectedInstalledApproval: reviewedApproval,+ expectedManifest: detail.manifest,+ allowSourceReplacement: false,});- if (generation !== batchGeneration) return;- if (!batchOwnerCurrent()) {- voidStaleBatch();- return;+ if (result.cancelled) {+ patchRow(generation, next.pluginId, { status: 'skipped' });+ continue;}- patchRow(generation, next.pluginId, {- status: result.cancelled ? 'skipped' : 'done',- });+ patchRow(generation, next.pluginId, { status: 'done' });} catch (error) {- if (generation !== batchGeneration) return;- if (!batchOwnerCurrent()) {- voidStaleBatch();- return;+ if (batchGeneration !== generation) return;+ // 前置条件变化(基线复核否决 / release 变了 / 自定义源换了 manifest)+ // 不是「更新失败」而是「事实已变,请重新审阅」。落成终态 failed 会让+ // 这一项彻底没有入口,用户只能关掉弹窗重启整批。改为可恢复的待重审:+ // 弹窗显示「权限差异已过期 / 重新审阅」,点一下就按当前事实重算。+ // detail 为 null 说明连详情都没取到,没有可写回的 release,此时重审也+ // 无从下手,按失败处理更诚实。+ if (extractIpcError(error)?.code === 'PRECONDITION_FAILED' && detail !== null) {+ holdRowForReReview(generation, next.pluginId, {+ releaseId: detail.releaseId,+ toVersion: detail.version,+ });+ continue;}+ // 失败也只写回自己的批次:代际失效时这条错误属于已作废的批次。patchRow(generation, next.pluginId, {status: 'failed',errorText: i18n.t(pluginMarketErrorKey(error)),@@@ -572,16 -204,7 +589,19 @@@ export function skipUpdateExpansion(plumaybeFinishToast();}-/** 页面外的已装/市场事实变化只用于收束尚未开始的行。 */+/**- * 与外部事实对账:账号切换 → 整批作废;待确认行的插件被卸载 → 跳过、++ * 与外部事实对账:账号切换 → 整批作废;待确认行或尚未开始的行被卸载 → 跳过、+ * **目标 release 已落账**(市场快照报 'installed')→ 记为完成、+ * 权限基线被换掉(含同版本替换 manifest)→ 旧 permissionDiff 已不对应+ * 现实,清掉并标记待重审(真正的重算在 approve 时做,那里能取详情)。+ *++ * `pending` 行按来源事实收束(来源隔离,#2043):市场快照不再报++ * `update-available`(conflict 等)→ 跳过,不再静默切换来源。++ *+ * 完成判据只认市场快照的 installState,不认版本号:同版本不同 release+ * (从文件装入)在版本比对下无法区分,会把没装上目标 release 的行误收成完成。+ * 页面在已装清单、市场快照或身份变化时调用,并把当前市场快照传进来。+ */export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[] = []): void {if (state.rows === null) return;if (!batchOwnerCurrent()) {@@@ -594,40 -220,29 +617,61 @@@let rows = state.rows;let changed = false;for (const row of state.rows) {- if (row.status !== 'needs-confirm') continue;- const installedGhost = installedGhostOf(row.ghostId);- if (installedGhost === null) {- if (row.status !== 'pending') continue;- const installed = installedById.get(row.ghostId);- if (!installed) {-- rows = updateRow(rows, row.pluginId, { status: 'skipped' });-- changed = true;-- } else if (installStateByPluginId.get(row.pluginId) === 'installed') {- // 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。-- rows = updateRow(rows, row.pluginId, { status: 'done' });-- changed = true;-- } else if (- ghostPermissionBaselineKey(installedGhost.manifest) !== row.reviewedBaseline ||- ghostInstallApprovalToken(installedGhost.approval) !== row.reviewedApproval- installStateByPluginId.has(row.pluginId) &&- installStateByPluginId.get(row.pluginId) !== 'update-available'-- ) {- // 权限基线或批准态变了(含 approved receipt 失效):旧审阅作废。- rows = updateRow(rows, row.pluginId, {- fromVersion: installedGhost.manifest.version,- permissionDiff: undefined,- staleReview: true,- reviewedApproval: undefined,- });- rows = updateRow(rows, row.pluginId, { status: 'skipped' });-- changed = true;- } else if (installedGhost.manifest.version !== row.fromVersion) {- // 权限面没变、只是版本号变了:审阅结论仍然成立,同步展示用版本即可。- rows = updateRow(rows, row.pluginId, { fromVersion: installedGhost.manifest.version });- } else if (installed.version !== row.fromVersion) {- rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });-- changed = true;++ if (row.status === 'pending') {++ const installed = installedById.get(row.ghostId);++ if (!installed) {++ rows = updateRow(rows, row.pluginId, { status: 'skipped' });++ changed = true;++ } else if (installStateByPluginId.get(row.pluginId) === 'installed') {++ // 目标 release 已落账:无需再装。++ rows = updateRow(rows, row.pluginId, { status: 'done' });++ changed = true;++ } else if (++ installStateByPluginId.has(row.pluginId) &&++ installStateByPluginId.get(row.pluginId) !== 'update-available'++ ) {++ // 来源隔离:来源已变化(conflict 等),不静默替换,按跳过收束。++ rows = updateRow(rows, row.pluginId, { status: 'skipped' });++ changed = true;++ } else if (installed.version !== row.fromVersion) {++ rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });++ changed = true;++ }++ } else if (row.status === 'needs-confirm') {++ const installedGhost = installedGhostOf(row.ghostId);++ if (installedGhost === null) {++ rows = updateRow(rows, row.pluginId, { status: 'skipped' });++ changed = true;++ } else if (installStateByPluginId.get(row.pluginId) === 'installed') {++ // 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。++ rows = updateRow(rows, row.pluginId, { status: 'done' });++ changed = true;++ } else if (++ ghostPermissionBaselineKey(installedGhost.manifest) !== row.reviewedBaseline ||++ ghostInstallApprovalToken(installedGhost.approval) !== row.reviewedApproval++ ) {++ // 权限基线或批准态变了(含 approved receipt 失效):旧审阅作废。++ rows = updateRow(rows, row.pluginId, {++ fromVersion: installedGhost.manifest.version,++ permissionDiff: undefined,++ staleReview: true,++ reviewedApproval: undefined,++ });++ changed = true;++ } else if (installedGhost.manifest.version !== row.fromVersion) {++ // 权限面没变、只是版本号变了:审阅结论仍然成立,同步展示用版本即可。++ rows = updateRow(rows, row.pluginId, { fromVersion: installedGhost.manifest.version });++ changed = true;++ }}}- if (changed) emit({ ...state, rows });+ if (changed) {+ emit({ ...state, rows });+ maybeFinishToast();+ }}-/** 仅测试用:清空模块级批次状态。 */+/** 仅测试用:清空模块级批次状态与回调注册。 */export function __resetUpdateAllBatchForTest(): void {state = { rows: null, running: false };finishToastShown = false;diff --cc apps/desktop/src/shared/pluginMarket.tsindex d50643ee99,fd0ac9373e..e7711c22db--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@@ -126,18 -137,10 +137,20 @@@ export interface PluginMarketPackageRev}export interface PluginMarketInstallOptions {- /** 用户审阅时看到的目标 release;Main 会在下载前重新核对。 */+ /** 用户点击时看到的目标 release;Main 会在下载前重新核对。 */expectedReleaseId: string;+ /** 安装前展示给用户的完整清单;Main 会与当前来源事实重新核对。 */- expectedManifest: GhostManifest;++ expectedManifest?: GhostManifest;+ /** 仅用于自定义市场确认其本地真实 manifest 的扩权。 */+ allowPermissionExpansion?: boolean;+ /** 用户审阅目标权限时的已装权限基线。 */+ reviewedBaseline?: string;+ /**+ * receipt 模型的并发护栏:receipt 派生 token。确认与落位之间批准状态若变化即拒绝。+ */+ expectedInstalledApproval?: string;+ /** 仅详情页上用户明确点击“替换”时为 true;更新和批量更新不得切换来源。 */+ allowSourceReplacement?: boolean;}/** 安装成功,或用户在事务内取消真实包权限确认。 */