Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close plugin approval review gaps
Yuewei-LL604c642c083f
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex 403e5ed90f..958ada4c75 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -564,6 +564,41 @@ it('fails closed when owner projection roots cannot be enumerated', () => {}});+it('lstats owner projection namespaces when readdir returns unknown Dirent types', async () => {+ const root = await tempRoot();+ const ownerKey = dataOwnerStorageKey('cloud-a');+ await fs.mkdir(path.join(root, 'owners', ownerKey), { recursive: true });+ const directoryType = vi.spyOn(fsSync.Dirent.prototype, 'isDirectory').mockReturnValue(false);+ try {+ expect(listLegacyOwnerProjectionRoots(root)).toEqual(expect.arrayContaining([+ path.join(root, 'owners', ownerKey, 'brain'),+ path.join(root, 'owners', ownerKey, 'cindy-brain'),+ path.join(root, 'owners', ownerKey, 'ghost-install-state'),+ ]));+ } finally {+ directoryType.mockRestore();+ }+});++it('fails closed when an owner projection namespace is replaced by a link', async () => {+ const root = await tempRoot();+ const external = await tempRoot();+ const ownerKey = dataOwnerStorageKey('cloud-a');+ await fs.mkdir(path.join(root, 'owners'), { recursive: true });+ try {+ await fs.symlink(+ external,+ path.join(root, 'owners', ownerKey),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }+ expect(() => listLegacyOwnerProjectionRoots(root)).toThrow(+ 'owner projection namespace is not a regular directory',+ );+});+describe('legacy Ghost plugin recovery', () => {it('persists a durable backfill queue before moving a legacy plugin', async () => {const root = await tempRoot();diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex c8944abb88..e21ed9a7cb 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -1587,7 +1587,39 @@ export class GhostManager {};}}- const dir = path.join(this.contentRootDir(), id);+ const contentRoot = this.contentRootDir();+ const dir = path.join(contentRoot, id);+ if (!this.isRealDirChild(contentRoot, id)) {+ return {+ rejection: { code: 'state-changed', reason: '插件安装目录在确认后发生了变化,请重新确认' },+ };+ }+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ let markerExisted = false;+ try {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ markerExisted = true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ // 先提交兼容镜像,再提交权威 receipt。否则 marker 失败会留下“返回成功但实际+ // 启停态与 receipt 矛盾”的部分成功。没有状态变化时不触碰 marker。+ if (opts.enable) {+ if (markerExisted) await fs.promises.rm(marker, { force: true });+ } else if (!markerExisted) {+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } catch (err) {+ return {+ rejection: {+ code: 'io',+ reason: `启停标记写入失败:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }try {const localeResources = inspected.localeResources;const iconDataUrl = inspected.iconDataUrl;@@ -1604,28 +1636,40 @@ export class GhostManager {{ skillSourceDir: dir },);} catch (err) {+ const markerChanged = opts.enable ? markerExisted : !markerExisted;+ if (markerChanged) {+ try {+ if (!this.isRealDirChild(contentRoot, id)) {+ throw new Error('ghost install directory changed before marker rollback');+ }+ if (markerExisted) {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (markerError) {+ if ((markerError as NodeJS.ErrnoException).code !== 'ENOENT') throw markerError;+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } else {+ await fs.promises.rm(marker, { force: true });+ }+ } catch (rollbackErr) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost reapproval receipt failed and marker rollback also failed',+ {+ id,+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ },+ );+ }+ }return {rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },};}this.untrustedApprovals.delete(this.isolationKey(id));- // 与 setEnabled 同款:启停镜像同步维护,回滚到旧客户端不错位。写入前先 no-follow- // 复核 marker 是受管普通文件(B-3):安装目录可变,marker 被换成符号链接时裸- // writeFile 会穿透截断链接目标,与 setEnabled/writeDisabledMarkerSync 判据保持一致。- try {- const marker = path.join(dir, DISABLED_MARKER_FILE);- try {- if (classifyGhostDirEntrySync(marker) !== 'file') {- throw new Error('ghost disabled marker is not a regular file');- }- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- }- if (opts.enable) await fs.promises.rm(marker, { force: true });- else await fs.promises.writeFile(marker, '');- } catch {- // 镜像写不动不影响批准事实;receipt 是权威。- }this.options.log?.info('ghost reapproved from installed dir', {id,enabled: opts.enable,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 947c491322..5abbc374c1 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -807,6 +807,140 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复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');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 99bbc0b930..70a796a64b 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -25,6 +25,7 @@ import {type ForgeScaffoldTemplate,} from '../forge';import { GhostManager } from '../GhostManager';+import { sameForgeScaffoldParentIdentity } from '../forgeScaffoldIdentity';import { GHOST_SIGNATURE_FILE, signGhostPackage } from '../ghostSignature';import { GHOST_INSTALL_MANIFEST_MAX_BYTES } from '../../../shared/ghost';@@ -48,13 +49,7 @@ let workDir: string;async function testScaffoldWriter(request: ForgeScaffoldWriteRequest) {const parentStats = await fs.promises.lstat(request.parentDir, { bigint: true });- if (!parentStats.isDirectory() || parentStats.isSymbolicLink()) {- return { ok: false as const, errorCode: 'INTERNAL' as const, message: 'unsafe parent' };- }- if (- !(request.expectedParent.dev === 0n && request.expectedParent.ino === 0n) &&- (parentStats.dev !== request.expectedParent.dev || parentStats.ino !== request.expectedParent.ino)- ) {+ if (!sameForgeScaffoldParentIdentity(parentStats, request.expectedParent)) {return { ok: false as const, errorCode: 'INTERNAL' as const, message: 'parent changed' };}const target = path.join(request.parentDir, request.targetName);@@ -1053,6 +1048,29 @@ describe('packGhostDir', () => {});describe('scaffoldGhostDir', () => {+ it('fails closed when the scaffold parent has no trustworthy filesystem identity', async () => {+ const parentStat = await fs.promises.lstat(workDir, { bigint: true });+ const realPath = await fs.promises.realpath(workDir);+ expect(+ sameForgeScaffoldParentIdentity(parentStat, { realPath, dev: 0n, ino: 0n }),+ ).toBe(false);++ const zeroIdentityStat = new Proxy(parentStat, {+ get(target, key) {+ if (key === 'dev' || key === 'ino') return 0n;+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ expect(+ sameForgeScaffoldParentIdentity(zeroIdentityStat, {+ realPath,+ dev: parentStat.dev,+ ino: parentStat.ino,+ }),+ ).toBe(false);+ });+it('passes the stable parent identity as lossless bigint values', async () => {const parentStat = await fs.promises.lstat(workDir, { bigint: true });let captured: ForgeScaffoldWriteRequest | undefined;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.tsindex 92cf6196eb..3a7b179530 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts@@ -9,8 +9,9 @@import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { Readable } from 'node:stream';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {classifyGhostDirEntry,@@ -275,6 +276,58 @@ describe('hashGhostContentFiles', () => {await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow();});+ it('rejects a same-inode leaf file rewritten while its bytes are being hashed', async () => {+ const root = path.join(workDir, 'plugin');+ const file = path.join(root, 'main.js');+ const originalBytes = Buffer.from('old-prefix|old-suffix');+ const replacementBytes = Buffer.from('new-prefix|new-suffix');+ expect(replacementBytes.byteLength).toBe(originalBytes.byteLength);+ await fs.promises.mkdir(root, { recursive: true });+ await fs.promises.writeFile(file, originalBytes);+ const tree = await collectGhostContentFiles(root, {+ dotEntries: 'include',+ nonRegular: 'throw',+ label: 'test',+ });++ const splitAt = 'old-prefix|'.length;+ const realOpen = fs.promises.open;+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (+ ...args: Parameters<typeof fs.promises.open>+ ) => {+ const handle = await realOpen(...args);+ if (path.resolve(String(args[0])) !== path.resolve(file)) return handle;+ return new Proxy(handle, {+ get(target, key) {+ if (key === 'createReadStream') {+ return () => Readable.from((async function*() {+ const first = Buffer.alloc(splitAt);+ const firstRead = await handle.read(first, 0, first.byteLength, 0);+ yield first.subarray(0, firstRead.bytesRead);++ await fs.promises.writeFile(file, replacementBytes);+ const changedAt = new Date(Date.now() + 5_000);+ await fs.promises.utimes(file, changedAt, changedAt);++ const rest = Buffer.alloc(replacementBytes.byteLength - splitAt);+ const restRead = await handle.read(rest, 0, rest.byteLength, splitAt);+ yield rest.subarray(0, restRead.bytesRead);+ })());+ }+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ }) as typeof fs.promises.open);+ try {+ await expect(+ hashGhostContentFiles(root, tree.files, tree.rootIdentity),+ ).rejects.toThrow(/entry changed while reading/);+ } finally {+ openSpy.mockRestore();+ }+ });+it('rejects the content root being replaced between collection and hashing', async () => {const root = path.join(workDir, 'plugin');await fs.promises.mkdir(root, { recursive: true });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.tsindex 7973f639bb..4fc2ed2579 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts@@ -27,6 +27,7 @@ describe('Node runtime packaging contract', () => {);expect(worker).toContain('parentPort');expect(worker).toContain('verifyParent');+ expect(worker).toContain('sameForgeScaffoldParentIdentity');expect(worker).toContain('fs.promises.rename(staging, request.targetName)');expect(worker).not.toContain('ELECTRON_RUN_AS_NODE');const capability = fs.readFileSync(diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex 02d51b5e32..f51e5b3efd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -432,9 +432,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {expect(fs.existsSync(managedLink)).toBe(false);});- it('账号边界读取全局技能根失败:记 warning 继续,不抛错阻断边界', async () => {- // 撤链是尽力而为契约:读不动某个共享根不能把整轮撤链(以及登出)整体炸掉,- // 否则一条无关坏项就能堵死账号边界。读失败记 warning,调用正常返回。+ it('账号边界读取全局技能根失败:记 blocker,禁止在未确认清空时提交新 owner', async () => {const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');await fs.promises.mkdir(ownerRoot, { recursive: true });const readdir = vi.spyOn(fs.promises, 'readdir').mockRejectedValueOnce(@@ -443,20 +441,101 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {try {const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);expect(result.warnings.some((w) => w.includes('Unable to read global skill root'))).toBe(true);+ expect(result.blockers.some((w) => w.includes('Unable to read global skill root'))).toBe(true);} finally {readdir.mockRestore();}});- it('账号边界不会把被替换成 symlink 的 owner 根当作受管根:记 warning 跳过,不抛错', async () => {+ it('账号边界删除已识别的旧 owner 投影失败:记 blocker,不能静默跨账号保留', async () => {+ const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ const managedTarget = path.join(ownerRoot, 'other-ghost', 'skills', 'foo');+ await fs.promises.mkdir(managedTarget, { recursive: true });+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.symlink(+ managedTarget,+ managedLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const realUnlink = fs.promises.unlink;+ const unlink = vi.spyOn(fs.promises, 'unlink').mockImplementation(async (target) => {+ if (path.resolve(String(target)) === path.resolve(managedLink)) {+ throw Object.assign(new Error('denied'), { code: 'EACCES' });+ }+ return realUnlink(target);+ });+ try {+ const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);+ expect(result.changed).toBe(false);+ expect(result.blockers.some((w) => w.includes('Unable to remove owner skill link'))).toBe(true);+ expect(fs.existsSync(managedLink)).toBe(true);+ } finally {+ unlink.mockRestore();+ }+ });++ it('账号边界不信任 Dirent 类型位:类型 unknown 时仍用 lstat 撤销旧 owner 链接', async () => {+ const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ const managedTarget = path.join(ownerRoot, 'other-ghost', 'skills', 'foo');+ await fs.promises.mkdir(managedTarget, { recursive: true });+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.symlink(+ managedTarget,+ managedLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const direntType = vi.spyOn(fs.Dirent.prototype, 'isSymbolicLink').mockReturnValue(false);+ try {+ const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);+ expect(result.changed).toBe(true);+ expect(result.blockers).toEqual([]);+ expect(fs.existsSync(managedLink)).toBe(false);+ } finally {+ direntType.mockRestore();+ }+ });++ it('账号边界仍只警告可判定为外来的坏链接,不让无关条目制造 blocker', async () => {+ const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ const foreignTarget = path.join(workDir, 'projects', 'foreign', 'skills', 'foo');+ await fs.promises.mkdir(ownerRoot, { recursive: true });+ await fs.promises.mkdir(foreignTarget, { recursive: true });+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const foreignLink = path.join(sharedDir(), 'foreign--foo');+ await fs.promises.symlink(+ foreignTarget,+ foreignLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const realRealpath = fs.promises.realpath;+ const realpath = vi.spyOn(fs.promises, 'realpath').mockImplementation(async (target) => {+ if (path.resolve(String(target)) === path.resolve(foreignLink)) {+ throw Object.assign(new Error('denied'), { code: 'EACCES' });+ }+ return realRealpath(target);+ });+ try {+ const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);+ expect(result.warnings.some((w) => w.includes('Unable to resolve owner skill link'))).toBe(true);+ expect(result.blockers).toEqual([]);+ expect(fs.existsSync(foreignLink)).toBe(true);+ } finally {+ realpath.mockRestore();+ }+ });++ it('账号边界不会跟随被替换成 symlink 的 owner 根,并阻止提交未清理的新 owner', async () => {const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-outside-'));const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');try {await fs.promises.mkdir(path.dirname(ownerRoot), { recursive: true });await fs.promises.symlink(outside, ownerRoot, process.platform === 'win32' ? 'junction' : 'dir');const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);- // 该根被记 warning 并跳过(不进 resolvedRoots),既不抛错也不把 symlink 目标当受管根。+ // 该根不进 resolvedRoots,既不跟随到外部,也不允许账号边界在清理不确定时继续。expect(result.warnings.some((w) => w.includes(ownerRoot))).toBe(true);+ expect(result.blockers.some((w) => w.includes(ownerRoot))).toBe(true);} finally {await fs.promises.rm(outside, { recursive: true, force: true });}diff --git a/apps/desktop/src/main/cindy-brain/forgeScaffoldIdentity.ts b/apps/desktop/src/main/cindy-brain/forgeScaffoldIdentity.tsnew file mode 100644index 0000000000..c53cf914a3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/forgeScaffoldIdentity.ts@@ -0,0 +1,23 @@+import type fs from 'node:fs';++export interface ForgeScaffoldParentIdentity {+ realPath: string;+ dev: bigint;+ ino: bigint;+}++/**+ * Forge scaffold can only promise a stable parent when both sides expose a+ * real filesystem identity. Zero-valued identities are "unknown", not a+ * wildcard: accepting them would reduce the worker check to a same-path test.+ */+export function sameForgeScaffoldParentIdentity(+ stats: fs.BigIntStats,+ expected: ForgeScaffoldParentIdentity,+): boolean {+ if (!stats.isDirectory() || stats.isSymbolicLink()) return false;+ if (stats.dev === 0n || stats.ino === 0n || expected.dev === 0n || expected.ino === 0n) {+ return false;+ }+ return stats.dev === expected.dev && stats.ino === expected.ino;+}diff --git a/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.tsindex a8765c4f70..5b3c257821 100644--- a/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts+++ b/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts@@ -1,8 +1,13 @@import fs from 'node:fs';import path from 'node:path';+import {+ sameForgeScaffoldParentIdentity,+ type ForgeScaffoldParentIdentity,+} from './forgeScaffoldIdentity.js';+interface Request {- expectedParent: { realPath: string; dev: bigint; ino: bigint };+ expectedParent: ForgeScaffoldParentIdentity;targetName: string;files: Array<{ path: string; base64: string }>;}@@ -31,15 +36,11 @@ function hasCode(error: unknown, code: string): boolean {return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);}-function sameParentIdentity(stats: fs.BigIntStats, expected: Request['expectedParent']): boolean {- if (!stats.isDirectory() || stats.isSymbolicLink()) return false;- return (expected.dev === 0n && expected.ino === 0n) ||- (stats.dev === expected.dev && stats.ino === expected.ino);-}-async function verifyParent(expected: Request['expectedParent']): Promise<void> {const stats = await fs.promises.lstat('.', { bigint: true });- if (!sameParentIdentity(stats, expected)) throw new Error('Forge scaffold parent identity changed');+ 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');}diff --git a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts b/apps/desktop/src/main/cindy-brain/ghostContentTree.tsindex 0d36e7fa80..a10c07f1c2 100644--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts@@ -180,6 +180,14 @@ function sameFileIdentity(return a.dev === b.dev && a.ino === b.ino;}+function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {+ return after.isFile() &&+ sameFileIdentity(before, after) &&+ before.size === after.size &&+ before.mtimeNs === after.mtimeNs &&+ before.ctimeNs === after.ctimeNs;+}+async function captureGhostContentRootIdentity(rootDir: string): Promise<GhostContentRootIdentity> {const realPath = await fs.promises.realpath(rootDir);const [pathStat, realStat] = await Promise.all([@@ -371,6 +379,10 @@ export async function hashGhostContentFiles(const stream = handle.createReadStream({ autoClose: false });for await (const chunk of stream) fileHash.update(chunk as Buffer);+ const afterReadStat = await handle.stat({ bigint: true });+ if (!sameStableFileState(handleStat, afterReadStat)) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }assertGhostContentAncestorIdentities(ancestorIdentities,await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex b9400bc502..2b7b9f630b 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -838,6 +838,12 @@ export async function suspendAllGhosts(): Promise<void> {for (const warning of skillCleanup.warnings) {log.warn('ghost owner skill cleanup warning', { warning });}+ if (skillCleanup.blockers.length > 0) {+ for (const blocker of skillCleanup.blockers) {+ log.error('ghost owner skill cleanup blocked account boundary', { blocker });+ }+ throw new Error(`ghost owner skill cleanup incomplete (${skillCleanup.blockers.length})`);+ }}let ipcRegistered = false;diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 56f42e8a6c..c525b9d8ac 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -105,19 +105,17 @@ export interface ReconcileGhostSkillLinksResult {* boundary must revoke all Cindy-owned projections before the next owner is* visible.*- * Best-effort by contract: the shared skill roots are world-writable and shared- * with other tools, so a single unrelated bad entry (a self-referential link, an- * inaccessible target segment) must NOT abort the whole revocation. Every failure- * is collected into `warnings` and the sweep continues; callers log the warnings- * but proceed with the account boundary. Throwing here would both strand old- * owner links across the boundary (I-2) and block logout entirely (the teardown- * path does not wrap this call).+ * The sweep keeps unrelated foreign-link failures as warnings, but separately+ * reports blockers whenever it cannot prove a shared root is clean or cannot+ * remove an identified owner projection. The account boundary must not expose a+ * new owner while one of those blockers remains (I-2).*/export async function removeGhostSkillLinksForRoots(managedRoots: readonly string[],homeDir?: string,-): Promise<{ changed: boolean; warnings: string[] }> {+): Promise<{ changed: boolean; warnings: string[]; blockers: string[] }> {const warnings: string[] = [];+ const blockers: string[] = [];let changed = false;const paths = sharedGlobalSkillsPaths(homeDir);const lexicalRoots = [...new Set(managedRoots.map(normalizeForCompare))];@@ -126,17 +124,21 @@ export async function removeGhostSkillLinksForRoots(try {const rootStat = await fsp.lstat(root);if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {- warnings.push(`Managed owner skill root is not a regular directory: ${root}`);+ const message = `Managed owner skill root is not a regular directory: ${root}`;+ warnings.push(message);+ blockers.push(message);continue;}resolvedRoots.push(normalizeForCompare(await fsp.realpath(root)));} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {- warnings.push(`Unable to resolve managed owner skill root ${root}: ${(err as Error).message}`);+ const message = `Unable to resolve managed owner skill root ${root}: ${(err as Error).message}`;+ warnings.push(message);+ blockers.push(message);}}}- if (lexicalRoots.length === 0) return { changed, warnings };+ if (lexicalRoots.length === 0) return { changed, warnings, blockers };for (const dir of [paths.sharedSkillsDir, paths.claudeSkillsDir, paths.codexSkillsDir]) {let entries: Dirent[];@@ -144,52 +146,67 @@ export async function removeGhostSkillLinksForRoots(entries = await fsp.readdir(dir, { withFileTypes: true });} catch (err) {if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;- warnings.push(`Unable to read global skill root ${dir}: ${(err as Error).message}`);+ const message = `Unable to read global skill root ${dir}: ${(err as Error).message}`;+ warnings.push(message);+ blockers.push(message);continue;}for (const entry of entries) {- if (!entry.isSymbolicLink()) continue;const linkPath = path.join(dir, entry.name);- let target: string;- let roots = resolvedRoots;try {- target = normalizeForCompare(await fsp.realpath(linkPath));+ // Dirent.d_type can be unknown on network filesystems and can become stale+ // before this sweep reaches the entry. lstat is the ownership/type verdict.+ if (!(await fsp.lstat(linkPath)).isSymbolicLink()) continue;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;+ const message = `Unable to inspect global skill entry ${linkPath}: ${(err as Error).message}`;+ warnings.push(message);+ blockers.push(message);+ continue;+ }+ let rawTarget: string;+ try {+ rawTarget = await fsp.readlink(linkPath);+ } catch (readlinkError) {+ if ((readlinkError as NodeJS.ErrnoException).code === 'ENOENT') continue;+ const message = `Unable to read owner skill link ${linkPath}: ${(readlinkError as Error).message}`;+ warnings.push(message);+ blockers.push(message);+ continue;+ }+ const lexicalTarget = normalizeForCompare(path.resolve(path.dirname(linkPath), rawTarget));+ let managed = lexicalRoots.some((root) => isSameOrInside(lexicalTarget, root));+ try {+ const resolvedTarget = normalizeForCompare(await fsp.realpath(linkPath));+ managed ||= resolvedRoots.some((root) => isSameOrInside(resolvedTarget, root));} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {- // 无关的坏链(自环 ELOOP、目标段 EACCES)不能中断整轮撤链:记 warning 跳过。+ // A resolvable raw target still lets us distinguish an unrelated bad link+ // from an owner projection whose target is temporarily inaccessible.warnings.push(`Unable to resolve owner skill link ${linkPath}: ${(err as Error).message}`);- continue;- }- let rawTarget: string;- try {- rawTarget = await fsp.readlink(linkPath);- } catch (readlinkError) {- if ((readlinkError as NodeJS.ErrnoException).code === 'ENOENT') continue;- warnings.push(- `Unable to read dangling owner skill link ${linkPath}: ${(readlinkError as Error).message}`,- );- continue;}- target = normalizeForCompare(path.resolve(path.dirname(linkPath), rawTarget));- roots = lexicalRoots;}- if (!roots.some((root) => isSameOrInside(target, root))) continue;+ if (!managed) continue;try {const stat = await fsp.lstat(linkPath);if (!stat.isSymbolicLink()) {- warnings.push(`Skipped owner skill link that changed before removal: ${linkPath}`);+ const message = `Skipped owner skill link that changed before removal: ${linkPath}`;+ warnings.push(message);+ blockers.push(message);continue;}await fsp.unlink(linkPath);changed = true;} catch (err) {if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;- warnings.push(`Unable to remove owner skill link ${linkPath}: ${(err as Error).message}`);+ const message = `Unable to remove owner skill link ${linkPath}: ${(err as Error).message}`;+ warnings.push(message);+ blockers.push(message);continue;}}}- return { changed, warnings };+ return { changed, warnings, blockers };}interface ReconcileOptions {diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 89e0ba48da..e3d38ab6c9 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -452,6 +452,8 @@ function ownerScopedLegacyGhostRootDir(userDataDir: string, ownerKey: string): sreturn path.join(userDataDir, 'owners', ownerKey, 'brain');}+const OWNER_STORAGE_KEY_RE = /^[a-f0-9]{20}$/;+/** All legacy/content and approval projection roots that must be revoked at an owner boundary. */export function listLegacyOwnerProjectionRoots(userDataDir: string): string[] {const ownersRoot = path.join(userDataDir, 'owners');@@ -466,8 +468,20 @@ export function listLegacyOwnerProjectionRoots(userDataDir: string): string[] {throw error;}for (const entry of entries) {- if (!entry.isDirectory() || entry.isSymbolicLink()) continue;+ if (!OWNER_STORAGE_KEY_RE.test(entry.name)) continue;const ownerRoot = path.join(ownersRoot, entry.name);+ let ownerStat: fsSync.Stats;+ try {+ // Dirent.d_type is not authoritative on network/special filesystems. A+ // missed owner directory would bypass the next account-boundary retry.+ ownerStat = fsSync.lstatSync(ownerRoot);+ } catch (error) {+ if (isMissing(error)) continue;+ throw error;+ }+ if (!ownerStat.isDirectory() || ownerStat.isSymbolicLink()) {+ throw new Error(`owner projection namespace is not a regular directory: ${ownerRoot}`);+ }roots.push(path.join(ownerRoot, 'brain'),path.join(ownerRoot, 'cindy-brain'),