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 plugin owner boundary and shared skill projection
Yuewei-LLb3c3848d791a
diff --git a/apps/desktop/src/main/__tests__/appCapabilitiesIpc.test.ts b/apps/desktop/src/main/__tests__/appCapabilitiesIpc.test.tsindex 99e54ba8bc..c565fa671b 100644--- a/apps/desktop/src/main/__tests__/appCapabilitiesIpc.test.ts+++ b/apps/desktop/src/main/__tests__/appCapabilitiesIpc.test.ts@@ -3,19 +3,25 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({mode: 'local' as 'local' | 'cloud',boundaryPending: false,+ ownerStable: true,}));vi.mock('../appSessionState.js', () => ({- getActiveAppSession: () => ({ mode: state.mode, dataOwnerId: null, generation: 0 }),+ getActiveAppSession: () => ({ mode: state.mode, dataOwnerId: 'owner-a', generation: 0 }),isAppSessionBoundaryPending: () => state.boundaryPending,}));+vi.mock('../authBoundaryQuarantine.js', () => ({+ isGhostSkillProjectionBoundaryStableForOwner: () => state.ownerStable,+}));+import { requireAppCapability } from '../appCapabilities.js';describe('requireAppCapability IPC errors', () => {beforeEach(() => {state.mode = 'local';state.boundaryPending = false;+ state.ownerStable = true;});it('encodes unavailable account capabilities as permission errors', () => {@@ -27,4 +33,12 @@ describe('requireAppCapability IPC errors', () => {state.boundaryPending = true;expect(() => requireAppCapability('canUseDeviceLink')).toThrow(/\[PRECONDITION_FAILED\]/);});++ it('keeps cloud capabilities closed while the durable owner is unstable', () => {+ state.mode = 'cloud';+ state.ownerStable = false;+ expect(() => requireAppCapability('canUseCindyAccountServices')).toThrow(+ /\[PRECONDITION_FAILED\]/,+ );+ });});diff --git a/apps/desktop/src/main/__tests__/appSessionPolicy.test.ts b/apps/desktop/src/main/__tests__/appSessionPolicy.test.tsindex 1380c218cb..95edef4068 100644--- a/apps/desktop/src/main/__tests__/appSessionPolicy.test.ts+++ b/apps/desktop/src/main/__tests__/appSessionPolicy.test.ts@@ -21,6 +21,12 @@ describe('local app-session policy', () => {expect(deriveAppCapabilities('cloud', false).canUseCindyAccountServices).toBe(true);});+ it('fails closed while the durable cloud owner is not stable', () => {+ expect(deriveAppCapabilities('cloud', false, false).canUseCindyAccountServices).toBe(false);+ expect(deriveAppCapabilities('cloud', false, false).canUseCindyGateway).toBe(false);+ expect(deriveAppCapabilities('cloud', false, true).canUseCindyAccountServices).toBe(true);+ });+it('rejects local DB work while the matching owner boundary is pending', () => {const state = { dataOwnerId: 'cloud-a' };expect(isLocalDbOwnerCurrent(state, 'cloud-a', false)).toBe(true);diff --git a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.tsindex 8429c7f76e..864de5f128 100644--- a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts+++ b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts@@ -1,7 +1,7 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {prepareSharedGlobalSkillLinks,@@ -57,6 +57,41 @@ describe('prepareSharedGlobalSkillLinks', () => {expect(await sameRealPath(path.join(paths.sharedSkillsDir, 'claude-only'), claudeSkill)).toBe(true);});+ it('stops before the next shared-root write when the owner changes mid-fanout', async () => {+ const root = await makeTmpDir();+ const homeDir = path.join(root, 'home');+ const paths = sharedGlobalSkillsPaths(homeDir);+ await writeSkill(paths.claudeSkillsDir, 'a-first');+ await writeSkill(paths.claudeSkillsDir, 'b-second');++ let ownerStable = true;+ const realSymlink = fs.symlink;+ const symlinkSpy = vi.spyOn(fs, 'symlink').mockImplementation(async (...args) => {+ await realSymlink(...args);+ ownerStable = false;+ });+ try {+ await expect(+ prepareSharedGlobalSkillLinks({+ homeDir,+ assertOwnerStable: () => {+ if (!ownerStable) throw new Error('owner changed');+ },+ }),+ ).rejects.toThrow('owner changed');+ } finally {+ symlinkSpy.mockRestore();+ }++ expect(await sameRealPath(+ path.join(paths.sharedSkillsDir, 'a-first'),+ path.join(paths.claudeSkillsDir, 'a-first'),+ )).toBe(true);+ await expect(fs.lstat(path.join(paths.sharedSkillsDir, 'b-second'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ });+it('links shared skills into Claude skills so Claude Code can load them', async () => {const root = await makeTmpDir();const homeDir = path.join(root, 'home');diff --git a/apps/desktop/src/main/appCapabilities.ts b/apps/desktop/src/main/appCapabilities.tsindex d58b258f1c..05296530a1 100644--- a/apps/desktop/src/main/appCapabilities.ts+++ b/apps/desktop/src/main/appCapabilities.ts@@ -10,6 +10,7 @@ import {isAppSessionBoundaryPending,type AppSessionMode,} from './appSessionState.js';+import { isGhostSkillProjectionBoundaryStableForOwner } from './authBoundaryQuarantine.js';import { throwIpcError } from './utils/ipcValidate.js';export interface AppCapabilities {@@ -24,8 +25,9 @@ export interface AppCapabilities {export function deriveAppCapabilities(mode: AppSessionMode,boundaryPending = false,+ ownerStable = true,): AppCapabilities {- const cloud = mode === 'cloud' && !boundaryPending;+ const cloud = mode === 'cloud' && !boundaryPending && ownerStable;return {canUseCindyAccountServices: cloud,canUseCindyGateway: cloud,@@ -41,6 +43,7 @@ export function getAppCapabilities(): AppCapabilities {return deriveAppCapabilities(session.mode,isAppSessionBoundaryPending(),+ isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId),);}@@ -48,8 +51,11 @@ export function requireAppCapability(capability: keyof AppCapabilities,message = 'This feature requires a Cindy account.',): void {- if (getAppCapabilities()[capability]) return;- if (isAppSessionBoundaryPending()) {+ const session = getActiveAppSession();+ const boundaryPending = isAppSessionBoundaryPending();+ const ownerStable = isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId);+ if (deriveAppCapabilities(session.mode, boundaryPending, ownerStable)[capability]) return;+ if (boundaryPending || (session.mode === 'cloud' && !ownerStable)) {throwIpcError('PRECONDITION_FAILED','App session is switching; retry after the owner boundary settles.',diff --git a/apps/desktop/src/main/authBoundaryQuarantine.ts b/apps/desktop/src/main/authBoundaryQuarantine.tsindex c63e3d738e..0f9afb9c6c 100644--- a/apps/desktop/src/main/authBoundaryQuarantine.ts+++ b/apps/desktop/src/main/authBoundaryQuarantine.ts@@ -424,11 +424,20 @@ export async function withGhostSkillProjectionReconcile<T>(ownerId: string,reconcile: () => Promise<T>,): Promise<T> {- if (isPassiveSharedUserDataInstance()) {- throw new Error('Passive shared-userData instances cannot mutate the Ghost skill projection');- }const normalizedOwnerId = ownerId.trim();if (!normalizedOwnerId) throw new Error('Ghost skill reconcile requires a committed owner');+ return withSharedGlobalSkillProjectionMutation(normalizedOwnerId, reconcile);+}++/** Serialize every mutation of the shared home-level skill discovery roots. */+export async function withSharedGlobalSkillProjectionMutation<T>(+ ownerId: string | null,+ mutation: () => Promise<T>,+): Promise<T> {+ if (isPassiveSharedUserDataInstance()) {+ throw new Error('Passive shared-userData instances cannot mutate global skill projections');+ }+ const normalizedOwnerId = normalizeOwnerArgument(ownerId);return withStrictBoundaryLock(async () => {if (processProjectionQuarantined || isDurablyQuarantined()) {throw new Error(@@ -443,7 +452,7 @@ export async function withGhostSkillProjectionReconcile<T>() {throw new Error('Ghost skill projection is not stable for the active owner');}- return reconcile();+ return mutation();});}@@ -481,7 +490,13 @@ export function isGhostSkillProjectionBoundaryStableForOwner(ownerId: string | nexport function assertGhostSkillProjectionStableOwner(ownerId: string): void {const normalizedOwnerId = ownerId.trim();if (!normalizedOwnerId) throw new Error('Ghost skill projection requires a committed owner');- if (!isGhostSkillProjectionBoundaryStableForOwner(normalizedOwnerId)) {+ assertGhostSkillProjectionBoundaryStableForOwner(normalizedOwnerId);+}++export function assertGhostSkillProjectionBoundaryStableForOwner(+ ownerId: string | null,+): void {+ if (!isGhostSkillProjectionBoundaryStableForOwner(ownerId)) {throw new Error('Ghost skill projection is not stable for the active owner');}}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex 8a5696a029..955d74b06a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -22,7 +22,8 @@ describe('market Ghost session boundary', () => {const captureEnd = source.indexOf('\n}\n', captureStart);const captureBody = source.slice(captureStart, captureEnd);expect(captureBody).toContain('isAppSessionBoundaryPending()');- expect(captureBody).toContain('return getActiveAppSession();');+ expect(captureBody).toContain('const owner = getActiveAppSession();');+ expect(captureBody).toContain('isGhostSkillProjectionBoundaryStableForOwner(owner.dataOwnerId)');const leaseStart = source.indexOf('function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex a6db2ee589..3b3922abaf 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -89,6 +89,61 @@ function rpcRequest(method = 'echo', params: unknown = { value: 1 }) {return { type: 'node-request', method, params };}+describe('nodeRuntimeBroker owner boundary races', () => {+ it('owner boundary change during startup kills the worker and fails closed', async () => {+ let generation = 1;+ const invalidated = vi.fn();+ const ghost = fakeGhost();+ const child = new FakeNodeProcess(undefined, false);+ const spawnProcess = vi.fn(() => child as unknown as NodeWorkerProcess);+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess,+ ownerScope: {+ capture: () => generation,+ isCurrent: (scope) => scope === generation,+ isStable: (scope) => scope === generation,+ onInvalidated: invalidated,+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest('startup'));+ await vi.waitFor(() => expect(spawnProcess).toHaveBeenCalledTimes(1));+ generation = 2;+ child.emit('spawn');++ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(child.killed).toBe(true);+ expect(invalidated).toHaveBeenCalledWith('node-ghost');+ });++ it('owner boundary change before a response discards the response and stops the worker', async () => {+ let generation = 1;+ const invalidated = vi.fn();+ const ghost = fakeGhost();+ const child = new FakeNodeProcess();+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess: () => child as unknown as NodeWorkerProcess,+ ownerScope: {+ capture: () => generation,+ isCurrent: (scope) => scope === generation,+ isStable: (scope) => scope === generation,+ onInvalidated: invalidated,+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest('response'));+ await vi.waitFor(() => expect(child.received).toHaveLength(1));+ generation = 2;+ child.send({ jsonrpc: '2.0', id: child.received[0].id, result: { stale: true } });++ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'PROCESS_EXITED' });+ expect(child.killed).toBe(true);+ expect(invalidated).toHaveBeenCalledWith('node-ghost');+ });+});+function makeAutoReplyProcess(methods?: string[]) {const process = new FakeNodeProcess((message) => {if (typeof message.method === 'string') methods?.push(message.method);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex f03037078b..8ffaca156d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -28,6 +28,14 @@ function fakeGhost(overrides: Partial<InstalledGhost> = {}): InstalledGhost {} as InstalledGhost;}+function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void;+ const promise = new Promise<void>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}+interface Harness {dispatcher: GhostPipeDispatcher;deps: {@@ -47,6 +55,7 @@ function makeHarness(opts: {ghost?: InstalledGhost | null;state?: GhostRuntimeState;timeoutMs?: number;+ ownerScope?: PipeDispatcherDeps['ownerScope'];} = {}): Harness {const sent: GhostPipeToolCall[] = [];const deps = {@@ -65,6 +74,7 @@ function makeHarness(opts: {const dispatcher = new GhostPipeDispatcher({...deps,timeoutMs: opts.timeoutMs,+ ownerScope: opts.ownerScope,} as unknown as PipeDispatcherDeps);return { dispatcher, deps, sent };}@@ -178,6 +188,36 @@ describe('按需拉起', () => {expect(r).toMatchObject({ ok: false, errorCode: 'GHOST_CRASHED' });expect(h.dispatcher.pendingCount()).toBe(0);});++ it('owner changes while spawn is pending: stops the runtime and never dispatches', async () => {+ let generation = 1;+ const invalidated = vi.fn();+ const spawnStarted = deferred();+ const releaseSpawn = deferred();+ const h = makeHarness({+ state: 'off',+ ownerScope: {+ capture: () => generation,+ isCurrent: (scope) => scope === generation,+ isStable: (scope) => scope === generation,+ onInvalidated: invalidated,+ },+ });+ h.deps.spawn.mockImplementation(async () => {+ spawnStarted.resolve();+ await releaseSpawn.promise;+ return { ok: true as const };+ });++ const pending = h.dispatcher.callGhostTool(CALL);+ await spawnStarted.promise;+ generation = 2;+ releaseSpawn.resolve();++ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'GHOST_ASLEEP' });+ expect(h.deps.sendToGhost).not.toHaveBeenCalled();+ expect(invalidated).toHaveBeenCalledWith('art');+ });});describe('配对交卷', () => {@@ -197,6 +237,33 @@ describe('配对交卷', () => {expect(h.dispatcher.pendingCount()).toBe(0);});+ it('rejects a stale result after the owner generation changes', async () => {+ let generation = 1;+ const invalidated = vi.fn();+ const h = makeHarness({+ ownerScope: {+ capture: () => generation,+ isCurrent: (scope) => scope === generation,+ isStable: (scope) => scope === generation,+ onInvalidated: invalidated,+ },+ });+ const pending = h.dispatcher.callGhostTool(CALL);+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));++ generation = 2;+ const outcome = h.dispatcher.handleToolResult('art', {+ type: 'tool-result',+ callId: h.sent[0].callId,+ ok: true,+ result: { stale: true },+ });++ expect(outcome).toMatchObject({ accepted: false });+ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'GHOST_ASLEEP' });+ expect(invalidated).toHaveBeenCalledWith('art');+ });+it('完成日志只含元数据,不记录参数或返回内容', async () => {const h = makeHarness();const secretArg = 'must-not-log-argument';diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 38d3d6347a..1448d714b9 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -473,7 +473,11 @@ function captureGhostMutationOwner(): ActiveAppSession {if (isAppSessionBoundaryPending()) {throw new Error('账号切换中,已取消本次 Plugin 操作');}- return getActiveAppSession();+ const owner = getActiveAppSession();+ if (!isGhostSkillProjectionBoundaryStableForOwner(owner.dataOwnerId)) {+ throw new Error('Plugin owner boundary is not durably stable');+ }+ return owner;}/**@@ -486,8 +490,11 @@ function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {if (isAppSessionBoundaryPending()) {throw new Error('账号切换中,已取消本次 Plugin 操作');}+ const currentOwner = getActiveAppSession();+ if (!isGhostSkillProjectionBoundaryStableForOwner(currentOwner.dataOwnerId)) {+ throw new Error('Plugin owner boundary is not durably stable');+ }if (expectedOwner) {- const currentOwner = getActiveAppSession();if (currentOwner.mode !== expectedOwner.mode ||currentOwner.dataOwnerId !== expectedOwner.dataOwnerId ||@@ -1406,6 +1413,7 @@ export function getGhostPipeDispatcher(): GhostPipeDispatcher {if (!dispatcherSingleton) {dispatcherSingleton = new GhostPipeDispatcher({getGhost: findAvailableGhost,+ ownerScope: ghostOwnerScope,runtimeStateOf: (id) => getGhostRuntime().stateOf(id),spawn: async (ghost) => {const r = await getGhostRuntime().spawn(ghost);@@ -1495,6 +1503,7 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {if (!nodeRuntimeBrokerSingleton) {nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({getGhost: findAvailableGhost,+ ownerScope: ghostOwnerScope,readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),sendToGhost: (ghostId, payload) => {sendToGhostLogic(ghostId, payload);diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex aa39635fac..12c7c7cbcc 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -37,6 +37,7 @@ import {isGhostNodeMcpReservedMethod,parseGhostNodeChildToHostMessage,} from '../../shared/ghost.js';+import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';const DEFAULT_IDLE_TIMEOUT_MS = 2 * 60_000;const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;@@ -100,6 +101,7 @@ export interface NodeWorkerProcess {export interface GhostNodeRuntimeBrokerDeps {getGhost(id: string): InstalledGhost | null;+ ownerScope?: GhostOwnerScope;/*** 读取当前插件自己声明的 Node 凭证。生产接 safeStorage;返回 null =* 未保存或保险库不可用。调用方不得记录返回值。@@ -133,6 +135,7 @@ interface PendingRpc {deadlineAt: number | null;/** 超时收尾(初臂/续命共用同一段收尾逻辑)。 */expire(): void;+ ownerScopeSnapshot: unknown;}/** 宿主代启的原样 stdio 子进程(childSpawn;挂在某个 worker 名下)。 */@@ -146,6 +149,7 @@ interface ChildProcEntry {interface WorkerEntry {ghost: InstalledGhost;+ ownerScopeSnapshot: unknown;/** 本进程对应的入口(相对路径;主入口 = manifest.node.entry)。 */entryRel: string;child: NodeWorkerProcess;@@ -195,6 +199,7 @@ class WorkerStartError extends Error {message: string,readonly retryable: boolean,readonly silent = false,+ readonly ownerBoundary = false,) {super(message);}@@ -449,7 +454,9 @@ export class GhostNodeRuntimeBroker {async startResident(ghost: InstalledGhost): Promise<void> {this.stoppedGhosts.delete(ghost.manifest.id);if (!ghost.enabled || ghost.manifest.node?.lifecycle !== 'resident') return;- const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry);+ const ownerScopeSnapshot = this.captureOwnerScope();+ const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry, ownerScopeSnapshot);+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);}@@ -457,7 +464,9 @@ export class GhostNodeRuntimeBroker {async startForRecovery(ghost: InstalledGhost): Promise<void> {this.stoppedGhosts.delete(ghost.manifest.id);if (!ghost.enabled || !ghost.manifest.node) return;- const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry);+ const ownerScopeSnapshot = this.captureOwnerScope();+ const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry, ownerScopeSnapshot);+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);}@@ -544,11 +553,22 @@ export class GhostNodeRuntimeBroker {return errorResult('INVALID_REQUEST', 'MCP 初始化由 Cindy 主机统一管理');}+ let ownerScopeSnapshot: unknown;+ try {+ ownerScopeSnapshot = this.captureOwnerScope();+ } catch {+ return errorResult('PERMISSION_DENIED', 'Plugin owner boundary is not stable');+ }+let hostSecrets: Record<string, string> | undefined;if (secretBindings.length > 0) {hostSecrets = Object.create(null) as Record<string, string>;try {for (const binding of secretBindings) {+ if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', 'Plugin owner boundary is not stable');+ }const value = this.deps.readSecret?.(ghostId, binding.key) ?? null;if (value === null) {clearHostSecrets(hostSecrets);@@ -559,6 +579,10 @@ export class GhostNodeRuntimeBroker {}hostSecrets[binding.key] = value;}+ if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', 'Plugin owner boundary is not stable');+ }} catch {clearHostSecrets(hostSecrets);return errorResult('INTERNAL', '读取 Node 请求所需凭证失败');@@ -567,9 +591,13 @@ export class GhostNodeRuntimeBroker {let entry: WorkerEntry;try {- entry = await this.ensureWorker(ghost, entryRel);+ entry = await this.ensureWorker(ghost, entryRel, ownerScopeSnapshot);+ this.assertOwnerScopeUsable(ghostId, ownerScopeSnapshot);} catch (error) {clearHostSecrets(hostSecrets);+ if (error instanceof WorkerStartError && error.ownerBoundary) {+ return errorResult('PERMISSION_DENIED', error.message);+ }return errorResult('PROCESS_START_FAILED',error instanceof Error ? error.message : 'Node 工作进程启动失败',@@ -583,6 +611,7 @@ export class GhostNodeRuntimeBroker {try {if (ghost.manifest.node.protocol === 'mcp-stdio') {await this.ensureMcpInitialized(entry);+ this.assertOwnerScopeUsable(ghostId, ownerScopeSnapshot);if (entry.pending.size >= MAX_PENDING_REQUESTS) {return errorResult('RATE_LIMITED', '这个插件同时等待的 Node 请求太多');}@@ -599,6 +628,7 @@ export class GhostNodeRuntimeBroker {effectiveTimeoutMs,request.maxTotalMs as number | undefined,hostSecrets,+ ownerScopeSnapshot,);// writeLine/JSON.stringify 在 sendRpc 内同步完成;随即抹掉本次临时对象,// 不让凭证明文跟随 Promise 生命周期常驻在 broker 闭包里。@@ -625,6 +655,7 @@ export class GhostNodeRuntimeBroker {/** worker 引导层上行控制帧的总入口:形状不合静默丢,资格逐项查。 */private handleWorkerControl(entry: WorkerEntry, raw: unknown): void {+ if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;const message = parseGhostNodeChildToHostMessage(raw);if (!message) return;if (message.type === 'spawn-child') {@@ -658,6 +689,7 @@ export class GhostNodeRuntimeBroker {private readonly childReservations = new Map<string, number>();private replyToWorker(entry: WorkerEntry, message: GhostNodeChildToWorkerMessage): void {+ if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;entry.child.sendControl?.(message);}@@ -681,6 +713,10 @@ export class GhostNodeRuntimeBroker {message: reason,});};+ if (!this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)) {+ fail('Plugin owner boundary changed before child process dispatch');+ return;+ }const ghost = this.deps.getGhost(ghostId);const node = ghost?.enabled ? ghost.manifest.node : undefined;if (!node || node.childSpawn !== true) {@@ -771,7 +807,10 @@ export class GhostNodeRuntimeBroker {}// worker 在等待答复期间死了/被停:孩子不能变孤儿,就地收掉。- if (this.workers.get(GhostNodeRuntimeBroker.keyOf(ghostId, entry.entryRel)) !== entry) {+ if (+ this.workers.get(GhostNodeRuntimeBroker.keyOf(ghostId, entry.entryRel)) !== entry+ || !this.ownerScopeUsable(ghostId, entry.ownerScopeSnapshot)+ ) {try {proc.kill('SIGKILL');} catch {@@ -913,13 +952,26 @@ export class GhostNodeRuntimeBroker {/** destroyAll(主机退出)后置真:退避中的重试不得再拉新进程。 */private destroyed = false;- private async ensureWorker(ghost: InstalledGhost, entryRel: string): Promise<WorkerEntry> {+ private async ensureWorker(+ ghost: InstalledGhost,+ entryRel: string,+ ownerScopeSnapshot: unknown,+ ): Promise<WorkerEntry> {const key = GhostNodeRuntimeBroker.keyOf(ghost.manifest.id, entryRel);const inflight = this.startingWorkers.get(key);- if (inflight) return inflight;+ if (inflight) {+ const entry = await inflight;+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);+ this.assertOwnerScopeUsable(ghost.manifest.id, entry.ownerScopeSnapshot);+ return entry;+ }const existing = this.workers.get(key);- if (existing) return existing;- const starting = this.startWorkerWithRetry(ghost, entryRel, key);+ if (existing) {+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);+ this.assertOwnerScopeUsable(ghost.manifest.id, existing.ownerScopeSnapshot);+ return existing;+ }+ const starting = this.startWorkerWithRetry(ghost, entryRel, key, ownerScopeSnapshot);this.startingWorkers.set(key, starting);try {return await starting;@@ -932,7 +984,9 @@ export class GhostNodeRuntimeBroker {ghost: InstalledGhost,entryRel: string,key: string,+ ownerScopeSnapshot: unknown,): Promise<WorkerEntry> {+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {throw new WorkerStartError('Node 工作进程启动已取消', false, true);}@@ -942,6 +996,7 @@ export class GhostNodeRuntimeBroker {for (let attempt = 1; attempt <= WORKER_START_ATTEMPTS; attempt++) {if (attempt > 1) {await this.delay(WORKER_START_RETRY_DELAYS_MS[attempt - 2] ?? 750);+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);// 退避期间插件可能被停用/卸载/更新/停止,主机也可能正在退出:// 现查现用;已停用/已收摊/已停止就不再拉进程,也不补发状态事件。if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) throw lastError;@@ -954,7 +1009,7 @@ export class GhostNodeRuntimeBroker {current = fresh;}try {- return await this.startWorkerOnce(current, entryRel, key);+ return await this.startWorkerOnce(current, entryRel, key, ownerScopeSnapshot);} catch (error) {lastError = error instanceof Error ? error : new Error(String(error));const retryable = error instanceof WorkerStartError ? error.retryable : true;@@ -977,7 +1032,9 @@ export class GhostNodeRuntimeBroker {ghost: InstalledGhost,entryRel: string,key: string,+ ownerScopeSnapshot: unknown,): Promise<WorkerEntry> {+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);const node = ghost.manifest.node;if (!node) throw new WorkerStartError('ghost.json 缺少 node 工作进程详单', false);const entryPath = path.resolve(ghost.dir, ...entryRel.split('/'));@@ -993,6 +1050,7 @@ export class GhostNodeRuntimeBroker {}const entry: WorkerEntry = {ghost,+ ownerScopeSnapshot,entryRel,child,startupPhase: true,@@ -1047,7 +1105,10 @@ export class GhostNodeRuntimeBroker {const text = decoded.trim().slice(0, 4_096);if (text) this.deps.log?.warn('ghost node stderr', { ghostId: ghost.manifest.id, text });// 进程已退出后不再续命——定时器已冻结,由 settleExit 统一结算。- if (!entry.exitDrain) {+ if (+ !entry.exitDrain+ && this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)+ ) {// stderr 是手册钦定的日志口——构建刷日志就是活着的证据,给续命请求重置沉默窗口。this.renewPendingOnActivity(entry);}@@ -1106,6 +1167,7 @@ export class GhostNodeRuntimeBroker {throw error;}entry.startupPhase = false;+ this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);this.deps.log?.info('ghost node process started', {ghostId: ghost.manifest.id,entry: entryRel,@@ -1136,6 +1198,7 @@ export class GhostNodeRuntimeBroker {},10_000,).then(() => {+ this.assertOwnerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot);this.writeLine(entry, {jsonrpc: '2.0',method: 'notifications/initialized',@@ -1156,7 +1219,9 @@ export class GhostNodeRuntimeBroker {timeoutMs: number,maxTotalMs?: number,hostSecrets?: Readonly<Record<string, string>>,+ ownerScopeSnapshot: unknown = entry.ownerScopeSnapshot,): Promise<unknown> {+ this.assertOwnerScopeUsable(entry.ghost.manifest.id, ownerScopeSnapshot);this.clearIdleTimer(entry);const id = String(entry.nextId++);return new Promise((resolve, reject) => {@@ -1172,6 +1237,7 @@ export class GhostNodeRuntimeBroker {reject(new NodeRpcError('timeout', `Node 请求 ${method} 等待超时`));this.scheduleIdleStop(entry);},+ ownerScopeSnapshot,};entry.pending.set(id, pending);this.armPendingTimer(pending);@@ -1231,6 +1297,7 @@ export class GhostNodeRuntimeBroker {private handleStdout(entry: WorkerEntry, chunk: Buffer | string): void {const key = GhostNodeRuntimeBroker.keyOf(entry.ghost.manifest.id, entry.entryRel);if (this.workers.get(key) !== entry) return;+ if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;entry.stdoutBuffer += entry.stdoutDecoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8'),);@@ -1259,6 +1326,7 @@ export class GhostNodeRuntimeBroker {}private handleRpcMessage(entry: WorkerEntry, message: unknown): void {+ if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;if (!message || typeof message !== 'object' || Array.isArray(message)) {this.failProtocol(entry, 'Node 返回的 JSON-RPC 消息必须是对象');return;@@ -1273,6 +1341,10 @@ export class GhostNodeRuntimeBroker {if (!pending) return; // 迟到或未知 response,静默丢弃。entry.pending.delete(String(msg.id));this.clearTimer(pending.timer);+ if (!this.ownerScopeUsable(entry.ghost.manifest.id, pending.ownerScopeSnapshot)) {+ pending.reject(new NodeRpcError('exit', 'Plugin owner boundary changed before response'));+ return;+ }if (msg.error && typeof msg.error === 'object') {const rpcError = msg.error as Record<string, unknown>;pending.reject(@@ -1330,6 +1402,27 @@ export class GhostNodeRuntimeBroker {}}+ private captureOwnerScope(): unknown {+ return this.deps.ownerScope?.capture();+ }++ private ownerScopeUsable(ghostId: string, captured: unknown): boolean {+ if (isGhostOwnerScopeUsable(this.deps.ownerScope, captured)) return true;+ this.deps.ownerScope?.onInvalidated?.(ghostId);+ this.stop(ghostId);+ return false;+ }++ private assertOwnerScopeUsable(ghostId: string, captured: unknown): void {+ if (this.ownerScopeUsable(ghostId, captured)) return;+ throw new WorkerStartError(+ 'Plugin owner boundary changed before Node dispatch',+ false,+ true,+ true,+ );+ }+private handleExit(entry: WorkerEntry,code: number | null,diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.tsindex 8fe1754094..0f41fbd640 100644--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts@@ -28,6 +28,7 @@ import type {} from '../../shared/ghost.js';import { GHOST_PIPE_CALL_MAX_TOTAL_MS, isGhostPluginErrorCode } from '../../shared/ghost.js';import type { GhostRuntimeState } from './runtime/GhostRuntime.js';+import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';export interface PipeDispatcherDeps {/** 按 id 取已装意识(未装 → null)。 */@@ -38,6 +39,7 @@ export interface PipeDispatcherDeps {spawn(ghost: InstalledGhost): Promise<{ ok: true } | { ok: false; reason: string }>;/** 把下行消息发到该意识的电子脑逻辑页;false = 逻辑页不在线。 */sendToGhost(ghostId: string, payload: GhostPipeToolCall): boolean;+ ownerScope?: GhostOwnerScope;/** 单次调用超时(默认 330s,见 DEFAULT_TIMEOUT_MS 注释)。 */timeoutMs?: number;setTimeoutFn?: typeof setTimeout;@@ -59,6 +61,7 @@ interface PendingBindingClaim {interface PendingCall {ghostId: string;tool: string;+ ownerScopeSnapshot: unknown;/** 宿主能力按用途绑定,允许同请求一次受控重试,禁止换参或无限消费。 */claimedBindings: Map<string, PendingBindingClaim>;resolve: (result: GhostToolCallResult) => void;@@ -165,6 +168,12 @@ export class GhostPipeDispatcher {if (this.deps.runtimeStateOf(ghostId) === 'fused') {return { ok: false, errorCode: 'GHOST_CRASHED', message: `插件 ${ghostId} 已熔断(反复崩溃),重载或重新启用后再试` };}+ let ownerScopeSnapshot: unknown;+ try {+ ownerScopeSnapshot = this.deps.ownerScope?.capture();+ } catch {+ return this.ownerBoundaryResult();+ }// ── 按需拉起 ────────────────────────────────────────────────────────if (this.deps.runtimeStateOf(ghostId) !== 'running') {@@ -173,6 +182,9 @@ export class GhostPipeDispatcher {return { ok: false, errorCode: 'GHOST_CRASHED', message: `插件启动失败:${spawned.reason}` };}}+ if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {+ return this.ownerBoundaryResult();+ }// ── 派发 + 配对等待 ────────────────────────────────────────────────const callId = request.callId && request.callId.length > 0 ? request.callId : randomUUID();@@ -184,6 +196,7 @@ export class GhostPipeDispatcher {const entry: PendingCall = {ghostId,tool,+ ownerScopeSnapshot,claimedBindings: new Map(),resolve,timer: undefined,@@ -196,6 +209,10 @@ export class GhostPipeDispatcher {this.pending.set(callId, entry);this.armTimer(callId, entry);+ if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {+ this.settle(callId, this.ownerBoundaryResult());+ return;+ }if (!this.deps.sendToGhost(ghostId, payload)) {// 逻辑页不在线(拉起后瞬时死亡等):立即收卷。this.settle(callId, { ok: false, errorCode: 'GHOST_CRASHED', message: '电子脑离线,派发失败' });@@ -368,6 +385,10 @@ export class GhostPipeDispatcher {if (entry.ghostId !== senderGhostId) {return { accepted: false, reason: '不是你的卷子' };}+ if (!this.ownerScopeUsable(senderGhostId, entry.ownerScopeSnapshot)) {+ this.settle(p.callId, this.ownerBoundaryResult());+ return { accepted: false, reason: '账号边界已变化' };+ }if (entry.timeoutExtensionsAllowed) {this.extendDeadline(p.callId, entry, Date.now() + entry.baseTimeoutMs);}@@ -403,6 +424,10 @@ export class GhostPipeDispatcher {});return { accepted: false, reason: '不是你的卷子' };}+ if (!this.ownerScopeUsable(senderGhostId, entry.ownerScopeSnapshot)) {+ this.settle(p.callId, this.ownerBoundaryResult());+ return { accepted: false, reason: '账号边界已变化' };+ }const result: GhostToolCallResult = p.ok? { ok: true, result: p.result ?? null }: {@@ -447,4 +472,18 @@ export class GhostPipeDispatcher {});entry.resolve(result);}++ private ownerScopeUsable(ghostId: string, captured: unknown): boolean {+ if (isGhostOwnerScopeUsable(this.deps.ownerScope, captured)) return true;+ this.deps.ownerScope?.onInvalidated?.(ghostId);+ return false;+ }++ private ownerBoundaryResult(): GhostToolCallResult {+ return {+ ok: false,+ errorCode: 'GHOST_ASLEEP',+ message: 'Plugin owner boundary changed before dispatch; retry after the active session settles.',+ };+ }}diff --git a/apps/desktop/src/main/learn-host/apply.ts b/apps/desktop/src/main/learn-host/apply.tsindex 9c9bbcede5..776945caa7 100644--- a/apps/desktop/src/main/learn-host/apply.ts+++ b/apps/desktop/src/main/learn-host/apply.ts@@ -15,7 +15,11 @@ import crypto from 'node:crypto';import { ownerScopedUserDataPath } from '../appSessionState';import { createLogger, maskPath } from '../logger';-import { getCurrentUserId } from '../authManager';+import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';+import {+ assertGhostSkillProjectionBoundaryStableForOwner,+ withSharedGlobalSkillProjectionMutation,+} from '../authBoundaryQuarantine.js';import { registryService } from '../skillhub/registry';import { computeFolderHash } from '../skillhub/folderHash';import { ensureSymlinkToShared } from '../skillhub/installService';@@ -285,7 +289,13 @@ export async function applyProposal(params: ApplyProposalParams): Promise<ApplyP}}try {- const linkResult = await prepareSharedGlobalSkillLinks();+ const ownerId = getCurrentDataOwnerId();+ const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>+ prepareSharedGlobalSkillLinks({+ assertOwnerStable: () =>+ assertGhostSkillProjectionBoundaryStableForOwner(ownerId),+ }),+ );for (const warning of linkResult.warnings) {log.warn('shared global skill link warning:', warning);}diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex cc47978fce..382e5d11fa 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -84,6 +84,10 @@ import {isAppSessionBoundaryPending,type ActiveAppSession,} from '../appSessionState.js';+import {+ assertGhostSkillProjectionBoundaryStableForOwner,+ withSharedGlobalSkillProjectionMutation,+} from '../authBoundaryQuarantine.js';import {bindNativeProviderAuth,claimDetectedNativeProviderAuth,@@ -493,7 +497,13 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {private async runEnsureSharedGlobalSkills(): Promise<void> {try {- const result = await prepareSharedGlobalSkillLinks();+ const ownerId = getActiveAppSession().dataOwnerId;+ const result = await withSharedGlobalSkillProjectionMutation(ownerId, () =>+ prepareSharedGlobalSkillLinks({+ assertOwnerStable: () =>+ assertGhostSkillProjectionBoundaryStableForOwner(ownerId),+ }),+ );for (const warning of result.warnings) {assetPrepLog.warn('shared global skill warning', { warning });}@@ -1057,7 +1067,13 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {private async runEnsureGlobalCodexAssets(): Promise<void> {// Load-bearing order: Codex skill linking scans ~/.agents/skills, so shared// links must populate that directory before prepareCodexGlobalSkillsLinks runs.- const sharedOutcome = await prepareSharedGlobalSkillLinks().then(+ const ownerId = getActiveAppSession().dataOwnerId;+ const sharedOutcome = await withSharedGlobalSkillProjectionMutation(ownerId, () =>+ prepareSharedGlobalSkillLinks({+ assertOwnerStable: () =>+ assertGhostSkillProjectionBoundaryStableForOwner(ownerId),+ }),+ ).then((r) => ({ ok: true as const, label: 'shared-skills' as const, warnings: r.warnings }),(err: Error) => ({ ok: false as const, label: 'shared-skills' as const, err }),);diff --git a/apps/desktop/src/main/maker-host/shared-global-skills.ts b/apps/desktop/src/main/maker-host/shared-global-skills.tsindex bbec9a67d9..3c329d1055 100644--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts@@ -184,6 +184,7 @@ async function cleanupBrokenManagedLinks(rootPath: string,managedRoots: string[],staleManagedDiscoveryRoots: string[] = [],+ assertMutationAllowed?: () => void,): Promise<boolean> {let entries;try {@@ -216,6 +217,7 @@ async function cleanupBrokenManagedLinks();if (!pointsIntoCurrentRoots && !matchesMovedProjectLink) continue;+ assertMutationAllowed?.();try {await fsp.unlink(linkPath);changed = true;@@ -230,6 +232,7 @@ async function ensureDirectoryLink(source: SkillEntry,targetPath: string,useRelativeTarget = false,+ assertMutationAllowed?: () => void,): Promise<{ status: LinkStatus; changed: boolean; reason?: string }> {const targetReal = await realPathOrNull(targetPath);if (targetReal && targetReal === source.realPath) {@@ -251,8 +254,15 @@ async function ensureDirectoryLink(}}+ assertMutationAllowed?.();try {await fsp.mkdir(path.dirname(targetPath), { recursive: true });+ } catch (err) {+ return { status: 'error', changed: false, reason: (err as Error).message };+ }++ assertMutationAllowed?.();+ try {const linkTarget = useRelativeTarget && process.platform !== 'win32'? path.relative(path.dirname(targetPath), source.path): source.path;@@ -267,6 +277,7 @@ async function linkEntriesIntoRoot(entries: SkillEntry[],targetRoot: string,useRelativeTarget = false,+ assertMutationAllowed?: () => void,): Promise<{ actions: LinkAction[]; changed: boolean; warnings: string[] }> {const actions: LinkAction[] = [];const warnings: string[] = [];@@ -286,7 +297,12 @@ async function linkEntriesIntoRoot(}const targetPath = path.join(targetRoot, entry.name);- const result = await ensureDirectoryLink(entry, targetPath, useRelativeTarget);+ const result = await ensureDirectoryLink(+ entry,+ targetPath,+ useRelativeTarget,+ assertMutationAllowed,+ );changed = changed || result.changed;const action: LinkAction = {name: entry.name,@@ -320,7 +336,9 @@ export async function prepareSharedGlobalSkillLinks(): Promise<SharedGlobalSkillLinksResult> {opts.assertOwnerStable?.();const paths = sharedGlobalSkillsPaths(opts.homeDir);+ opts.assertOwnerStable?.();await fsp.mkdir(paths.sharedSkillsDir, { recursive: true });+ opts.assertOwnerStable?.();await fsp.mkdir(paths.claudeSkillsDir, { recursive: true });const sharedRootCompare = (await realPathOrNull(paths.sharedSkillsDir)) ?? normalizeForCompare(paths.sharedSkillsDir);const claudeRootCompare = (await realPathOrNull(paths.claudeSkillsDir)) ?? normalizeForCompare(paths.claudeSkillsDir);@@ -338,29 +356,55 @@ export async function prepareSharedGlobalSkillLinks(normalizeForCompare(paths.codexSkillsDir),]));- changed = (await cleanupBrokenManagedLinks(paths.sharedSkillsDir, managedRoots)) || changed;- changed = (await cleanupBrokenManagedLinks(paths.claudeSkillsDir, managedRoots)) || changed;+ changed = (await cleanupBrokenManagedLinks(+ paths.sharedSkillsDir,+ managedRoots,+ [],+ opts.assertOwnerStable,+ )) || changed;+ changed = (await cleanupBrokenManagedLinks(+ paths.claudeSkillsDir,+ managedRoots,+ [],+ opts.assertOwnerStable,+ )) || changed;const initialClaudeEntries = (await listSkillEntries('claude', paths.claudeSkillsDir)).filter((entry) => !(entry.isSymlink && pointsInto(entry, [sharedRootCompare, codexRootCompare])));- const claudeToShared = await linkEntriesIntoRoot(initialClaudeEntries, paths.sharedSkillsDir);+ const claudeToShared = await linkEntriesIntoRoot(+ initialClaudeEntries,+ paths.sharedSkillsDir,+ false,+ opts.assertOwnerStable,+ );actions.push(...claudeToShared.actions);warnings.push(...claudeToShared.warnings);changed = changed || claudeToShared.changed;const sharedEntries = await listSkillEntries('shared', paths.sharedSkillsDir);- const sharedToClaude = await linkEntriesIntoRoot(sharedEntries, paths.claudeSkillsDir);+ const sharedToClaude = await linkEntriesIntoRoot(+ sharedEntries,+ paths.claudeSkillsDir,+ false,+ opts.assertOwnerStable,+ );actions.push(...sharedToClaude.actions);warnings.push(...sharedToClaude.warnings);changed = changed || sharedToClaude.changed;const codexEntries = (await listSkillEntries('codex', paths.codexSkillsDir)).filter((entry) => !(entry.isSymlink && pointsInto(entry, [sharedRootCompare, claudeRootCompare])));- const codexToClaude = await linkEntriesIntoRoot(codexEntries, paths.claudeSkillsDir);+ const codexToClaude = await linkEntriesIntoRoot(+ codexEntries,+ paths.claudeSkillsDir,+ false,+ opts.assertOwnerStable,+ );actions.push(...codexToClaude.actions);warnings.push(...codexToClaude.warnings);changed = changed || codexToClaude.changed;+ opts.assertOwnerStable?.();return {...paths,changed,diff --git a/apps/desktop/src/main/skillhub/importLocalSkill.ts b/apps/desktop/src/main/skillhub/importLocalSkill.tsindex 787fc853c9..8a10d2f0dd 100644--- a/apps/desktop/src/main/skillhub/importLocalSkill.ts+++ b/apps/desktop/src/main/skillhub/importLocalSkill.ts@@ -11,7 +11,11 @@ import path from 'node:path';import { app } from 'electron';import JSZip from 'jszip';-import { getCurrentUserId } from '../authManager';+import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';+import {+ assertGhostSkillProjectionBoundaryStableForOwner,+ withSharedGlobalSkillProjectionMutation,+} from '../authBoundaryQuarantine.js';import { createLogger, maskPath } from '../logger';import {prepareSharedGlobalSkillLinks,@@ -552,7 +556,13 @@ export async function importLocalSkill(params: ImportLocalParams): Promise<Imporconst projectWorkingDir = await reconcileProjectLinks(finalDir);try {- const linkResult = await prepareSharedGlobalSkillLinks();+ const ownerId = getCurrentDataOwnerId();+ const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>+ prepareSharedGlobalSkillLinks({+ assertOwnerStable: () =>+ assertGhostSkillProjectionBoundaryStableForOwner(ownerId),+ }),+ );for (const warning of linkResult.warnings) {log.warn('[importLocal] shared global skill link warning:', warning);}diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.tsindex 4c56255ed2..2044585508 100644--- a/apps/desktop/src/main/skillhub/installService.ts+++ b/apps/desktop/src/main/skillhub/installService.ts@@ -31,6 +31,10 @@ import JSZip from 'jszip';import { skillhubApiFetch } from './hubApi';import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';import { getAppCapabilities } from '../appCapabilities.js';+import {+ assertGhostSkillProjectionBoundaryStableForOwner,+ withSharedGlobalSkillProjectionMutation,+} from '../authBoundaryQuarantine.js';import { registryService } from './registry';import type { StoredInstall } from './registry/types';import { computeFolderHash } from './folderHash';@@ -875,7 +879,13 @@ export async function install(}const projectWorkingDir = await reconcileProjectSkillLinksForPaths(logicalFinalDir, finalDir);try {- const linkResult = await prepareSharedGlobalSkillLinks();+ const ownerId = getCurrentDataOwnerId();+ const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>+ prepareSharedGlobalSkillLinks({+ assertOwnerStable: () =>+ assertGhostSkillProjectionBoundaryStableForOwner(ownerId),+ }),+ );for (const warning of linkResult.warnings) {log.warn('[skillInstall] shared global skill link warning:', warning);}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxindex f5f2ddd7e5..17ffe36c6b 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx@@ -202,7 +202,7 @@ describe('GhostPermissionDiffView(更新权限 diff)', () => {render(<GhostPermissionDiffView diff={diffGhostPermissionItems(prev, next)} />);// 真正的权限变化(新增网络域名)仍在折叠区之外,第一屏就能看到。expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();- expect(screen.getAllByText('settings.ghosts.perm.added')).toHaveLength(2);+ expect(screen.getByText('settings.ghosts.perm.added')).toBeTruthy();// 新增 network 槽后 code 项的主机固定说明换版本(codeDetail → codeDetailNetwork):// 指纹含 detailKey 后这算权限面变化,但同 key 配对成一条「更新」行,// 不渲染成「移除+新增」两条误导用户。diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 4e9f92ec21..297a48231b 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -27,7 +27,6 @@ import {isOfficialGhostId,isValidGhostNetworkHostPattern,layoutWithGhostPanel,- unreviewedGhostPermissionItems,parseGhostPartition,resolveGhostManifestLocale,validateGhostManifest,diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 1bbc324075..89d6b74e3f 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1685,7 +1685,7 @@ function ghostPermissionProjectionTuple(item: GhostPermissionItem): unknown[] {return [item.key,item.kind,- item.labelKey,+ permissionLabelKeyForFingerprint(item),sortRecord(item.labelArgs),item.detail ?? null,permissionDetailKeyForFingerprint(item) || null,@@ -2104,6 +2104,24 @@ export interface GhostPermissionDiff {* 形态),只看 key+detail 会把"说明/成本面变了"漏判成"权限面没变",更新时* 用户看不到重新确认。*/+function isGithubCredentialCompatibilityItem(item: GhostPermissionItem): boolean {+ return (+ item.key === 'network:secret:github_pat' &&+ (item.detailKey === 'networkSecretGhostInputDetail' ||+ item.detailKey === 'networkSecretGhCliDetail')+ );+}++function permissionLabelKeyForFingerprint(item: GhostPermissionItem): string {+ if (+ isGithubCredentialCompatibilityItem(item) &&+ (item.labelKey === 'networkSecret' || item.labelKey === 'networkSecretGhCli')+ ) {+ return 'networkSecretGithubCredential';+ }+ return item.labelKey;+}+function permissionDetailKeyForFingerprint(item: GhostPermissionItem): string {// cindy-github 从存量 PAT(source:user)升级为 Host 优先 gh-cli 时,凭证仍由// Main 只注入同一个 network secret key 与同一组目标;变化的是设置页/权限@@ -2111,10 +2129,7 @@ function permissionDetailKeyForFingerprint(item: GhostPermissionItem): string {// 同时也必须共用审阅指纹,否则升级会被误判成扩权并要求存量用户重新确认。// gh-cli 的 manifest 校验只允许官方 cindy-github,因此这个兼容等价不会// 放宽其它插件;其它 detailKey/detailArgs 变化仍按新说明完整性规则复核。- if (- item.detailKey === 'networkSecretGhostInputDetail' ||- item.detailKey === 'networkSecretGhCliDetail'- ) {+ if (isGithubCredentialCompatibilityItem(item)) {return 'networkSecretGithubCredentialDetail';}return item.detailKey ?? '';